You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

GC.java 39KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232
  1. /*
  2. * Copyright (C) 2012, Christian Halstrick <christian.halstrick@sap.com>
  3. * Copyright (C) 2011, Shawn O. Pearce <spearce@spearce.org>
  4. * and other copyright owners as documented in the project's IP log.
  5. *
  6. * This program and the accompanying materials are made available
  7. * under the terms of the Eclipse Distribution License v1.0 which
  8. * accompanies this distribution, is reproduced below, and is
  9. * available at http://www.eclipse.org/org/documents/edl-v10.php
  10. *
  11. * All rights reserved.
  12. *
  13. * Redistribution and use in source and binary forms, with or
  14. * without modification, are permitted provided that the following
  15. * conditions are met:
  16. *
  17. * - Redistributions of source code must retain the above copyright
  18. * notice, this list of conditions and the following disclaimer.
  19. *
  20. * - Redistributions in binary form must reproduce the above
  21. * copyright notice, this list of conditions and the following
  22. * disclaimer in the documentation and/or other materials provided
  23. * with the distribution.
  24. *
  25. * - Neither the name of the Eclipse Foundation, Inc. nor the
  26. * names of its contributors may be used to endorse or promote
  27. * products derived from this software without specific prior
  28. * written permission.
  29. *
  30. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  31. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  32. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  33. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  34. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  35. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  36. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  37. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  38. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  39. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  40. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  41. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  42. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  43. */
  44. package org.eclipse.jgit.internal.storage.file;
  45. import static org.eclipse.jgit.internal.storage.pack.PackExt.BITMAP_INDEX;
  46. import static org.eclipse.jgit.internal.storage.pack.PackExt.INDEX;
  47. import java.io.File;
  48. import java.io.FileOutputStream;
  49. import java.io.IOException;
  50. import java.io.OutputStream;
  51. import java.nio.channels.Channels;
  52. import java.nio.channels.FileChannel;
  53. import java.nio.file.DirectoryStream;
  54. import java.nio.file.Files;
  55. import java.nio.file.Path;
  56. import java.nio.file.StandardCopyOption;
  57. import java.text.MessageFormat;
  58. import java.text.ParseException;
  59. import java.util.ArrayList;
  60. import java.util.Collection;
  61. import java.util.Collections;
  62. import java.util.Comparator;
  63. import java.util.Date;
  64. import java.util.HashMap;
  65. import java.util.HashSet;
  66. import java.util.Iterator;
  67. import java.util.LinkedList;
  68. import java.util.List;
  69. import java.util.Map;
  70. import java.util.Objects;
  71. import java.util.Set;
  72. import java.util.TreeMap;
  73. import java.util.regex.Pattern;
  74. import org.eclipse.jgit.annotations.NonNull;
  75. import org.eclipse.jgit.dircache.DirCacheIterator;
  76. import org.eclipse.jgit.errors.CorruptObjectException;
  77. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  78. import org.eclipse.jgit.errors.MissingObjectException;
  79. import org.eclipse.jgit.errors.NoWorkTreeException;
  80. import org.eclipse.jgit.internal.JGitText;
  81. import org.eclipse.jgit.internal.storage.pack.PackExt;
  82. import org.eclipse.jgit.internal.storage.pack.PackWriter;
  83. import org.eclipse.jgit.internal.storage.reftree.RefTreeNames;
  84. import org.eclipse.jgit.lib.ConfigConstants;
  85. import org.eclipse.jgit.lib.Constants;
  86. import org.eclipse.jgit.lib.FileMode;
  87. import org.eclipse.jgit.lib.NullProgressMonitor;
  88. import org.eclipse.jgit.lib.ObjectId;
  89. import org.eclipse.jgit.lib.ObjectIdSet;
  90. import org.eclipse.jgit.lib.ProgressMonitor;
  91. import org.eclipse.jgit.lib.Ref;
  92. import org.eclipse.jgit.lib.Ref.Storage;
  93. import org.eclipse.jgit.lib.RefDatabase;
  94. import org.eclipse.jgit.lib.ReflogEntry;
  95. import org.eclipse.jgit.lib.ReflogReader;
  96. import org.eclipse.jgit.revwalk.ObjectWalk;
  97. import org.eclipse.jgit.revwalk.RevObject;
  98. import org.eclipse.jgit.revwalk.RevWalk;
  99. import org.eclipse.jgit.storage.pack.PackConfig;
  100. import org.eclipse.jgit.treewalk.TreeWalk;
  101. import org.eclipse.jgit.treewalk.filter.TreeFilter;
  102. import org.eclipse.jgit.util.FileUtils;
  103. import org.eclipse.jgit.util.GitDateParser;
  104. import org.eclipse.jgit.util.SystemReader;
  105. import org.slf4j.Logger;
  106. import org.slf4j.LoggerFactory;
  107. /**
  108. * A garbage collector for git {@link FileRepository}. Instances of this class
  109. * are not thread-safe. Don't use the same instance from multiple threads.
  110. *
  111. * This class started as a copy of DfsGarbageCollector from Shawn O. Pearce
  112. * adapted to FileRepositories.
  113. */
  114. public class GC {
  115. private final static Logger LOG = LoggerFactory
  116. .getLogger(GC.class);
  117. private static final String PRUNE_EXPIRE_DEFAULT = "2.weeks.ago"; //$NON-NLS-1$
  118. private static final String PRUNE_PACK_EXPIRE_DEFAULT = "1.hour.ago"; //$NON-NLS-1$
  119. private static final Pattern PATTERN_LOOSE_OBJECT = Pattern
  120. .compile("[0-9a-fA-F]{38}"); //$NON-NLS-1$
  121. private static final int DEFAULT_AUTOPACKLIMIT = 50;
  122. private static final int DEFAULT_AUTOLIMIT = 6700;
  123. private final FileRepository repo;
  124. private ProgressMonitor pm;
  125. private long expireAgeMillis = -1;
  126. private Date expire;
  127. private long packExpireAgeMillis = -1;
  128. private Date packExpire;
  129. private PackConfig pconfig = null;
  130. /**
  131. * the refs which existed during the last call to {@link #repack()}. This is
  132. * needed during {@link #prune(Set)} where we can optimize by looking at the
  133. * difference between the current refs and the refs which existed during
  134. * last {@link #repack()}.
  135. */
  136. private Collection<Ref> lastPackedRefs;
  137. /**
  138. * Holds the starting time of the last repack() execution. This is needed in
  139. * prune() to inspect only those reflog entries which have been added since
  140. * last repack().
  141. */
  142. private long lastRepackTime;
  143. /**
  144. * Whether gc should do automatic housekeeping
  145. */
  146. private boolean automatic;
  147. /**
  148. * Creates a new garbage collector with default values. An expirationTime of
  149. * two weeks and <code>null</code> as progress monitor will be used.
  150. *
  151. * @param repo
  152. * the repo to work on
  153. */
  154. public GC(FileRepository repo) {
  155. this.repo = repo;
  156. this.pm = NullProgressMonitor.INSTANCE;
  157. }
  158. /**
  159. * Runs a garbage collector on a {@link FileRepository}. It will
  160. * <ul>
  161. * <li>pack loose references into packed-refs</li>
  162. * <li>repack all reachable objects into new pack files and delete the old
  163. * pack files</li>
  164. * <li>prune all loose objects which are now reachable by packs</li>
  165. * </ul>
  166. *
  167. * If {@link #setAuto(boolean)} was set to {@code true} {@code gc} will
  168. * first check whether any housekeeping is required; if not, it exits
  169. * without performing any work.
  170. *
  171. * @return the collection of {@link PackFile}'s which are newly created
  172. * @throws IOException
  173. * @throws ParseException
  174. * If the configuration parameter "gc.pruneexpire" couldn't be
  175. * parsed
  176. */
  177. public Collection<PackFile> gc() throws IOException, ParseException {
  178. if (automatic && !needGc()) {
  179. return Collections.emptyList();
  180. }
  181. pm.start(6 /* tasks */);
  182. packRefs();
  183. // TODO: implement reflog_expire(pm, repo);
  184. Collection<PackFile> newPacks = repack();
  185. prune(Collections.<ObjectId> emptySet());
  186. // TODO: implement rerere_gc(pm);
  187. return newPacks;
  188. }
  189. /**
  190. * Delete old pack files. What is 'old' is defined by specifying a set of
  191. * old pack files and a set of new pack files. Each pack file contained in
  192. * old pack files but not contained in new pack files will be deleted. If an
  193. * expirationDate is set then pack files which are younger than the
  194. * expirationDate will not be deleted.
  195. *
  196. * @param oldPacks
  197. * @param newPacks
  198. * @throws ParseException
  199. * @throws IOException
  200. */
  201. private void deleteOldPacks(Collection<PackFile> oldPacks,
  202. Collection<PackFile> newPacks) throws ParseException, IOException {
  203. long packExpireDate = getPackExpireDate();
  204. oldPackLoop: for (PackFile oldPack : oldPacks) {
  205. String oldName = oldPack.getPackName();
  206. // check whether an old pack file is also among the list of new
  207. // pack files. Then we must not delete it.
  208. for (PackFile newPack : newPacks)
  209. if (oldName.equals(newPack.getPackName()))
  210. continue oldPackLoop;
  211. if (!oldPack.shouldBeKept()
  212. && repo.getFS().lastModified(
  213. oldPack.getPackFile()) < packExpireDate) {
  214. oldPack.close();
  215. prunePack(oldName);
  216. }
  217. }
  218. // close the complete object database. Thats my only chance to force
  219. // rescanning and to detect that certain pack files are now deleted.
  220. repo.getObjectDatabase().close();
  221. }
  222. /**
  223. * Delete files associated with a single pack file. First try to delete the
  224. * ".pack" file because on some platforms the ".pack" file may be locked and
  225. * can't be deleted. In such a case it is better to detect this early and
  226. * give up on deleting files for this packfile. Otherwise we may delete the
  227. * ".index" file and when failing to delete the ".pack" file we are left
  228. * with a ".pack" file without a ".index" file.
  229. *
  230. * @param packName
  231. */
  232. private void prunePack(String packName) {
  233. PackExt[] extensions = PackExt.values();
  234. try {
  235. // Delete the .pack file first and if this fails give up on deleting
  236. // the other files
  237. int deleteOptions = FileUtils.RETRY | FileUtils.SKIP_MISSING;
  238. for (PackExt ext : extensions)
  239. if (PackExt.PACK.equals(ext)) {
  240. File f = nameFor(packName, "." + ext.getExtension()); //$NON-NLS-1$
  241. FileUtils.delete(f, deleteOptions);
  242. break;
  243. }
  244. // The .pack file has been deleted. Delete as many as the other
  245. // files as you can.
  246. deleteOptions |= FileUtils.IGNORE_ERRORS;
  247. for (PackExt ext : extensions) {
  248. if (!PackExt.PACK.equals(ext)) {
  249. File f = nameFor(packName, "." + ext.getExtension()); //$NON-NLS-1$
  250. FileUtils.delete(f, deleteOptions);
  251. }
  252. }
  253. } catch (IOException e) {
  254. // Deletion of the .pack file failed. Silently return.
  255. }
  256. }
  257. /**
  258. * Like "git prune-packed" this method tries to prune all loose objects
  259. * which can be found in packs. If certain objects can't be pruned (e.g.
  260. * because the filesystem delete operation fails) this is silently ignored.
  261. *
  262. * @throws IOException
  263. */
  264. public void prunePacked() throws IOException {
  265. ObjectDirectory objdb = repo.getObjectDatabase();
  266. Collection<PackFile> packs = objdb.getPacks();
  267. File objects = repo.getObjectsDirectory();
  268. String[] fanout = objects.list();
  269. if (fanout != null && fanout.length > 0) {
  270. pm.beginTask(JGitText.get().pruneLoosePackedObjects, fanout.length);
  271. try {
  272. for (String d : fanout) {
  273. pm.update(1);
  274. if (d.length() != 2)
  275. continue;
  276. String[] entries = new File(objects, d).list();
  277. if (entries == null)
  278. continue;
  279. for (String e : entries) {
  280. if (e.length() != Constants.OBJECT_ID_STRING_LENGTH - 2)
  281. continue;
  282. ObjectId id;
  283. try {
  284. id = ObjectId.fromString(d + e);
  285. } catch (IllegalArgumentException notAnObject) {
  286. // ignoring the file that does not represent loose
  287. // object
  288. continue;
  289. }
  290. boolean found = false;
  291. for (PackFile p : packs)
  292. if (p.hasObject(id)) {
  293. found = true;
  294. break;
  295. }
  296. if (found)
  297. FileUtils.delete(objdb.fileFor(id), FileUtils.RETRY
  298. | FileUtils.SKIP_MISSING
  299. | FileUtils.IGNORE_ERRORS);
  300. }
  301. }
  302. } finally {
  303. pm.endTask();
  304. }
  305. }
  306. }
  307. /**
  308. * Like "git prune" this method tries to prune all loose objects which are
  309. * unreferenced. If certain objects can't be pruned (e.g. because the
  310. * filesystem delete operation fails) this is silently ignored.
  311. *
  312. * @param objectsToKeep
  313. * a set of objects which should explicitly not be pruned
  314. *
  315. * @throws IOException
  316. * @throws ParseException
  317. * If the configuration parameter "gc.pruneexpire" couldn't be
  318. * parsed
  319. */
  320. public void prune(Set<ObjectId> objectsToKeep) throws IOException,
  321. ParseException {
  322. long expireDate = getExpireDate();
  323. // Collect all loose objects which are old enough, not referenced from
  324. // the index and not in objectsToKeep
  325. Map<ObjectId, File> deletionCandidates = new HashMap<ObjectId, File>();
  326. Set<ObjectId> indexObjects = null;
  327. File objects = repo.getObjectsDirectory();
  328. String[] fanout = objects.list();
  329. if (fanout != null && fanout.length > 0) {
  330. pm.beginTask(JGitText.get().pruneLooseUnreferencedObjects,
  331. fanout.length);
  332. try {
  333. for (String d : fanout) {
  334. pm.update(1);
  335. if (d.length() != 2)
  336. continue;
  337. File[] entries = new File(objects, d).listFiles();
  338. if (entries == null)
  339. continue;
  340. for (File f : entries) {
  341. String fName = f.getName();
  342. if (fName.length() != Constants.OBJECT_ID_STRING_LENGTH - 2)
  343. continue;
  344. if (repo.getFS().lastModified(f) >= expireDate)
  345. continue;
  346. try {
  347. ObjectId id = ObjectId.fromString(d + fName);
  348. if (objectsToKeep.contains(id))
  349. continue;
  350. if (indexObjects == null)
  351. indexObjects = listNonHEADIndexObjects();
  352. if (indexObjects.contains(id))
  353. continue;
  354. deletionCandidates.put(id, f);
  355. } catch (IllegalArgumentException notAnObject) {
  356. // ignoring the file that does not represent loose
  357. // object
  358. continue;
  359. }
  360. }
  361. }
  362. } finally {
  363. pm.endTask();
  364. }
  365. }
  366. if (deletionCandidates.isEmpty())
  367. return;
  368. // From the set of current refs remove all those which have been handled
  369. // during last repack(). Only those refs will survive which have been
  370. // added or modified since the last repack. Only these can save existing
  371. // loose refs from being pruned.
  372. Collection<Ref> newRefs;
  373. if (lastPackedRefs == null || lastPackedRefs.isEmpty())
  374. newRefs = getAllRefs();
  375. else {
  376. Map<String, Ref> last = new HashMap<>();
  377. for (Ref r : lastPackedRefs) {
  378. last.put(r.getName(), r);
  379. }
  380. newRefs = new ArrayList<>();
  381. for (Ref r : getAllRefs()) {
  382. Ref old = last.get(r.getName());
  383. if (!equals(r, old)) {
  384. newRefs.add(r);
  385. }
  386. }
  387. }
  388. if (!newRefs.isEmpty()) {
  389. // There are new/modified refs! Check which loose objects are now
  390. // referenced by these modified refs (or their reflogentries).
  391. // Remove these loose objects
  392. // from the deletionCandidates. When the last candidate is removed
  393. // leave this method.
  394. ObjectWalk w = new ObjectWalk(repo);
  395. try {
  396. for (Ref cr : newRefs)
  397. w.markStart(w.parseAny(cr.getObjectId()));
  398. if (lastPackedRefs != null)
  399. for (Ref lpr : lastPackedRefs)
  400. w.markUninteresting(w.parseAny(lpr.getObjectId()));
  401. removeReferenced(deletionCandidates, w);
  402. } finally {
  403. w.dispose();
  404. }
  405. }
  406. if (deletionCandidates.isEmpty())
  407. return;
  408. // Since we have not left the method yet there are still
  409. // deletionCandidates. Last chance for these objects not to be pruned is
  410. // that they are referenced by reflog entries. Even refs which currently
  411. // point to the same object as during last repack() may have
  412. // additional reflog entries not handled during last repack()
  413. ObjectWalk w = new ObjectWalk(repo);
  414. try {
  415. for (Ref ar : getAllRefs())
  416. for (ObjectId id : listRefLogObjects(ar, lastRepackTime))
  417. w.markStart(w.parseAny(id));
  418. if (lastPackedRefs != null)
  419. for (Ref lpr : lastPackedRefs)
  420. w.markUninteresting(w.parseAny(lpr.getObjectId()));
  421. removeReferenced(deletionCandidates, w);
  422. } finally {
  423. w.dispose();
  424. }
  425. if (deletionCandidates.isEmpty())
  426. return;
  427. // delete all candidates which have survived: these are unreferenced
  428. // loose objects. Make a last check, though, to avoid deleting objects
  429. // that could have been referenced while the candidates list was being
  430. // built (by an incoming push, for example).
  431. for (File f : deletionCandidates.values()) {
  432. if (f.lastModified() < expireDate) {
  433. f.delete();
  434. }
  435. }
  436. repo.getObjectDatabase().close();
  437. }
  438. private long getExpireDate() throws ParseException {
  439. long expireDate = Long.MAX_VALUE;
  440. if (expire == null && expireAgeMillis == -1) {
  441. String pruneExpireStr = repo.getConfig().getString(
  442. ConfigConstants.CONFIG_GC_SECTION, null,
  443. ConfigConstants.CONFIG_KEY_PRUNEEXPIRE);
  444. if (pruneExpireStr == null)
  445. pruneExpireStr = PRUNE_EXPIRE_DEFAULT;
  446. expire = GitDateParser.parse(pruneExpireStr, null, SystemReader
  447. .getInstance().getLocale());
  448. expireAgeMillis = -1;
  449. }
  450. if (expire != null)
  451. expireDate = expire.getTime();
  452. if (expireAgeMillis != -1)
  453. expireDate = System.currentTimeMillis() - expireAgeMillis;
  454. return expireDate;
  455. }
  456. private long getPackExpireDate() throws ParseException {
  457. long packExpireDate = Long.MAX_VALUE;
  458. if (packExpire == null && packExpireAgeMillis == -1) {
  459. String prunePackExpireStr = repo.getConfig().getString(
  460. ConfigConstants.CONFIG_GC_SECTION, null,
  461. ConfigConstants.CONFIG_KEY_PRUNEPACKEXPIRE);
  462. if (prunePackExpireStr == null)
  463. prunePackExpireStr = PRUNE_PACK_EXPIRE_DEFAULT;
  464. packExpire = GitDateParser.parse(prunePackExpireStr, null,
  465. SystemReader.getInstance().getLocale());
  466. packExpireAgeMillis = -1;
  467. }
  468. if (packExpire != null)
  469. packExpireDate = packExpire.getTime();
  470. if (packExpireAgeMillis != -1)
  471. packExpireDate = System.currentTimeMillis() - packExpireAgeMillis;
  472. return packExpireDate;
  473. }
  474. /**
  475. * Remove all entries from a map which key is the id of an object referenced
  476. * by the given ObjectWalk
  477. *
  478. * @param id2File
  479. * @param w
  480. * @throws MissingObjectException
  481. * @throws IncorrectObjectTypeException
  482. * @throws IOException
  483. */
  484. private void removeReferenced(Map<ObjectId, File> id2File,
  485. ObjectWalk w) throws MissingObjectException,
  486. IncorrectObjectTypeException, IOException {
  487. RevObject ro = w.next();
  488. while (ro != null) {
  489. if (id2File.remove(ro.getId()) != null)
  490. if (id2File.isEmpty())
  491. return;
  492. ro = w.next();
  493. }
  494. ro = w.nextObject();
  495. while (ro != null) {
  496. if (id2File.remove(ro.getId()) != null)
  497. if (id2File.isEmpty())
  498. return;
  499. ro = w.nextObject();
  500. }
  501. }
  502. private static boolean equals(Ref r1, Ref r2) {
  503. if (r1 == null || r2 == null)
  504. return false;
  505. if (r1.isSymbolic()) {
  506. if (!r2.isSymbolic())
  507. return false;
  508. return r1.getTarget().getName().equals(r2.getTarget().getName());
  509. } else {
  510. if (r2.isSymbolic()) {
  511. return false;
  512. }
  513. return Objects.equals(r1.getObjectId(), r2.getObjectId());
  514. }
  515. }
  516. /**
  517. * Packs all non-symbolic, loose refs into packed-refs.
  518. *
  519. * @throws IOException
  520. */
  521. public void packRefs() throws IOException {
  522. Collection<Ref> refs = repo.getRefDatabase().getRefs(Constants.R_REFS).values();
  523. List<String> refsToBePacked = new ArrayList<String>(refs.size());
  524. pm.beginTask(JGitText.get().packRefs, refs.size());
  525. try {
  526. for (Ref ref : refs) {
  527. if (!ref.isSymbolic() && ref.getStorage().isLoose())
  528. refsToBePacked.add(ref.getName());
  529. pm.update(1);
  530. }
  531. ((RefDirectory) repo.getRefDatabase()).pack(refsToBePacked);
  532. } finally {
  533. pm.endTask();
  534. }
  535. }
  536. /**
  537. * Packs all objects which reachable from any of the heads into one pack
  538. * file. Additionally all objects which are not reachable from any head but
  539. * which are reachable from any of the other refs (e.g. tags), special refs
  540. * (e.g. FETCH_HEAD) or index are packed into a separate pack file. Objects
  541. * included in pack files which have a .keep file associated are never
  542. * repacked. All old pack files which existed before are deleted.
  543. *
  544. * @return a collection of the newly created pack files
  545. * @throws IOException
  546. * when during reading of refs, index, packfiles, objects,
  547. * reflog-entries or during writing to the packfiles
  548. * {@link IOException} occurs
  549. */
  550. public Collection<PackFile> repack() throws IOException {
  551. Collection<PackFile> toBeDeleted = repo.getObjectDatabase().getPacks();
  552. long time = System.currentTimeMillis();
  553. Collection<Ref> refsBefore = getAllRefs();
  554. Set<ObjectId> allHeads = new HashSet<ObjectId>();
  555. Set<ObjectId> nonHeads = new HashSet<ObjectId>();
  556. Set<ObjectId> txnHeads = new HashSet<ObjectId>();
  557. Set<ObjectId> tagTargets = new HashSet<ObjectId>();
  558. Set<ObjectId> indexObjects = listNonHEADIndexObjects();
  559. RefDatabase refdb = repo.getRefDatabase();
  560. for (Ref ref : refsBefore) {
  561. nonHeads.addAll(listRefLogObjects(ref, 0));
  562. if (ref.isSymbolic() || ref.getObjectId() == null)
  563. continue;
  564. if (isHead(ref) || isTag(ref))
  565. allHeads.add(ref.getObjectId());
  566. else if (RefTreeNames.isRefTree(refdb, ref.getName()))
  567. txnHeads.add(ref.getObjectId());
  568. else
  569. nonHeads.add(ref.getObjectId());
  570. if (ref.getPeeledObjectId() != null)
  571. tagTargets.add(ref.getPeeledObjectId());
  572. }
  573. List<ObjectIdSet> excluded = new LinkedList<ObjectIdSet>();
  574. for (final PackFile f : repo.getObjectDatabase().getPacks())
  575. if (f.shouldBeKept())
  576. excluded.add(f.getIndex());
  577. tagTargets.addAll(allHeads);
  578. nonHeads.addAll(indexObjects);
  579. List<PackFile> ret = new ArrayList<PackFile>(2);
  580. PackFile heads = null;
  581. if (!allHeads.isEmpty()) {
  582. heads = writePack(allHeads, Collections.<ObjectId> emptySet(),
  583. tagTargets, excluded);
  584. if (heads != null) {
  585. ret.add(heads);
  586. excluded.add(0, heads.getIndex());
  587. }
  588. }
  589. if (!nonHeads.isEmpty()) {
  590. PackFile rest = writePack(nonHeads, allHeads, tagTargets, excluded);
  591. if (rest != null)
  592. ret.add(rest);
  593. }
  594. if (!txnHeads.isEmpty()) {
  595. PackFile txn = writePack(txnHeads, PackWriter.NONE, null, excluded);
  596. if (txn != null)
  597. ret.add(txn);
  598. }
  599. try {
  600. deleteOldPacks(toBeDeleted, ret);
  601. } catch (ParseException e) {
  602. // TODO: the exception has to be wrapped into an IOException because
  603. // throwing the ParseException directly would break the API, instead
  604. // we should throw a ConfigInvalidException
  605. throw new IOException(e);
  606. }
  607. prunePacked();
  608. lastPackedRefs = refsBefore;
  609. lastRepackTime = time;
  610. return ret;
  611. }
  612. private static boolean isHead(Ref ref) {
  613. return ref.getName().startsWith(Constants.R_HEADS);
  614. }
  615. private static boolean isTag(Ref ref) {
  616. return ref.getName().startsWith(Constants.R_TAGS);
  617. }
  618. /**
  619. * @param ref
  620. * the ref which log should be inspected
  621. * @param minTime only reflog entries not older then this time are processed
  622. * @return the {@link ObjectId}s contained in the reflog
  623. * @throws IOException
  624. */
  625. private Set<ObjectId> listRefLogObjects(Ref ref, long minTime) throws IOException {
  626. ReflogReader reflogReader = repo.getReflogReader(ref.getName());
  627. if (reflogReader == null) {
  628. return Collections.emptySet();
  629. }
  630. List<ReflogEntry> rlEntries = reflogReader
  631. .getReverseEntries();
  632. if (rlEntries == null || rlEntries.isEmpty())
  633. return Collections.<ObjectId> emptySet();
  634. Set<ObjectId> ret = new HashSet<ObjectId>();
  635. for (ReflogEntry e : rlEntries) {
  636. if (e.getWho().getWhen().getTime() < minTime)
  637. break;
  638. ObjectId newId = e.getNewId();
  639. if (newId != null && !ObjectId.zeroId().equals(newId))
  640. ret.add(newId);
  641. ObjectId oldId = e.getOldId();
  642. if (oldId != null && !ObjectId.zeroId().equals(oldId))
  643. ret.add(oldId);
  644. }
  645. return ret;
  646. }
  647. /**
  648. * Returns a collection of all refs and additional refs.
  649. *
  650. * Additional refs which don't start with "refs/" are not returned because
  651. * they should not save objects from being garbage collected. Examples for
  652. * such references are ORIG_HEAD, MERGE_HEAD, FETCH_HEAD and
  653. * CHERRY_PICK_HEAD.
  654. *
  655. * @return a collection of refs pointing to live objects.
  656. * @throws IOException
  657. */
  658. private Collection<Ref> getAllRefs() throws IOException {
  659. RefDatabase refdb = repo.getRefDatabase();
  660. Collection<Ref> refs = refdb.getRefs(RefDatabase.ALL).values();
  661. List<Ref> addl = refdb.getAdditionalRefs();
  662. if (!addl.isEmpty()) {
  663. List<Ref> all = new ArrayList<>(refs.size() + addl.size());
  664. all.addAll(refs);
  665. // add additional refs which start with refs/
  666. for (Ref r : addl) {
  667. if (r.getName().startsWith(Constants.R_REFS)) {
  668. all.add(r);
  669. }
  670. }
  671. return all;
  672. }
  673. return refs;
  674. }
  675. /**
  676. * Return a list of those objects in the index which differ from whats in
  677. * HEAD
  678. *
  679. * @return a set of ObjectIds of changed objects in the index
  680. * @throws IOException
  681. * @throws CorruptObjectException
  682. * @throws NoWorkTreeException
  683. */
  684. private Set<ObjectId> listNonHEADIndexObjects()
  685. throws CorruptObjectException, IOException {
  686. if (repo.isBare()) {
  687. return Collections.emptySet();
  688. }
  689. try (TreeWalk treeWalk = new TreeWalk(repo)) {
  690. treeWalk.addTree(new DirCacheIterator(repo.readDirCache()));
  691. ObjectId headID = repo.resolve(Constants.HEAD);
  692. if (headID != null) {
  693. try (RevWalk revWalk = new RevWalk(repo)) {
  694. treeWalk.addTree(revWalk.parseTree(headID));
  695. }
  696. }
  697. treeWalk.setFilter(TreeFilter.ANY_DIFF);
  698. treeWalk.setRecursive(true);
  699. Set<ObjectId> ret = new HashSet<ObjectId>();
  700. while (treeWalk.next()) {
  701. ObjectId objectId = treeWalk.getObjectId(0);
  702. switch (treeWalk.getRawMode(0) & FileMode.TYPE_MASK) {
  703. case FileMode.TYPE_MISSING:
  704. case FileMode.TYPE_GITLINK:
  705. continue;
  706. case FileMode.TYPE_TREE:
  707. case FileMode.TYPE_FILE:
  708. case FileMode.TYPE_SYMLINK:
  709. ret.add(objectId);
  710. continue;
  711. default:
  712. throw new IOException(MessageFormat.format(
  713. JGitText.get().corruptObjectInvalidMode3,
  714. String.format("%o", //$NON-NLS-1$
  715. Integer.valueOf(treeWalk.getRawMode(0))),
  716. (objectId == null) ? "null" : objectId.name(), //$NON-NLS-1$
  717. treeWalk.getPathString(), //
  718. repo.getIndexFile()));
  719. }
  720. }
  721. return ret;
  722. }
  723. }
  724. private PackFile writePack(@NonNull Set<? extends ObjectId> want,
  725. @NonNull Set<? extends ObjectId> have, Set<ObjectId> tagTargets,
  726. List<ObjectIdSet> excludeObjects) throws IOException {
  727. File tmpPack = null;
  728. Map<PackExt, File> tmpExts = new TreeMap<PackExt, File>(
  729. new Comparator<PackExt>() {
  730. public int compare(PackExt o1, PackExt o2) {
  731. // INDEX entries must be returned last, so the pack
  732. // scanner does pick up the new pack until all the
  733. // PackExt entries have been written.
  734. if (o1 == o2)
  735. return 0;
  736. if (o1 == PackExt.INDEX)
  737. return 1;
  738. if (o2 == PackExt.INDEX)
  739. return -1;
  740. return Integer.signum(o1.hashCode() - o2.hashCode());
  741. }
  742. });
  743. try (PackWriter pw = new PackWriter(
  744. (pconfig == null) ? new PackConfig(repo) : pconfig,
  745. repo.newObjectReader())) {
  746. // prepare the PackWriter
  747. pw.setDeltaBaseAsOffset(true);
  748. pw.setReuseDeltaCommits(false);
  749. if (tagTargets != null)
  750. pw.setTagTargets(tagTargets);
  751. if (excludeObjects != null)
  752. for (ObjectIdSet idx : excludeObjects)
  753. pw.excludeObjects(idx);
  754. pw.preparePack(pm, want, have);
  755. if (pw.getObjectCount() == 0)
  756. return null;
  757. // create temporary files
  758. String id = pw.computeName().getName();
  759. File packdir = new File(repo.getObjectsDirectory(), "pack"); //$NON-NLS-1$
  760. tmpPack = File.createTempFile("gc_", ".pack_tmp", packdir); //$NON-NLS-1$ //$NON-NLS-2$
  761. final String tmpBase = tmpPack.getName()
  762. .substring(0, tmpPack.getName().lastIndexOf('.'));
  763. File tmpIdx = new File(packdir, tmpBase + ".idx_tmp"); //$NON-NLS-1$
  764. tmpExts.put(INDEX, tmpIdx);
  765. if (!tmpIdx.createNewFile())
  766. throw new IOException(MessageFormat.format(
  767. JGitText.get().cannotCreateIndexfile, tmpIdx.getPath()));
  768. // write the packfile
  769. FileOutputStream fos = new FileOutputStream(tmpPack);
  770. FileChannel channel = fos.getChannel();
  771. OutputStream channelStream = Channels.newOutputStream(channel);
  772. try {
  773. pw.writePack(pm, pm, channelStream);
  774. } finally {
  775. channel.force(true);
  776. channelStream.close();
  777. fos.close();
  778. }
  779. // write the packindex
  780. fos = new FileOutputStream(tmpIdx);
  781. FileChannel idxChannel = fos.getChannel();
  782. OutputStream idxStream = Channels.newOutputStream(idxChannel);
  783. try {
  784. pw.writeIndex(idxStream);
  785. } finally {
  786. idxChannel.force(true);
  787. idxStream.close();
  788. fos.close();
  789. }
  790. if (pw.prepareBitmapIndex(pm)) {
  791. File tmpBitmapIdx = new File(packdir, tmpBase + ".bitmap_tmp"); //$NON-NLS-1$
  792. tmpExts.put(BITMAP_INDEX, tmpBitmapIdx);
  793. if (!tmpBitmapIdx.createNewFile())
  794. throw new IOException(MessageFormat.format(
  795. JGitText.get().cannotCreateIndexfile,
  796. tmpBitmapIdx.getPath()));
  797. fos = new FileOutputStream(tmpBitmapIdx);
  798. idxChannel = fos.getChannel();
  799. idxStream = Channels.newOutputStream(idxChannel);
  800. try {
  801. pw.writeBitmapIndex(idxStream);
  802. } finally {
  803. idxChannel.force(true);
  804. idxStream.close();
  805. fos.close();
  806. }
  807. }
  808. // rename the temporary files to real files
  809. File realPack = nameFor(id, ".pack"); //$NON-NLS-1$
  810. // if the packfile already exists (because we are rewriting a
  811. // packfile for the same set of objects maybe with different
  812. // PackConfig) then make sure we get rid of all handles on the file.
  813. // Windows will not allow for rename otherwise.
  814. if (realPack.exists())
  815. for (PackFile p : repo.getObjectDatabase().getPacks())
  816. if (realPack.getPath().equals(p.getPackFile().getPath())) {
  817. p.close();
  818. break;
  819. }
  820. tmpPack.setReadOnly();
  821. FileUtils.rename(tmpPack, realPack, StandardCopyOption.ATOMIC_MOVE);
  822. for (Map.Entry<PackExt, File> tmpEntry : tmpExts.entrySet()) {
  823. File tmpExt = tmpEntry.getValue();
  824. tmpExt.setReadOnly();
  825. File realExt = nameFor(id,
  826. "." + tmpEntry.getKey().getExtension()); //$NON-NLS-1$
  827. try {
  828. FileUtils.rename(tmpExt, realExt,
  829. StandardCopyOption.ATOMIC_MOVE);
  830. } catch (IOException e) {
  831. File newExt = new File(realExt.getParentFile(),
  832. realExt.getName() + ".new"); //$NON-NLS-1$
  833. try {
  834. FileUtils.rename(tmpExt, newExt,
  835. StandardCopyOption.ATOMIC_MOVE);
  836. } catch (IOException e2) {
  837. newExt = tmpExt;
  838. e = e2;
  839. }
  840. throw new IOException(MessageFormat.format(
  841. JGitText.get().panicCantRenameIndexFile, newExt,
  842. realExt), e);
  843. }
  844. }
  845. return repo.getObjectDatabase().openPack(realPack);
  846. } finally {
  847. if (tmpPack != null && tmpPack.exists())
  848. tmpPack.delete();
  849. for (File tmpExt : tmpExts.values()) {
  850. if (tmpExt.exists())
  851. tmpExt.delete();
  852. }
  853. }
  854. }
  855. private File nameFor(String name, String ext) {
  856. File packdir = new File(repo.getObjectsDirectory(), "pack"); //$NON-NLS-1$
  857. return new File(packdir, "pack-" + name + ext); //$NON-NLS-1$
  858. }
  859. /**
  860. * A class holding statistical data for a FileRepository regarding how many
  861. * objects are stored as loose or packed objects
  862. */
  863. public static class RepoStatistics {
  864. /**
  865. * The number of objects stored in pack files. If the same object is
  866. * stored in multiple pack files then it is counted as often as it
  867. * occurs in pack files.
  868. */
  869. public long numberOfPackedObjects;
  870. /**
  871. * The number of pack files
  872. */
  873. public long numberOfPackFiles;
  874. /**
  875. * The number of objects stored as loose objects.
  876. */
  877. public long numberOfLooseObjects;
  878. /**
  879. * The sum of the sizes of all files used to persist loose objects.
  880. */
  881. public long sizeOfLooseObjects;
  882. /**
  883. * The sum of the sizes of all pack files.
  884. */
  885. public long sizeOfPackedObjects;
  886. /**
  887. * The number of loose refs.
  888. */
  889. public long numberOfLooseRefs;
  890. /**
  891. * The number of refs stored in pack files.
  892. */
  893. public long numberOfPackedRefs;
  894. /**
  895. * The number of bitmaps in the bitmap indices.
  896. */
  897. public long numberOfBitmaps;
  898. public String toString() {
  899. final StringBuilder b = new StringBuilder();
  900. b.append("numberOfPackedObjects=").append(numberOfPackedObjects); //$NON-NLS-1$
  901. b.append(", numberOfPackFiles=").append(numberOfPackFiles); //$NON-NLS-1$
  902. b.append(", numberOfLooseObjects=").append(numberOfLooseObjects); //$NON-NLS-1$
  903. b.append(", numberOfLooseRefs=").append(numberOfLooseRefs); //$NON-NLS-1$
  904. b.append(", numberOfPackedRefs=").append(numberOfPackedRefs); //$NON-NLS-1$
  905. b.append(", sizeOfLooseObjects=").append(sizeOfLooseObjects); //$NON-NLS-1$
  906. b.append(", sizeOfPackedObjects=").append(sizeOfPackedObjects); //$NON-NLS-1$
  907. b.append(", numberOfBitmaps=").append(numberOfBitmaps); //$NON-NLS-1$
  908. return b.toString();
  909. }
  910. }
  911. /**
  912. * Returns information about objects and pack files for a FileRepository.
  913. *
  914. * @return information about objects and pack files for a FileRepository
  915. * @throws IOException
  916. */
  917. public RepoStatistics getStatistics() throws IOException {
  918. RepoStatistics ret = new RepoStatistics();
  919. Collection<PackFile> packs = repo.getObjectDatabase().getPacks();
  920. for (PackFile f : packs) {
  921. ret.numberOfPackedObjects += f.getIndex().getObjectCount();
  922. ret.numberOfPackFiles++;
  923. ret.sizeOfPackedObjects += f.getPackFile().length();
  924. if (f.getBitmapIndex() != null)
  925. ret.numberOfBitmaps += f.getBitmapIndex().getBitmapCount();
  926. }
  927. File objDir = repo.getObjectsDirectory();
  928. String[] fanout = objDir.list();
  929. if (fanout != null && fanout.length > 0) {
  930. for (String d : fanout) {
  931. if (d.length() != 2)
  932. continue;
  933. File[] entries = new File(objDir, d).listFiles();
  934. if (entries == null)
  935. continue;
  936. for (File f : entries) {
  937. if (f.getName().length() != Constants.OBJECT_ID_STRING_LENGTH - 2)
  938. continue;
  939. ret.numberOfLooseObjects++;
  940. ret.sizeOfLooseObjects += f.length();
  941. }
  942. }
  943. }
  944. RefDatabase refDb = repo.getRefDatabase();
  945. for (Ref r : refDb.getRefs(RefDatabase.ALL).values()) {
  946. Storage storage = r.getStorage();
  947. if (storage == Storage.LOOSE || storage == Storage.LOOSE_PACKED)
  948. ret.numberOfLooseRefs++;
  949. if (storage == Storage.PACKED || storage == Storage.LOOSE_PACKED)
  950. ret.numberOfPackedRefs++;
  951. }
  952. return ret;
  953. }
  954. /**
  955. * Set the progress monitor used for garbage collection methods.
  956. *
  957. * @param pm
  958. * @return this
  959. */
  960. public GC setProgressMonitor(ProgressMonitor pm) {
  961. this.pm = (pm == null) ? NullProgressMonitor.INSTANCE : pm;
  962. return this;
  963. }
  964. /**
  965. * During gc() or prune() each unreferenced, loose object which has been
  966. * created or modified in the last <code>expireAgeMillis</code> milliseconds
  967. * will not be pruned. Only older objects may be pruned. If set to 0 then
  968. * every object is a candidate for pruning.
  969. *
  970. * @param expireAgeMillis
  971. * minimal age of objects to be pruned in milliseconds.
  972. */
  973. public void setExpireAgeMillis(long expireAgeMillis) {
  974. this.expireAgeMillis = expireAgeMillis;
  975. expire = null;
  976. }
  977. /**
  978. * During gc() or prune() packfiles which are created or modified in the
  979. * last <code>packExpireAgeMillis</code> milliseconds will not be deleted.
  980. * Only older packfiles may be deleted. If set to 0 then every packfile is a
  981. * candidate for deletion.
  982. *
  983. * @param packExpireAgeMillis
  984. * minimal age of packfiles to be deleted in milliseconds.
  985. */
  986. public void setPackExpireAgeMillis(long packExpireAgeMillis) {
  987. this.packExpireAgeMillis = packExpireAgeMillis;
  988. expire = null;
  989. }
  990. /**
  991. * Set the PackConfig used when (re-)writing packfiles. This allows to
  992. * influence how packs are written and to implement something similar to
  993. * "git gc --aggressive"
  994. *
  995. * @since 3.6
  996. * @param pconfig
  997. * the {@link PackConfig} used when writing packs
  998. */
  999. public void setPackConfig(PackConfig pconfig) {
  1000. this.pconfig = pconfig;
  1001. }
  1002. /**
  1003. * During gc() or prune() each unreferenced, loose object which has been
  1004. * created or modified after or at <code>expire</code> will not be pruned.
  1005. * Only older objects may be pruned. If set to null then every object is a
  1006. * candidate for pruning.
  1007. *
  1008. * @param expire
  1009. * instant in time which defines object expiration
  1010. * objects with modification time before this instant are expired
  1011. * objects with modification time newer or equal to this instant
  1012. * are not expired
  1013. */
  1014. public void setExpire(Date expire) {
  1015. this.expire = expire;
  1016. expireAgeMillis = -1;
  1017. }
  1018. /**
  1019. * During gc() or prune() packfiles which are created or modified after or
  1020. * at <code>packExpire</code> will not be deleted. Only older packfiles may
  1021. * be deleted. If set to null then every packfile is a candidate for
  1022. * deletion.
  1023. *
  1024. * @param packExpire
  1025. * instant in time which defines packfile expiration
  1026. */
  1027. public void setPackExpire(Date packExpire) {
  1028. this.packExpire = packExpire;
  1029. packExpireAgeMillis = -1;
  1030. }
  1031. /**
  1032. * Set the {@code gc --auto} option.
  1033. *
  1034. * With this option, gc checks whether any housekeeping is required; if not,
  1035. * it exits without performing any work. Some JGit commands run
  1036. * {@code gc --auto} after performing operations that could create many
  1037. * loose objects.
  1038. * <p/>
  1039. * Housekeeping is required if there are too many loose objects or too many
  1040. * packs in the repository. If the number of loose objects exceeds the value
  1041. * of the gc.auto option JGit GC consolidates all existing packs into a
  1042. * single pack (equivalent to {@code -A} option), whereas git-core would
  1043. * combine all loose objects into a single pack using {@code repack -d -l}.
  1044. * Setting the value of {@code gc.auto} to 0 disables automatic packing of
  1045. * loose objects.
  1046. * <p/>
  1047. * If the number of packs exceeds the value of {@code gc.autoPackLimit},
  1048. * then existing packs (except those marked with a .keep file) are
  1049. * consolidated into a single pack by using the {@code -A} option of repack.
  1050. * Setting {@code gc.autoPackLimit} to 0 disables automatic consolidation of
  1051. * packs.
  1052. * <p/>
  1053. * Like git the following jgit commands run auto gc:
  1054. * <ul>
  1055. * <li>fetch</li>
  1056. * <li>merge</li>
  1057. * <li>rebase</li>
  1058. * <li>receive-pack</li>
  1059. * </ul>
  1060. * The auto gc for receive-pack can be suppressed by setting the config
  1061. * option {@code receive.autogc = false}
  1062. *
  1063. * @param auto
  1064. * defines whether gc should do automatic housekeeping
  1065. * @since 4.5
  1066. */
  1067. public void setAuto(boolean auto) {
  1068. this.automatic = auto;
  1069. }
  1070. private boolean needGc() {
  1071. if (tooManyPacks()) {
  1072. addRepackAllOption();
  1073. } else if (!tooManyLooseObjects()) {
  1074. return false;
  1075. }
  1076. // TODO run pre-auto-gc hook, if it fails return false
  1077. return true;
  1078. }
  1079. private void addRepackAllOption() {
  1080. // TODO: if JGit GC is enhanced to support repack's option -l this
  1081. // method needs to be implemented
  1082. }
  1083. /**
  1084. * @return {@code true} if number of packs > gc.autopacklimit (default 50)
  1085. */
  1086. boolean tooManyPacks() {
  1087. int autopacklimit = repo.getConfig().getInt(
  1088. ConfigConstants.CONFIG_GC_SECTION,
  1089. ConfigConstants.CONFIG_KEY_AUTOPACKLIMIT,
  1090. DEFAULT_AUTOPACKLIMIT);
  1091. if (autopacklimit <= 0) {
  1092. return false;
  1093. }
  1094. // JGit always creates two packfiles, one for the objects reachable from
  1095. // branches, and another one for the rest
  1096. return repo.getObjectDatabase().getPacks().size() > (autopacklimit + 1);
  1097. }
  1098. /**
  1099. * Quickly estimate number of loose objects, SHA1 is distributed evenly so
  1100. * counting objects in one directory (bucket 17) is sufficient
  1101. *
  1102. * @return {@code true} if number of loose objects > gc.auto (default 6700)
  1103. */
  1104. boolean tooManyLooseObjects() {
  1105. int auto = repo.getConfig().getInt(ConfigConstants.CONFIG_GC_SECTION,
  1106. ConfigConstants.CONFIG_KEY_AUTO, DEFAULT_AUTOLIMIT);
  1107. if (auto <= 0) {
  1108. return false;
  1109. }
  1110. int n = 0;
  1111. int threshold = (auto + 255) / 256;
  1112. Path dir = repo.getObjectsDirectory().toPath().resolve("17"); //$NON-NLS-1$
  1113. if (!Files.exists(dir)) {
  1114. return false;
  1115. }
  1116. try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir,
  1117. new DirectoryStream.Filter<Path>() {
  1118. public boolean accept(Path file) throws IOException {
  1119. Path fileName = file.getFileName();
  1120. return Files.isRegularFile(file) && fileName != null
  1121. && PATTERN_LOOSE_OBJECT
  1122. .matcher(fileName.toString()).matches();
  1123. }
  1124. })) {
  1125. for (Iterator<Path> iter = stream.iterator(); iter.hasNext();
  1126. iter.next()) {
  1127. if (++n > threshold) {
  1128. return true;
  1129. }
  1130. }
  1131. } catch (IOException e) {
  1132. LOG.error(e.getMessage(), e);
  1133. }
  1134. return false;
  1135. }
  1136. }