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