View Javadoc
1   /*
2    * Copyright (C) 2012, Christian Halstrick <christian.halstrick@sap.com>
3    * Copyright (C) 2011, Shawn O. Pearce <spearce@spearce.org> and others
4    *
5    * This program and the accompanying materials are made available under the
6    * terms of the Eclipse Distribution License v. 1.0 which is available at
7    * https://www.eclipse.org/org/documents/edl-v10.php.
8    *
9    * SPDX-License-Identifier: BSD-3-Clause
10   */
11  package org.eclipse.jgit.internal.storage.file;
12  
13  import static org.eclipse.jgit.internal.storage.pack.PackExt.BITMAP_INDEX;
14  import static org.eclipse.jgit.internal.storage.pack.PackExt.INDEX;
15  import static org.eclipse.jgit.internal.storage.pack.PackExt.PACK;
16  import static org.eclipse.jgit.internal.storage.pack.PackExt.KEEP;
17  
18  import java.io.File;
19  import java.io.FileOutputStream;
20  import java.io.IOException;
21  import java.io.OutputStream;
22  import java.io.PrintWriter;
23  import java.io.StringWriter;
24  import java.nio.channels.Channels;
25  import java.nio.channels.FileChannel;
26  import java.nio.file.DirectoryNotEmptyException;
27  import java.nio.file.DirectoryStream;
28  import java.nio.file.Files;
29  import java.nio.file.Path;
30  import java.nio.file.StandardCopyOption;
31  import java.text.MessageFormat;
32  import java.text.ParseException;
33  import java.time.Instant;
34  import java.time.temporal.ChronoUnit;
35  import java.util.ArrayList;
36  import java.util.Collection;
37  import java.util.Collections;
38  import java.util.Comparator;
39  import java.util.Date;
40  import java.util.HashMap;
41  import java.util.HashSet;
42  import java.util.Iterator;
43  import java.util.LinkedList;
44  import java.util.List;
45  import java.util.Map;
46  import java.util.Objects;
47  import java.util.Set;
48  import java.util.TreeMap;
49  import java.util.concurrent.Callable;
50  import java.util.concurrent.ExecutorService;
51  import java.util.regex.Pattern;
52  import java.util.stream.Collectors;
53  import java.util.stream.Stream;
54  
55  import org.eclipse.jgit.annotations.NonNull;
56  import org.eclipse.jgit.dircache.DirCacheIterator;
57  import org.eclipse.jgit.errors.CancelledException;
58  import org.eclipse.jgit.errors.CorruptObjectException;
59  import org.eclipse.jgit.errors.IncorrectObjectTypeException;
60  import org.eclipse.jgit.errors.MissingObjectException;
61  import org.eclipse.jgit.errors.NoWorkTreeException;
62  import org.eclipse.jgit.internal.JGitText;
63  import org.eclipse.jgit.internal.storage.pack.PackExt;
64  import org.eclipse.jgit.internal.storage.pack.PackWriter;
65  import org.eclipse.jgit.lib.ConfigConstants;
66  import org.eclipse.jgit.lib.Constants;
67  import org.eclipse.jgit.lib.FileMode;
68  import org.eclipse.jgit.lib.NullProgressMonitor;
69  import org.eclipse.jgit.lib.ObjectId;
70  import org.eclipse.jgit.lib.ObjectIdSet;
71  import org.eclipse.jgit.lib.ObjectLoader;
72  import org.eclipse.jgit.lib.ObjectReader;
73  import org.eclipse.jgit.lib.ProgressMonitor;
74  import org.eclipse.jgit.lib.Ref;
75  import org.eclipse.jgit.lib.Ref.Storage;
76  import org.eclipse.jgit.lib.RefDatabase;
77  import org.eclipse.jgit.lib.ReflogEntry;
78  import org.eclipse.jgit.lib.ReflogReader;
79  import org.eclipse.jgit.lib.internal.WorkQueue;
80  import org.eclipse.jgit.revwalk.ObjectWalk;
81  import org.eclipse.jgit.revwalk.RevObject;
82  import org.eclipse.jgit.revwalk.RevWalk;
83  import org.eclipse.jgit.storage.pack.PackConfig;
84  import org.eclipse.jgit.treewalk.TreeWalk;
85  import org.eclipse.jgit.treewalk.filter.TreeFilter;
86  import org.eclipse.jgit.util.FileUtils;
87  import org.eclipse.jgit.util.GitDateParser;
88  import org.eclipse.jgit.util.SystemReader;
89  import org.slf4j.Logger;
90  import org.slf4j.LoggerFactory;
91  
92  /**
93   * A garbage collector for git
94   * {@link org.eclipse.jgit.internal.storage.file.FileRepository}. Instances of
95   * this class are not thread-safe. Don't use the same instance from multiple
96   * threads.
97   *
98   * This class started as a copy of DfsGarbageCollector from Shawn O. Pearce
99   * adapted to FileRepositories.
100  */
101 public class GC {
102 	private static final Logger LOG = LoggerFactory
103 			.getLogger(GC.class);
104 
105 	private static final String PRUNE_EXPIRE_DEFAULT = "2.weeks.ago"; //$NON-NLS-1$
106 
107 	private static final String PRUNE_PACK_EXPIRE_DEFAULT = "1.hour.ago"; //$NON-NLS-1$
108 
109 	private static final Pattern PATTERN_LOOSE_OBJECT = Pattern
110 			.compile("[0-9a-fA-F]{38}"); //$NON-NLS-1$
111 
112 	private static final String PACK_EXT = "." + PackExt.PACK.getExtension();//$NON-NLS-1$
113 
114 	private static final String BITMAP_EXT = "." //$NON-NLS-1$
115 			+ PackExt.BITMAP_INDEX.getExtension();
116 
117 	private static final String INDEX_EXT = "." + PackExt.INDEX.getExtension(); //$NON-NLS-1$
118 
119 	private static final String KEEP_EXT = "." + PackExt.KEEP.getExtension(); //$NON-NLS-1$
120 
121 	private static final int DEFAULT_AUTOPACKLIMIT = 50;
122 
123 	private static final int DEFAULT_AUTOLIMIT = 6700;
124 
125 	private static volatile ExecutorService executor;
126 
127 	/**
128 	 * Set the executor for running auto-gc in the background. If no executor is
129 	 * set JGit's own WorkQueue will be used.
130 	 *
131 	 * @param e
132 	 *            the executor to be used for running auto-gc
133 	 */
134 	public static void setExecutor(ExecutorService e) {
135 		executor = e;
136 	}
137 
138 	private final FileRepository repo;
139 
140 	private ProgressMonitor pm;
141 
142 	private long expireAgeMillis = -1;
143 
144 	private Date expire;
145 
146 	private long packExpireAgeMillis = -1;
147 
148 	private Date packExpire;
149 
150 	private PackConfig pconfig;
151 
152 	/**
153 	 * the refs which existed during the last call to {@link #repack()}. This is
154 	 * needed during {@link #prune(Set)} where we can optimize by looking at the
155 	 * difference between the current refs and the refs which existed during
156 	 * last {@link #repack()}.
157 	 */
158 	private Collection<Ref> lastPackedRefs;
159 
160 	/**
161 	 * Holds the starting time of the last repack() execution. This is needed in
162 	 * prune() to inspect only those reflog entries which have been added since
163 	 * last repack().
164 	 */
165 	private long lastRepackTime;
166 
167 	/**
168 	 * Whether gc should do automatic housekeeping
169 	 */
170 	private boolean automatic;
171 
172 	/**
173 	 * Whether to run gc in a background thread
174 	 */
175 	private boolean background;
176 
177 	/**
178 	 * Creates a new garbage collector with default values. An expirationTime of
179 	 * two weeks and <code>null</code> as progress monitor will be used.
180 	 *
181 	 * @param repo
182 	 *            the repo to work on
183 	 */
184 	public GC(FileRepository repo) {
185 		this.repo = repo;
186 		this.pconfig = new PackConfig(repo);
187 		this.pm = NullProgressMonitor.INSTANCE;
188 	}
189 
190 	/**
191 	 * Runs a garbage collector on a
192 	 * {@link org.eclipse.jgit.internal.storage.file.FileRepository}. It will
193 	 * <ul>
194 	 * <li>pack loose references into packed-refs</li>
195 	 * <li>repack all reachable objects into new pack files and delete the old
196 	 * pack files</li>
197 	 * <li>prune all loose objects which are now reachable by packs</li>
198 	 * </ul>
199 	 *
200 	 * If {@link #setAuto(boolean)} was set to {@code true} {@code gc} will
201 	 * first check whether any housekeeping is required; if not, it exits
202 	 * without performing any work.
203 	 *
204 	 * If {@link #setBackground(boolean)} was set to {@code true}
205 	 * {@code collectGarbage} will start the gc in the background, and then
206 	 * return immediately. In this case, errors will not be reported except in
207 	 * gc.log.
208 	 *
209 	 * @return the collection of
210 	 *         {@link org.eclipse.jgit.internal.storage.file.Pack}'s which
211 	 *         are newly created
212 	 * @throws java.io.IOException
213 	 * @throws java.text.ParseException
214 	 *             If the configuration parameter "gc.pruneexpire" couldn't be
215 	 *             parsed
216 	 */
217 	// TODO(ms): change signature and return Future<Collection<Pack>>
218 	@SuppressWarnings("FutureReturnValueIgnored")
219 	public Collection<Pack> gc() throws IOException, ParseException {
220 		if (!background) {
221 			return doGc();
222 		}
223 		final GcLog gcLog = new GcLog(repo);
224 		if (!gcLog.lock()) {
225 			// there is already a background gc running
226 			return Collections.emptyList();
227 		}
228 
229 		Callable<Collection<Pack>> gcTask = () -> {
230 			try {
231 				Collection<Pack> newPacks = doGc();
232 				if (automatic && tooManyLooseObjects()) {
233 					String message = JGitText.get().gcTooManyUnpruned;
234 					gcLog.write(message);
235 					gcLog.commit();
236 				}
237 				return newPacks;
238 			} catch (IOException | ParseException e) {
239 				try {
240 					gcLog.write(e.getMessage());
241 					StringWriter sw = new StringWriter();
242 					e.printStackTrace(new PrintWriter(sw));
243 					gcLog.write(sw.toString());
244 					gcLog.commit();
245 				} catch (IOException e2) {
246 					e2.addSuppressed(e);
247 					LOG.error(e2.getMessage(), e2);
248 				}
249 			} finally {
250 				gcLog.unlock();
251 			}
252 			return Collections.emptyList();
253 		};
254 		// TODO(ms): change signature and return the Future
255 		executor().submit(gcTask);
256 		return Collections.emptyList();
257 	}
258 
259 	private ExecutorService executor() {
260 		return (executor != null) ? executor : WorkQueue.getExecutor();
261 	}
262 
263 	private Collection<Pack> doGc() throws IOException, ParseException {
264 		if (automatic && !needGc()) {
265 			return Collections.emptyList();
266 		}
267 		pm.start(6 /* tasks */);
268 		packRefs();
269 		// TODO: implement reflog_expire(pm, repo);
270 		Collection<Pack> newPacks = repack();
271 		prune(Collections.emptySet());
272 		// TODO: implement rerere_gc(pm);
273 		return newPacks;
274 	}
275 
276 	/**
277 	 * Loosen objects in a pack file which are not also in the newly-created
278 	 * pack files.
279 	 *
280 	 * @param inserter
281 	 * @param reader
282 	 * @param pack
283 	 * @param existing
284 	 * @throws IOException
285 	 */
286 	private void loosen(ObjectDirectoryInserter inserter, ObjectReader reader, Pack pack, HashSet<ObjectId> existing)
287 			throws IOException {
288 		for (PackIndex.MutableEntry entry : pack) {
289 			ObjectId oid = entry.toObjectId();
290 			if (existing.contains(oid)) {
291 				continue;
292 			}
293 			existing.add(oid);
294 			ObjectLoader loader = reader.open(oid);
295 			inserter.insert(loader.getType(),
296 					loader.getSize(),
297 					loader.openStream(),
298 					true /* create this object even though it's a duplicate */);
299 		}
300 	}
301 
302 	/**
303 	 * Delete old pack files. What is 'old' is defined by specifying a set of
304 	 * old pack files and a set of new pack files. Each pack file contained in
305 	 * old pack files but not contained in new pack files will be deleted. If
306 	 * preserveOldPacks is set, keep a copy of the pack file in the preserve
307 	 * directory. If an expirationDate is set then pack files which are younger
308 	 * than the expirationDate will not be deleted nor preserved.
309 	 * <p>
310 	 * If we're not immediately expiring loose objects, loosen any objects
311 	 * in the old pack files which aren't in the new pack files.
312 	 *
313 	 * @param oldPacks
314 	 * @param newPacks
315 	 * @throws ParseException
316 	 * @throws IOException
317 	 */
318 	private void deleteOldPacks(Collection<Pack> oldPacks,
319 			Collection<Pack> newPacks) throws ParseException, IOException {
320 		HashSet<ObjectId> ids = new HashSet<>();
321 		for (Pack pack : newPacks) {
322 			for (PackIndex.MutableEntry entry : pack) {
323 				ids.add(entry.toObjectId());
324 			}
325 		}
326 		ObjectReader reader = repo.newObjectReader();
327 		ObjectDirectory dir = repo.getObjectDatabase();
328 		ObjectDirectoryInserter inserter = dir.newInserter();
329 		boolean shouldLoosen = !"now".equals(getPruneExpireStr()) && //$NON-NLS-1$
330 			getExpireDate() < Long.MAX_VALUE;
331 
332 		prunePreserved();
333 		long packExpireDate = getPackExpireDate();
334 		oldPackLoop: for (Pack oldPack : oldPacks) {
335 			checkCancelled();
336 			String oldName = oldPack.getPackName();
337 			// check whether an old pack file is also among the list of new
338 			// pack files. Then we must not delete it.
339 			for (Pack newPack : newPacks)
340 				if (oldName.equals(newPack.getPackName()))
341 					continue oldPackLoop;
342 
343 			if (!oldPack.shouldBeKept()
344 					&& repo.getFS()
345 							.lastModifiedInstant(oldPack.getPackFile())
346 							.toEpochMilli() < packExpireDate) {
347 				if (shouldLoosen) {
348 					loosen(inserter, reader, oldPack, ids);
349 				}
350 				oldPack.close();
351 				prunePack(oldPack.getPackFile());
352 			}
353 		}
354 
355 		// close the complete object database. That's my only chance to force
356 		// rescanning and to detect that certain pack files are now deleted.
357 		repo.getObjectDatabase().close();
358 	}
359 
360 	/**
361 	 * Deletes old pack file, unless 'preserve-oldpacks' is set, in which case it
362 	 * moves the pack file to the preserved directory
363 	 *
364 	 * @param packFile
365 	 * @param deleteOptions
366 	 * @throws IOException
367 	 */
368 	private void removeOldPack(PackFile packFile, int deleteOptions)
369 			throws IOException {
370 		if (pconfig.isPreserveOldPacks()) {
371 			File oldPackDir = repo.getObjectDatabase().getPreservedDirectory();
372 			FileUtils.mkdir(oldPackDir, true);
373 
374 			PackFile oldPackFile = packFile
375 					.createPreservedForDirectory(oldPackDir);
376 			FileUtils.rename(packFile, oldPackFile);
377 		} else {
378 			FileUtils.delete(packFile, deleteOptions);
379 		}
380 	}
381 
382 	/**
383 	 * Delete the preserved directory including all pack files within
384 	 */
385 	private void prunePreserved() {
386 		if (pconfig.isPrunePreserved()) {
387 			try {
388 				FileUtils.delete(repo.getObjectDatabase().getPreservedDirectory(),
389 						FileUtils.RECURSIVE | FileUtils.RETRY | FileUtils.SKIP_MISSING);
390 			} catch (IOException e) {
391 				// Deletion of the preserved pack files failed. Silently return.
392 			}
393 		}
394 	}
395 
396 	/**
397 	 * Delete files associated with a single pack file. First try to delete the
398 	 * ".pack" file because on some platforms the ".pack" file may be locked and
399 	 * can't be deleted. In such a case it is better to detect this early and
400 	 * give up on deleting files for this packfile. Otherwise we may delete the
401 	 * ".index" file and when failing to delete the ".pack" file we are left
402 	 * with a ".pack" file without a ".index" file.
403 	 *
404 	 * @param packFile
405 	 */
406 	private void prunePack(PackFile packFile) {
407 		try {
408 			// Delete the .pack file first and if this fails give up on deleting
409 			// the other files
410 			int deleteOptions = FileUtils.RETRY | FileUtils.SKIP_MISSING;
411 			removeOldPack(packFile.create(PackExt.PACK), deleteOptions);
412 
413 			// The .pack file has been deleted. Delete as many as the other
414 			// files as you can.
415 			deleteOptions |= FileUtils.IGNORE_ERRORS;
416 			for (PackExt ext : PackExt.values()) {
417 				if (!PackExt.PACK.equals(ext)) {
418 					removeOldPack(packFile.create(ext), deleteOptions);
419 				}
420 			}
421 		} catch (IOException e) {
422 			// Deletion of the .pack file failed. Silently return.
423 		}
424 	}
425 
426 	/**
427 	 * Like "git prune-packed" this method tries to prune all loose objects
428 	 * which can be found in packs. If certain objects can't be pruned (e.g.
429 	 * because the filesystem delete operation fails) this is silently ignored.
430 	 *
431 	 * @throws java.io.IOException
432 	 */
433 	public void prunePacked() throws IOException {
434 		ObjectDirectory objdb = repo.getObjectDatabase();
435 		Collection<Pack> packs = objdb.getPacks();
436 		File objects = repo.getObjectsDirectory();
437 		String[] fanout = objects.list();
438 
439 		if (fanout != null && fanout.length > 0) {
440 			pm.beginTask(JGitText.get().pruneLoosePackedObjects, fanout.length);
441 			try {
442 				for (String d : fanout) {
443 					checkCancelled();
444 					pm.update(1);
445 					if (d.length() != 2)
446 						continue;
447 					String[] entries = new File(objects, d).list();
448 					if (entries == null)
449 						continue;
450 					for (String e : entries) {
451 						checkCancelled();
452 						if (e.length() != Constants.OBJECT_ID_STRING_LENGTH - 2)
453 							continue;
454 						ObjectId id;
455 						try {
456 							id = ObjectId.fromString(d + e);
457 						} catch (IllegalArgumentException notAnObject) {
458 							// ignoring the file that does not represent loose
459 							// object
460 							continue;
461 						}
462 						boolean found = false;
463 						for (Pack p : packs) {
464 							checkCancelled();
465 							if (p.hasObject(id)) {
466 								found = true;
467 								break;
468 							}
469 						}
470 						if (found)
471 							FileUtils.delete(objdb.fileFor(id), FileUtils.RETRY
472 									| FileUtils.SKIP_MISSING
473 									| FileUtils.IGNORE_ERRORS);
474 					}
475 				}
476 			} finally {
477 				pm.endTask();
478 			}
479 		}
480 	}
481 
482 	/**
483 	 * Like "git prune" this method tries to prune all loose objects which are
484 	 * unreferenced. If certain objects can't be pruned (e.g. because the
485 	 * filesystem delete operation fails) this is silently ignored.
486 	 *
487 	 * @param objectsToKeep
488 	 *            a set of objects which should explicitly not be pruned
489 	 * @throws java.io.IOException
490 	 * @throws java.text.ParseException
491 	 *             If the configuration parameter "gc.pruneexpire" couldn't be
492 	 *             parsed
493 	 */
494 	public void prune(Set<ObjectId> objectsToKeep) throws IOException,
495 			ParseException {
496 		long expireDate = getExpireDate();
497 
498 		// Collect all loose objects which are old enough, not referenced from
499 		// the index and not in objectsToKeep
500 		Map<ObjectId, File> deletionCandidates = new HashMap<>();
501 		Set<ObjectId> indexObjects = null;
502 		File objects = repo.getObjectsDirectory();
503 		String[] fanout = objects.list();
504 		if (fanout == null || fanout.length == 0) {
505 			return;
506 		}
507 		pm.beginTask(JGitText.get().pruneLooseUnreferencedObjects,
508 				fanout.length);
509 		try {
510 			for (String d : fanout) {
511 				checkCancelled();
512 				pm.update(1);
513 				if (d.length() != 2)
514 					continue;
515 				File dir = new File(objects, d);
516 				File[] entries = dir.listFiles();
517 				if (entries == null || entries.length == 0) {
518 					FileUtils.delete(dir, FileUtils.IGNORE_ERRORS);
519 					continue;
520 				}
521 				for (File f : entries) {
522 					checkCancelled();
523 					String fName = f.getName();
524 					if (fName.length() != Constants.OBJECT_ID_STRING_LENGTH - 2)
525 						continue;
526 					if (repo.getFS().lastModifiedInstant(f)
527 							.toEpochMilli() >= expireDate) {
528 						continue;
529 					}
530 					try {
531 						ObjectId id = ObjectId.fromString(d + fName);
532 						if (objectsToKeep.contains(id))
533 							continue;
534 						if (indexObjects == null)
535 							indexObjects = listNonHEADIndexObjects();
536 						if (indexObjects.contains(id))
537 							continue;
538 						deletionCandidates.put(id, f);
539 					} catch (IllegalArgumentException notAnObject) {
540 						// ignoring the file that does not represent loose
541 						// object
542 					}
543 				}
544 			}
545 		} finally {
546 			pm.endTask();
547 		}
548 
549 		if (deletionCandidates.isEmpty()) {
550 			return;
551 		}
552 
553 		checkCancelled();
554 
555 		// From the set of current refs remove all those which have been handled
556 		// during last repack(). Only those refs will survive which have been
557 		// added or modified since the last repack. Only these can save existing
558 		// loose refs from being pruned.
559 		Collection<Ref> newRefs;
560 		if (lastPackedRefs == null || lastPackedRefs.isEmpty())
561 			newRefs = getAllRefs();
562 		else {
563 			Map<String, Ref> last = new HashMap<>();
564 			for (Ref r : lastPackedRefs) {
565 				last.put(r.getName(), r);
566 			}
567 			newRefs = new ArrayList<>();
568 			for (Ref r : getAllRefs()) {
569 				Ref old = last.get(r.getName());
570 				if (!equals(r, old)) {
571 					newRefs.add(r);
572 				}
573 			}
574 		}
575 
576 		if (!newRefs.isEmpty()) {
577 			// There are new/modified refs! Check which loose objects are now
578 			// referenced by these modified refs (or their reflogentries).
579 			// Remove these loose objects
580 			// from the deletionCandidates. When the last candidate is removed
581 			// leave this method.
582 			ObjectWalk w = new ObjectWalk(repo);
583 			try {
584 				for (Ref cr : newRefs) {
585 					checkCancelled();
586 					w.markStart(w.parseAny(cr.getObjectId()));
587 				}
588 				if (lastPackedRefs != null)
589 					for (Ref lpr : lastPackedRefs) {
590 						w.markUninteresting(w.parseAny(lpr.getObjectId()));
591 					}
592 				removeReferenced(deletionCandidates, w);
593 			} finally {
594 				w.dispose();
595 			}
596 		}
597 
598 		if (deletionCandidates.isEmpty())
599 			return;
600 
601 		// Since we have not left the method yet there are still
602 		// deletionCandidates. Last chance for these objects not to be pruned is
603 		// that they are referenced by reflog entries. Even refs which currently
604 		// point to the same object as during last repack() may have
605 		// additional reflog entries not handled during last repack()
606 		ObjectWalk w = new ObjectWalk(repo);
607 		try {
608 			for (Ref ar : getAllRefs())
609 				for (ObjectId id : listRefLogObjects(ar, lastRepackTime)) {
610 					checkCancelled();
611 					w.markStart(w.parseAny(id));
612 				}
613 			if (lastPackedRefs != null)
614 				for (Ref lpr : lastPackedRefs) {
615 					checkCancelled();
616 					w.markUninteresting(w.parseAny(lpr.getObjectId()));
617 				}
618 			removeReferenced(deletionCandidates, w);
619 		} finally {
620 			w.dispose();
621 		}
622 
623 		if (deletionCandidates.isEmpty())
624 			return;
625 
626 		checkCancelled();
627 
628 		// delete all candidates which have survived: these are unreferenced
629 		// loose objects. Make a last check, though, to avoid deleting objects
630 		// that could have been referenced while the candidates list was being
631 		// built (by an incoming push, for example).
632 		Set<File> touchedFanout = new HashSet<>();
633 		for (File f : deletionCandidates.values()) {
634 			if (f.lastModified() < expireDate) {
635 				f.delete();
636 				touchedFanout.add(f.getParentFile());
637 			}
638 		}
639 
640 		for (File f : touchedFanout) {
641 			FileUtils.delete(f,
642 					FileUtils.EMPTY_DIRECTORIES_ONLY | FileUtils.IGNORE_ERRORS);
643 		}
644 
645 		repo.getObjectDatabase().close();
646 	}
647 
648 	private long getExpireDate() throws ParseException {
649 		long expireDate = Long.MAX_VALUE;
650 
651 		if (expire == null && expireAgeMillis == -1) {
652 			String pruneExpireStr = getPruneExpireStr();
653 			if (pruneExpireStr == null)
654 				pruneExpireStr = PRUNE_EXPIRE_DEFAULT;
655 			expire = GitDateParser.parse(pruneExpireStr, null, SystemReader
656 					.getInstance().getLocale());
657 			expireAgeMillis = -1;
658 		}
659 		if (expire != null)
660 			expireDate = expire.getTime();
661 		if (expireAgeMillis != -1)
662 			expireDate = System.currentTimeMillis() - expireAgeMillis;
663 		return expireDate;
664 	}
665 
666 	private String getPruneExpireStr() {
667 		return repo.getConfig().getString(
668                         ConfigConstants.CONFIG_GC_SECTION, null,
669                         ConfigConstants.CONFIG_KEY_PRUNEEXPIRE);
670 	}
671 
672 	private long getPackExpireDate() throws ParseException {
673 		long packExpireDate = Long.MAX_VALUE;
674 
675 		if (packExpire == null && packExpireAgeMillis == -1) {
676 			String prunePackExpireStr = repo.getConfig().getString(
677 					ConfigConstants.CONFIG_GC_SECTION, null,
678 					ConfigConstants.CONFIG_KEY_PRUNEPACKEXPIRE);
679 			if (prunePackExpireStr == null)
680 				prunePackExpireStr = PRUNE_PACK_EXPIRE_DEFAULT;
681 			packExpire = GitDateParser.parse(prunePackExpireStr, null,
682 					SystemReader.getInstance().getLocale());
683 			packExpireAgeMillis = -1;
684 		}
685 		if (packExpire != null)
686 			packExpireDate = packExpire.getTime();
687 		if (packExpireAgeMillis != -1)
688 			packExpireDate = System.currentTimeMillis() - packExpireAgeMillis;
689 		return packExpireDate;
690 	}
691 
692 	/**
693 	 * Remove all entries from a map which key is the id of an object referenced
694 	 * by the given ObjectWalk
695 	 *
696 	 * @param id2File
697 	 * @param w
698 	 * @throws MissingObjectException
699 	 * @throws IncorrectObjectTypeException
700 	 * @throws IOException
701 	 */
702 	private void removeReferenced(Map<ObjectId, File> id2File,
703 			ObjectWalk w) throws MissingObjectException,
704 			IncorrectObjectTypeException, IOException {
705 		RevObject ro = w.next();
706 		while (ro != null) {
707 			checkCancelled();
708 			if (id2File.remove(ro.getId()) != null && id2File.isEmpty()) {
709 				return;
710 			}
711 			ro = w.next();
712 		}
713 		ro = w.nextObject();
714 		while (ro != null) {
715 			checkCancelled();
716 			if (id2File.remove(ro.getId()) != null && id2File.isEmpty()) {
717 				return;
718 			}
719 			ro = w.nextObject();
720 		}
721 	}
722 
723 	private static boolean equals(Ref r1, Ref r2) {
724 		if (r1 == null || r2 == null) {
725 			return false;
726 		}
727 		if (r1.isSymbolic()) {
728 			return r2.isSymbolic() && r1.getTarget().getName()
729 					.equals(r2.getTarget().getName());
730 		}
731 		return !r2.isSymbolic()
732 				&& Objects.equals(r1.getObjectId(), r2.getObjectId());
733 	}
734 
735 	/**
736 	 * Pack ref storage. For a RefDirectory database, this packs all
737 	 * non-symbolic, loose refs into packed-refs. For Reftable, all of the data
738 	 * is compacted into a single table.
739 	 *
740 	 * @throws java.io.IOException
741 	 */
742 	public void packRefs() throws IOException {
743 		RefDatabase refDb = repo.getRefDatabase();
744 		if (refDb instanceof FileReftableDatabase) {
745 			// TODO: abstract this more cleanly.
746 			pm.beginTask(JGitText.get().packRefs, 1);
747 			try {
748 				((FileReftableDatabase) refDb).compactFully();
749 			} finally {
750 				pm.endTask();
751 			}
752 			return;
753 		}
754 
755 		Collection<Ref> refs = refDb.getRefsByPrefix(Constants.R_REFS);
756 		List<String> refsToBePacked = new ArrayList<>(refs.size());
757 		pm.beginTask(JGitText.get().packRefs, refs.size());
758 		try {
759 			for (Ref ref : refs) {
760 				checkCancelled();
761 				if (!ref.isSymbolic() && ref.getStorage().isLoose())
762 					refsToBePacked.add(ref.getName());
763 				pm.update(1);
764 			}
765 			((RefDirectory) repo.getRefDatabase()).pack(refsToBePacked);
766 		} finally {
767 			pm.endTask();
768 		}
769 	}
770 
771 	/**
772 	 * Packs all objects which reachable from any of the heads into one pack
773 	 * file. Additionally all objects which are not reachable from any head but
774 	 * which are reachable from any of the other refs (e.g. tags), special refs
775 	 * (e.g. FETCH_HEAD) or index are packed into a separate pack file. Objects
776 	 * included in pack files which have a .keep file associated are never
777 	 * repacked. All old pack files which existed before are deleted.
778 	 *
779 	 * @return a collection of the newly created pack files
780 	 * @throws java.io.IOException
781 	 *             when during reading of refs, index, packfiles, objects,
782 	 *             reflog-entries or during writing to the packfiles
783 	 *             {@link java.io.IOException} occurs
784 	 */
785 	public Collection<Pack> repack() throws IOException {
786 		Collection<Pack> toBeDeleted = repo.getObjectDatabase().getPacks();
787 
788 		long time = System.currentTimeMillis();
789 		Collection<Ref> refsBefore = getAllRefs();
790 
791 		Set<ObjectId> allHeadsAndTags = new HashSet<>();
792 		Set<ObjectId> allHeads = new HashSet<>();
793 		Set<ObjectId> allTags = new HashSet<>();
794 		Set<ObjectId> nonHeads = new HashSet<>();
795 		Set<ObjectId> txnHeads = new HashSet<>();
796 		Set<ObjectId> tagTargets = new HashSet<>();
797 		Set<ObjectId> indexObjects = listNonHEADIndexObjects();
798 
799 		for (Ref ref : refsBefore) {
800 			checkCancelled();
801 			nonHeads.addAll(listRefLogObjects(ref, 0));
802 			if (ref.isSymbolic() || ref.getObjectId() == null) {
803 				continue;
804 			}
805 			if (isHead(ref)) {
806 				allHeads.add(ref.getObjectId());
807 			} else if (isTag(ref)) {
808 				allTags.add(ref.getObjectId());
809 			} else {
810 				nonHeads.add(ref.getObjectId());
811 			}
812 			if (ref.getPeeledObjectId() != null) {
813 				tagTargets.add(ref.getPeeledObjectId());
814 			}
815 		}
816 
817 		List<ObjectIdSet> excluded = new LinkedList<>();
818 		for (Pack p : repo.getObjectDatabase().getPacks()) {
819 			checkCancelled();
820 			if (p.shouldBeKept())
821 				excluded.add(p.getIndex());
822 		}
823 
824 		// Don't exclude tags that are also branch tips
825 		allTags.removeAll(allHeads);
826 		allHeadsAndTags.addAll(allHeads);
827 		allHeadsAndTags.addAll(allTags);
828 
829 		// Hoist all branch tips and tags earlier in the pack file
830 		tagTargets.addAll(allHeadsAndTags);
831 		nonHeads.addAll(indexObjects);
832 
833 		// Combine the GC_REST objects into the GC pack if requested
834 		if (pconfig.getSinglePack()) {
835 			allHeadsAndTags.addAll(nonHeads);
836 			nonHeads.clear();
837 		}
838 
839 		List<Pack> ret = new ArrayList<>(2);
840 		Pack heads = null;
841 		if (!allHeadsAndTags.isEmpty()) {
842 			heads = writePack(allHeadsAndTags, PackWriter.NONE, allTags,
843 					tagTargets, excluded);
844 			if (heads != null) {
845 				ret.add(heads);
846 				excluded.add(0, heads.getIndex());
847 			}
848 		}
849 		if (!nonHeads.isEmpty()) {
850 			Pack rest = writePack(nonHeads, allHeadsAndTags, PackWriter.NONE,
851 					tagTargets, excluded);
852 			if (rest != null)
853 				ret.add(rest);
854 		}
855 		if (!txnHeads.isEmpty()) {
856 			Pack txn = writePack(txnHeads, PackWriter.NONE, PackWriter.NONE,
857 					null, excluded);
858 			if (txn != null)
859 				ret.add(txn);
860 		}
861 		try {
862 			deleteOldPacks(toBeDeleted, ret);
863 		} catch (ParseException e) {
864 			// TODO: the exception has to be wrapped into an IOException because
865 			// throwing the ParseException directly would break the API, instead
866 			// we should throw a ConfigInvalidException
867 			throw new IOException(e);
868 		}
869 		prunePacked();
870 		if (repo.getRefDatabase() instanceof RefDirectory) {
871 			// TODO: abstract this more cleanly.
872 			deleteEmptyRefsFolders();
873 		}
874 		deleteOrphans();
875 		deleteTempPacksIdx();
876 
877 		lastPackedRefs = refsBefore;
878 		lastRepackTime = time;
879 		return ret;
880 	}
881 
882 	private static boolean isHead(Ref ref) {
883 		return ref.getName().startsWith(Constants.R_HEADS);
884 	}
885 
886 	private static boolean isTag(Ref ref) {
887 		return ref.getName().startsWith(Constants.R_TAGS);
888 	}
889 
890 	private void deleteEmptyRefsFolders() throws IOException {
891 		Path refs = repo.getDirectory().toPath().resolve(Constants.R_REFS);
892 		// Avoid deleting a folder that was created after the threshold so that concurrent
893 		// operations trying to create a reference are not impacted
894 		Instant threshold = Instant.now().minus(30, ChronoUnit.SECONDS);
895 		try (Stream<Path> entries = Files.list(refs)
896 				.filter(Files::isDirectory)) {
897 			Iterator<Path> iterator = entries.iterator();
898 			while (iterator.hasNext()) {
899 				try (Stream<Path> s = Files.list(iterator.next())) {
900 					s.filter(path -> canBeSafelyDeleted(path, threshold)).forEach(this::deleteDir);
901 				}
902 			}
903 		}
904 	}
905 
906 	private boolean canBeSafelyDeleted(Path path, Instant threshold) {
907 		try {
908 			return Files.getLastModifiedTime(path).toInstant().isBefore(threshold);
909 		}
910 		catch (IOException e) {
911 			LOG.warn(MessageFormat.format(
912 					JGitText.get().cannotAccessLastModifiedForSafeDeletion,
913 					path), e);
914 			return false;
915 		}
916 	}
917 
918 	private void deleteDir(Path dir) {
919 		try (Stream<Path> dirs = Files.walk(dir)) {
920 			dirs.filter(this::isDirectory).sorted(Comparator.reverseOrder())
921 					.forEach(this::delete);
922 		} catch (IOException e) {
923 			LOG.error(e.getMessage(), e);
924 		}
925 	}
926 
927 	private boolean isDirectory(Path p) {
928 		return p.toFile().isDirectory();
929 	}
930 
931 	private void delete(Path d) {
932 		try {
933 			Files.delete(d);
934 		} catch (DirectoryNotEmptyException e) {
935 			// Don't log
936 		} catch (IOException e) {
937 			LOG.error(MessageFormat.format(JGitText.get().cannotDeleteFile, d),
938 					e);
939 		}
940 	}
941 
942 	/**
943 	 * Deletes orphans
944 	 * <p>
945 	 * A file is considered an orphan if it is either a "bitmap" or an index
946 	 * file, and its corresponding pack file is missing in the list.
947 	 * </p>
948 	 */
949 	private void deleteOrphans() {
950 		Path packDir = repo.getObjectDatabase().getPackDirectory().toPath();
951 		List<String> fileNames = null;
952 		try (Stream<Path> files = Files.list(packDir)) {
953 			fileNames = files.map(path -> path.getFileName().toString())
954 					.filter(name -> (name.endsWith(PACK_EXT)
955 							|| name.endsWith(BITMAP_EXT)
956 							|| name.endsWith(INDEX_EXT)
957 							|| name.endsWith(KEEP_EXT)))
958 					// sort files with same base name in the order:
959 					// .pack, .keep, .index, .bitmap to avoid look ahead
960 					.sorted(Collections.reverseOrder())
961 					.collect(Collectors.toList());
962 		} catch (IOException e) {
963 			LOG.error(e.getMessage(), e);
964 			return;
965 		}
966 		if (fileNames == null) {
967 			return;
968 		}
969 
970 		String latestId = null;
971 		for (String n : fileNames) {
972 			PackFile pf = new PackFile(packDir.toFile(), n);
973 			PackExt ext = pf.getPackExt();
974 			if (ext.equals(PACK) || ext.equals(KEEP)) {
975 				latestId = pf.getId();
976 			}
977 			if (latestId == null || !pf.getId().equals(latestId)) {
978 				// no pack or keep for this id
979 				try {
980 					FileUtils.delete(pf,
981 							FileUtils.RETRY | FileUtils.SKIP_MISSING);
982 					LOG.warn(JGitText.get().deletedOrphanInPackDir, pf);
983 				} catch (IOException e) {
984 					LOG.error(e.getMessage(), e);
985 				}
986 			}
987 		}
988 	}
989 
990 	private void deleteTempPacksIdx() {
991 		Path packDir = repo.getObjectDatabase().getPackDirectory().toPath();
992 		Instant threshold = Instant.now().minus(1, ChronoUnit.DAYS);
993 		if (!Files.exists(packDir)) {
994 			return;
995 		}
996 		try (DirectoryStream<Path> stream =
997 				Files.newDirectoryStream(packDir, "gc_*_tmp")) { //$NON-NLS-1$
998 			stream.forEach(t -> {
999 				try {
1000 					Instant lastModified = Files.getLastModifiedTime(t)
1001 							.toInstant();
1002 					if (lastModified.isBefore(threshold)) {
1003 						Files.deleteIfExists(t);
1004 					}
1005 				} catch (IOException e) {
1006 					LOG.error(e.getMessage(), e);
1007 				}
1008 			});
1009 		} catch (IOException e) {
1010 			LOG.error(e.getMessage(), e);
1011 		}
1012 	}
1013 
1014 	/**
1015 	 * @param ref
1016 	 *            the ref which log should be inspected
1017 	 * @param minTime only reflog entries not older then this time are processed
1018 	 * @return the {@link ObjectId}s contained in the reflog
1019 	 * @throws IOException
1020 	 */
1021 	private Set<ObjectId> listRefLogObjects(Ref ref, long minTime) throws IOException {
1022 		ReflogReader reflogReader = repo.getReflogReader(ref.getName());
1023 		if (reflogReader == null) {
1024 			return Collections.emptySet();
1025 		}
1026 		List<ReflogEntry> rlEntries = reflogReader
1027 				.getReverseEntries();
1028 		if (rlEntries == null || rlEntries.isEmpty())
1029 			return Collections.emptySet();
1030 		Set<ObjectId> ret = new HashSet<>();
1031 		for (ReflogEntry e : rlEntries) {
1032 			if (e.getWho().getWhen().getTime() < minTime)
1033 				break;
1034 			ObjectId newId = e.getNewId();
1035 			if (newId != null && !ObjectId.zeroId().equals(newId))
1036 				ret.add(newId);
1037 			ObjectId oldId = e.getOldId();
1038 			if (oldId != null && !ObjectId.zeroId().equals(oldId))
1039 				ret.add(oldId);
1040 		}
1041 		return ret;
1042 	}
1043 
1044 	/**
1045 	 * Returns a collection of all refs and additional refs.
1046 	 *
1047 	 * Additional refs which don't start with "refs/" are not returned because
1048 	 * they should not save objects from being garbage collected. Examples for
1049 	 * such references are ORIG_HEAD, MERGE_HEAD, FETCH_HEAD and
1050 	 * CHERRY_PICK_HEAD.
1051 	 *
1052 	 * @return a collection of refs pointing to live objects.
1053 	 * @throws IOException
1054 	 */
1055 	private Collection<Ref> getAllRefs() throws IOException {
1056 		RefDatabase refdb = repo.getRefDatabase();
1057 		Collection<Ref> refs = refdb.getRefs();
1058 		List<Ref> addl = refdb.getAdditionalRefs();
1059 		if (!addl.isEmpty()) {
1060 			List<Ref> all = new ArrayList<>(refs.size() + addl.size());
1061 			all.addAll(refs);
1062 			// add additional refs which start with refs/
1063 			for (Ref r : addl) {
1064 				checkCancelled();
1065 				if (r.getName().startsWith(Constants.R_REFS)) {
1066 					all.add(r);
1067 				}
1068 			}
1069 			return all;
1070 		}
1071 		return refs;
1072 	}
1073 
1074 	/**
1075 	 * Return a list of those objects in the index which differ from whats in
1076 	 * HEAD
1077 	 *
1078 	 * @return a set of ObjectIds of changed objects in the index
1079 	 * @throws IOException
1080 	 * @throws CorruptObjectException
1081 	 * @throws NoWorkTreeException
1082 	 */
1083 	private Set<ObjectId> listNonHEADIndexObjects()
1084 			throws CorruptObjectException, IOException {
1085 		if (repo.isBare()) {
1086 			return Collections.emptySet();
1087 		}
1088 		try (TreeWalk treeWalk = new TreeWalk(repo)) {
1089 			treeWalk.addTree(new DirCacheIterator(repo.readDirCache()));
1090 			ObjectId headID = repo.resolve(Constants.HEAD);
1091 			if (headID != null) {
1092 				try (RevWalk revWalk = new RevWalk(repo)) {
1093 					treeWalk.addTree(revWalk.parseTree(headID));
1094 				}
1095 			}
1096 
1097 			treeWalk.setFilter(TreeFilter.ANY_DIFF);
1098 			treeWalk.setRecursive(true);
1099 			Set<ObjectId> ret = new HashSet<>();
1100 
1101 			while (treeWalk.next()) {
1102 				checkCancelled();
1103 				ObjectId objectId = treeWalk.getObjectId(0);
1104 				switch (treeWalk.getRawMode(0) & FileMode.TYPE_MASK) {
1105 				case FileMode.TYPE_MISSING:
1106 				case FileMode.TYPE_GITLINK:
1107 					continue;
1108 				case FileMode.TYPE_TREE:
1109 				case FileMode.TYPE_FILE:
1110 				case FileMode.TYPE_SYMLINK:
1111 					ret.add(objectId);
1112 					continue;
1113 				default:
1114 					throw new IOException(MessageFormat.format(
1115 							JGitText.get().corruptObjectInvalidMode3,
1116 							String.format("%o", //$NON-NLS-1$
1117 									Integer.valueOf(treeWalk.getRawMode(0))),
1118 							(objectId == null) ? "null" : objectId.name(), //$NON-NLS-1$
1119 							treeWalk.getPathString(), //
1120 							repo.getIndexFile()));
1121 				}
1122 			}
1123 			return ret;
1124 		}
1125 	}
1126 
1127 	private Pack writePack(@NonNull Set<? extends ObjectId> want,
1128 			@NonNull Set<? extends ObjectId> have, @NonNull Set<ObjectId> tags,
1129 			Set<ObjectId> tagTargets, List<ObjectIdSet> excludeObjects)
1130 			throws IOException {
1131 		checkCancelled();
1132 		File tmpPack = null;
1133 		Map<PackExt, File> tmpExts = new TreeMap<>((o1, o2) -> {
1134 			// INDEX entries must be returned last, so the pack
1135 			// scanner does pick up the new pack until all the
1136 			// PackExt entries have been written.
1137 			if (o1 == o2) {
1138 				return 0;
1139 			}
1140 			if (o1 == PackExt.INDEX) {
1141 				return 1;
1142 			}
1143 			if (o2 == PackExt.INDEX) {
1144 				return -1;
1145 			}
1146 			return Integer.signum(o1.hashCode() - o2.hashCode());
1147 		});
1148 		try (PackWriter pw = new PackWriter(
1149 				pconfig,
1150 				repo.newObjectReader())) {
1151 			// prepare the PackWriter
1152 			pw.setDeltaBaseAsOffset(true);
1153 			pw.setReuseDeltaCommits(false);
1154 			if (tagTargets != null) {
1155 				pw.setTagTargets(tagTargets);
1156 			}
1157 			if (excludeObjects != null)
1158 				for (ObjectIdSet idx : excludeObjects)
1159 					pw.excludeObjects(idx);
1160 			pw.preparePack(pm, want, have, PackWriter.NONE, tags);
1161 			if (pw.getObjectCount() == 0)
1162 				return null;
1163 			checkCancelled();
1164 
1165 			// create temporary files
1166 			ObjectId id = pw.computeName();
1167 			File packdir = repo.getObjectDatabase().getPackDirectory();
1168 			packdir.mkdirs();
1169 			tmpPack = File.createTempFile("gc_", ".pack_tmp", packdir); //$NON-NLS-1$ //$NON-NLS-2$
1170 			final String tmpBase = tmpPack.getName()
1171 					.substring(0, tmpPack.getName().lastIndexOf('.'));
1172 			File tmpIdx = new File(packdir, tmpBase + ".idx_tmp"); //$NON-NLS-1$
1173 			tmpExts.put(INDEX, tmpIdx);
1174 
1175 			if (!tmpIdx.createNewFile())
1176 				throw new IOException(MessageFormat.format(
1177 						JGitText.get().cannotCreateIndexfile, tmpIdx.getPath()));
1178 
1179 			// write the packfile
1180 			try (FileOutputStream fos = new FileOutputStream(tmpPack);
1181 					FileChannel channel = fos.getChannel();
1182 					OutputStream channelStream = Channels
1183 							.newOutputStream(channel)) {
1184 				pw.writePack(pm, pm, channelStream);
1185 				channel.force(true);
1186 			}
1187 
1188 			// write the packindex
1189 			try (FileOutputStream fos = new FileOutputStream(tmpIdx);
1190 					FileChannel idxChannel = fos.getChannel();
1191 					OutputStream idxStream = Channels
1192 							.newOutputStream(idxChannel)) {
1193 				pw.writeIndex(idxStream);
1194 				idxChannel.force(true);
1195 			}
1196 
1197 			if (pw.prepareBitmapIndex(pm)) {
1198 				File tmpBitmapIdx = new File(packdir, tmpBase + ".bitmap_tmp"); //$NON-NLS-1$
1199 				tmpExts.put(BITMAP_INDEX, tmpBitmapIdx);
1200 
1201 				if (!tmpBitmapIdx.createNewFile())
1202 					throw new IOException(MessageFormat.format(
1203 							JGitText.get().cannotCreateIndexfile,
1204 							tmpBitmapIdx.getPath()));
1205 
1206 				try (FileOutputStream fos = new FileOutputStream(tmpBitmapIdx);
1207 						FileChannel idxChannel = fos.getChannel();
1208 						OutputStream idxStream = Channels
1209 								.newOutputStream(idxChannel)) {
1210 					pw.writeBitmapIndex(idxStream);
1211 					idxChannel.force(true);
1212 				}
1213 			}
1214 
1215 			// rename the temporary files to real files
1216 			File packDir = repo.getObjectDatabase().getPackDirectory();
1217 			PackFile realPack = new PackFile(packDir, id, PackExt.PACK);
1218 
1219 			repo.getObjectDatabase().closeAllPackHandles(realPack);
1220 			tmpPack.setReadOnly();
1221 
1222 			FileUtils.rename(tmpPack, realPack, StandardCopyOption.ATOMIC_MOVE);
1223 			for (Map.Entry<PackExt, File> tmpEntry : tmpExts.entrySet()) {
1224 				File tmpExt = tmpEntry.getValue();
1225 				tmpExt.setReadOnly();
1226 
1227 				PackFile realExt = new PackFile(packDir, id, tmpEntry.getKey());
1228 				try {
1229 					FileUtils.rename(tmpExt, realExt,
1230 							StandardCopyOption.ATOMIC_MOVE);
1231 				} catch (IOException e) {
1232 					File newExt = new File(realExt.getParentFile(),
1233 							realExt.getName() + ".new"); //$NON-NLS-1$
1234 					try {
1235 						FileUtils.rename(tmpExt, newExt,
1236 								StandardCopyOption.ATOMIC_MOVE);
1237 					} catch (IOException e2) {
1238 						newExt = tmpExt;
1239 						e = e2;
1240 					}
1241 					throw new IOException(MessageFormat.format(
1242 							JGitText.get().panicCantRenameIndexFile, newExt,
1243 							realExt), e);
1244 				}
1245 			}
1246 			boolean interrupted = false;
1247 			try {
1248 				FileSnapshot snapshot = FileSnapshot.save(realPack);
1249 				if (pconfig.doWaitPreventRacyPack(snapshot.size())) {
1250 					snapshot.waitUntilNotRacy();
1251 				}
1252 			} catch (InterruptedException e) {
1253 				interrupted = true;
1254 			}
1255 			try {
1256 				return repo.getObjectDatabase().openPack(realPack);
1257 			} finally {
1258 				if (interrupted) {
1259 					// Re-set interrupted flag
1260 					Thread.currentThread().interrupt();
1261 				}
1262 			}
1263 		} finally {
1264 			if (tmpPack != null && tmpPack.exists())
1265 				tmpPack.delete();
1266 			for (File tmpExt : tmpExts.values()) {
1267 				if (tmpExt.exists())
1268 					tmpExt.delete();
1269 			}
1270 		}
1271 	}
1272 
1273 	private void checkCancelled() throws CancelledException {
1274 		if (pm.isCancelled() || Thread.currentThread().isInterrupted()) {
1275 			throw new CancelledException(JGitText.get().operationCanceled);
1276 		}
1277 	}
1278 
1279 	/**
1280 	 * A class holding statistical data for a FileRepository regarding how many
1281 	 * objects are stored as loose or packed objects
1282 	 */
1283 	public static class RepoStatistics {
1284 		/**
1285 		 * The number of objects stored in pack files. If the same object is
1286 		 * stored in multiple pack files then it is counted as often as it
1287 		 * occurs in pack files.
1288 		 */
1289 		public long numberOfPackedObjects;
1290 
1291 		/**
1292 		 * The number of pack files
1293 		 */
1294 		public long numberOfPackFiles;
1295 
1296 		/**
1297 		 * The number of objects stored as loose objects.
1298 		 */
1299 		public long numberOfLooseObjects;
1300 
1301 		/**
1302 		 * The sum of the sizes of all files used to persist loose objects.
1303 		 */
1304 		public long sizeOfLooseObjects;
1305 
1306 		/**
1307 		 * The sum of the sizes of all pack files.
1308 		 */
1309 		public long sizeOfPackedObjects;
1310 
1311 		/**
1312 		 * The number of loose refs.
1313 		 */
1314 		public long numberOfLooseRefs;
1315 
1316 		/**
1317 		 * The number of refs stored in pack files.
1318 		 */
1319 		public long numberOfPackedRefs;
1320 
1321 		/**
1322 		 * The number of bitmaps in the bitmap indices.
1323 		 */
1324 		public long numberOfBitmaps;
1325 
1326 		@Override
1327 		public String toString() {
1328 			final StringBuilder b = new StringBuilder();
1329 			b.append("numberOfPackedObjects=").append(numberOfPackedObjects); //$NON-NLS-1$
1330 			b.append(", numberOfPackFiles=").append(numberOfPackFiles); //$NON-NLS-1$
1331 			b.append(", numberOfLooseObjects=").append(numberOfLooseObjects); //$NON-NLS-1$
1332 			b.append(", numberOfLooseRefs=").append(numberOfLooseRefs); //$NON-NLS-1$
1333 			b.append(", numberOfPackedRefs=").append(numberOfPackedRefs); //$NON-NLS-1$
1334 			b.append(", sizeOfLooseObjects=").append(sizeOfLooseObjects); //$NON-NLS-1$
1335 			b.append(", sizeOfPackedObjects=").append(sizeOfPackedObjects); //$NON-NLS-1$
1336 			b.append(", numberOfBitmaps=").append(numberOfBitmaps); //$NON-NLS-1$
1337 			return b.toString();
1338 		}
1339 	}
1340 
1341 	/**
1342 	 * Returns information about objects and pack files for a FileRepository.
1343 	 *
1344 	 * @return information about objects and pack files for a FileRepository
1345 	 * @throws java.io.IOException
1346 	 */
1347 	public RepoStatistics getStatistics() throws IOException {
1348 		RepoStatistics ret = new RepoStatistics();
1349 		Collection<Pack> packs = repo.getObjectDatabase().getPacks();
1350 		for (Pack p : packs) {
1351 			ret.numberOfPackedObjects += p.getIndex().getObjectCount();
1352 			ret.numberOfPackFiles++;
1353 			ret.sizeOfPackedObjects += p.getPackFile().length();
1354 			if (p.getBitmapIndex() != null)
1355 				ret.numberOfBitmaps += p.getBitmapIndex().getBitmapCount();
1356 		}
1357 		File objDir = repo.getObjectsDirectory();
1358 		String[] fanout = objDir.list();
1359 		if (fanout != null && fanout.length > 0) {
1360 			for (String d : fanout) {
1361 				if (d.length() != 2)
1362 					continue;
1363 				File[] entries = new File(objDir, d).listFiles();
1364 				if (entries == null)
1365 					continue;
1366 				for (File f : entries) {
1367 					if (f.getName().length() != Constants.OBJECT_ID_STRING_LENGTH - 2)
1368 						continue;
1369 					ret.numberOfLooseObjects++;
1370 					ret.sizeOfLooseObjects += f.length();
1371 				}
1372 			}
1373 		}
1374 
1375 		RefDatabase refDb = repo.getRefDatabase();
1376 		for (Ref r : refDb.getRefs()) {
1377 			Storage storage = r.getStorage();
1378 			if (storage == Storage.LOOSE || storage == Storage.LOOSE_PACKED)
1379 				ret.numberOfLooseRefs++;
1380 			if (storage == Storage.PACKED || storage == Storage.LOOSE_PACKED)
1381 				ret.numberOfPackedRefs++;
1382 		}
1383 
1384 		return ret;
1385 	}
1386 
1387 	/**
1388 	 * Set the progress monitor used for garbage collection methods.
1389 	 *
1390 	 * @param pm a {@link org.eclipse.jgit.lib.ProgressMonitor} object.
1391 	 * @return this
1392 	 */
1393 	public GC setProgressMonitor(ProgressMonitor pm) {
1394 		this.pm = (pm == null) ? NullProgressMonitor.INSTANCE : pm;
1395 		return this;
1396 	}
1397 
1398 	/**
1399 	 * During gc() or prune() each unreferenced, loose object which has been
1400 	 * created or modified in the last <code>expireAgeMillis</code> milliseconds
1401 	 * will not be pruned. Only older objects may be pruned. If set to 0 then
1402 	 * every object is a candidate for pruning.
1403 	 *
1404 	 * @param expireAgeMillis
1405 	 *            minimal age of objects to be pruned in milliseconds.
1406 	 */
1407 	public void setExpireAgeMillis(long expireAgeMillis) {
1408 		this.expireAgeMillis = expireAgeMillis;
1409 		expire = null;
1410 	}
1411 
1412 	/**
1413 	 * During gc() or prune() packfiles which are created or modified in the
1414 	 * last <code>packExpireAgeMillis</code> milliseconds will not be deleted.
1415 	 * Only older packfiles may be deleted. If set to 0 then every packfile is a
1416 	 * candidate for deletion.
1417 	 *
1418 	 * @param packExpireAgeMillis
1419 	 *            minimal age of packfiles to be deleted in milliseconds.
1420 	 */
1421 	public void setPackExpireAgeMillis(long packExpireAgeMillis) {
1422 		this.packExpireAgeMillis = packExpireAgeMillis;
1423 		expire = null;
1424 	}
1425 
1426 	/**
1427 	 * Set the PackConfig used when (re-)writing packfiles. This allows to
1428 	 * influence how packs are written and to implement something similar to
1429 	 * "git gc --aggressive"
1430 	 *
1431 	 * @param pconfig
1432 	 *            the {@link org.eclipse.jgit.storage.pack.PackConfig} used when
1433 	 *            writing packs
1434 	 */
1435 	public void setPackConfig(@NonNull PackConfig pconfig) {
1436 		this.pconfig = pconfig;
1437 	}
1438 
1439 	/**
1440 	 * During gc() or prune() each unreferenced, loose object which has been
1441 	 * created or modified after or at <code>expire</code> will not be pruned.
1442 	 * Only older objects may be pruned. If set to null then every object is a
1443 	 * candidate for pruning.
1444 	 *
1445 	 * @param expire
1446 	 *            instant in time which defines object expiration
1447 	 *            objects with modification time before this instant are expired
1448 	 *            objects with modification time newer or equal to this instant
1449 	 *            are not expired
1450 	 */
1451 	public void setExpire(Date expire) {
1452 		this.expire = expire;
1453 		expireAgeMillis = -1;
1454 	}
1455 
1456 	/**
1457 	 * During gc() or prune() packfiles which are created or modified after or
1458 	 * at <code>packExpire</code> will not be deleted. Only older packfiles may
1459 	 * be deleted. If set to null then every packfile is a candidate for
1460 	 * deletion.
1461 	 *
1462 	 * @param packExpire
1463 	 *            instant in time which defines packfile expiration
1464 	 */
1465 	public void setPackExpire(Date packExpire) {
1466 		this.packExpire = packExpire;
1467 		packExpireAgeMillis = -1;
1468 	}
1469 
1470 	/**
1471 	 * Set the {@code gc --auto} option.
1472 	 *
1473 	 * With this option, gc checks whether any housekeeping is required; if not,
1474 	 * it exits without performing any work. Some JGit commands run
1475 	 * {@code gc --auto} after performing operations that could create many
1476 	 * loose objects.
1477 	 * <p>
1478 	 * Housekeeping is required if there are too many loose objects or too many
1479 	 * packs in the repository. If the number of loose objects exceeds the value
1480 	 * of the gc.auto option JGit GC consolidates all existing packs into a
1481 	 * single pack (equivalent to {@code -A} option), whereas git-core would
1482 	 * combine all loose objects into a single pack using {@code repack -d -l}.
1483 	 * Setting the value of {@code gc.auto} to 0 disables automatic packing of
1484 	 * loose objects.
1485 	 * <p>
1486 	 * If the number of packs exceeds the value of {@code gc.autoPackLimit},
1487 	 * then existing packs (except those marked with a .keep file) are
1488 	 * consolidated into a single pack by using the {@code -A} option of repack.
1489 	 * Setting {@code gc.autoPackLimit} to 0 disables automatic consolidation of
1490 	 * packs.
1491 	 * <p>
1492 	 * Like git the following jgit commands run auto gc:
1493 	 * <ul>
1494 	 * <li>fetch</li>
1495 	 * <li>merge</li>
1496 	 * <li>rebase</li>
1497 	 * <li>receive-pack</li>
1498 	 * </ul>
1499 	 * The auto gc for receive-pack can be suppressed by setting the config
1500 	 * option {@code receive.autogc = false}
1501 	 *
1502 	 * @param auto
1503 	 *            defines whether gc should do automatic housekeeping
1504 	 */
1505 	public void setAuto(boolean auto) {
1506 		this.automatic = auto;
1507 	}
1508 
1509 	/**
1510 	 * @param background
1511 	 *            whether to run the gc in a background thread.
1512 	 */
1513 	void setBackground(boolean background) {
1514 		this.background = background;
1515 	}
1516 
1517 	private boolean needGc() {
1518 		if (tooManyPacks()) {
1519 			addRepackAllOption();
1520 		} else {
1521 			return tooManyLooseObjects();
1522 		}
1523 		// TODO run pre-auto-gc hook, if it fails return false
1524 		return true;
1525 	}
1526 
1527 	private void addRepackAllOption() {
1528 		// TODO: if JGit GC is enhanced to support repack's option -l this
1529 		// method needs to be implemented
1530 	}
1531 
1532 	/**
1533 	 * @return {@code true} if number of packs > gc.autopacklimit (default 50)
1534 	 */
1535 	boolean tooManyPacks() {
1536 		int autopacklimit = repo.getConfig().getInt(
1537 				ConfigConstants.CONFIG_GC_SECTION,
1538 				ConfigConstants.CONFIG_KEY_AUTOPACKLIMIT,
1539 				DEFAULT_AUTOPACKLIMIT);
1540 		if (autopacklimit <= 0) {
1541 			return false;
1542 		}
1543 		// JGit always creates two packfiles, one for the objects reachable from
1544 		// branches, and another one for the rest
1545 		return repo.getObjectDatabase().getPacks().size() > (autopacklimit + 1);
1546 	}
1547 
1548 	/**
1549 	 * Quickly estimate number of loose objects, SHA1 is distributed evenly so
1550 	 * counting objects in one directory (bucket 17) is sufficient
1551 	 *
1552 	 * @return {@code true} if number of loose objects > gc.auto (default 6700)
1553 	 */
1554 	boolean tooManyLooseObjects() {
1555 		int auto = getLooseObjectLimit();
1556 		if (auto <= 0) {
1557 			return false;
1558 		}
1559 		int n = 0;
1560 		int threshold = (auto + 255) / 256;
1561 		Path dir = repo.getObjectsDirectory().toPath().resolve("17"); //$NON-NLS-1$
1562 		if (!dir.toFile().exists()) {
1563 			return false;
1564 		}
1565 		try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, file -> {
1566 					Path fileName = file.getFileName();
1567 					return file.toFile().isFile() && fileName != null
1568 							&& PATTERN_LOOSE_OBJECT.matcher(fileName.toString())
1569 									.matches();
1570 				})) {
1571 			for (Iterator<Path> iter = stream.iterator(); iter.hasNext(); iter
1572 					.next()) {
1573 				if (++n > threshold) {
1574 					return true;
1575 				}
1576 			}
1577 		} catch (IOException e) {
1578 			LOG.error(e.getMessage(), e);
1579 		}
1580 		return false;
1581 	}
1582 
1583 	private int getLooseObjectLimit() {
1584 		return repo.getConfig().getInt(ConfigConstants.CONFIG_GC_SECTION,
1585 				ConfigConstants.CONFIG_KEY_AUTO, DEFAULT_AUTOLIMIT);
1586 	}
1587 }