View Javadoc
1   /*
2    * Copyright (C) 2007, Dave Watson <dwatson@mimvista.com>
3    * Copyright (C) 2009-2010, Google Inc.
4    * Copyright (C) 2007, Robin Rosenberg <robin.rosenberg@dewire.com>
5    * Copyright (C) 2006, Shawn O. Pearce <spearce@spearce.org>
6    * and other copyright owners as documented in the project's IP log.
7    *
8    * This program and the accompanying materials are made available
9    * under the terms of the Eclipse Distribution License v1.0 which
10   * accompanies this distribution, is reproduced below, and is
11   * available at http://www.eclipse.org/org/documents/edl-v10.php
12   *
13   * All rights reserved.
14   *
15   * Redistribution and use in source and binary forms, with or
16   * without modification, are permitted provided that the following
17   * conditions are met:
18   *
19   * - Redistributions of source code must retain the above copyright
20   *   notice, this list of conditions and the following disclaimer.
21   *
22   * - Redistributions in binary form must reproduce the above
23   *   copyright notice, this list of conditions and the following
24   *   disclaimer in the documentation and/or other materials provided
25   *   with the distribution.
26   *
27   * - Neither the name of the Eclipse Foundation, Inc. nor the
28   *   names of its contributors may be used to endorse or promote
29   *   products derived from this software without specific prior
30   *   written permission.
31   *
32   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
33   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
34   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
35   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
36   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
37   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
38   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
39   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
40   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
41   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
42   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
43   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
44   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
45   */
46  package org.eclipse.jgit.internal.storage.file;
47  
48  import static org.eclipse.jgit.lib.Constants.HEAD;
49  import static org.eclipse.jgit.lib.Constants.R_HEADS;
50  import static org.eclipse.jgit.lib.Constants.R_NOTES;
51  import static org.eclipse.jgit.lib.Constants.R_REFS;
52  import static org.eclipse.jgit.lib.Constants.R_REMOTES;
53  
54  import java.io.File;
55  import java.io.FileNotFoundException;
56  import java.io.FileOutputStream;
57  import java.io.IOException;
58  import java.nio.ByteBuffer;
59  import java.nio.channels.FileChannel;
60  import java.text.MessageFormat;
61  
62  import org.eclipse.jgit.internal.JGitText;
63  import org.eclipse.jgit.lib.Constants;
64  import org.eclipse.jgit.lib.CoreConfig;
65  import org.eclipse.jgit.lib.ObjectId;
66  import org.eclipse.jgit.lib.PersonIdent;
67  import org.eclipse.jgit.lib.Ref;
68  import org.eclipse.jgit.lib.RefUpdate;
69  import org.eclipse.jgit.lib.ReflogEntry;
70  import org.eclipse.jgit.util.FileUtils;
71  
72  /**
73   * Utility for writing reflog entries using the traditional one-file-per-log
74   * format.
75   */
76  public class ReflogWriter {
77  
78  	/**
79  	 * Get the ref name to be used for when locking a ref's log for rewriting.
80  	 *
81  	 * @param name
82  	 *            name of the ref, relative to the Git repository top level
83  	 *            directory (so typically starts with refs/).
84  	 * @return the name of the ref's lock ref.
85  	 */
86  	public static String refLockFor(String name) {
87  		return name + LockFile.SUFFIX;
88  	}
89  
90  	private final RefDirectory refdb;
91  
92  	private final boolean forceWrite;
93  
94  	/**
95  	 * Create writer for ref directory.
96  	 *
97  	 * @param refdb
98  	 */
99  	public ReflogWriter(RefDirectory refdb) {
100 		this(refdb, false);
101 	}
102 
103 	/**
104 	 * Create writer for ref directory.
105 	 *
106 	 * @param refdb
107 	 * @param forceWrite
108 	 *            true to write to disk all entries logged, false to respect the
109 	 *            repository's config and current log file status.
110 	 */
111 	public ReflogWriter(RefDirectory refdb, boolean forceWrite) {
112 		this.refdb = refdb;
113 		this.forceWrite = forceWrite;
114 	}
115 
116 	/**
117 	 * Create the log directories.
118 	 *
119 	 * @throws IOException
120 	 * @return this writer.
121 	 */
122 	public ReflogWriter create() throws IOException {
123 		FileUtils.mkdir(refdb.logsDir);
124 		FileUtils.mkdir(refdb.logsRefsDir);
125 		FileUtils.mkdir(
126 				new File(refdb.logsRefsDir, R_HEADS.substring(R_REFS.length())));
127 		return this;
128 	}
129 
130 	/**
131 	 * Write the given entry to the ref's log.
132 	 *
133 	 * @param refName
134 	 * @param entry
135 	 * @return this writer
136 	 * @throws IOException
137 	 */
138 	public ReflogWriter log(String refName, ReflogEntry entry)
139 			throws IOException {
140 		return log(refName, entry.getOldId(), entry.getNewId(), entry.getWho(),
141 				entry.getComment());
142 	}
143 
144 	/**
145 	 * Write the given entry information to the ref's log
146 	 *
147 	 * @param refName
148 	 * @param oldId
149 	 * @param newId
150 	 * @param ident
151 	 * @param message
152 	 * @return this writer
153 	 * @throws IOException
154 	 */
155 	public ReflogWriter log(String refName, ObjectId oldId,
156 			ObjectId newId, PersonIdent ident, String message) throws IOException {
157 		byte[] encoded = encode(oldId, newId, ident, message);
158 		return log(refName, encoded);
159 	}
160 
161 	/**
162 	 * Write the given ref update to the ref's log.
163 	 *
164 	 * @param update
165 	 * @param msg
166 	 * @param deref
167 	 * @return this writer
168 	 * @throws IOException
169 	 */
170 	public ReflogWriter log(RefUpdate update, String msg,
171 			boolean deref) throws IOException {
172 		ObjectId oldId = update.getOldObjectId();
173 		ObjectId newId = update.getNewObjectId();
174 		Ref ref = update.getRef();
175 
176 		PersonIdent ident = update.getRefLogIdent();
177 		if (ident == null)
178 			ident = new PersonIdent(refdb.getRepository());
179 		else
180 			ident = new PersonIdent(ident);
181 
182 		byte[] rec = encode(oldId, newId, ident, msg);
183 		if (deref && ref.isSymbolic()) {
184 			log(ref.getName(), rec);
185 			log(ref.getLeaf().getName(), rec);
186 		} else
187 			log(ref.getName(), rec);
188 
189 		return this;
190 	}
191 
192 	private byte[] encode(ObjectId oldId, ObjectId newId, PersonIdent ident,
193 			String message) {
194 		StringBuilder r = new StringBuilder();
195 		r.append(ObjectId.toString(oldId));
196 		r.append(' ');
197 		r.append(ObjectId.toString(newId));
198 		r.append(' ');
199 		r.append(ident.toExternalString());
200 		r.append('\t');
201 		r.append(
202 				message.replace("\r\n", " ") //$NON-NLS-1$ //$NON-NLS-2$
203 						.replace("\n", " ")); //$NON-NLS-1$ //$NON-NLS-2$
204 		r.append('\n');
205 		return Constants.encode(r.toString());
206 	}
207 
208 	private ReflogWriter log(String refName, byte[] rec) throws IOException {
209 		File log = refdb.logFor(refName);
210 		boolean write = forceWrite
211 				|| (isLogAllRefUpdates() && shouldAutoCreateLog(refName))
212 				|| log.isFile();
213 		if (!write)
214 			return this;
215 
216 		WriteConfig wc = refdb.getRepository().getConfig().get(WriteConfig.KEY);
217 		FileOutputStream out;
218 		try {
219 			out = new FileOutputStream(log, true);
220 		} catch (FileNotFoundException err) {
221 			File dir = log.getParentFile();
222 			if (dir.exists())
223 				throw err;
224 			if (!dir.mkdirs() && !dir.isDirectory())
225 				throw new IOException(MessageFormat.format(
226 						JGitText.get().cannotCreateDirectory, dir));
227 			out = new FileOutputStream(log, true);
228 		}
229 		try {
230 			if (wc.getFSyncRefFiles()) {
231 				FileChannel fc = out.getChannel();
232 				ByteBuffer buf = ByteBuffer.wrap(rec);
233 				while (0 < buf.remaining())
234 					fc.write(buf);
235 				fc.force(true);
236 			} else
237 				out.write(rec);
238 		} finally {
239 			out.close();
240 		}
241 		return this;
242 	}
243 
244 	private boolean isLogAllRefUpdates() {
245 		return refdb.getRepository().getConfig().get(CoreConfig.KEY)
246 				.isLogAllRefUpdates();
247 	}
248 
249 	private boolean shouldAutoCreateLog(String refName) {
250 		return refName.equals(HEAD)
251 				|| refName.startsWith(R_HEADS)
252 				|| refName.startsWith(R_REMOTES)
253 				|| refName.startsWith(R_NOTES);
254 	}
255 }