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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  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.storage.file;
  44. import java.io.BufferedReader;
  45. import java.io.File;
  46. import java.io.FileInputStream;
  47. import java.io.FileNotFoundException;
  48. import java.io.FileReader;
  49. import java.io.IOException;
  50. import java.text.MessageFormat;
  51. import java.util.ArrayList;
  52. import java.util.Arrays;
  53. import java.util.Collection;
  54. import java.util.Collections;
  55. import java.util.HashMap;
  56. import java.util.HashSet;
  57. import java.util.List;
  58. import java.util.Map;
  59. import java.util.Set;
  60. import java.util.concurrent.atomic.AtomicReference;
  61. import org.eclipse.jgit.JGitText;
  62. import org.eclipse.jgit.errors.PackMismatchException;
  63. import org.eclipse.jgit.lib.AbbreviatedObjectId;
  64. import org.eclipse.jgit.lib.AnyObjectId;
  65. import org.eclipse.jgit.lib.Config;
  66. import org.eclipse.jgit.lib.Constants;
  67. import org.eclipse.jgit.lib.ObjectDatabase;
  68. import org.eclipse.jgit.lib.ObjectId;
  69. import org.eclipse.jgit.lib.ObjectLoader;
  70. import org.eclipse.jgit.lib.RepositoryCache;
  71. import org.eclipse.jgit.lib.RepositoryCache.FileKey;
  72. import org.eclipse.jgit.storage.pack.ObjectToPack;
  73. import org.eclipse.jgit.storage.pack.PackWriter;
  74. import org.eclipse.jgit.util.FS;
  75. import org.eclipse.jgit.util.FileUtils;
  76. /**
  77. * Traditional file system based {@link ObjectDatabase}.
  78. * <p>
  79. * This is the classical object database representation for a Git repository,
  80. * where objects are stored loose by hashing them into directories by their
  81. * {@link ObjectId}, or are stored in compressed containers known as
  82. * {@link PackFile}s.
  83. * <p>
  84. * Optionally an object database can reference one or more alternates; other
  85. * ObjectDatabase instances that are searched in addition to the current
  86. * database.
  87. * <p>
  88. * Databases are divided into two halves: a half that is considered to be fast
  89. * to search (the {@code PackFile}s), and a half that is considered to be slow
  90. * to search (loose objects). When alternates are present the fast half is fully
  91. * searched (recursively through all alternates) before the slow half is
  92. * considered.
  93. */
  94. public class ObjectDirectory extends FileObjectDatabase {
  95. private static final PackList NO_PACKS = new PackList(
  96. FileSnapshot.DIRTY, new PackFile[0]);
  97. /** Maximum number of candidates offered as resolutions of abbreviation. */
  98. private static final int RESOLVE_ABBREV_LIMIT = 256;
  99. private final Config config;
  100. private final File objects;
  101. private final File infoDirectory;
  102. private final File packDirectory;
  103. private final File alternatesFile;
  104. private final AtomicReference<PackList> packList;
  105. private final FS fs;
  106. private final AtomicReference<AlternateHandle[]> alternates;
  107. private final UnpackedObjectCache unpackedObjectCache;
  108. /**
  109. * Initialize a reference to an on-disk object directory.
  110. *
  111. * @param cfg
  112. * configuration this directory consults for write settings.
  113. * @param dir
  114. * the location of the <code>objects</code> directory.
  115. * @param alternatePaths
  116. * a list of alternate object directories
  117. * @param fs
  118. * the file system abstraction which will be necessary to perform
  119. * certain file system operations.
  120. * @throws IOException
  121. * an alternate object cannot be opened.
  122. */
  123. public ObjectDirectory(final Config cfg, final File dir,
  124. File[] alternatePaths, FS fs) throws IOException {
  125. config = cfg;
  126. objects = dir;
  127. infoDirectory = new File(objects, "info");
  128. packDirectory = new File(objects, "pack");
  129. alternatesFile = new File(infoDirectory, "alternates");
  130. packList = new AtomicReference<PackList>(NO_PACKS);
  131. unpackedObjectCache = new UnpackedObjectCache();
  132. this.fs = fs;
  133. alternates = new AtomicReference<AlternateHandle[]>();
  134. if (alternatePaths != null) {
  135. AlternateHandle[] alt;
  136. alt = new AlternateHandle[alternatePaths.length];
  137. for (int i = 0; i < alternatePaths.length; i++)
  138. alt[i] = openAlternate(alternatePaths[i]);
  139. alternates.set(alt);
  140. }
  141. }
  142. /**
  143. * @return the location of the <code>objects</code> directory.
  144. */
  145. public final File getDirectory() {
  146. return objects;
  147. }
  148. @Override
  149. public boolean exists() {
  150. return objects.exists();
  151. }
  152. @Override
  153. public void create() throws IOException {
  154. FileUtils.mkdirs(objects);
  155. FileUtils.mkdir(infoDirectory);
  156. FileUtils.mkdir(packDirectory);
  157. }
  158. @Override
  159. public ObjectDirectoryInserter newInserter() {
  160. return new ObjectDirectoryInserter(this, config);
  161. }
  162. @Override
  163. public void close() {
  164. unpackedObjectCache.clear();
  165. final PackList packs = packList.get();
  166. packList.set(NO_PACKS);
  167. for (final PackFile p : packs.packs)
  168. p.close();
  169. // Fully close all loaded alternates and clear the alternate list.
  170. AlternateHandle[] alt = alternates.get();
  171. if (alt != null) {
  172. alternates.set(null);
  173. for(final AlternateHandle od : alt)
  174. od.close();
  175. }
  176. }
  177. /**
  178. * Compute the location of a loose object file.
  179. *
  180. * @param objectId
  181. * identity of the loose object to map to the directory.
  182. * @return location of the object, if it were to exist as a loose object.
  183. */
  184. @Override
  185. public File fileFor(final AnyObjectId objectId) {
  186. return super.fileFor(objectId);
  187. }
  188. /**
  189. * @return unmodifiable collection of all known pack files local to this
  190. * directory. Most recent packs are presented first. Packs most
  191. * likely to contain more recent objects appear before packs
  192. * containing objects referenced by commits further back in the
  193. * history of the repository.
  194. */
  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. * @param idx
  208. * path of the corresponding index file.
  209. * @return the pack that was opened and added to the database.
  210. * @throws IOException
  211. * index file could not be opened, read, or is not recognized as
  212. * a Git pack file index.
  213. */
  214. public PackFile openPack(final File pack, final File idx)
  215. throws IOException {
  216. final String p = pack.getName();
  217. final String i = idx.getName();
  218. if (p.length() != 50 || !p.startsWith("pack-") || !p.endsWith(".pack"))
  219. throw new IOException(MessageFormat.format(JGitText.get().notAValidPack, pack));
  220. if (i.length() != 49 || !i.startsWith("pack-") || !i.endsWith(".idx"))
  221. throw new IOException(MessageFormat.format(JGitText.get().notAValidPack, idx));
  222. if (!p.substring(0, 45).equals(i.substring(0, 45)))
  223. throw new IOException(MessageFormat.format(JGitText.get().packDoesNotMatchIndex, pack));
  224. PackFile res = new PackFile(idx, pack);
  225. insertPack(res);
  226. return res;
  227. }
  228. @Override
  229. public String toString() {
  230. return "ObjectDirectory[" + getDirectory() + "]";
  231. }
  232. boolean hasObject1(final AnyObjectId objectId) {
  233. if (unpackedObjectCache.isUnpacked(objectId))
  234. return true;
  235. for (final PackFile p : packList.get().packs) {
  236. try {
  237. if (p.hasObject(objectId)) {
  238. return true;
  239. }
  240. } catch (IOException e) {
  241. // The hasObject call should have only touched the index,
  242. // so any failure here indicates the index is unreadable
  243. // by this process, and the pack is likewise not readable.
  244. //
  245. removePack(p);
  246. continue;
  247. }
  248. }
  249. return false;
  250. }
  251. void resolve(Set<ObjectId> matches, AbbreviatedObjectId id)
  252. throws IOException {
  253. // Go through the packs once. If we didn't find any resolutions
  254. // scan for new packs and check once more.
  255. //
  256. int oldSize = matches.size();
  257. PackList pList = packList.get();
  258. for (;;) {
  259. for (PackFile p : pList.packs) {
  260. try {
  261. p.resolve(matches, id, RESOLVE_ABBREV_LIMIT);
  262. } catch (IOException e) {
  263. // Assume the pack is corrupted.
  264. //
  265. removePack(p);
  266. }
  267. if (matches.size() > RESOLVE_ABBREV_LIMIT)
  268. return;
  269. }
  270. if (matches.size() == oldSize) {
  271. PackList nList = scanPacks(pList);
  272. if (nList == pList || nList.packs.length == 0)
  273. break;
  274. pList = nList;
  275. continue;
  276. }
  277. break;
  278. }
  279. String fanOut = id.name().substring(0, 2);
  280. String[] entries = new File(getDirectory(), fanOut).list();
  281. if (entries != null) {
  282. for (String e : entries) {
  283. if (e.length() != Constants.OBJECT_ID_STRING_LENGTH - 2)
  284. continue;
  285. try {
  286. ObjectId entId = ObjectId.fromString(fanOut + e);
  287. if (id.prefixCompare(entId) == 0)
  288. matches.add(entId);
  289. } catch (IllegalArgumentException notId) {
  290. continue;
  291. }
  292. if (matches.size() > RESOLVE_ABBREV_LIMIT)
  293. return;
  294. }
  295. }
  296. for (AlternateHandle alt : myAlternates()) {
  297. alt.db.resolve(matches, id);
  298. if (matches.size() > RESOLVE_ABBREV_LIMIT)
  299. return;
  300. }
  301. }
  302. ObjectLoader openObject1(final WindowCursor curs,
  303. final AnyObjectId objectId) throws IOException {
  304. if (unpackedObjectCache.isUnpacked(objectId)) {
  305. ObjectLoader ldr = openObject2(curs, objectId.name(), objectId);
  306. if (ldr != null)
  307. return ldr;
  308. else
  309. unpackedObjectCache.remove(objectId);
  310. }
  311. PackList pList = packList.get();
  312. SEARCH: for (;;) {
  313. for (final PackFile p : pList.packs) {
  314. try {
  315. final ObjectLoader ldr = p.get(curs, objectId);
  316. if (ldr != null)
  317. return ldr;
  318. } catch (PackMismatchException e) {
  319. // Pack was modified; refresh the entire pack list.
  320. //
  321. pList = scanPacks(pList);
  322. continue SEARCH;
  323. } catch (IOException e) {
  324. // Assume the pack is corrupted.
  325. //
  326. removePack(p);
  327. }
  328. }
  329. return null;
  330. }
  331. }
  332. long getObjectSize1(final WindowCursor curs, final AnyObjectId objectId)
  333. throws IOException {
  334. PackList pList = packList.get();
  335. SEARCH: for (;;) {
  336. for (final PackFile p : pList.packs) {
  337. try {
  338. long sz = p.getObjectSize(curs, objectId);
  339. if (0 <= sz)
  340. return sz;
  341. } catch (PackMismatchException e) {
  342. // Pack was modified; refresh the entire pack list.
  343. //
  344. pList = scanPacks(pList);
  345. continue SEARCH;
  346. } catch (IOException e) {
  347. // Assume the pack is corrupted.
  348. //
  349. removePack(p);
  350. }
  351. }
  352. return -1;
  353. }
  354. }
  355. @Override
  356. long getObjectSize2(WindowCursor curs, String objectName,
  357. AnyObjectId objectId) throws IOException {
  358. try {
  359. File path = fileFor(objectName);
  360. FileInputStream in = new FileInputStream(path);
  361. try {
  362. return UnpackedObject.getSize(in, objectId, curs);
  363. } finally {
  364. in.close();
  365. }
  366. } catch (FileNotFoundException noFile) {
  367. return -1;
  368. }
  369. }
  370. @Override
  371. void selectObjectRepresentation(PackWriter packer, ObjectToPack otp,
  372. WindowCursor curs) throws IOException {
  373. PackList pList = packList.get();
  374. SEARCH: for (;;) {
  375. for (final PackFile p : pList.packs) {
  376. try {
  377. LocalObjectRepresentation rep = p.representation(curs, otp);
  378. if (rep != null)
  379. packer.select(otp, rep);
  380. } catch (PackMismatchException e) {
  381. // Pack was modified; refresh the entire pack list.
  382. //
  383. pList = scanPacks(pList);
  384. continue SEARCH;
  385. } catch (IOException e) {
  386. // Assume the pack is corrupted.
  387. //
  388. removePack(p);
  389. }
  390. }
  391. break SEARCH;
  392. }
  393. for (AlternateHandle h : myAlternates())
  394. h.db.selectObjectRepresentation(packer, otp, curs);
  395. }
  396. boolean hasObject2(final String objectName) {
  397. return fileFor(objectName).exists();
  398. }
  399. ObjectLoader openObject2(final WindowCursor curs,
  400. final String objectName, final AnyObjectId objectId)
  401. throws IOException {
  402. try {
  403. File path = fileFor(objectName);
  404. FileInputStream in = new FileInputStream(path);
  405. try {
  406. unpackedObjectCache.add(objectId);
  407. return UnpackedObject.open(in, path, objectId, curs);
  408. } finally {
  409. in.close();
  410. }
  411. } catch (FileNotFoundException noFile) {
  412. unpackedObjectCache.remove(objectId);
  413. return null;
  414. }
  415. }
  416. @Override
  417. InsertLooseObjectResult insertUnpackedObject(File tmp, ObjectId id,
  418. boolean createDuplicate) throws IOException {
  419. // If the object is already in the repository, remove temporary file.
  420. //
  421. if (unpackedObjectCache.isUnpacked(id)) {
  422. FileUtils.delete(tmp);
  423. return InsertLooseObjectResult.EXISTS_LOOSE;
  424. }
  425. if (!createDuplicate && has(id)) {
  426. FileUtils.delete(tmp);
  427. return InsertLooseObjectResult.EXISTS_PACKED;
  428. }
  429. final File dst = fileFor(id);
  430. if (dst.exists()) {
  431. // We want to be extra careful and avoid replacing an object
  432. // that already exists. We can't be sure renameTo() would
  433. // fail on all platforms if dst exists, so we check first.
  434. //
  435. FileUtils.delete(tmp);
  436. return InsertLooseObjectResult.EXISTS_LOOSE;
  437. }
  438. if (tmp.renameTo(dst)) {
  439. dst.setReadOnly();
  440. unpackedObjectCache.add(id);
  441. return InsertLooseObjectResult.INSERTED;
  442. }
  443. // Maybe the directory doesn't exist yet as the object
  444. // directories are always lazily created. Note that we
  445. // try the rename first as the directory likely does exist.
  446. //
  447. FileUtils.mkdir(dst.getParentFile());
  448. if (tmp.renameTo(dst)) {
  449. dst.setReadOnly();
  450. unpackedObjectCache.add(id);
  451. return InsertLooseObjectResult.INSERTED;
  452. }
  453. if (!createDuplicate && has(id)) {
  454. FileUtils.delete(tmp);
  455. return InsertLooseObjectResult.EXISTS_PACKED;
  456. }
  457. // The object failed to be renamed into its proper
  458. // location and it doesn't exist in the repository
  459. // either. We really don't know what went wrong, so
  460. // fail.
  461. //
  462. FileUtils.delete(tmp);
  463. return InsertLooseObjectResult.FAILURE;
  464. }
  465. boolean tryAgain1() {
  466. final PackList old = packList.get();
  467. if (old.snapshot.isModified(packDirectory))
  468. return old != scanPacks(old);
  469. return false;
  470. }
  471. Config getConfig() {
  472. return config;
  473. }
  474. @Override
  475. FS getFS() {
  476. return fs;
  477. }
  478. private void insertPack(final PackFile pf) {
  479. PackList o, n;
  480. do {
  481. o = packList.get();
  482. // If the pack in question is already present in the list
  483. // (picked up by a concurrent thread that did a scan?) we
  484. // do not want to insert it a second time.
  485. //
  486. final PackFile[] oldList = o.packs;
  487. final String name = pf.getPackFile().getName();
  488. for (PackFile p : oldList) {
  489. if (PackFile.SORT.compare(pf, p) < 0)
  490. break;
  491. if (name.equals(p.getPackFile().getName()))
  492. return;
  493. }
  494. final PackFile[] newList = new PackFile[1 + oldList.length];
  495. newList[0] = pf;
  496. System.arraycopy(oldList, 0, newList, 1, oldList.length);
  497. n = new PackList(o.snapshot, newList);
  498. } while (!packList.compareAndSet(o, n));
  499. }
  500. private void removePack(final PackFile deadPack) {
  501. PackList o, n;
  502. do {
  503. o = packList.get();
  504. final PackFile[] oldList = o.packs;
  505. final int j = indexOf(oldList, deadPack);
  506. if (j < 0)
  507. break;
  508. final PackFile[] newList = new PackFile[oldList.length - 1];
  509. System.arraycopy(oldList, 0, newList, 0, j);
  510. System.arraycopy(oldList, j + 1, newList, j, newList.length - j);
  511. n = new PackList(o.snapshot, newList);
  512. } while (!packList.compareAndSet(o, n));
  513. deadPack.close();
  514. }
  515. private static int indexOf(final PackFile[] list, final PackFile pack) {
  516. for (int i = 0; i < list.length; i++) {
  517. if (list[i] == pack)
  518. return i;
  519. }
  520. return -1;
  521. }
  522. private PackList scanPacks(final PackList original) {
  523. synchronized (packList) {
  524. PackList o, n;
  525. do {
  526. o = packList.get();
  527. if (o != original) {
  528. // Another thread did the scan for us, while we
  529. // were blocked on the monitor above.
  530. //
  531. return o;
  532. }
  533. n = scanPacksImpl(o);
  534. if (n == o)
  535. return n;
  536. } while (!packList.compareAndSet(o, n));
  537. return n;
  538. }
  539. }
  540. private PackList scanPacksImpl(final PackList old) {
  541. final Map<String, PackFile> forReuse = reuseMap(old);
  542. final FileSnapshot snapshot = FileSnapshot.save(packDirectory);
  543. final Set<String> names = listPackDirectory();
  544. final List<PackFile> list = new ArrayList<PackFile>(names.size() >> 2);
  545. boolean foundNew = false;
  546. for (final String indexName : names) {
  547. // Must match "pack-[0-9a-f]{40}.idx" to be an index.
  548. //
  549. if (indexName.length() != 49 || !indexName.endsWith(".idx"))
  550. continue;
  551. final String base = indexName.substring(0, indexName.length() - 4);
  552. final String packName = base + ".pack";
  553. if (!names.contains(packName)) {
  554. // Sometimes C Git's HTTP fetch transport leaves a
  555. // .idx file behind and does not download the .pack.
  556. // We have to skip over such useless indexes.
  557. //
  558. continue;
  559. }
  560. final PackFile oldPack = forReuse.remove(packName);
  561. if (oldPack != null) {
  562. list.add(oldPack);
  563. continue;
  564. }
  565. final File packFile = new File(packDirectory, packName);
  566. final File idxFile = new File(packDirectory, indexName);
  567. list.add(new PackFile(idxFile, packFile));
  568. foundNew = true;
  569. }
  570. // If we did not discover any new files, the modification time was not
  571. // changed, and we did not remove any files, then the set of files is
  572. // the same as the set we were given. Instead of building a new object
  573. // return the same collection.
  574. //
  575. if (!foundNew && forReuse.isEmpty() && snapshot.equals(old.snapshot)) {
  576. old.snapshot.setClean(snapshot);
  577. return old;
  578. }
  579. for (final PackFile p : forReuse.values()) {
  580. p.close();
  581. }
  582. if (list.isEmpty())
  583. return new PackList(snapshot, NO_PACKS.packs);
  584. final PackFile[] r = list.toArray(new PackFile[list.size()]);
  585. Arrays.sort(r, PackFile.SORT);
  586. return new PackList(snapshot, r);
  587. }
  588. private static Map<String, PackFile> reuseMap(final PackList old) {
  589. final Map<String, PackFile> forReuse = new HashMap<String, PackFile>();
  590. for (final PackFile p : old.packs) {
  591. if (p.invalid()) {
  592. // The pack instance is corrupted, and cannot be safely used
  593. // again. Do not include it in our reuse map.
  594. //
  595. p.close();
  596. continue;
  597. }
  598. final PackFile prior = forReuse.put(p.getPackFile().getName(), p);
  599. if (prior != null) {
  600. // This should never occur. It should be impossible for us
  601. // to have two pack files with the same name, as all of them
  602. // came out of the same directory. If it does, we promised to
  603. // close any PackFiles we did not reuse, so close the second,
  604. // readers are likely to be actively using the first.
  605. //
  606. forReuse.put(prior.getPackFile().getName(), prior);
  607. p.close();
  608. }
  609. }
  610. return forReuse;
  611. }
  612. private Set<String> listPackDirectory() {
  613. final String[] nameList = packDirectory.list();
  614. if (nameList == null)
  615. return Collections.emptySet();
  616. final Set<String> nameSet = new HashSet<String>(nameList.length << 1);
  617. for (final String name : nameList) {
  618. if (name.startsWith("pack-"))
  619. nameSet.add(name);
  620. }
  621. return nameSet;
  622. }
  623. AlternateHandle[] myAlternates() {
  624. AlternateHandle[] alt = alternates.get();
  625. if (alt == null) {
  626. synchronized (alternates) {
  627. alt = alternates.get();
  628. if (alt == null) {
  629. try {
  630. alt = loadAlternates();
  631. } catch (IOException e) {
  632. alt = new AlternateHandle[0];
  633. }
  634. alternates.set(alt);
  635. }
  636. }
  637. }
  638. return alt;
  639. }
  640. private AlternateHandle[] loadAlternates() throws IOException {
  641. final List<AlternateHandle> l = new ArrayList<AlternateHandle>(4);
  642. final BufferedReader br = open(alternatesFile);
  643. try {
  644. String line;
  645. while ((line = br.readLine()) != null) {
  646. l.add(openAlternate(line));
  647. }
  648. } finally {
  649. br.close();
  650. }
  651. return l.toArray(new AlternateHandle[l.size()]);
  652. }
  653. private static BufferedReader open(final File f)
  654. throws FileNotFoundException {
  655. return new BufferedReader(new FileReader(f));
  656. }
  657. private AlternateHandle openAlternate(final String location)
  658. throws IOException {
  659. final File objdir = fs.resolve(objects, location);
  660. return openAlternate(objdir);
  661. }
  662. private AlternateHandle openAlternate(File objdir) throws IOException {
  663. final File parent = objdir.getParentFile();
  664. if (FileKey.isGitRepository(parent, fs)) {
  665. FileKey key = FileKey.exact(parent, fs);
  666. FileRepository db = (FileRepository) RepositoryCache.open(key);
  667. return new AlternateRepository(db);
  668. }
  669. ObjectDirectory db = new ObjectDirectory(config, objdir, null, fs);
  670. return new AlternateHandle(db);
  671. }
  672. private static final class PackList {
  673. /** State just before reading the pack directory. */
  674. final FileSnapshot snapshot;
  675. /** All known packs, sorted by {@link PackFile#SORT}. */
  676. final PackFile[] packs;
  677. PackList(final FileSnapshot monitor, final PackFile[] packs) {
  678. this.snapshot = monitor;
  679. this.packs = packs;
  680. }
  681. }
  682. @Override
  683. public ObjectDatabase newCachedDatabase() {
  684. return newCachedFileObjectDatabase();
  685. }
  686. FileObjectDatabase newCachedFileObjectDatabase() {
  687. return new CachedObjectDirectory(this);
  688. }
  689. }