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 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950
  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.text.MessageFormat;
  54. import java.text.ParseException;
  55. import java.util.ArrayList;
  56. import java.util.Collection;
  57. import java.util.Collections;
  58. import java.util.Comparator;
  59. import java.util.Date;
  60. import java.util.HashMap;
  61. import java.util.HashSet;
  62. import java.util.Iterator;
  63. import java.util.LinkedList;
  64. import java.util.List;
  65. import java.util.Map;
  66. import java.util.Map.Entry;
  67. import java.util.Set;
  68. import java.util.TreeMap;
  69. import org.eclipse.jgit.dircache.DirCacheIterator;
  70. import org.eclipse.jgit.errors.CorruptObjectException;
  71. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  72. import org.eclipse.jgit.errors.MissingObjectException;
  73. import org.eclipse.jgit.errors.NoWorkTreeException;
  74. import org.eclipse.jgit.internal.JGitText;
  75. import org.eclipse.jgit.internal.storage.pack.PackExt;
  76. import org.eclipse.jgit.internal.storage.pack.PackWriter;
  77. import org.eclipse.jgit.internal.storage.pack.PackWriter.ObjectIdSet;
  78. import org.eclipse.jgit.lib.AnyObjectId;
  79. import org.eclipse.jgit.lib.ConfigConstants;
  80. import org.eclipse.jgit.lib.Constants;
  81. import org.eclipse.jgit.lib.FileMode;
  82. import org.eclipse.jgit.lib.NullProgressMonitor;
  83. import org.eclipse.jgit.lib.ObjectId;
  84. import org.eclipse.jgit.lib.ProgressMonitor;
  85. import org.eclipse.jgit.lib.Ref;
  86. import org.eclipse.jgit.lib.Ref.Storage;
  87. import org.eclipse.jgit.lib.RefDatabase;
  88. import org.eclipse.jgit.lib.ReflogEntry;
  89. import org.eclipse.jgit.revwalk.ObjectWalk;
  90. import org.eclipse.jgit.revwalk.RevObject;
  91. import org.eclipse.jgit.revwalk.RevWalk;
  92. import org.eclipse.jgit.treewalk.TreeWalk;
  93. import org.eclipse.jgit.treewalk.filter.TreeFilter;
  94. import org.eclipse.jgit.util.FileUtils;
  95. import org.eclipse.jgit.util.GitDateParser;
  96. /**
  97. * A garbage collector for git {@link FileRepository}. Instances of this class
  98. * are not thread-safe. Don't use the same instance from multiple threads.
  99. *
  100. * This class started as a copy of DfsGarbageCollector from Shawn O. Pearce
  101. * adapted to FileRepositories.
  102. */
  103. public class GC {
  104. private static final String PRUNE_EXPIRE_DEFAULT = "2.weeks.ago"; //$NON-NLS-1$
  105. private final FileRepository repo;
  106. private ProgressMonitor pm;
  107. private long expireAgeMillis = -1;
  108. private Date expire;
  109. /**
  110. * the refs which existed during the last call to {@link #repack()}. This is
  111. * needed during {@link #prune(Set)} where we can optimize by looking at the
  112. * difference between the current refs and the refs which existed during
  113. * last {@link #repack()}.
  114. */
  115. private Map<String, Ref> lastPackedRefs;
  116. /**
  117. * Holds the starting time of the last repack() execution. This is needed in
  118. * prune() to inspect only those reflog entries which have been added since
  119. * last repack().
  120. */
  121. private long lastRepackTime;
  122. /**
  123. * Creates a new garbage collector with default values. An expirationTime of
  124. * two weeks and <code>null</code> as progress monitor will be used.
  125. *
  126. * @param repo
  127. * the repo to work on
  128. */
  129. public GC(FileRepository repo) {
  130. this.repo = repo;
  131. this.pm = NullProgressMonitor.INSTANCE;
  132. }
  133. /**
  134. * Runs a garbage collector on a {@link FileRepository}. It will
  135. * <ul>
  136. * <li>pack loose references into packed-refs</li>
  137. * <li>repack all reachable objects into new pack files and delete the old
  138. * pack files</li>
  139. * <li>prune all loose objects which are now reachable by packs</li>
  140. * </ul>
  141. *
  142. * @return the collection of {@link PackFile}'s which are newly created
  143. * @throws IOException
  144. * @throws ParseException
  145. * If the configuration parameter "gc.pruneexpire" couldn't be
  146. * parsed
  147. */
  148. public Collection<PackFile> gc() throws IOException, ParseException {
  149. pm.start(6 /* tasks */);
  150. packRefs();
  151. // TODO: implement reflog_expire(pm, repo);
  152. Collection<PackFile> newPacks = repack();
  153. prune(Collections.<ObjectId> emptySet());
  154. // TODO: implement rerere_gc(pm);
  155. return newPacks;
  156. }
  157. /**
  158. * Delete old pack files. What is 'old' is defined by specifying a set of
  159. * old pack files and a set of new pack files. Each pack file contained in
  160. * old pack files but not contained in new pack files will be deleted.
  161. *
  162. * @param oldPacks
  163. * @param newPacks
  164. * @param ignoreErrors
  165. * <code>true</code> if we should ignore the fact that a certain
  166. * pack files or index files couldn't be deleted.
  167. * <code>false</code> if an exception should be thrown in such
  168. * cases
  169. * @throws IOException
  170. * if a pack file couldn't be deleted and
  171. * <code>ignoreErrors</code> is set to <code>false</code>
  172. */
  173. private void deleteOldPacks(Collection<PackFile> oldPacks,
  174. Collection<PackFile> newPacks, boolean ignoreErrors)
  175. throws IOException {
  176. int deleteOptions = FileUtils.RETRY | FileUtils.SKIP_MISSING;
  177. if (ignoreErrors)
  178. deleteOptions |= FileUtils.IGNORE_ERRORS;
  179. oldPackLoop: for (PackFile oldPack : oldPacks) {
  180. String oldName = oldPack.getPackName();
  181. // check whether an old pack file is also among the list of new
  182. // pack files. Then we must not delete it.
  183. for (PackFile newPack : newPacks)
  184. if (oldName.equals(newPack.getPackName()))
  185. continue oldPackLoop;
  186. if (!oldPack.shouldBeKept()) {
  187. oldPack.close();
  188. for (PackExt ext : PackExt.values()) {
  189. File f = nameFor(oldName, "." + ext.getExtension()); //$NON-NLS-1$
  190. FileUtils.delete(f, deleteOptions);
  191. }
  192. }
  193. }
  194. // close the complete object database. Thats my only chance to force
  195. // rescanning and to detect that certain pack files are now deleted.
  196. repo.getObjectDatabase().close();
  197. }
  198. /**
  199. * Like "git prune-packed" this method tries to prune all loose objects
  200. * which can be found in packs. If certain objects can't be pruned (e.g.
  201. * because the filesystem delete operation fails) this is silently ignored.
  202. *
  203. * @throws IOException
  204. */
  205. public void prunePacked() throws IOException {
  206. ObjectDirectory objdb = repo.getObjectDatabase();
  207. Collection<PackFile> packs = objdb.getPacks();
  208. File objects = repo.getObjectsDirectory();
  209. String[] fanout = objects.list();
  210. if (fanout != null && fanout.length > 0) {
  211. pm.beginTask(JGitText.get().pruneLoosePackedObjects, fanout.length);
  212. try {
  213. for (String d : fanout) {
  214. pm.update(1);
  215. if (d.length() != 2)
  216. continue;
  217. String[] entries = new File(objects, d).list();
  218. if (entries == null)
  219. continue;
  220. for (String e : entries) {
  221. if (e.length() != Constants.OBJECT_ID_STRING_LENGTH - 2)
  222. continue;
  223. ObjectId id;
  224. try {
  225. id = ObjectId.fromString(d + e);
  226. } catch (IllegalArgumentException notAnObject) {
  227. // ignoring the file that does not represent loose
  228. // object
  229. continue;
  230. }
  231. boolean found = false;
  232. for (PackFile p : packs)
  233. if (p.hasObject(id)) {
  234. found = true;
  235. break;
  236. }
  237. if (found)
  238. FileUtils.delete(objdb.fileFor(id), FileUtils.RETRY
  239. | FileUtils.SKIP_MISSING
  240. | FileUtils.IGNORE_ERRORS);
  241. }
  242. }
  243. } finally {
  244. pm.endTask();
  245. }
  246. }
  247. }
  248. /**
  249. * Like "git prune" this method tries to prune all loose objects which are
  250. * unreferenced. If certain objects can't be pruned (e.g. because the
  251. * filesystem delete operation fails) this is silently ignored.
  252. *
  253. * @param objectsToKeep
  254. * a set of objects which should explicitly not be pruned
  255. *
  256. * @throws IOException
  257. * @throws ParseException
  258. * If the configuration parameter "gc.pruneexpire" couldn't be
  259. * parsed
  260. */
  261. public void prune(Set<ObjectId> objectsToKeep) throws IOException,
  262. ParseException {
  263. long expireDate = Long.MAX_VALUE;
  264. if (expire == null && expireAgeMillis == -1) {
  265. String pruneExpireStr = repo.getConfig().getString(
  266. ConfigConstants.CONFIG_GC_SECTION, null,
  267. ConfigConstants.CONFIG_KEY_PRUNEEXPIRE);
  268. if (pruneExpireStr == null)
  269. pruneExpireStr = PRUNE_EXPIRE_DEFAULT;
  270. expire = GitDateParser.parse(pruneExpireStr, null);
  271. expireAgeMillis = -1;
  272. }
  273. if (expire != null)
  274. expireDate = expire.getTime();
  275. if (expireAgeMillis != -1)
  276. expireDate = System.currentTimeMillis() - expireAgeMillis;
  277. // Collect all loose objects which are old enough, not referenced from
  278. // the index and not in objectsToKeep
  279. Map<ObjectId, File> deletionCandidates = new HashMap<ObjectId, File>();
  280. Set<ObjectId> indexObjects = null;
  281. File objects = repo.getObjectsDirectory();
  282. String[] fanout = objects.list();
  283. if (fanout != null && fanout.length > 0) {
  284. pm.beginTask(JGitText.get().pruneLooseUnreferencedObjects,
  285. fanout.length);
  286. try {
  287. for (String d : fanout) {
  288. pm.update(1);
  289. if (d.length() != 2)
  290. continue;
  291. File[] entries = new File(objects, d).listFiles();
  292. if (entries == null)
  293. continue;
  294. for (File f : entries) {
  295. String fName = f.getName();
  296. if (fName.length() != Constants.OBJECT_ID_STRING_LENGTH - 2)
  297. continue;
  298. if (f.lastModified() >= expireDate)
  299. continue;
  300. try {
  301. ObjectId id = ObjectId.fromString(d + fName);
  302. if (objectsToKeep.contains(id))
  303. continue;
  304. if (indexObjects == null)
  305. indexObjects = listNonHEADIndexObjects();
  306. if (indexObjects.contains(id))
  307. continue;
  308. deletionCandidates.put(id, f);
  309. } catch (IllegalArgumentException notAnObject) {
  310. // ignoring the file that does not represent loose
  311. // object
  312. continue;
  313. }
  314. }
  315. }
  316. } finally {
  317. pm.endTask();
  318. }
  319. }
  320. if (deletionCandidates.isEmpty())
  321. return;
  322. // From the set of current refs remove all those which have been handled
  323. // during last repack(). Only those refs will survive which have been
  324. // added or modified since the last repack. Only these can save existing
  325. // loose refs from being pruned.
  326. Map<String, Ref> newRefs;
  327. if (lastPackedRefs == null || lastPackedRefs.isEmpty())
  328. newRefs = getAllRefs();
  329. else {
  330. newRefs = new HashMap<String, Ref>();
  331. for (Iterator<Map.Entry<String, Ref>> i = getAllRefs().entrySet()
  332. .iterator(); i.hasNext();) {
  333. Entry<String, Ref> newEntry = i.next();
  334. Ref old = lastPackedRefs.get(newEntry.getKey());
  335. if (!equals(newEntry.getValue(), old))
  336. newRefs.put(newEntry.getKey(), newEntry.getValue());
  337. }
  338. }
  339. if (!newRefs.isEmpty()) {
  340. // There are new/modified refs! Check which loose objects are now
  341. // referenced by these modified refs (or their reflogentries).
  342. // Remove these loose objects
  343. // from the deletionCandidates. When the last candidate is removed
  344. // leave this method.
  345. ObjectWalk w = new ObjectWalk(repo);
  346. try {
  347. for (Ref cr : newRefs.values())
  348. w.markStart(w.parseAny(cr.getObjectId()));
  349. if (lastPackedRefs != null)
  350. for (Ref lpr : lastPackedRefs.values())
  351. w.markUninteresting(w.parseAny(lpr.getObjectId()));
  352. removeReferenced(deletionCandidates, w);
  353. } finally {
  354. w.dispose();
  355. }
  356. }
  357. if (deletionCandidates.isEmpty())
  358. return;
  359. // Since we have not left the method yet there are still
  360. // deletionCandidates. Last chance for these objects not to be pruned is
  361. // that they are referenced by reflog entries. Even refs which currently
  362. // point to the same object as during last repack() may have
  363. // additional reflog entries not handled during last repack()
  364. ObjectWalk w = new ObjectWalk(repo);
  365. try {
  366. for (Ref ar : getAllRefs().values())
  367. for (ObjectId id : listRefLogObjects(ar, lastRepackTime))
  368. w.markStart(w.parseAny(id));
  369. if (lastPackedRefs != null)
  370. for (Ref lpr : lastPackedRefs.values())
  371. w.markUninteresting(w.parseAny(lpr.getObjectId()));
  372. removeReferenced(deletionCandidates, w);
  373. } finally {
  374. w.dispose();
  375. }
  376. if (deletionCandidates.isEmpty())
  377. return;
  378. // delete all candidates which have survived: these are unreferenced
  379. // loose objects
  380. for (File f : deletionCandidates.values())
  381. f.delete();
  382. repo.getObjectDatabase().close();
  383. }
  384. /**
  385. * Remove all entries from a map which key is the id of an object referenced
  386. * by the given ObjectWalk
  387. *
  388. * @param id2File
  389. * @param w
  390. * @throws MissingObjectException
  391. * @throws IncorrectObjectTypeException
  392. * @throws IOException
  393. */
  394. private void removeReferenced(Map<ObjectId, File> id2File,
  395. ObjectWalk w) throws MissingObjectException,
  396. IncorrectObjectTypeException, IOException {
  397. RevObject ro = w.next();
  398. while (ro != null) {
  399. if (id2File.remove(ro.getId()) != null)
  400. if (id2File.isEmpty())
  401. return;
  402. ro = w.next();
  403. }
  404. ro = w.nextObject();
  405. while (ro != null) {
  406. if (id2File.remove(ro.getId()) != null)
  407. if (id2File.isEmpty())
  408. return;
  409. ro = w.nextObject();
  410. }
  411. }
  412. private static boolean equals(Ref r1, Ref r2) {
  413. if (r1 == null || r2 == null)
  414. return false;
  415. if (r1.isSymbolic()) {
  416. if (!r2.isSymbolic())
  417. return false;
  418. return r1.getTarget().getName().equals(r2.getTarget().getName());
  419. } else {
  420. if (r2.isSymbolic())
  421. return false;
  422. return r1.getObjectId().equals(r2.getObjectId());
  423. }
  424. }
  425. /**
  426. * Packs all non-symbolic, loose refs into packed-refs.
  427. *
  428. * @throws IOException
  429. */
  430. public void packRefs() throws IOException {
  431. Collection<Ref> refs = repo.getAllRefs().values();
  432. List<String> refsToBePacked = new ArrayList<String>(refs.size());
  433. pm.beginTask(JGitText.get().packRefs, refs.size());
  434. try {
  435. for (Ref ref : refs) {
  436. if (!ref.isSymbolic() && ref.getStorage().isLoose())
  437. refsToBePacked.add(ref.getName());
  438. pm.update(1);
  439. }
  440. ((RefDirectory) repo.getRefDatabase()).pack(refsToBePacked);
  441. } finally {
  442. pm.endTask();
  443. }
  444. }
  445. /**
  446. * Packs all objects which reachable from any of the heads into one pack
  447. * file. Additionally all objects which are not reachable from any head but
  448. * which are reachable from any of the other refs (e.g. tags), special refs
  449. * (e.g. FETCH_HEAD) or index are packed into a separate pack file. Objects
  450. * included in pack files which have a .keep file associated are never
  451. * repacked. All old pack files which existed before are deleted.
  452. *
  453. * @return a collection of the newly created pack files
  454. * @throws IOException
  455. * when during reading of refs, index, packfiles, objects,
  456. * reflog-entries or during writing to the packfiles
  457. * {@link IOException} occurs
  458. */
  459. public Collection<PackFile> repack() throws IOException {
  460. Collection<PackFile> toBeDeleted = repo.getObjectDatabase().getPacks();
  461. long time = System.currentTimeMillis();
  462. Map<String, Ref> refsBefore = getAllRefs();
  463. Set<ObjectId> allHeads = new HashSet<ObjectId>();
  464. Set<ObjectId> nonHeads = new HashSet<ObjectId>();
  465. Set<ObjectId> tagTargets = new HashSet<ObjectId>();
  466. Set<ObjectId> indexObjects = listNonHEADIndexObjects();
  467. for (Ref ref : refsBefore.values()) {
  468. nonHeads.addAll(listRefLogObjects(ref, 0));
  469. if (ref.isSymbolic() || ref.getObjectId() == null)
  470. continue;
  471. if (ref.getName().startsWith(Constants.R_HEADS))
  472. allHeads.add(ref.getObjectId());
  473. else
  474. nonHeads.add(ref.getObjectId());
  475. if (ref.getPeeledObjectId() != null)
  476. tagTargets.add(ref.getPeeledObjectId());
  477. }
  478. List<ObjectIdSet> excluded = new LinkedList<ObjectIdSet>();
  479. for (final PackFile f : repo.getObjectDatabase().getPacks())
  480. if (f.shouldBeKept())
  481. excluded.add(objectIdSet(f.getIndex()));
  482. tagTargets.addAll(allHeads);
  483. nonHeads.addAll(indexObjects);
  484. List<PackFile> ret = new ArrayList<PackFile>(2);
  485. PackFile heads = null;
  486. if (!allHeads.isEmpty()) {
  487. heads = writePack(allHeads, Collections.<ObjectId> emptySet(),
  488. tagTargets, excluded);
  489. if (heads != null) {
  490. ret.add(heads);
  491. excluded.add(0, objectIdSet(heads.getIndex()));
  492. }
  493. }
  494. if (!nonHeads.isEmpty()) {
  495. PackFile rest = writePack(nonHeads, allHeads, tagTargets, excluded);
  496. if (rest != null)
  497. ret.add(rest);
  498. }
  499. deleteOldPacks(toBeDeleted, ret, true);
  500. prunePacked();
  501. lastPackedRefs = refsBefore;
  502. lastRepackTime = time;
  503. return ret;
  504. }
  505. /**
  506. * @param ref
  507. * the ref which log should be inspected
  508. * @param minTime only reflog entries not older then this time are processed
  509. * @return the {@link ObjectId}s contained in the reflog
  510. * @throws IOException
  511. */
  512. private Set<ObjectId> listRefLogObjects(Ref ref, long minTime) throws IOException {
  513. List<ReflogEntry> rlEntries = repo.getReflogReader(ref.getName())
  514. .getReverseEntries();
  515. if (rlEntries == null || rlEntries.isEmpty())
  516. return Collections.<ObjectId> emptySet();
  517. Set<ObjectId> ret = new HashSet<ObjectId>();
  518. for (ReflogEntry e : rlEntries) {
  519. if (e.getWho().getWhen().getTime() < minTime)
  520. break;
  521. ObjectId newId = e.getNewId();
  522. if (newId != null && !ObjectId.zeroId().equals(newId))
  523. ret.add(newId);
  524. ObjectId oldId = e.getOldId();
  525. if (oldId != null && !ObjectId.zeroId().equals(oldId))
  526. ret.add(oldId);
  527. }
  528. return ret;
  529. }
  530. /**
  531. * Returns a map of all refs and additional refs (e.g. FETCH_HEAD,
  532. * MERGE_HEAD, ...)
  533. *
  534. * @return a map where names of refs point to ref objects
  535. * @throws IOException
  536. */
  537. private Map<String, Ref> getAllRefs() throws IOException {
  538. Map<String, Ref> ret = repo.getAllRefs();
  539. for (Ref ref : repo.getRefDatabase().getAdditionalRefs())
  540. ret.put(ref.getName(), ref);
  541. return ret;
  542. }
  543. /**
  544. * Return a list of those objects in the index which differ from whats in
  545. * HEAD
  546. *
  547. * @return a set of ObjectIds of changed objects in the index
  548. * @throws IOException
  549. * @throws CorruptObjectException
  550. * @throws NoWorkTreeException
  551. */
  552. private Set<ObjectId> listNonHEADIndexObjects()
  553. throws CorruptObjectException, IOException {
  554. RevWalk revWalk = null;
  555. try {
  556. if (repo.getIndexFile() == null)
  557. return Collections.emptySet();
  558. } catch (NoWorkTreeException e) {
  559. return Collections.emptySet();
  560. }
  561. TreeWalk treeWalk = new TreeWalk(repo);
  562. try {
  563. treeWalk.addTree(new DirCacheIterator(repo.readDirCache()));
  564. ObjectId headID = repo.resolve(Constants.HEAD);
  565. if (headID != null) {
  566. revWalk = new RevWalk(repo);
  567. treeWalk.addTree(revWalk.parseTree(headID));
  568. revWalk.dispose();
  569. revWalk = null;
  570. }
  571. treeWalk.setFilter(TreeFilter.ANY_DIFF);
  572. treeWalk.setRecursive(true);
  573. Set<ObjectId> ret = new HashSet<ObjectId>();
  574. while (treeWalk.next()) {
  575. ObjectId objectId = treeWalk.getObjectId(0);
  576. switch (treeWalk.getRawMode(0) & FileMode.TYPE_MASK) {
  577. case FileMode.TYPE_MISSING:
  578. case FileMode.TYPE_GITLINK:
  579. continue;
  580. case FileMode.TYPE_TREE:
  581. case FileMode.TYPE_FILE:
  582. case FileMode.TYPE_SYMLINK:
  583. ret.add(objectId);
  584. continue;
  585. default:
  586. throw new IOException(MessageFormat.format(
  587. JGitText.get().corruptObjectInvalidMode3, String
  588. .format("%o", Integer.valueOf(treeWalk //$NON-NLS-1$
  589. .getRawMode(0)),
  590. (objectId == null) ? "null" //$NON-NLS-1$
  591. : objectId.name(), treeWalk
  592. .getPathString(), repo
  593. .getIndexFile())));
  594. }
  595. }
  596. return ret;
  597. } finally {
  598. if (revWalk != null)
  599. revWalk.dispose();
  600. treeWalk.release();
  601. }
  602. }
  603. private PackFile writePack(Set<? extends ObjectId> want,
  604. Set<? extends ObjectId> have, Set<ObjectId> tagTargets,
  605. List<ObjectIdSet> excludeObjects) throws IOException {
  606. File tmpPack = null;
  607. Map<PackExt, File> tmpExts = new TreeMap<PackExt, File>(
  608. new Comparator<PackExt>() {
  609. public int compare(PackExt o1, PackExt o2) {
  610. // INDEX entries must be returned last, so the pack
  611. // scanner does pick up the new pack until all the
  612. // PackExt entries have been written.
  613. if (o1 == o2)
  614. return 0;
  615. if (o1 == PackExt.INDEX)
  616. return 1;
  617. if (o2 == PackExt.INDEX)
  618. return -1;
  619. return Integer.signum(o1.hashCode() - o2.hashCode());
  620. }
  621. });
  622. PackWriter pw = new PackWriter(repo);
  623. try {
  624. // prepare the PackWriter
  625. pw.setDeltaBaseAsOffset(true);
  626. pw.setReuseDeltaCommits(false);
  627. if (tagTargets != null)
  628. pw.setTagTargets(tagTargets);
  629. if (excludeObjects != null)
  630. for (ObjectIdSet idx : excludeObjects)
  631. pw.excludeObjects(idx);
  632. pw.preparePack(pm, want, have);
  633. if (pw.getObjectCount() == 0)
  634. return null;
  635. // create temporary files
  636. String id = pw.computeName().getName();
  637. File packdir = new File(repo.getObjectsDirectory(), "pack"); //$NON-NLS-1$
  638. tmpPack = File.createTempFile("gc_", ".pack_tmp", packdir); //$NON-NLS-1$ //$NON-NLS-2$
  639. final String tmpBase = tmpPack.getName()
  640. .substring(0, tmpPack.getName().lastIndexOf('.'));
  641. File tmpIdx = new File(packdir, tmpBase + ".idx_tmp"); //$NON-NLS-1$
  642. tmpExts.put(INDEX, tmpIdx);
  643. if (!tmpIdx.createNewFile())
  644. throw new IOException(MessageFormat.format(
  645. JGitText.get().cannotCreateIndexfile, tmpIdx.getPath()));
  646. // write the packfile
  647. @SuppressWarnings("resource" /* java 7 */)
  648. FileChannel channel = new FileOutputStream(tmpPack).getChannel();
  649. OutputStream channelStream = Channels.newOutputStream(channel);
  650. try {
  651. pw.writePack(pm, pm, channelStream);
  652. } finally {
  653. channel.force(true);
  654. channelStream.close();
  655. channel.close();
  656. }
  657. // write the packindex
  658. @SuppressWarnings("resource")
  659. FileChannel idxChannel = new FileOutputStream(tmpIdx).getChannel();
  660. OutputStream idxStream = Channels.newOutputStream(idxChannel);
  661. try {
  662. pw.writeIndex(idxStream);
  663. } finally {
  664. idxChannel.force(true);
  665. idxStream.close();
  666. idxChannel.close();
  667. }
  668. if (pw.prepareBitmapIndex(pm)) {
  669. File tmpBitmapIdx = new File(packdir, tmpBase + ".bitmap_tmp"); //$NON-NLS-1$
  670. tmpExts.put(BITMAP_INDEX, tmpBitmapIdx);
  671. if (!tmpBitmapIdx.createNewFile())
  672. throw new IOException(MessageFormat.format(
  673. JGitText.get().cannotCreateIndexfile,
  674. tmpBitmapIdx.getPath()));
  675. idxChannel = new FileOutputStream(tmpBitmapIdx).getChannel();
  676. idxStream = Channels.newOutputStream(idxChannel);
  677. try {
  678. pw.writeBitmapIndex(idxStream);
  679. } finally {
  680. idxChannel.force(true);
  681. idxStream.close();
  682. idxChannel.close();
  683. }
  684. }
  685. // rename the temporary files to real files
  686. File realPack = nameFor(id, ".pack"); //$NON-NLS-1$
  687. // if the packfile already exists (because we are rewriting a
  688. // packfile for the same set of objects maybe with different
  689. // PackConfig) then make sure we get rid of all handles on the file.
  690. // Windows will not allow for rename otherwise.
  691. if (realPack.exists())
  692. for (PackFile p : repo.getObjectDatabase().getPacks())
  693. if (realPack.getPath().equals(p.getPackFile().getPath())) {
  694. p.close();
  695. break;
  696. }
  697. tmpPack.setReadOnly();
  698. boolean delete = true;
  699. try {
  700. FileUtils.rename(tmpPack, realPack);
  701. delete = false;
  702. for (Map.Entry<PackExt, File> tmpEntry : tmpExts.entrySet()) {
  703. File tmpExt = tmpEntry.getValue();
  704. tmpExt.setReadOnly();
  705. File realExt = nameFor(
  706. id, "." + tmpEntry.getKey().getExtension()); //$NON-NLS-1$
  707. try {
  708. FileUtils.rename(tmpExt, realExt);
  709. } catch (IOException e) {
  710. File newExt = new File(realExt.getParentFile(),
  711. realExt.getName() + ".new"); //$NON-NLS-1$
  712. if (!tmpExt.renameTo(newExt))
  713. newExt = tmpExt;
  714. throw new IOException(MessageFormat.format(
  715. JGitText.get().panicCantRenameIndexFile, newExt,
  716. realExt));
  717. }
  718. }
  719. } finally {
  720. if (delete) {
  721. if (tmpPack.exists())
  722. tmpPack.delete();
  723. for (File tmpExt : tmpExts.values()) {
  724. if (tmpExt.exists())
  725. tmpExt.delete();
  726. }
  727. }
  728. }
  729. return repo.getObjectDatabase().openPack(realPack);
  730. } finally {
  731. pw.release();
  732. if (tmpPack != null && tmpPack.exists())
  733. tmpPack.delete();
  734. for (File tmpExt : tmpExts.values()) {
  735. if (tmpExt.exists())
  736. tmpExt.delete();
  737. }
  738. }
  739. }
  740. private File nameFor(String name, String ext) {
  741. File packdir = new File(repo.getObjectsDirectory(), "pack"); //$NON-NLS-1$
  742. return new File(packdir, "pack-" + name + ext); //$NON-NLS-1$
  743. }
  744. /**
  745. * A class holding statistical data for a FileRepository regarding how many
  746. * objects are stored as loose or packed objects
  747. */
  748. public class RepoStatistics {
  749. /**
  750. * The number of objects stored in pack files. If the same object is
  751. * stored in multiple pack files then it is counted as often as it
  752. * occurs in pack files.
  753. */
  754. public long numberOfPackedObjects;
  755. /**
  756. * The number of pack files
  757. */
  758. public long numberOfPackFiles;
  759. /**
  760. * The number of objects stored as loose objects.
  761. */
  762. public long numberOfLooseObjects;
  763. /**
  764. * The sum of the sizes of all files used to persist loose objects.
  765. */
  766. public long sizeOfLooseObjects;
  767. /**
  768. * The sum of the sizes of all pack files.
  769. */
  770. public long sizeOfPackedObjects;
  771. /**
  772. * The number of loose refs.
  773. */
  774. public long numberOfLooseRefs;
  775. /**
  776. * The number of refs stored in pack files.
  777. */
  778. public long numberOfPackedRefs;
  779. public String toString() {
  780. final StringBuilder b = new StringBuilder();
  781. b.append("numberOfPackedObjects=").append(numberOfPackedObjects); //$NON-NLS-1$
  782. b.append(", numberOfPackFiles=").append(numberOfPackFiles); //$NON-NLS-1$
  783. b.append(", numberOfLooseObjects=").append(numberOfLooseObjects); //$NON-NLS-1$
  784. b.append(", numberOfLooseRefs=").append(numberOfLooseRefs); //$NON-NLS-1$
  785. b.append(", numberOfPackedRefs=").append(numberOfPackedRefs); //$NON-NLS-1$
  786. b.append(", sizeOfLooseObjects=").append(sizeOfLooseObjects); //$NON-NLS-1$
  787. b.append(", sizeOfPackedObjects=").append(sizeOfPackedObjects); //$NON-NLS-1$
  788. return b.toString();
  789. }
  790. }
  791. /**
  792. * Returns the number of objects stored in pack files. If an object is
  793. * contained in multiple pack files it is counted as often as it occurs.
  794. *
  795. * @return the number of objects stored in pack files
  796. * @throws IOException
  797. */
  798. public RepoStatistics getStatistics() throws IOException {
  799. RepoStatistics ret = new RepoStatistics();
  800. Collection<PackFile> packs = repo.getObjectDatabase().getPacks();
  801. for (PackFile f : packs) {
  802. ret.numberOfPackedObjects += f.getIndex().getObjectCount();
  803. ret.numberOfPackFiles++;
  804. ret.sizeOfPackedObjects += f.getPackFile().length();
  805. }
  806. File objDir = repo.getObjectsDirectory();
  807. String[] fanout = objDir.list();
  808. if (fanout != null && fanout.length > 0) {
  809. for (String d : fanout) {
  810. if (d.length() != 2)
  811. continue;
  812. File[] entries = new File(objDir, d).listFiles();
  813. if (entries == null)
  814. continue;
  815. for (File f : entries) {
  816. if (f.getName().length() != Constants.OBJECT_ID_STRING_LENGTH - 2)
  817. continue;
  818. ret.numberOfLooseObjects++;
  819. ret.sizeOfLooseObjects += f.length();
  820. }
  821. }
  822. }
  823. RefDatabase refDb = repo.getRefDatabase();
  824. for (Ref r : refDb.getRefs(RefDatabase.ALL).values()) {
  825. Storage storage = r.getStorage();
  826. if (storage == Storage.LOOSE || storage == Storage.LOOSE_PACKED)
  827. ret.numberOfLooseRefs++;
  828. if (storage == Storage.PACKED || storage == Storage.LOOSE_PACKED)
  829. ret.numberOfPackedRefs++;
  830. }
  831. return ret;
  832. }
  833. /**
  834. * Set the progress monitor used for garbage collection methods.
  835. *
  836. * @param pm
  837. * @return this
  838. */
  839. public GC setProgressMonitor(ProgressMonitor pm) {
  840. this.pm = (pm == null) ? NullProgressMonitor.INSTANCE : pm;
  841. return this;
  842. }
  843. /**
  844. * During gc() or prune() each unreferenced, loose object which has been
  845. * created or modified in the last <code>expireAgeMillis</code> milliseconds
  846. * will not be pruned. Only older objects may be pruned. If set to 0 then
  847. * every object is a candidate for pruning.
  848. *
  849. * @param expireAgeMillis
  850. * minimal age of objects to be pruned in milliseconds.
  851. */
  852. public void setExpireAgeMillis(long expireAgeMillis) {
  853. this.expireAgeMillis = expireAgeMillis;
  854. expire = null;
  855. }
  856. /**
  857. * During gc() or prune() each unreferenced, loose object which has been
  858. * created or modified after or at <code>expire</code> will not be pruned.
  859. * Only older objects may be pruned. If set to null then every object is a
  860. * candidate for pruning.
  861. *
  862. * @param expire
  863. * instant in time which defines object expiration
  864. * objects with modification time before this instant are expired
  865. * objects with modification time newer or equal to this instant
  866. * are not expired
  867. */
  868. public void setExpire(Date expire) {
  869. this.expire = expire;
  870. expireAgeMillis = -1;
  871. }
  872. private static ObjectIdSet objectIdSet(final PackIndex idx) {
  873. return new ObjectIdSet() {
  874. public boolean contains(AnyObjectId objectId) {
  875. return idx.hasObject(objectId);
  876. }
  877. };
  878. }
  879. }