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.

ObjectDirectory.java 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929
  1. /*
  2. * Copyright (C) 2009, Google Inc.
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.internal.storage.file;
  44. import static org.eclipse.jgit.internal.storage.pack.PackExt.INDEX;
  45. import static org.eclipse.jgit.internal.storage.pack.PackExt.PACK;
  46. import java.io.BufferedReader;
  47. import java.io.File;
  48. import java.io.FileInputStream;
  49. import java.io.FileNotFoundException;
  50. import java.io.FileReader;
  51. import java.io.IOException;
  52. import java.text.MessageFormat;
  53. import java.util.ArrayList;
  54. import java.util.Arrays;
  55. import java.util.Collection;
  56. import java.util.Collections;
  57. import java.util.HashMap;
  58. import java.util.HashSet;
  59. import java.util.List;
  60. import java.util.Map;
  61. import java.util.Set;
  62. import java.util.concurrent.atomic.AtomicReference;
  63. import org.eclipse.jgit.errors.PackMismatchException;
  64. import org.eclipse.jgit.internal.JGitText;
  65. import org.eclipse.jgit.internal.storage.pack.ObjectToPack;
  66. import org.eclipse.jgit.internal.storage.pack.PackExt;
  67. import org.eclipse.jgit.internal.storage.pack.PackWriter;
  68. import org.eclipse.jgit.lib.AbbreviatedObjectId;
  69. import org.eclipse.jgit.lib.AnyObjectId;
  70. import org.eclipse.jgit.lib.Config;
  71. import org.eclipse.jgit.lib.Constants;
  72. import org.eclipse.jgit.lib.ObjectDatabase;
  73. import org.eclipse.jgit.lib.ObjectId;
  74. import org.eclipse.jgit.lib.ObjectLoader;
  75. import org.eclipse.jgit.lib.RepositoryCache;
  76. import org.eclipse.jgit.lib.RepositoryCache.FileKey;
  77. import org.eclipse.jgit.util.FS;
  78. import org.eclipse.jgit.util.FileUtils;
  79. /**
  80. * Traditional file system based {@link ObjectDatabase}.
  81. * <p>
  82. * This is the classical object database representation for a Git repository,
  83. * where objects are stored loose by hashing them into directories by their
  84. * {@link ObjectId}, or are stored in compressed containers known as
  85. * {@link PackFile}s.
  86. * <p>
  87. * Optionally an object database can reference one or more alternates; other
  88. * ObjectDatabase instances that are searched in addition to the current
  89. * database.
  90. * <p>
  91. * Databases are divided into two halves: a half that is considered to be fast
  92. * to search (the {@code PackFile}s), and a half that is considered to be slow
  93. * to search (loose objects). When alternates are present the fast half is fully
  94. * searched (recursively through all alternates) before the slow half is
  95. * considered.
  96. */
  97. public class ObjectDirectory extends FileObjectDatabase {
  98. private static final PackList NO_PACKS = new PackList(
  99. FileSnapshot.DIRTY, new PackFile[0]);
  100. /** Maximum number of candidates offered as resolutions of abbreviation. */
  101. private static final int RESOLVE_ABBREV_LIMIT = 256;
  102. private final Config config;
  103. private final File objects;
  104. private final File infoDirectory;
  105. private final File packDirectory;
  106. private final File alternatesFile;
  107. private final AtomicReference<PackList> packList;
  108. private final FS fs;
  109. private final AtomicReference<AlternateHandle[]> alternates;
  110. private final UnpackedObjectCache unpackedObjectCache;
  111. private final File shallowFile;
  112. private FileSnapshot shallowFileSnapshot = FileSnapshot.DIRTY;
  113. private Set<ObjectId> shallowCommitsIds;
  114. /**
  115. * Initialize a reference to an on-disk object directory.
  116. *
  117. * @param cfg
  118. * configuration this directory consults for write settings.
  119. * @param dir
  120. * the location of the <code>objects</code> directory.
  121. * @param alternatePaths
  122. * a list of alternate object directories
  123. * @param fs
  124. * the file system abstraction which will be necessary to perform
  125. * certain file system operations.
  126. * @param shallowFile
  127. * file which contains IDs of shallow commits, null if shallow
  128. * commits handling should be turned off
  129. * @throws IOException
  130. * an alternate object cannot be opened.
  131. */
  132. public ObjectDirectory(final Config cfg, final File dir,
  133. File[] alternatePaths, FS fs, File shallowFile) throws IOException {
  134. config = cfg;
  135. objects = dir;
  136. infoDirectory = new File(objects, "info"); //$NON-NLS-1$
  137. packDirectory = new File(objects, "pack"); //$NON-NLS-1$
  138. alternatesFile = new File(infoDirectory, "alternates"); //$NON-NLS-1$
  139. packList = new AtomicReference<PackList>(NO_PACKS);
  140. unpackedObjectCache = new UnpackedObjectCache();
  141. this.fs = fs;
  142. this.shallowFile = shallowFile;
  143. alternates = new AtomicReference<AlternateHandle[]>();
  144. if (alternatePaths != null) {
  145. AlternateHandle[] alt;
  146. alt = new AlternateHandle[alternatePaths.length];
  147. for (int i = 0; i < alternatePaths.length; i++)
  148. alt[i] = openAlternate(alternatePaths[i]);
  149. alternates.set(alt);
  150. }
  151. }
  152. /**
  153. * @return the location of the <code>objects</code> directory.
  154. */
  155. public final File getDirectory() {
  156. return objects;
  157. }
  158. @Override
  159. public boolean exists() {
  160. return fs.exists(objects);
  161. }
  162. @Override
  163. public void create() throws IOException {
  164. FileUtils.mkdirs(objects);
  165. FileUtils.mkdir(infoDirectory);
  166. FileUtils.mkdir(packDirectory);
  167. }
  168. @Override
  169. public ObjectDirectoryInserter newInserter() {
  170. return new ObjectDirectoryInserter(this, config);
  171. }
  172. @Override
  173. public void close() {
  174. unpackedObjectCache.clear();
  175. final PackList packs = packList.get();
  176. if (packs != NO_PACKS && packList.compareAndSet(packs, NO_PACKS)) {
  177. for (PackFile p : packs.packs)
  178. p.close();
  179. }
  180. // Fully close all loaded alternates and clear the alternate list.
  181. AlternateHandle[] alt = alternates.get();
  182. if (alt != null && alternates.compareAndSet(alt, null)) {
  183. for(final AlternateHandle od : alt)
  184. od.close();
  185. }
  186. }
  187. /**
  188. * @return unmodifiable collection of all known pack files local to this
  189. * directory. Most recent packs are presented first. Packs most
  190. * likely to contain more recent objects appear before packs
  191. * containing objects referenced by commits further back in the
  192. * history of the repository.
  193. */
  194. @Override
  195. public Collection<PackFile> getPacks() {
  196. PackList list = packList.get();
  197. if (list == NO_PACKS)
  198. list = scanPacks(list);
  199. PackFile[] packs = list.packs;
  200. return Collections.unmodifiableCollection(Arrays.asList(packs));
  201. }
  202. /**
  203. * Add a single existing pack to the list of available pack files.
  204. *
  205. * @param pack
  206. * path of the pack file to open.
  207. * @return the pack that was opened and added to the database.
  208. * @throws IOException
  209. * index file could not be opened, read, or is not recognized as
  210. * a Git pack file index.
  211. */
  212. public PackFile openPack(final File pack)
  213. throws IOException {
  214. final String p = pack.getName();
  215. if (p.length() != 50 || !p.startsWith("pack-") || !p.endsWith(".pack")) //$NON-NLS-1$ //$NON-NLS-2$
  216. throw new IOException(MessageFormat.format(JGitText.get().notAValidPack, pack));
  217. // The pack and index are assumed to exist. The existence of other
  218. // extensions needs to be explicitly checked.
  219. //
  220. int extensions = PACK.getBit() | INDEX.getBit();
  221. final String base = p.substring(0, p.length() - 4);
  222. for (PackExt ext : PackExt.values()) {
  223. if ((extensions & ext.getBit()) == 0) {
  224. final String name = base + ext.getExtension();
  225. if (new File(pack.getParentFile(), name).exists())
  226. extensions |= ext.getBit();
  227. }
  228. }
  229. PackFile res = new PackFile(pack, extensions);
  230. insertPack(res);
  231. return res;
  232. }
  233. @Override
  234. public String toString() {
  235. return "ObjectDirectory[" + getDirectory() + "]"; //$NON-NLS-1$ //$NON-NLS-2$
  236. }
  237. @Override
  238. public boolean has(AnyObjectId objectId) {
  239. return unpackedObjectCache.isUnpacked(objectId)
  240. || hasPackedInSelfOrAlternate(objectId)
  241. || hasLooseInSelfOrAlternate(objectId);
  242. }
  243. private boolean hasPackedInSelfOrAlternate(AnyObjectId objectId) {
  244. if (hasPackedObject(objectId))
  245. return true;
  246. for (AlternateHandle alt : myAlternates()) {
  247. if (alt.db.hasPackedInSelfOrAlternate(objectId))
  248. return true;
  249. }
  250. return false;
  251. }
  252. private boolean hasLooseInSelfOrAlternate(AnyObjectId objectId) {
  253. if (fileFor(objectId).exists())
  254. return true;
  255. for (AlternateHandle alt : myAlternates()) {
  256. if (alt.db.hasLooseInSelfOrAlternate(objectId))
  257. return true;
  258. }
  259. return false;
  260. }
  261. boolean hasPackedObject(AnyObjectId objectId) {
  262. PackList pList;
  263. do {
  264. pList = packList.get();
  265. for (PackFile p : pList.packs) {
  266. try {
  267. if (p.hasObject(objectId))
  268. return true;
  269. } catch (IOException e) {
  270. // The hasObject call should have only touched the index,
  271. // so any failure here indicates the index is unreadable
  272. // by this process, and the pack is likewise not readable.
  273. removePack(p);
  274. }
  275. }
  276. } while (searchPacksAgain(pList));
  277. return false;
  278. }
  279. @Override
  280. void resolve(Set<ObjectId> matches, AbbreviatedObjectId id)
  281. throws IOException {
  282. // Go through the packs once. If we didn't find any resolutions
  283. // scan for new packs and check once more.
  284. int oldSize = matches.size();
  285. PackList pList;
  286. do {
  287. pList = packList.get();
  288. for (PackFile p : pList.packs) {
  289. try {
  290. p.resolve(matches, id, RESOLVE_ABBREV_LIMIT);
  291. } catch (IOException e) {
  292. // Assume the pack is corrupted.
  293. //
  294. removePack(p);
  295. }
  296. if (matches.size() > RESOLVE_ABBREV_LIMIT)
  297. return;
  298. }
  299. } while (matches.size() == oldSize && searchPacksAgain(pList));
  300. String fanOut = id.name().substring(0, 2);
  301. String[] entries = new File(getDirectory(), fanOut).list();
  302. if (entries != null) {
  303. for (String e : entries) {
  304. if (e.length() != Constants.OBJECT_ID_STRING_LENGTH - 2)
  305. continue;
  306. try {
  307. ObjectId entId = ObjectId.fromString(fanOut + e);
  308. if (id.prefixCompare(entId) == 0)
  309. matches.add(entId);
  310. } catch (IllegalArgumentException notId) {
  311. continue;
  312. }
  313. if (matches.size() > RESOLVE_ABBREV_LIMIT)
  314. return;
  315. }
  316. }
  317. for (AlternateHandle alt : myAlternates()) {
  318. alt.db.resolve(matches, id);
  319. if (matches.size() > RESOLVE_ABBREV_LIMIT)
  320. return;
  321. }
  322. }
  323. @Override
  324. ObjectLoader openObject(WindowCursor curs, AnyObjectId objectId)
  325. throws IOException {
  326. if (unpackedObjectCache.isUnpacked(objectId)) {
  327. ObjectLoader ldr = openLooseObject(curs, objectId);
  328. if (ldr != null)
  329. return ldr;
  330. }
  331. ObjectLoader ldr = openPackedFromSelfOrAlternate(curs, objectId);
  332. if (ldr != null)
  333. return ldr;
  334. return openLooseFromSelfOrAlternate(curs, objectId);
  335. }
  336. private ObjectLoader openPackedFromSelfOrAlternate(WindowCursor curs,
  337. AnyObjectId objectId) {
  338. ObjectLoader ldr = openPackedObject(curs, objectId);
  339. if (ldr != null)
  340. return ldr;
  341. for (AlternateHandle alt : myAlternates()) {
  342. ldr = alt.db.openPackedFromSelfOrAlternate(curs, objectId);
  343. if (ldr != null)
  344. return ldr;
  345. }
  346. return null;
  347. }
  348. private ObjectLoader openLooseFromSelfOrAlternate(WindowCursor curs,
  349. AnyObjectId objectId) throws IOException {
  350. ObjectLoader ldr = openLooseObject(curs, objectId);
  351. if (ldr != null)
  352. return ldr;
  353. for (AlternateHandle alt : myAlternates()) {
  354. ldr = alt.db.openLooseFromSelfOrAlternate(curs, objectId);
  355. if (ldr != null)
  356. return ldr;
  357. }
  358. return null;
  359. }
  360. ObjectLoader openPackedObject(WindowCursor curs, AnyObjectId objectId) {
  361. PackList pList;
  362. do {
  363. SEARCH: for (;;) {
  364. pList = packList.get();
  365. for (PackFile p : pList.packs) {
  366. try {
  367. ObjectLoader ldr = p.get(curs, objectId);
  368. if (ldr != null)
  369. return ldr;
  370. } catch (PackMismatchException e) {
  371. // Pack was modified; refresh the entire pack list.
  372. if (searchPacksAgain(pList))
  373. continue SEARCH;
  374. } catch (IOException e) {
  375. // Assume the pack is corrupted.
  376. removePack(p);
  377. }
  378. }
  379. break SEARCH;
  380. }
  381. } while (searchPacksAgain(pList));
  382. return null;
  383. }
  384. ObjectLoader openLooseObject(WindowCursor curs, AnyObjectId id)
  385. throws IOException {
  386. try {
  387. File path = fileFor(id);
  388. FileInputStream in = new FileInputStream(path);
  389. try {
  390. unpackedObjectCache.add(id);
  391. return UnpackedObject.open(in, path, id, curs);
  392. } finally {
  393. in.close();
  394. }
  395. } catch (FileNotFoundException noFile) {
  396. unpackedObjectCache.remove(id);
  397. return null;
  398. }
  399. }
  400. long getObjectSize(WindowCursor curs, AnyObjectId id)
  401. throws IOException {
  402. if (unpackedObjectCache.isUnpacked(id)) {
  403. long len = getLooseObjectSize(curs, id);
  404. if (0 <= len)
  405. return len;
  406. }
  407. long len = getPackedSizeFromSelfOrAlternate(curs, id);
  408. if (0 <= len)
  409. return len;
  410. return getLooseSizeFromSelfOrAlternate(curs, id);
  411. }
  412. private long getPackedSizeFromSelfOrAlternate(WindowCursor curs,
  413. AnyObjectId id) {
  414. long len = getPackedObjectSize(curs, id);
  415. if (0 <= len)
  416. return len;
  417. for (AlternateHandle alt : myAlternates()) {
  418. len = alt.db.getPackedSizeFromSelfOrAlternate(curs, id);
  419. if (0 <= len)
  420. return len;
  421. }
  422. return -1;
  423. }
  424. private long getLooseSizeFromSelfOrAlternate(WindowCursor curs,
  425. AnyObjectId id) throws IOException {
  426. long len = getLooseObjectSize(curs, id);
  427. if (0 <= len)
  428. return len;
  429. for (AlternateHandle alt : myAlternates()) {
  430. len = alt.db.getLooseSizeFromSelfOrAlternate(curs, id);
  431. if (0 <= len)
  432. return len;
  433. }
  434. return -1;
  435. }
  436. private long getPackedObjectSize(WindowCursor curs, AnyObjectId id) {
  437. PackList pList;
  438. do {
  439. SEARCH: for (;;) {
  440. pList = packList.get();
  441. for (PackFile p : pList.packs) {
  442. try {
  443. long len = p.getObjectSize(curs, id);
  444. if (0 <= len)
  445. return len;
  446. } catch (PackMismatchException e) {
  447. // Pack was modified; refresh the entire pack list.
  448. if (searchPacksAgain(pList))
  449. continue SEARCH;
  450. } catch (IOException e) {
  451. // Assume the pack is corrupted.
  452. removePack(p);
  453. }
  454. }
  455. break SEARCH;
  456. }
  457. } while (searchPacksAgain(pList));
  458. return -1;
  459. }
  460. private long getLooseObjectSize(WindowCursor curs, AnyObjectId id)
  461. throws IOException {
  462. try {
  463. FileInputStream in = new FileInputStream(fileFor(id));
  464. try {
  465. unpackedObjectCache.add(id);
  466. return UnpackedObject.getSize(in, id, curs);
  467. } finally {
  468. in.close();
  469. }
  470. } catch (FileNotFoundException noFile) {
  471. unpackedObjectCache.remove(id);
  472. return -1;
  473. }
  474. }
  475. @Override
  476. void selectObjectRepresentation(PackWriter packer, ObjectToPack otp,
  477. WindowCursor curs) throws IOException {
  478. PackList pList = packList.get();
  479. SEARCH: for (;;) {
  480. for (final PackFile p : pList.packs) {
  481. try {
  482. LocalObjectRepresentation rep = p.representation(curs, otp);
  483. if (rep != null)
  484. packer.select(otp, rep);
  485. } catch (PackMismatchException e) {
  486. // Pack was modified; refresh the entire pack list.
  487. //
  488. pList = scanPacks(pList);
  489. continue SEARCH;
  490. } catch (IOException e) {
  491. // Assume the pack is corrupted.
  492. //
  493. removePack(p);
  494. }
  495. }
  496. break SEARCH;
  497. }
  498. for (AlternateHandle h : myAlternates())
  499. h.db.selectObjectRepresentation(packer, otp, curs);
  500. }
  501. @Override
  502. InsertLooseObjectResult insertUnpackedObject(File tmp, ObjectId id,
  503. boolean createDuplicate) throws IOException {
  504. // If the object is already in the repository, remove temporary file.
  505. //
  506. if (unpackedObjectCache.isUnpacked(id)) {
  507. FileUtils.delete(tmp);
  508. return InsertLooseObjectResult.EXISTS_LOOSE;
  509. }
  510. if (!createDuplicate && has(id)) {
  511. FileUtils.delete(tmp);
  512. return InsertLooseObjectResult.EXISTS_PACKED;
  513. }
  514. final File dst = fileFor(id);
  515. if (fs.exists(dst)) {
  516. // We want to be extra careful and avoid replacing an object
  517. // that already exists. We can't be sure renameTo() would
  518. // fail on all platforms if dst exists, so we check first.
  519. //
  520. FileUtils.delete(tmp);
  521. return InsertLooseObjectResult.EXISTS_LOOSE;
  522. }
  523. if (tmp.renameTo(dst)) {
  524. dst.setReadOnly();
  525. unpackedObjectCache.add(id);
  526. return InsertLooseObjectResult.INSERTED;
  527. }
  528. // Maybe the directory doesn't exist yet as the object
  529. // directories are always lazily created. Note that we
  530. // try the rename first as the directory likely does exist.
  531. //
  532. FileUtils.mkdir(dst.getParentFile(), true);
  533. if (tmp.renameTo(dst)) {
  534. dst.setReadOnly();
  535. unpackedObjectCache.add(id);
  536. return InsertLooseObjectResult.INSERTED;
  537. }
  538. if (!createDuplicate && has(id)) {
  539. FileUtils.delete(tmp);
  540. return InsertLooseObjectResult.EXISTS_PACKED;
  541. }
  542. // The object failed to be renamed into its proper
  543. // location and it doesn't exist in the repository
  544. // either. We really don't know what went wrong, so
  545. // fail.
  546. //
  547. FileUtils.delete(tmp);
  548. return InsertLooseObjectResult.FAILURE;
  549. }
  550. private boolean searchPacksAgain(PackList old) {
  551. return old.snapshot.isModified(packDirectory) && old != scanPacks(old);
  552. }
  553. Config getConfig() {
  554. return config;
  555. }
  556. @Override
  557. FS getFS() {
  558. return fs;
  559. }
  560. @Override
  561. Set<ObjectId> getShallowCommits() throws IOException {
  562. if (shallowFile == null || !shallowFile.isFile())
  563. return Collections.emptySet();
  564. if (shallowFileSnapshot == null
  565. || shallowFileSnapshot.isModified(shallowFile)) {
  566. shallowCommitsIds = new HashSet<ObjectId>();
  567. final BufferedReader reader = open(shallowFile);
  568. try {
  569. String line;
  570. while ((line = reader.readLine()) != null)
  571. shallowCommitsIds.add(ObjectId.fromString(line));
  572. } finally {
  573. reader.close();
  574. }
  575. shallowFileSnapshot = FileSnapshot.save(shallowFile);
  576. }
  577. return shallowCommitsIds;
  578. }
  579. private void insertPack(final PackFile pf) {
  580. PackList o, n;
  581. do {
  582. o = packList.get();
  583. // If the pack in question is already present in the list
  584. // (picked up by a concurrent thread that did a scan?) we
  585. // do not want to insert it a second time.
  586. //
  587. final PackFile[] oldList = o.packs;
  588. final String name = pf.getPackFile().getName();
  589. for (PackFile p : oldList) {
  590. if (PackFile.SORT.compare(pf, p) < 0)
  591. break;
  592. if (name.equals(p.getPackFile().getName()))
  593. return;
  594. }
  595. final PackFile[] newList = new PackFile[1 + oldList.length];
  596. newList[0] = pf;
  597. System.arraycopy(oldList, 0, newList, 1, oldList.length);
  598. n = new PackList(o.snapshot, newList);
  599. } while (!packList.compareAndSet(o, n));
  600. }
  601. private void removePack(final PackFile deadPack) {
  602. PackList o, n;
  603. do {
  604. o = packList.get();
  605. final PackFile[] oldList = o.packs;
  606. final int j = indexOf(oldList, deadPack);
  607. if (j < 0)
  608. break;
  609. final PackFile[] newList = new PackFile[oldList.length - 1];
  610. System.arraycopy(oldList, 0, newList, 0, j);
  611. System.arraycopy(oldList, j + 1, newList, j, newList.length - j);
  612. n = new PackList(o.snapshot, newList);
  613. } while (!packList.compareAndSet(o, n));
  614. deadPack.close();
  615. }
  616. private static int indexOf(final PackFile[] list, final PackFile pack) {
  617. for (int i = 0; i < list.length; i++) {
  618. if (list[i] == pack)
  619. return i;
  620. }
  621. return -1;
  622. }
  623. private PackList scanPacks(final PackList original) {
  624. synchronized (packList) {
  625. PackList o, n;
  626. do {
  627. o = packList.get();
  628. if (o != original) {
  629. // Another thread did the scan for us, while we
  630. // were blocked on the monitor above.
  631. //
  632. return o;
  633. }
  634. n = scanPacksImpl(o);
  635. if (n == o)
  636. return n;
  637. } while (!packList.compareAndSet(o, n));
  638. return n;
  639. }
  640. }
  641. private PackList scanPacksImpl(final PackList old) {
  642. final Map<String, PackFile> forReuse = reuseMap(old);
  643. final FileSnapshot snapshot = FileSnapshot.save(packDirectory);
  644. final Set<String> names = listPackDirectory();
  645. final List<PackFile> list = new ArrayList<PackFile>(names.size() >> 2);
  646. boolean foundNew = false;
  647. for (final String indexName : names) {
  648. // Must match "pack-[0-9a-f]{40}.idx" to be an index.
  649. //
  650. if (indexName.length() != 49 || !indexName.endsWith(".idx")) //$NON-NLS-1$
  651. continue;
  652. final String base = indexName.substring(0, indexName.length() - 3);
  653. int extensions = 0;
  654. for (PackExt ext : PackExt.values()) {
  655. if (names.contains(base + ext.getExtension()))
  656. extensions |= ext.getBit();
  657. }
  658. if ((extensions & PACK.getBit()) == 0) {
  659. // Sometimes C Git's HTTP fetch transport leaves a
  660. // .idx file behind and does not download the .pack.
  661. // We have to skip over such useless indexes.
  662. //
  663. continue;
  664. }
  665. final String packName = base + PACK.getExtension();
  666. final PackFile oldPack = forReuse.remove(packName);
  667. if (oldPack != null) {
  668. list.add(oldPack);
  669. continue;
  670. }
  671. final File packFile = new File(packDirectory, packName);
  672. list.add(new PackFile(packFile, extensions));
  673. foundNew = true;
  674. }
  675. // If we did not discover any new files, the modification time was not
  676. // changed, and we did not remove any files, then the set of files is
  677. // the same as the set we were given. Instead of building a new object
  678. // return the same collection.
  679. //
  680. if (!foundNew && forReuse.isEmpty() && snapshot.equals(old.snapshot)) {
  681. old.snapshot.setClean(snapshot);
  682. return old;
  683. }
  684. for (final PackFile p : forReuse.values()) {
  685. p.close();
  686. }
  687. if (list.isEmpty())
  688. return new PackList(snapshot, NO_PACKS.packs);
  689. final PackFile[] r = list.toArray(new PackFile[list.size()]);
  690. Arrays.sort(r, PackFile.SORT);
  691. return new PackList(snapshot, r);
  692. }
  693. private static Map<String, PackFile> reuseMap(final PackList old) {
  694. final Map<String, PackFile> forReuse = new HashMap<String, PackFile>();
  695. for (final PackFile p : old.packs) {
  696. if (p.invalid()) {
  697. // The pack instance is corrupted, and cannot be safely used
  698. // again. Do not include it in our reuse map.
  699. //
  700. p.close();
  701. continue;
  702. }
  703. final PackFile prior = forReuse.put(p.getPackFile().getName(), p);
  704. if (prior != null) {
  705. // This should never occur. It should be impossible for us
  706. // to have two pack files with the same name, as all of them
  707. // came out of the same directory. If it does, we promised to
  708. // close any PackFiles we did not reuse, so close the second,
  709. // readers are likely to be actively using the first.
  710. //
  711. forReuse.put(prior.getPackFile().getName(), prior);
  712. p.close();
  713. }
  714. }
  715. return forReuse;
  716. }
  717. private Set<String> listPackDirectory() {
  718. final String[] nameList = packDirectory.list();
  719. if (nameList == null)
  720. return Collections.emptySet();
  721. final Set<String> nameSet = new HashSet<String>(nameList.length << 1);
  722. for (final String name : nameList) {
  723. if (name.startsWith("pack-")) //$NON-NLS-1$
  724. nameSet.add(name);
  725. }
  726. return nameSet;
  727. }
  728. AlternateHandle[] myAlternates() {
  729. AlternateHandle[] alt = alternates.get();
  730. if (alt == null) {
  731. synchronized (alternates) {
  732. alt = alternates.get();
  733. if (alt == null) {
  734. try {
  735. alt = loadAlternates();
  736. } catch (IOException e) {
  737. alt = new AlternateHandle[0];
  738. }
  739. alternates.set(alt);
  740. }
  741. }
  742. }
  743. return alt;
  744. }
  745. private AlternateHandle[] loadAlternates() throws IOException {
  746. final List<AlternateHandle> l = new ArrayList<AlternateHandle>(4);
  747. final BufferedReader br = open(alternatesFile);
  748. try {
  749. String line;
  750. while ((line = br.readLine()) != null) {
  751. l.add(openAlternate(line));
  752. }
  753. } finally {
  754. br.close();
  755. }
  756. return l.toArray(new AlternateHandle[l.size()]);
  757. }
  758. private static BufferedReader open(final File f)
  759. throws FileNotFoundException {
  760. return new BufferedReader(new FileReader(f));
  761. }
  762. private AlternateHandle openAlternate(final String location)
  763. throws IOException {
  764. final File objdir = fs.resolve(objects, location);
  765. return openAlternate(objdir);
  766. }
  767. private AlternateHandle openAlternate(File objdir) throws IOException {
  768. final File parent = objdir.getParentFile();
  769. if (FileKey.isGitRepository(parent, fs)) {
  770. FileKey key = FileKey.exact(parent, fs);
  771. FileRepository db = (FileRepository) RepositoryCache.open(key);
  772. return new AlternateRepository(db);
  773. }
  774. ObjectDirectory db = new ObjectDirectory(config, objdir, null, fs, null);
  775. return new AlternateHandle(db);
  776. }
  777. /**
  778. * Compute the location of a loose object file.
  779. *
  780. * @param objectId
  781. * identity of the loose object to map to the directory.
  782. * @return location of the object, if it were to exist as a loose object.
  783. */
  784. public File fileFor(AnyObjectId objectId) {
  785. String n = objectId.name();
  786. String d = n.substring(0, 2);
  787. String f = n.substring(2);
  788. return new File(new File(getDirectory(), d), f);
  789. }
  790. private static final class PackList {
  791. /** State just before reading the pack directory. */
  792. final FileSnapshot snapshot;
  793. /** All known packs, sorted by {@link PackFile#SORT}. */
  794. final PackFile[] packs;
  795. PackList(final FileSnapshot monitor, final PackFile[] packs) {
  796. this.snapshot = monitor;
  797. this.packs = packs;
  798. }
  799. }
  800. static class AlternateHandle {
  801. final ObjectDirectory db;
  802. AlternateHandle(ObjectDirectory db) {
  803. this.db = db;
  804. }
  805. void close() {
  806. db.close();
  807. }
  808. }
  809. static class AlternateRepository extends AlternateHandle {
  810. final FileRepository repository;
  811. AlternateRepository(FileRepository r) {
  812. super(r.getObjectDatabase());
  813. repository = r;
  814. }
  815. void close() {
  816. repository.close();
  817. }
  818. }
  819. @Override
  820. public ObjectDatabase newCachedDatabase() {
  821. return newCachedFileObjectDatabase();
  822. }
  823. CachedObjectDirectory newCachedFileObjectDatabase() {
  824. return new CachedObjectDirectory(this);
  825. }
  826. }