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

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