View Javadoc
1   /*
2    * Copyright (C) 2007, Dave Watson <dwatson@mimvista.com>
3    * Copyright (C) 2008-2010, Google Inc.
4    * Copyright (C) 2006-2010, Robin Rosenberg <robin.rosenberg@dewire.com>
5    * Copyright (C) 2006-2008, 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  
47  package org.eclipse.jgit.internal.storage.file;
48  
49  import static org.eclipse.jgit.lib.RefDatabase.ALL;
50  
51  import java.io.File;
52  import java.io.IOException;
53  import java.text.MessageFormat;
54  import java.util.HashSet;
55  import java.util.Set;
56  
57  import org.eclipse.jgit.errors.ConfigInvalidException;
58  import org.eclipse.jgit.events.ConfigChangedEvent;
59  import org.eclipse.jgit.events.ConfigChangedListener;
60  import org.eclipse.jgit.events.IndexChangedEvent;
61  import org.eclipse.jgit.internal.JGitText;
62  import org.eclipse.jgit.internal.storage.file.ObjectDirectory.AlternateHandle;
63  import org.eclipse.jgit.internal.storage.file.ObjectDirectory.AlternateRepository;
64  import org.eclipse.jgit.lib.BaseRepositoryBuilder;
65  import org.eclipse.jgit.lib.ConfigConstants;
66  import org.eclipse.jgit.lib.Constants;
67  import org.eclipse.jgit.lib.CoreConfig.HideDotFiles;
68  import org.eclipse.jgit.lib.CoreConfig.SymLinks;
69  import org.eclipse.jgit.lib.ObjectId;
70  import org.eclipse.jgit.lib.Ref;
71  import org.eclipse.jgit.lib.RefDatabase;
72  import org.eclipse.jgit.lib.RefUpdate;
73  import org.eclipse.jgit.lib.ReflogReader;
74  import org.eclipse.jgit.lib.Repository;
75  import org.eclipse.jgit.storage.file.FileBasedConfig;
76  import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
77  import org.eclipse.jgit.util.FS;
78  import org.eclipse.jgit.util.FileUtils;
79  import org.eclipse.jgit.util.StringUtils;
80  import org.eclipse.jgit.util.SystemReader;
81  
82  /**
83   * Represents a Git repository. A repository holds all objects and refs used for
84   * managing source code (could by any type of file, but source code is what
85   * SCM's are typically used for).
86   *
87   * In Git terms all data is stored in GIT_DIR, typically a directory called
88   * .git. A work tree is maintained unless the repository is a bare repository.
89   * Typically the .git directory is located at the root of the work dir.
90   *
91   * <ul>
92   * <li>GIT_DIR
93   * 	<ul>
94   * 		<li>objects/ - objects</li>
95   * 		<li>refs/ - tags and heads</li>
96   * 		<li>config - configuration</li>
97   * 		<li>info/ - more configurations</li>
98   * 	</ul>
99   * </li>
100  * </ul>
101  * <p>
102  * This class is thread-safe.
103  * <p>
104  * This implementation only handles a subtly undocumented subset of git features.
105  *
106  */
107 public class FileRepository extends Repository {
108 	private final FileBasedConfig systemConfig;
109 
110 	private final FileBasedConfig userConfig;
111 
112 	private final FileBasedConfig repoConfig;
113 
114 	private final RefDatabase refs;
115 
116 	private final ObjectDirectory objectDatabase;
117 
118 	private FileSnapshot snapshot;
119 
120 	/**
121 	 * Construct a representation of a Git repository.
122 	 * <p>
123 	 * The work tree, object directory, alternate object directories and index
124 	 * file locations are deduced from the given git directory and the default
125 	 * rules by running {@link FileRepositoryBuilder}. This constructor is the
126 	 * same as saying:
127 	 *
128 	 * <pre>
129 	 * new FileRepositoryBuilder().setGitDir(gitDir).build()
130 	 * </pre>
131 	 *
132 	 * @param gitDir
133 	 *            GIT_DIR (the location of the repository metadata).
134 	 * @throws IOException
135 	 *             the repository appears to already exist but cannot be
136 	 *             accessed.
137 	 * @see FileRepositoryBuilder
138 	 */
139 	public FileRepository(final File gitDir) throws IOException {
140 		this(new FileRepositoryBuilder().setGitDir(gitDir).setup());
141 	}
142 
143 	/**
144 	 * A convenience API for {@link #FileRepository(File)}.
145 	 *
146 	 * @param gitDir
147 	 *            GIT_DIR (the location of the repository metadata).
148 	 * @throws IOException
149 	 *             the repository appears to already exist but cannot be
150 	 *             accessed.
151 	 * @see FileRepositoryBuilder
152 	 */
153 	public FileRepository(final String gitDir) throws IOException {
154 		this(new File(gitDir));
155 	}
156 
157 	/**
158 	 * Create a repository using the local file system.
159 	 *
160 	 * @param options
161 	 *            description of the repository's important paths.
162 	 * @throws IOException
163 	 *             the user configuration file or repository configuration file
164 	 *             cannot be accessed.
165 	 */
166 	public FileRepository(final BaseRepositoryBuilder options) throws IOException {
167 		super(options);
168 
169 		if (StringUtils.isEmptyOrNull(SystemReader.getInstance().getenv(
170 				Constants.GIT_CONFIG_NOSYSTEM_KEY)))
171 			systemConfig = SystemReader.getInstance().openSystemConfig(null,
172 					getFS());
173 		else
174 			systemConfig = new FileBasedConfig(null, FS.DETECTED) {
175 				public void load() {
176 					// empty, do not load
177 				}
178 
179 				public boolean isOutdated() {
180 					// regular class would bomb here
181 					return false;
182 				}
183 			};
184 		userConfig = SystemReader.getInstance().openUserConfig(systemConfig,
185 				getFS());
186 		repoConfig = new FileBasedConfig(userConfig, getFS().resolve(
187 				getDirectory(), Constants.CONFIG),
188 				getFS());
189 
190 		loadSystemConfig();
191 		loadUserConfig();
192 		loadRepoConfig();
193 
194 		repoConfig.addChangeListener(new ConfigChangedListener() {
195 			public void onConfigChanged(ConfigChangedEvent event) {
196 				fireEvent(event);
197 			}
198 		});
199 
200 		refs = new RefDirectory(this);
201 		objectDatabase = new ObjectDirectory(repoConfig, //
202 				options.getObjectDirectory(), //
203 				options.getAlternateObjectDirectories(), //
204 				getFS(), //
205 				new File(getDirectory(), Constants.SHALLOW));
206 
207 		if (objectDatabase.exists()) {
208 			final long repositoryFormatVersion = getConfig().getLong(
209 					ConfigConstants.CONFIG_CORE_SECTION, null,
210 					ConfigConstants.CONFIG_KEY_REPO_FORMAT_VERSION, 0);
211 			if (repositoryFormatVersion > 0)
212 				throw new IOException(MessageFormat.format(
213 						JGitText.get().unknownRepositoryFormat2,
214 						Long.valueOf(repositoryFormatVersion)));
215 		}
216 
217 		if (!isBare())
218 			snapshot = FileSnapshot.save(getIndexFile());
219 	}
220 
221 	private void loadSystemConfig() throws IOException {
222 		try {
223 			systemConfig.load();
224 		} catch (ConfigInvalidException e1) {
225 			IOException e2 = new IOException(MessageFormat.format(JGitText
226 					.get().systemConfigFileInvalid, systemConfig.getFile()
227 					.getAbsolutePath(), e1));
228 			e2.initCause(e1);
229 			throw e2;
230 		}
231 	}
232 
233 	private void loadUserConfig() throws IOException {
234 		try {
235 			userConfig.load();
236 		} catch (ConfigInvalidException e1) {
237 			IOException e2 = new IOException(MessageFormat.format(JGitText
238 					.get().userConfigFileInvalid, userConfig.getFile()
239 					.getAbsolutePath(), e1));
240 			e2.initCause(e1);
241 			throw e2;
242 		}
243 	}
244 
245 	private void loadRepoConfig() throws IOException {
246 		try {
247 			repoConfig.load();
248 		} catch (ConfigInvalidException e1) {
249 			IOException e2 = new IOException(JGitText.get().unknownRepositoryFormat);
250 			e2.initCause(e1);
251 			throw e2;
252 		}
253 	}
254 
255 	/**
256 	 * Create a new Git repository initializing the necessary files and
257 	 * directories.
258 	 *
259 	 * @param bare
260 	 *            if true, a bare repository is created.
261 	 *
262 	 * @throws IOException
263 	 *             in case of IO problem
264 	 */
265 	public void create(boolean bare) throws IOException {
266 		final FileBasedConfig cfg = getConfig();
267 		if (cfg.getFile().exists()) {
268 			throw new IllegalStateException(MessageFormat.format(
269 					JGitText.get().repositoryAlreadyExists, getDirectory()));
270 		}
271 		FileUtils.mkdirs(getDirectory(), true);
272 		HideDotFiles hideDotFiles = getConfig().getEnum(
273 				ConfigConstants.CONFIG_CORE_SECTION, null,
274 				ConfigConstants.CONFIG_KEY_HIDEDOTFILES,
275 				HideDotFiles.DOTGITONLY);
276 		if (hideDotFiles != HideDotFiles.FALSE && !isBare()
277 				&& getDirectory().getName().startsWith(".")) //$NON-NLS-1$
278 			getFS().setHidden(getDirectory(), true);
279 		refs.create();
280 		objectDatabase.create();
281 
282 		FileUtils.mkdir(new File(getDirectory(), "branches")); //$NON-NLS-1$
283 		FileUtils.mkdir(new File(getDirectory(), "hooks")); //$NON-NLS-1$
284 
285 		RefUpdate head = updateRef(Constants.HEAD);
286 		head.disableRefLog();
287 		head.link(Constants.R_HEADS + Constants.MASTER);
288 
289 		final boolean fileMode;
290 		if (getFS().supportsExecute()) {
291 			File tmp = File.createTempFile("try", "execute", getDirectory()); //$NON-NLS-1$ //$NON-NLS-2$
292 
293 			getFS().setExecute(tmp, true);
294 			final boolean on = getFS().canExecute(tmp);
295 
296 			getFS().setExecute(tmp, false);
297 			final boolean off = getFS().canExecute(tmp);
298 			FileUtils.delete(tmp);
299 
300 			fileMode = on && !off;
301 		} else {
302 			fileMode = false;
303 		}
304 
305 		SymLinks symLinks = SymLinks.FALSE;
306 		if (getFS().supportsSymlinks()) {
307 			File tmp = new File(getDirectory(), "tmplink"); //$NON-NLS-1$
308 			try {
309 				getFS().createSymLink(tmp, "target"); //$NON-NLS-1$
310 				symLinks = null;
311 				FileUtils.delete(tmp);
312 			} catch (IOException e) {
313 				// Normally a java.nio.file.FileSystemException
314 			}
315 		}
316 		if (symLinks != null)
317 			cfg.setString(ConfigConstants.CONFIG_CORE_SECTION, null,
318 					ConfigConstants.CONFIG_KEY_SYMLINKS, symLinks.name()
319 							.toLowerCase());
320 		cfg.setInt(ConfigConstants.CONFIG_CORE_SECTION, null,
321 				ConfigConstants.CONFIG_KEY_REPO_FORMAT_VERSION, 0);
322 		cfg.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null,
323 				ConfigConstants.CONFIG_KEY_FILEMODE, fileMode);
324 		if (bare)
325 			cfg.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null,
326 					ConfigConstants.CONFIG_KEY_BARE, true);
327 		cfg.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null,
328 				ConfigConstants.CONFIG_KEY_LOGALLREFUPDATES, !bare);
329 		if (SystemReader.getInstance().isMacOS())
330 			// Java has no other way
331 			cfg.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null,
332 					ConfigConstants.CONFIG_KEY_PRECOMPOSEUNICODE, true);
333 		if (!bare) {
334 			File workTree = getWorkTree();
335 			if (!getDirectory().getParentFile().equals(workTree)) {
336 				cfg.setString(ConfigConstants.CONFIG_CORE_SECTION, null,
337 						ConfigConstants.CONFIG_KEY_WORKTREE, getWorkTree()
338 								.getAbsolutePath());
339 				LockFile dotGitLockFile = new LockFile(new File(workTree,
340 						Constants.DOT_GIT), getFS());
341 				try {
342 					if (dotGitLockFile.lock()) {
343 						dotGitLockFile.write(Constants.encode(Constants.GITDIR
344 								+ getDirectory().getAbsolutePath()));
345 						dotGitLockFile.commit();
346 					}
347 				} finally {
348 					dotGitLockFile.unlock();
349 				}
350 			}
351 		}
352 		cfg.save();
353 	}
354 
355 	/**
356 	 * @return the directory containing the objects owned by this repository.
357 	 */
358 	public File getObjectsDirectory() {
359 		return objectDatabase.getDirectory();
360 	}
361 
362 	/**
363 	 * @return the object database which stores this repository's data.
364 	 */
365 	public ObjectDirectory getObjectDatabase() {
366 		return objectDatabase;
367 	}
368 
369 	/** @return the reference database which stores the reference namespace. */
370 	public RefDatabase getRefDatabase() {
371 		return refs;
372 	}
373 
374 	/**
375 	 * @return the configuration of this repository
376 	 */
377 	public FileBasedConfig getConfig() {
378 		if (systemConfig.isOutdated()) {
379 			try {
380 				loadSystemConfig();
381 			} catch (IOException e) {
382 				throw new RuntimeException(e);
383 			}
384 		}
385 		if (userConfig.isOutdated()) {
386 			try {
387 				loadUserConfig();
388 			} catch (IOException e) {
389 				throw new RuntimeException(e);
390 			}
391 		}
392 		if (repoConfig.isOutdated()) {
393 				try {
394 					loadRepoConfig();
395 				} catch (IOException e) {
396 					throw new RuntimeException(e);
397 				}
398 		}
399 		return repoConfig;
400 	}
401 
402 	/**
403 	 * Objects known to exist but not expressed by {@link #getAllRefs()}.
404 	 * <p>
405 	 * When a repository borrows objects from another repository, it can
406 	 * advertise that it safely has that other repository's references, without
407 	 * exposing any other details about the other repository.  This may help
408 	 * a client trying to push changes avoid pushing more than it needs to.
409 	 *
410 	 * @return unmodifiable collection of other known objects.
411 	 */
412 	public Set<ObjectId> getAdditionalHaves() {
413 		HashSet<ObjectId> r = new HashSet<ObjectId>();
414 		for (AlternateHandle d : objectDatabase.myAlternates()) {
415 			if (d instanceof AlternateRepository) {
416 				Repository repo;
417 
418 				repo = ((AlternateRepository) d).repository;
419 				for (Ref ref : repo.getAllRefs().values()) {
420 					if (ref.getObjectId() != null)
421 						r.add(ref.getObjectId());
422 					if (ref.getPeeledObjectId() != null)
423 						r.add(ref.getPeeledObjectId());
424 				}
425 				r.addAll(repo.getAdditionalHaves());
426 			}
427 		}
428 		return r;
429 	}
430 
431 	/**
432 	 * Add a single existing pack to the list of available pack files.
433 	 *
434 	 * @param pack
435 	 *            path of the pack file to open.
436 	 * @throws IOException
437 	 *             index file could not be opened, read, or is not recognized as
438 	 *             a Git pack file index.
439 	 */
440 	public void openPack(final File pack) throws IOException {
441 		objectDatabase.openPack(pack);
442 	}
443 
444 	@Override
445 	public void scanForRepoChanges() throws IOException {
446 		getRefDatabase().getRefs(ALL); // This will look for changes to refs
447 		detectIndexChanges();
448 	}
449 
450 	/**
451 	 * Detect index changes.
452 	 */
453 	private void detectIndexChanges() {
454 		if (isBare())
455 			return;
456 
457 		File indexFile = getIndexFile();
458 		if (snapshot == null)
459 			snapshot = FileSnapshot.save(indexFile);
460 		else if (snapshot.isModified(indexFile))
461 			notifyIndexChanged();
462 	}
463 
464 	@Override
465 	public void notifyIndexChanged() {
466 		snapshot = FileSnapshot.save(getIndexFile());
467 		fireEvent(new IndexChangedEvent());
468 	}
469 
470 	/**
471 	 * @param refName
472 	 * @return a {@link ReflogReader} for the supplied refname, or null if the
473 	 *         named ref does not exist.
474 	 * @throws IOException the ref could not be accessed.
475 	 */
476 	public ReflogReader getReflogReader(String refName) throws IOException {
477 		Ref ref = getRef(refName);
478 		if (ref != null)
479 			return new ReflogReaderImpl(this, ref.getName());
480 		return null;
481 	}
482 }