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