View Javadoc
1   /*
2    * Copyright (C) 2009, Google Inc.
3    * and other copyright owners as documented in the project's IP log.
4    *
5    * This program and the accompanying materials are made available
6    * under the terms of the Eclipse Distribution License v1.0 which
7    * accompanies this distribution, is reproduced below, and is
8    * available at http://www.eclipse.org/org/documents/edl-v10.php
9    *
10   * All rights reserved.
11   *
12   * Redistribution and use in source and binary forms, with or
13   * without modification, are permitted provided that the following
14   * conditions are met:
15   *
16   * - Redistributions of source code must retain the above copyright
17   *   notice, this list of conditions and the following disclaimer.
18   *
19   * - Redistributions in binary form must reproduce the above
20   *   copyright notice, this list of conditions and the following
21   *   disclaimer in the documentation and/or other materials provided
22   *   with the distribution.
23   *
24   * - Neither the name of the Eclipse Foundation, Inc. nor the
25   *   names of its contributors may be used to endorse or promote
26   *   products derived from this software without specific prior
27   *   written permission.
28   *
29   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
30   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
31   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
34   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
35   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
37   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
38   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
39   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
40   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
41   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42   */
43  
44  package org.eclipse.jgit.internal.storage.file;
45  
46  import static org.eclipse.jgit.internal.storage.pack.PackExt.INDEX;
47  import static org.eclipse.jgit.internal.storage.pack.PackExt.PACK;
48  
49  import java.io.BufferedReader;
50  import java.io.File;
51  import java.io.FileInputStream;
52  import java.io.FileNotFoundException;
53  import java.io.FileReader;
54  import java.io.IOException;
55  import java.text.MessageFormat;
56  import java.util.ArrayList;
57  import java.util.Arrays;
58  import java.util.Collection;
59  import java.util.Collections;
60  import java.util.HashMap;
61  import java.util.HashSet;
62  import java.util.List;
63  import java.util.Map;
64  import java.util.Set;
65  import java.util.concurrent.atomic.AtomicReference;
66  
67  import org.eclipse.jgit.errors.CorruptObjectException;
68  import org.eclipse.jgit.errors.PackInvalidException;
69  import org.eclipse.jgit.errors.PackMismatchException;
70  import org.eclipse.jgit.internal.JGitText;
71  import org.eclipse.jgit.internal.storage.pack.ObjectToPack;
72  import org.eclipse.jgit.internal.storage.pack.PackExt;
73  import org.eclipse.jgit.internal.storage.pack.PackWriter;
74  import org.eclipse.jgit.lib.AbbreviatedObjectId;
75  import org.eclipse.jgit.lib.AnyObjectId;
76  import org.eclipse.jgit.lib.Config;
77  import org.eclipse.jgit.lib.ConfigConstants;
78  import org.eclipse.jgit.lib.Constants;
79  import org.eclipse.jgit.lib.ObjectDatabase;
80  import org.eclipse.jgit.lib.ObjectId;
81  import org.eclipse.jgit.lib.ObjectLoader;
82  import org.eclipse.jgit.lib.RepositoryCache;
83  import org.eclipse.jgit.lib.RepositoryCache.FileKey;
84  import org.eclipse.jgit.util.FS;
85  import org.eclipse.jgit.util.FileUtils;
86  import org.slf4j.Logger;
87  import org.slf4j.LoggerFactory;
88  
89  /**
90   * Traditional file system based {@link ObjectDatabase}.
91   * <p>
92   * This is the classical object database representation for a Git repository,
93   * where objects are stored loose by hashing them into directories by their
94   * {@link ObjectId}, or are stored in compressed containers known as
95   * {@link PackFile}s.
96   * <p>
97   * Optionally an object database can reference one or more alternates; other
98   * ObjectDatabase instances that are searched in addition to the current
99   * database.
100  * <p>
101  * Databases are divided into two halves: a half that is considered to be fast
102  * to search (the {@code PackFile}s), and a half that is considered to be slow
103  * to search (loose objects). When alternates are present the fast half is fully
104  * searched (recursively through all alternates) before the slow half is
105  * considered.
106  */
107 public class ObjectDirectory extends FileObjectDatabase {
108 	private final static Logger LOG = LoggerFactory
109 			.getLogger(ObjectDirectory.class);
110 
111 	private static final PackList NO_PACKS = new PackList(
112 			FileSnapshot.DIRTY, new PackFile[0]);
113 
114 	/** Maximum number of candidates offered as resolutions of abbreviation. */
115 	private static final int RESOLVE_ABBREV_LIMIT = 256;
116 
117 	private static final String STALE_FILE_HANDLE_MSG = "stale file handle"; //$NON-NLS-1$
118 
119 	private final Config config;
120 
121 	private final File objects;
122 
123 	private final File infoDirectory;
124 
125 	private final File packDirectory;
126 
127 	private final File alternatesFile;
128 
129 	private final AtomicReference<PackList> packList;
130 
131 	private final FS fs;
132 
133 	private final AtomicReference<AlternateHandle[]> alternates;
134 
135 	private final UnpackedObjectCache unpackedObjectCache;
136 
137 	private final File shallowFile;
138 
139 	private FileSnapshot shallowFileSnapshot = FileSnapshot.DIRTY;
140 
141 	private Set<ObjectId> shallowCommitsIds;
142 
143 	/**
144 	 * Initialize a reference to an on-disk object directory.
145 	 *
146 	 * @param cfg
147 	 *            configuration this directory consults for write settings.
148 	 * @param dir
149 	 *            the location of the <code>objects</code> directory.
150 	 * @param alternatePaths
151 	 *            a list of alternate object directories
152 	 * @param fs
153 	 *            the file system abstraction which will be necessary to perform
154 	 *            certain file system operations.
155 	 * @param shallowFile
156 	 *            file which contains IDs of shallow commits, null if shallow
157 	 *            commits handling should be turned off
158 	 * @throws IOException
159 	 *             an alternate object cannot be opened.
160 	 */
161 	public ObjectDirectory(final Config cfg, final File dir,
162 			File[] alternatePaths, FS fs, File shallowFile) throws IOException {
163 		config = cfg;
164 		objects = dir;
165 		infoDirectory = new File(objects, "info"); //$NON-NLS-1$
166 		packDirectory = new File(objects, "pack"); //$NON-NLS-1$
167 		alternatesFile = new File(infoDirectory, "alternates"); //$NON-NLS-1$
168 		packList = new AtomicReference<PackList>(NO_PACKS);
169 		unpackedObjectCache = new UnpackedObjectCache();
170 		this.fs = fs;
171 		this.shallowFile = shallowFile;
172 
173 		alternates = new AtomicReference<AlternateHandle[]>();
174 		if (alternatePaths != null) {
175 			AlternateHandle[] alt;
176 
177 			alt = new AlternateHandle[alternatePaths.length];
178 			for (int i = 0; i < alternatePaths.length; i++)
179 				alt[i] = openAlternate(alternatePaths[i]);
180 			alternates.set(alt);
181 		}
182 	}
183 
184 	/**
185 	 * @return the location of the <code>objects</code> directory.
186 	 */
187 	public final File getDirectory() {
188 		return objects;
189 	}
190 
191 	@Override
192 	public boolean exists() {
193 		return fs.exists(objects);
194 	}
195 
196 	@Override
197 	public void create() throws IOException {
198 		FileUtils.mkdirs(objects);
199 		FileUtils.mkdir(infoDirectory);
200 		FileUtils.mkdir(packDirectory);
201 	}
202 
203 	@Override
204 	public ObjectDirectoryInserter newInserter() {
205 		return new ObjectDirectoryInserter(this, config);
206 	}
207 
208 	@Override
209 	public void close() {
210 		unpackedObjectCache.clear();
211 
212 		final PackList packs = packList.get();
213 		if (packs != NO_PACKS && packList.compareAndSet(packs, NO_PACKS)) {
214 			for (PackFile p : packs.packs)
215 				p.close();
216 		}
217 
218 		// Fully close all loaded alternates and clear the alternate list.
219 		AlternateHandle[] alt = alternates.get();
220 		if (alt != null && alternates.compareAndSet(alt, null)) {
221 			for(final AlternateHandle od : alt)
222 				od.close();
223 		}
224 	}
225 
226 	/**
227 	 * @return unmodifiable collection of all known pack files local to this
228 	 *         directory. Most recent packs are presented first. Packs most
229 	 *         likely to contain more recent objects appear before packs
230 	 *         containing objects referenced by commits further back in the
231 	 *         history of the repository.
232 	 */
233 	@Override
234 	public Collection<PackFile> getPacks() {
235 		PackList list = packList.get();
236 		if (list == NO_PACKS)
237 			list = scanPacks(list);
238 		PackFile[] packs = list.packs;
239 		return Collections.unmodifiableCollection(Arrays.asList(packs));
240 	}
241 
242 	/**
243 	 * Add a single existing pack to the list of available pack files.
244 	 *
245 	 * @param pack
246 	 *            path of the pack file to open.
247 	 * @return the pack that was opened and added to the database.
248 	 * @throws IOException
249 	 *             index file could not be opened, read, or is not recognized as
250 	 *             a Git pack file index.
251 	 */
252 	public PackFile openPack(final File pack)
253 			throws IOException {
254 		final String p = pack.getName();
255 		if (p.length() != 50 || !p.startsWith("pack-") || !p.endsWith(".pack")) //$NON-NLS-1$ //$NON-NLS-2$
256 			throw new IOException(MessageFormat.format(JGitText.get().notAValidPack, pack));
257 
258 		// The pack and index are assumed to exist. The existence of other
259 		// extensions needs to be explicitly checked.
260 		//
261 		int extensions = PACK.getBit() | INDEX.getBit();
262 		final String base = p.substring(0, p.length() - 4);
263 		for (PackExt ext : PackExt.values()) {
264 			if ((extensions & ext.getBit()) == 0) {
265 				final String name = base + ext.getExtension();
266 				if (new File(pack.getParentFile(), name).exists())
267 					extensions |= ext.getBit();
268 			}
269 		}
270 
271 		PackFile res = new PackFile(pack, extensions);
272 		insertPack(res);
273 		return res;
274 	}
275 
276 	@Override
277 	public String toString() {
278 		return "ObjectDirectory[" + getDirectory() + "]"; //$NON-NLS-1$ //$NON-NLS-2$
279 	}
280 
281 	@Override
282 	public boolean has(AnyObjectId objectId) {
283 		return unpackedObjectCache.isUnpacked(objectId)
284 				|| hasPackedInSelfOrAlternate(objectId)
285 				|| hasLooseInSelfOrAlternate(objectId);
286 	}
287 
288 	private boolean hasPackedInSelfOrAlternate(AnyObjectId objectId) {
289 		if (hasPackedObject(objectId))
290 			return true;
291 		for (AlternateHandle alt : myAlternates()) {
292 			if (alt.db.hasPackedInSelfOrAlternate(objectId))
293 				return true;
294 		}
295 		return false;
296 	}
297 
298 	private boolean hasLooseInSelfOrAlternate(AnyObjectId objectId) {
299 		if (fileFor(objectId).exists())
300 			return true;
301 		for (AlternateHandle alt : myAlternates()) {
302 			if (alt.db.hasLooseInSelfOrAlternate(objectId))
303 				return true;
304 		}
305 		return false;
306 	}
307 
308 	boolean hasPackedObject(AnyObjectId objectId) {
309 		PackList pList;
310 		do {
311 			pList = packList.get();
312 			for (PackFile p : pList.packs) {
313 				try {
314 					if (p.hasObject(objectId))
315 						return true;
316 				} catch (IOException e) {
317 					// The hasObject call should have only touched the index,
318 					// so any failure here indicates the index is unreadable
319 					// by this process, and the pack is likewise not readable.
320 					removePack(p);
321 				}
322 			}
323 		} while (searchPacksAgain(pList));
324 		return false;
325 	}
326 
327 	@Override
328 	void resolve(Set<ObjectId> matches, AbbreviatedObjectId id)
329 			throws IOException {
330 		// Go through the packs once. If we didn't find any resolutions
331 		// scan for new packs and check once more.
332 		int oldSize = matches.size();
333 		PackList pList;
334 		do {
335 			pList = packList.get();
336 			for (PackFile p : pList.packs) {
337 				try {
338 					p.resolve(matches, id, RESOLVE_ABBREV_LIMIT);
339 				} catch (IOException e) {
340 					handlePackError(e, p);
341 				}
342 				if (matches.size() > RESOLVE_ABBREV_LIMIT)
343 					return;
344 			}
345 		} while (matches.size() == oldSize && searchPacksAgain(pList));
346 
347 		String fanOut = id.name().substring(0, 2);
348 		String[] entries = new File(getDirectory(), fanOut).list();
349 		if (entries != null) {
350 			for (String e : entries) {
351 				if (e.length() != Constants.OBJECT_ID_STRING_LENGTH - 2)
352 					continue;
353 				try {
354 					ObjectId entId = ObjectId.fromString(fanOut + e);
355 					if (id.prefixCompare(entId) == 0)
356 						matches.add(entId);
357 				} catch (IllegalArgumentException notId) {
358 					continue;
359 				}
360 				if (matches.size() > RESOLVE_ABBREV_LIMIT)
361 					return;
362 			}
363 		}
364 
365 		for (AlternateHandle alt : myAlternates()) {
366 			alt.db.resolve(matches, id);
367 			if (matches.size() > RESOLVE_ABBREV_LIMIT)
368 				return;
369 		}
370 	}
371 
372 	@Override
373 	ObjectLoader openObject(WindowCursor curs, AnyObjectId objectId)
374 			throws IOException {
375 		if (unpackedObjectCache.isUnpacked(objectId)) {
376 			ObjectLoader ldr = openLooseObject(curs, objectId);
377 			if (ldr != null)
378 				return ldr;
379 		}
380 		ObjectLoader ldr = openPackedFromSelfOrAlternate(curs, objectId);
381 		if (ldr != null)
382 			return ldr;
383 		return openLooseFromSelfOrAlternate(curs, objectId);
384 	}
385 
386 	private ObjectLoader openPackedFromSelfOrAlternate(WindowCursor curs,
387 			AnyObjectId objectId) {
388 		ObjectLoader ldr = openPackedObject(curs, objectId);
389 		if (ldr != null)
390 			return ldr;
391 		for (AlternateHandle alt : myAlternates()) {
392 			ldr = alt.db.openPackedFromSelfOrAlternate(curs, objectId);
393 			if (ldr != null)
394 				return ldr;
395 		}
396 		return null;
397 	}
398 
399 	private ObjectLoader openLooseFromSelfOrAlternate(WindowCursor curs,
400 			AnyObjectId objectId) throws IOException {
401 		ObjectLoader ldr = openLooseObject(curs, objectId);
402 		if (ldr != null)
403 			return ldr;
404 		for (AlternateHandle alt : myAlternates()) {
405 			ldr = alt.db.openLooseFromSelfOrAlternate(curs, objectId);
406 			if (ldr != null)
407 				return ldr;
408 		}
409 		return null;
410 	}
411 
412 	ObjectLoader openPackedObject(WindowCursor curs, AnyObjectId objectId) {
413 		PackList pList;
414 		do {
415 			SEARCH: for (;;) {
416 				pList = packList.get();
417 				for (PackFile p : pList.packs) {
418 					try {
419 						ObjectLoader ldr = p.get(curs, objectId);
420 						if (ldr != null)
421 							return ldr;
422 					} catch (PackMismatchException e) {
423 						// Pack was modified; refresh the entire pack list.
424 						if (searchPacksAgain(pList))
425 							continue SEARCH;
426 					} catch (IOException e) {
427 						handlePackError(e, p);
428 					}
429 				}
430 				break SEARCH;
431 			}
432 		} while (searchPacksAgain(pList));
433 		return null;
434 	}
435 
436 	ObjectLoader openLooseObject(WindowCursor curs, AnyObjectId id)
437 			throws IOException {
438 		try {
439 			File path = fileFor(id);
440 			FileInputStream in = new FileInputStream(path);
441 			try {
442 				unpackedObjectCache.add(id);
443 				return UnpackedObject.open(in, path, id, curs);
444 			} finally {
445 				in.close();
446 			}
447 		} catch (FileNotFoundException noFile) {
448 			unpackedObjectCache.remove(id);
449 			return null;
450 		}
451 	}
452 
453 	long getObjectSize(WindowCursor curs, AnyObjectId id)
454 			throws IOException {
455 		if (unpackedObjectCache.isUnpacked(id)) {
456 			long len = getLooseObjectSize(curs, id);
457 			if (0 <= len)
458 				return len;
459 		}
460 		long len = getPackedSizeFromSelfOrAlternate(curs, id);
461 		if (0 <= len)
462 			return len;
463 		return getLooseSizeFromSelfOrAlternate(curs, id);
464 	}
465 
466 	private long getPackedSizeFromSelfOrAlternate(WindowCursor curs,
467 			AnyObjectId id) {
468 		long len = getPackedObjectSize(curs, id);
469 		if (0 <= len)
470 			return len;
471 		for (AlternateHandle alt : myAlternates()) {
472 			len = alt.db.getPackedSizeFromSelfOrAlternate(curs, id);
473 			if (0 <= len)
474 				return len;
475 		}
476 		return -1;
477 	}
478 
479 	private long getLooseSizeFromSelfOrAlternate(WindowCursor curs,
480 			AnyObjectId id) throws IOException {
481 		long len = getLooseObjectSize(curs, id);
482 		if (0 <= len)
483 			return len;
484 		for (AlternateHandle alt : myAlternates()) {
485 			len = alt.db.getLooseSizeFromSelfOrAlternate(curs, id);
486 			if (0 <= len)
487 				return len;
488 		}
489 		return -1;
490 	}
491 
492 	private long getPackedObjectSize(WindowCursor curs, AnyObjectId id) {
493 		PackList pList;
494 		do {
495 			SEARCH: for (;;) {
496 				pList = packList.get();
497 				for (PackFile p : pList.packs) {
498 					try {
499 						long len = p.getObjectSize(curs, id);
500 						if (0 <= len)
501 							return len;
502 					} catch (PackMismatchException e) {
503 						// Pack was modified; refresh the entire pack list.
504 						if (searchPacksAgain(pList))
505 							continue SEARCH;
506 					} catch (IOException e) {
507 						handlePackError(e, p);
508 					}
509 				}
510 				break SEARCH;
511 			}
512 		} while (searchPacksAgain(pList));
513 		return -1;
514 	}
515 
516 	private long getLooseObjectSize(WindowCursor curs, AnyObjectId id)
517 			throws IOException {
518 		try {
519 			FileInputStream in = new FileInputStream(fileFor(id));
520 			try {
521 				unpackedObjectCache.add(id);
522 				return UnpackedObject.getSize(in, id, curs);
523 			} finally {
524 				in.close();
525 			}
526 		} catch (FileNotFoundException noFile) {
527 			unpackedObjectCache.remove(id);
528 			return -1;
529 		}
530 	}
531 
532 	@Override
533 	void selectObjectRepresentation(PackWriter packer, ObjectToPack otp,
534 			WindowCursor curs) throws IOException {
535 		PackList pList = packList.get();
536 		SEARCH: for (;;) {
537 			for (final PackFile p : pList.packs) {
538 				try {
539 					LocalObjectRepresentation rep = p.representation(curs, otp);
540 					if (rep != null)
541 						packer.select(otp, rep);
542 				} catch (PackMismatchException e) {
543 					// Pack was modified; refresh the entire pack list.
544 					//
545 					pList = scanPacks(pList);
546 					continue SEARCH;
547 				} catch (IOException e) {
548 					handlePackError(e, p);
549 				}
550 			}
551 			break SEARCH;
552 		}
553 
554 		for (AlternateHandle h : myAlternates())
555 			h.db.selectObjectRepresentation(packer, otp, curs);
556 	}
557 
558 	private void handlePackError(IOException e, PackFile p) {
559 		String warnTmpl = null;
560 		if ((e instanceof CorruptObjectException)
561 				|| (e instanceof PackInvalidException)) {
562 			warnTmpl = JGitText.get().corruptPack;
563 			// Assume the pack is corrupted, and remove it from the list.
564 			removePack(p);
565 		} else if (e instanceof FileNotFoundException) {
566 			warnTmpl = JGitText.get().packWasDeleted;
567 			removePack(p);
568 		} else if (e.getMessage() != null
569 				&& e.getMessage().toLowerCase().contains(STALE_FILE_HANDLE_MSG)) {
570 			warnTmpl = JGitText.get().packHandleIsStale;
571 			removePack(p);
572 		}
573 		if (warnTmpl != null) {
574 			if (LOG.isDebugEnabled()) {
575 				LOG.debug(MessageFormat.format(warnTmpl,
576 						p.getPackFile().getAbsolutePath()), e);
577 			} else {
578 				LOG.warn(MessageFormat.format(warnTmpl,
579 						p.getPackFile().getAbsolutePath()));
580 			}
581 		} else {
582 			// Don't remove the pack from the list, as the error may be
583 			// transient.
584 			LOG.error(MessageFormat.format(
585 					JGitText.get().exceptionWhileReadingPack, p.getPackFile()
586 							.getAbsolutePath()), e);
587 		}
588 	}
589 
590 	@Override
591 	InsertLooseObjectResult insertUnpackedObject(File tmp, ObjectId id,
592 			boolean createDuplicate) throws IOException {
593 		// If the object is already in the repository, remove temporary file.
594 		//
595 		if (unpackedObjectCache.isUnpacked(id)) {
596 			FileUtils.delete(tmp, FileUtils.RETRY);
597 			return InsertLooseObjectResult.EXISTS_LOOSE;
598 		}
599 		if (!createDuplicate && has(id)) {
600 			FileUtils.delete(tmp, FileUtils.RETRY);
601 			return InsertLooseObjectResult.EXISTS_PACKED;
602 		}
603 
604 		final File dst = fileFor(id);
605 		if (fs.exists(dst)) {
606 			// We want to be extra careful and avoid replacing an object
607 			// that already exists. We can't be sure renameTo() would
608 			// fail on all platforms if dst exists, so we check first.
609 			//
610 			FileUtils.delete(tmp, FileUtils.RETRY);
611 			return InsertLooseObjectResult.EXISTS_LOOSE;
612 		}
613 		if (tmp.renameTo(dst)) {
614 			dst.setReadOnly();
615 			unpackedObjectCache.add(id);
616 			return InsertLooseObjectResult.INSERTED;
617 		}
618 
619 		// Maybe the directory doesn't exist yet as the object
620 		// directories are always lazily created. Note that we
621 		// try the rename first as the directory likely does exist.
622 		//
623 		FileUtils.mkdir(dst.getParentFile(), true);
624 		if (tmp.renameTo(dst)) {
625 			dst.setReadOnly();
626 			unpackedObjectCache.add(id);
627 			return InsertLooseObjectResult.INSERTED;
628 		}
629 
630 		if (!createDuplicate && has(id)) {
631 			FileUtils.delete(tmp, FileUtils.RETRY);
632 			return InsertLooseObjectResult.EXISTS_PACKED;
633 		}
634 
635 		// The object failed to be renamed into its proper
636 		// location and it doesn't exist in the repository
637 		// either. We really don't know what went wrong, so
638 		// fail.
639 		//
640 		FileUtils.delete(tmp, FileUtils.RETRY);
641 		return InsertLooseObjectResult.FAILURE;
642 	}
643 
644 	private boolean searchPacksAgain(PackList old) {
645 		// Whether to trust the pack folder's modification time. If set
646 		// to false we will always scan the .git/objects/pack folder to
647 		// check for new pack files. If set to true (default) we use the
648 		// lastmodified attribute of the folder and assume that no new
649 		// pack files can be in this folder if his modification time has
650 		// not changed.
651 		boolean trustFolderStat = config.getBoolean(
652 				ConfigConstants.CONFIG_CORE_SECTION,
653 				ConfigConstants.CONFIG_KEY_TRUSTFOLDERSTAT, true);
654 
655 		return ((!trustFolderStat) || old.snapshot.isModified(packDirectory))
656 				&& old != scanPacks(old);
657 	}
658 
659 	Config getConfig() {
660 		return config;
661 	}
662 
663 	@Override
664 	FS getFS() {
665 		return fs;
666 	}
667 
668 	@Override
669 	Set<ObjectId> getShallowCommits() throws IOException {
670 		if (shallowFile == null || !shallowFile.isFile())
671 			return Collections.emptySet();
672 
673 		if (shallowFileSnapshot == null
674 				|| shallowFileSnapshot.isModified(shallowFile)) {
675 			shallowCommitsIds = new HashSet<ObjectId>();
676 
677 			final BufferedReader reader = open(shallowFile);
678 			try {
679 				String line;
680 				while ((line = reader.readLine()) != null)
681 					shallowCommitsIds.add(ObjectId.fromString(line));
682 			} finally {
683 				reader.close();
684 			}
685 
686 			shallowFileSnapshot = FileSnapshot.save(shallowFile);
687 		}
688 
689 		return shallowCommitsIds;
690 	}
691 
692 	private void insertPack(final PackFile pf) {
693 		PackList o, n;
694 		do {
695 			o = packList.get();
696 
697 			// If the pack in question is already present in the list
698 			// (picked up by a concurrent thread that did a scan?) we
699 			// do not want to insert it a second time.
700 			//
701 			final PackFile[] oldList = o.packs;
702 			final String name = pf.getPackFile().getName();
703 			for (PackFile p : oldList) {
704 				if (PackFile.SORT.compare(pf, p) < 0)
705 					break;
706 				if (name.equals(p.getPackFile().getName()))
707 					return;
708 			}
709 
710 			final PackFile[] newList = new PackFile[1 + oldList.length];
711 			newList[0] = pf;
712 			System.arraycopy(oldList, 0, newList, 1, oldList.length);
713 			n = new PackList(o.snapshot, newList);
714 		} while (!packList.compareAndSet(o, n));
715 	}
716 
717 	private void removePack(final PackFile deadPack) {
718 		PackList o, n;
719 		do {
720 			o = packList.get();
721 
722 			final PackFile[] oldList = o.packs;
723 			final int j = indexOf(oldList, deadPack);
724 			if (j < 0)
725 				break;
726 
727 			final PackFile[] newList = new PackFile[oldList.length - 1];
728 			System.arraycopy(oldList, 0, newList, 0, j);
729 			System.arraycopy(oldList, j + 1, newList, j, newList.length - j);
730 			n = new PackList(o.snapshot, newList);
731 		} while (!packList.compareAndSet(o, n));
732 		deadPack.close();
733 	}
734 
735 	private static int indexOf(final PackFile[] list, final PackFile pack) {
736 		for (int i = 0; i < list.length; i++) {
737 			if (list[i] == pack)
738 				return i;
739 		}
740 		return -1;
741 	}
742 
743 	private PackList scanPacks(final PackList original) {
744 		synchronized (packList) {
745 			PackList o, n;
746 			do {
747 				o = packList.get();
748 				if (o != original) {
749 					// Another thread did the scan for us, while we
750 					// were blocked on the monitor above.
751 					//
752 					return o;
753 				}
754 				n = scanPacksImpl(o);
755 				if (n == o)
756 					return n;
757 			} while (!packList.compareAndSet(o, n));
758 			return n;
759 		}
760 	}
761 
762 	private PackList scanPacksImpl(final PackList old) {
763 		final Map<String, PackFile> forReuse = reuseMap(old);
764 		final FileSnapshot snapshot = FileSnapshot.save(packDirectory);
765 		final Set<String> names = listPackDirectory();
766 		final List<PackFile> list = new ArrayList<PackFile>(names.size() >> 2);
767 		boolean foundNew = false;
768 		for (final String indexName : names) {
769 			// Must match "pack-[0-9a-f]{40}.idx" to be an index.
770 			//
771 			if (indexName.length() != 49 || !indexName.endsWith(".idx")) //$NON-NLS-1$
772 				continue;
773 
774 			final String base = indexName.substring(0, indexName.length() - 3);
775 			int extensions = 0;
776 			for (PackExt ext : PackExt.values()) {
777 				if (names.contains(base + ext.getExtension()))
778 					extensions |= ext.getBit();
779 			}
780 
781 			if ((extensions & PACK.getBit()) == 0) {
782 				// Sometimes C Git's HTTP fetch transport leaves a
783 				// .idx file behind and does not download the .pack.
784 				// We have to skip over such useless indexes.
785 				//
786 				continue;
787 			}
788 
789 			final String packName = base + PACK.getExtension();
790 			final PackFile oldPack = forReuse.remove(packName);
791 			if (oldPack != null) {
792 				list.add(oldPack);
793 				continue;
794 			}
795 
796 			final File packFile = new File(packDirectory, packName);
797 			list.add(new PackFile(packFile, extensions));
798 			foundNew = true;
799 		}
800 
801 		// If we did not discover any new files, the modification time was not
802 		// changed, and we did not remove any files, then the set of files is
803 		// the same as the set we were given. Instead of building a new object
804 		// return the same collection.
805 		//
806 		if (!foundNew && forReuse.isEmpty() && snapshot.equals(old.snapshot)) {
807 			old.snapshot.setClean(snapshot);
808 			return old;
809 		}
810 
811 		for (final PackFile p : forReuse.values()) {
812 			p.close();
813 		}
814 
815 		if (list.isEmpty())
816 			return new PackList(snapshot, NO_PACKS.packs);
817 
818 		final PackFile[] r = list.toArray(new PackFile[list.size()]);
819 		Arrays.sort(r, PackFile.SORT);
820 		return new PackList(snapshot, r);
821 	}
822 
823 	private static Map<String, PackFile> reuseMap(final PackList old) {
824 		final Map<String, PackFile> forReuse = new HashMap<String, PackFile>();
825 		for (final PackFile p : old.packs) {
826 			if (p.invalid()) {
827 				// The pack instance is corrupted, and cannot be safely used
828 				// again. Do not include it in our reuse map.
829 				//
830 				p.close();
831 				continue;
832 			}
833 
834 			final PackFile prior = forReuse.put(p.getPackFile().getName(), p);
835 			if (prior != null) {
836 				// This should never occur. It should be impossible for us
837 				// to have two pack files with the same name, as all of them
838 				// came out of the same directory. If it does, we promised to
839 				// close any PackFiles we did not reuse, so close the second,
840 				// readers are likely to be actively using the first.
841 				//
842 				forReuse.put(prior.getPackFile().getName(), prior);
843 				p.close();
844 			}
845 		}
846 		return forReuse;
847 	}
848 
849 	private Set<String> listPackDirectory() {
850 		final String[] nameList = packDirectory.list();
851 		if (nameList == null)
852 			return Collections.emptySet();
853 		final Set<String> nameSet = new HashSet<String>(nameList.length << 1);
854 		for (final String name : nameList) {
855 			if (name.startsWith("pack-")) //$NON-NLS-1$
856 				nameSet.add(name);
857 		}
858 		return nameSet;
859 	}
860 
861 	AlternateHandle[] myAlternates() {
862 		AlternateHandle[] alt = alternates.get();
863 		if (alt == null) {
864 			synchronized (alternates) {
865 				alt = alternates.get();
866 				if (alt == null) {
867 					try {
868 						alt = loadAlternates();
869 					} catch (IOException e) {
870 						alt = new AlternateHandle[0];
871 					}
872 					alternates.set(alt);
873 				}
874 			}
875 		}
876 		return alt;
877 	}
878 
879 	private AlternateHandle[] loadAlternates() throws IOException {
880 		final List<AlternateHandle> l = new ArrayList<AlternateHandle>(4);
881 		final BufferedReader br = open(alternatesFile);
882 		try {
883 			String line;
884 			while ((line = br.readLine()) != null) {
885 				l.add(openAlternate(line));
886 			}
887 		} finally {
888 			br.close();
889 		}
890 		return l.toArray(new AlternateHandle[l.size()]);
891 	}
892 
893 	private static BufferedReader open(final File f)
894 			throws FileNotFoundException {
895 		return new BufferedReader(new FileReader(f));
896 	}
897 
898 	private AlternateHandle openAlternate(final String location)
899 			throws IOException {
900 		final File objdir = fs.resolve(objects, location);
901 		return openAlternate(objdir);
902 	}
903 
904 	private AlternateHandle openAlternate(File objdir) throws IOException {
905 		final File parent = objdir.getParentFile();
906 		if (FileKey.isGitRepository(parent, fs)) {
907 			FileKey key = FileKey.exact(parent, fs);
908 			FileRepository db = (FileRepository) RepositoryCache.open(key);
909 			return new AlternateRepository(db);
910 		}
911 
912 		ObjectDirectory db = new ObjectDirectory(config, objdir, null, fs, null);
913 		return new AlternateHandle(db);
914 	}
915 
916 	/**
917 	 * Compute the location of a loose object file.
918 	 *
919 	 * @param objectId
920 	 *            identity of the loose object to map to the directory.
921 	 * @return location of the object, if it were to exist as a loose object.
922 	 */
923 	public File fileFor(AnyObjectId objectId) {
924 		String n = objectId.name();
925 		String d = n.substring(0, 2);
926 		String f = n.substring(2);
927 		return new File(new File(getDirectory(), d), f);
928 	}
929 
930 	private static final class PackList {
931 		/** State just before reading the pack directory. */
932 		final FileSnapshot snapshot;
933 
934 		/** All known packs, sorted by {@link PackFile#SORT}. */
935 		final PackFile[] packs;
936 
937 		PackList(final FileSnapshot monitor, final PackFile[] packs) {
938 			this.snapshot = monitor;
939 			this.packs = packs;
940 		}
941 	}
942 
943 	static class AlternateHandle {
944 		final ObjectDirectory db;
945 
946 		AlternateHandle(ObjectDirectory db) {
947 			this.db = db;
948 		}
949 
950 		void close() {
951 			db.close();
952 		}
953 	}
954 
955 	static class AlternateRepository extends AlternateHandle {
956 		final FileRepository repository;
957 
958 		AlternateRepository(FileRepository r) {
959 			super(r.getObjectDatabase());
960 			repository = r;
961 		}
962 
963 		void close() {
964 			repository.close();
965 		}
966 	}
967 
968 	@Override
969 	public ObjectDatabase newCachedDatabase() {
970 		return newCachedFileObjectDatabase();
971 	}
972 
973 	CachedObjectDirectory newCachedFileObjectDatabase() {
974 		return new CachedObjectDirectory(this);
975 	}
976 }