ObjectDirectory.java

  1. /*
  2.  * Copyright (C) 2009, 2022 Google Inc. and others
  3.  *
  4.  * This program and the accompanying materials are made available under the
  5.  * terms of the Eclipse Distribution License v. 1.0 which is available at
  6.  * https://www.eclipse.org/org/documents/edl-v10.php.
  7.  *
  8.  * SPDX-License-Identifier: BSD-3-Clause
  9.  */

  10. package org.eclipse.jgit.internal.storage.file;

  11. import static java.nio.charset.StandardCharsets.UTF_8;
  12. import static org.eclipse.jgit.internal.storage.pack.PackExt.PACK;
  13. import static org.eclipse.jgit.internal.storage.pack.PackExt.BITMAP_INDEX;
  14. import static org.eclipse.jgit.internal.storage.pack.PackExt.INDEX;

  15. import java.io.BufferedReader;
  16. import java.io.File;
  17. import java.io.FileNotFoundException;
  18. import java.io.IOException;
  19. import java.io.OutputStream;
  20. import java.nio.file.Files;
  21. import java.text.MessageFormat;
  22. import java.util.ArrayList;
  23. import java.util.Collection;
  24. import java.util.Collections;
  25. import java.util.HashSet;
  26. import java.util.List;
  27. import java.util.Objects;
  28. import java.util.Set;
  29. import java.util.concurrent.atomic.AtomicReference;

  30. import org.eclipse.jgit.internal.JGitText;
  31. import org.eclipse.jgit.internal.storage.pack.ObjectToPack;
  32. import org.eclipse.jgit.internal.storage.pack.PackExt;
  33. import org.eclipse.jgit.internal.storage.pack.PackWriter;
  34. import org.eclipse.jgit.lib.AbbreviatedObjectId;
  35. import org.eclipse.jgit.lib.AnyObjectId;
  36. import org.eclipse.jgit.lib.Config;
  37. import org.eclipse.jgit.lib.Constants;
  38. import org.eclipse.jgit.lib.ObjectDatabase;
  39. import org.eclipse.jgit.lib.ObjectId;
  40. import org.eclipse.jgit.lib.ObjectLoader;
  41. import org.eclipse.jgit.lib.RepositoryCache;
  42. import org.eclipse.jgit.lib.RepositoryCache.FileKey;
  43. import org.eclipse.jgit.util.FS;
  44. import org.eclipse.jgit.util.FileUtils;

  45. /**
  46.  * Traditional file system based {@link org.eclipse.jgit.lib.ObjectDatabase}.
  47.  * <p>
  48.  * This is the classical object database representation for a Git repository,
  49.  * where objects are stored loose by hashing them into directories by their
  50.  * {@link org.eclipse.jgit.lib.ObjectId}, or are stored in compressed containers
  51.  * known as {@link org.eclipse.jgit.internal.storage.file.Pack}s.
  52.  * <p>
  53.  * Optionally an object database can reference one or more alternates; other
  54.  * ObjectDatabase instances that are searched in addition to the current
  55.  * database.
  56.  * <p>
  57.  * Databases are divided into two halves: a half that is considered to be fast
  58.  * to search (the {@code PackFile}s), and a half that is considered to be slow
  59.  * to search (loose objects). When alternates are present the fast half is fully
  60.  * searched (recursively through all alternates) before the slow half is
  61.  * considered.
  62.  */
  63. public class ObjectDirectory extends FileObjectDatabase {
  64.     /** Maximum number of candidates offered as resolutions of abbreviation. */
  65.     private static final int RESOLVE_ABBREV_LIMIT = 256;

  66.     private final AlternateHandle handle = new AlternateHandle(this);

  67.     private final Config config;

  68.     private final File objects;

  69.     private final File infoDirectory;

  70.     private final LooseObjects loose;

  71.     private final PackDirectory packed;

  72.     private final PackDirectory preserved;

  73.     private final File alternatesFile;

  74.     private final FS fs;

  75.     private final AtomicReference<AlternateHandle[]> alternates;

  76.     private final File shallowFile;

  77.     private FileSnapshot shallowFileSnapshot = FileSnapshot.DIRTY;

  78.     private Set<ObjectId> shallowCommitsIds;

  79.     /**
  80.      * Initialize a reference to an on-disk object directory.
  81.      *
  82.      * @param cfg
  83.      *            configuration this directory consults for write settings.
  84.      * @param dir
  85.      *            the location of the <code>objects</code> directory.
  86.      * @param alternatePaths
  87.      *            a list of alternate object directories
  88.      * @param fs
  89.      *            the file system abstraction which will be necessary to perform
  90.      *            certain file system operations.
  91.      * @param shallowFile
  92.      *            file which contains IDs of shallow commits, null if shallow
  93.      *            commits handling should be turned off
  94.      * @throws java.io.IOException
  95.      *             an alternate object cannot be opened.
  96.      */
  97.     public ObjectDirectory(final Config cfg, final File dir,
  98.             File[] alternatePaths, FS fs, File shallowFile) throws IOException {
  99.         config = cfg;
  100.         objects = dir;
  101.         infoDirectory = new File(objects, "info"); //$NON-NLS-1$
  102.         File packDirectory = new File(objects, "pack"); //$NON-NLS-1$
  103.         File preservedDirectory = new File(packDirectory, "preserved"); //$NON-NLS-1$
  104.         alternatesFile = new File(objects, Constants.INFO_ALTERNATES);
  105.         loose = new LooseObjects(objects);
  106.         packed = new PackDirectory(config, packDirectory);
  107.         preserved = new PackDirectory(config, preservedDirectory);
  108.         this.fs = fs;
  109.         this.shallowFile = shallowFile;

  110.         alternates = new AtomicReference<>();
  111.         if (alternatePaths != null) {
  112.             AlternateHandle[] alt;

  113.             alt = new AlternateHandle[alternatePaths.length];
  114.             for (int i = 0; i < alternatePaths.length; i++)
  115.                 alt[i] = openAlternate(alternatePaths[i]);
  116.             alternates.set(alt);
  117.         }
  118.     }

  119.     /** {@inheritDoc} */
  120.     @Override
  121.     public final File getDirectory() {
  122.         return loose.getDirectory();
  123.     }

  124.     /**
  125.      * <p>Getter for the field <code>packDirectory</code>.</p>
  126.      *
  127.      * @return the location of the <code>pack</code> directory.
  128.      */
  129.     public final File getPackDirectory() {
  130.         return packed.getDirectory();
  131.     }

  132.     /**
  133.      * <p>Getter for the field <code>preservedDirectory</code>.</p>
  134.      *
  135.      * @return the location of the <code>preserved</code> directory.
  136.      */
  137.     public final File getPreservedDirectory() {
  138.         return preserved.getDirectory();
  139.     }

  140.     /** {@inheritDoc} */
  141.     @Override
  142.     public boolean exists() {
  143.         return fs.exists(objects);
  144.     }

  145.     /** {@inheritDoc} */
  146.     @Override
  147.     public void create() throws IOException {
  148.         loose.create();
  149.         FileUtils.mkdir(infoDirectory);
  150.         packed.create();
  151.     }

  152.     /** {@inheritDoc} */
  153.     @Override
  154.     public ObjectDirectoryInserter newInserter() {
  155.         return new ObjectDirectoryInserter(this, config);
  156.     }

  157.     /**
  158.      * Create a new inserter that inserts all objects as pack files, not loose
  159.      * objects.
  160.      *
  161.      * @return new inserter.
  162.      */
  163.     public PackInserter newPackInserter() {
  164.         return new PackInserter(this);
  165.     }

  166.     /** {@inheritDoc} */
  167.     @Override
  168.     public void close() {
  169.         loose.close();

  170.         packed.close();

  171.         // Fully close all loaded alternates and clear the alternate list.
  172.         AlternateHandle[] alt = alternates.get();
  173.         if (alt != null && alternates.compareAndSet(alt, null)) {
  174.             for(AlternateHandle od : alt)
  175.                 od.close();
  176.         }
  177.     }

  178.     /** {@inheritDoc} */
  179.     @Override
  180.     public Collection<Pack> getPacks() {
  181.         return packed.getPacks();
  182.     }

  183.     /** {@inheritDoc} */
  184.     @Override
  185.     public long getApproximateObjectCount() {
  186.         long count = 0;
  187.         for (Pack p : getPacks()) {
  188.             try {
  189.                 count += p.getIndex().getObjectCount();
  190.             } catch (IOException e) {
  191.                 return -1;
  192.             }
  193.         }
  194.         return count;
  195.     }

  196.     /**
  197.      * {@inheritDoc}
  198.      * <p>
  199.      * Add a single existing pack to the list of available pack files.
  200.      */
  201.     @Override
  202.     public Pack openPack(File pack) throws IOException {
  203.         PackFile pf;
  204.         try {
  205.             pf = new PackFile(pack);
  206.         } catch (IllegalArgumentException e) {
  207.             throw new IOException(
  208.                     MessageFormat.format(JGitText.get().notAValidPack, pack),
  209.                     e);
  210.         }

  211.         String p = pf.getName();
  212.         // TODO(nasserg): See if PackFile can do these checks instead
  213.         if (p.length() != 50 || !p.startsWith("pack-") //$NON-NLS-1$
  214.                 || !pf.getPackExt().equals(PACK)) {
  215.             throw new IOException(
  216.                     MessageFormat.format(JGitText.get().notAValidPack, pack));
  217.         }

  218.         PackFile bitmapIdx = pf.create(BITMAP_INDEX);
  219.         Pack res = new Pack(pack, bitmapIdx.exists() ? bitmapIdx : null);
  220.         packed.insert(res);
  221.         return res;
  222.     }

  223.     /** {@inheritDoc} */
  224.     @Override
  225.     public String toString() {
  226.         return "ObjectDirectory[" + getDirectory() + "]"; //$NON-NLS-1$ //$NON-NLS-2$
  227.     }

  228.     /** {@inheritDoc} */
  229.     @Override
  230.     public boolean has(AnyObjectId objectId) {
  231.         return loose.hasCached(objectId)
  232.                 || hasPackedOrLooseInSelfOrAlternate(objectId)
  233.                 || (restoreFromSelfOrAlternate(objectId, null)
  234.                         && hasPackedOrLooseInSelfOrAlternate(objectId));
  235.     }

  236.     private boolean hasPackedOrLooseInSelfOrAlternate(AnyObjectId objectId) {
  237.         return hasPackedInSelfOrAlternate(objectId, null)
  238.                 || hasLooseInSelfOrAlternate(objectId, null);
  239.     }

  240.     private boolean hasPackedInSelfOrAlternate(AnyObjectId objectId,
  241.             Set<AlternateHandle.Id> skips) {
  242.         if (hasPackedObject(objectId)) {
  243.             return true;
  244.         }
  245.         skips = addMe(skips);
  246.         for (AlternateHandle alt : myAlternates()) {
  247.             if (!skips.contains(alt.getId())) {
  248.                 if (alt.db.hasPackedInSelfOrAlternate(objectId, skips)) {
  249.                     return true;
  250.                 }
  251.             }
  252.         }
  253.         return false;
  254.     }

  255.     private boolean hasLooseInSelfOrAlternate(AnyObjectId objectId,
  256.             Set<AlternateHandle.Id> skips) {
  257.         if (loose.has(objectId)) {
  258.             return true;
  259.         }
  260.         skips = addMe(skips);
  261.         for (AlternateHandle alt : myAlternates()) {
  262.             if (!skips.contains(alt.getId())) {
  263.                 if (alt.db.hasLooseInSelfOrAlternate(objectId, skips)) {
  264.                     return true;
  265.                 }
  266.             }
  267.         }
  268.         return false;
  269.     }

  270.     boolean hasPackedObject(AnyObjectId objectId) {
  271.         return packed.has(objectId);
  272.     }

  273.     @Override
  274.     void resolve(Set<ObjectId> matches, AbbreviatedObjectId id)
  275.             throws IOException {
  276.         resolve(matches, id, null);
  277.     }

  278.     private void resolve(Set<ObjectId> matches, AbbreviatedObjectId id,
  279.             Set<AlternateHandle.Id> skips)
  280.             throws IOException {
  281.         if (!packed.resolve(matches, id, RESOLVE_ABBREV_LIMIT))
  282.             return;

  283.         if (!loose.resolve(matches, id, RESOLVE_ABBREV_LIMIT))
  284.             return;

  285.         skips = addMe(skips);
  286.         for (AlternateHandle alt : myAlternates()) {
  287.             if (!skips.contains(alt.getId())) {
  288.                 alt.db.resolve(matches, id, skips);
  289.                 if (matches.size() > RESOLVE_ABBREV_LIMIT) {
  290.                     return;
  291.                 }
  292.             }
  293.         }
  294.     }

  295.     @Override
  296.     ObjectLoader openObject(WindowCursor curs, AnyObjectId objectId)
  297.             throws IOException {
  298.         ObjectLoader ldr = openObjectWithoutRestoring(curs, objectId);
  299.         if (ldr == null && restoreFromSelfOrAlternate(objectId, null)) {
  300.             ldr = openObjectWithoutRestoring(curs, objectId);
  301.         }
  302.         return ldr;
  303.     }

  304.     private ObjectLoader openObjectWithoutRestoring(WindowCursor curs, AnyObjectId objectId)
  305.             throws IOException {
  306.         if (loose.hasCached(objectId)) {
  307.             ObjectLoader ldr = openLooseObject(curs, objectId);
  308.             if (ldr != null) {
  309.                 return ldr;
  310.             }
  311.         }
  312.         ObjectLoader ldr = openPackedFromSelfOrAlternate(curs, objectId, null);
  313.         if (ldr != null) {
  314.             return ldr;
  315.         }
  316.         return openLooseFromSelfOrAlternate(curs, objectId, null);
  317.     }

  318.     private ObjectLoader openPackedFromSelfOrAlternate(WindowCursor curs,
  319.             AnyObjectId objectId, Set<AlternateHandle.Id> skips) {
  320.         ObjectLoader ldr = openPackedObject(curs, objectId);
  321.         if (ldr != null) {
  322.             return ldr;
  323.         }
  324.         skips = addMe(skips);
  325.         for (AlternateHandle alt : myAlternates()) {
  326.             if (!skips.contains(alt.getId())) {
  327.                 ldr = alt.db.openPackedFromSelfOrAlternate(curs, objectId, skips);
  328.                 if (ldr != null) {
  329.                     return ldr;
  330.                 }
  331.             }
  332.         }
  333.         return null;
  334.     }

  335.     private ObjectLoader openLooseFromSelfOrAlternate(WindowCursor curs,
  336.             AnyObjectId objectId, Set<AlternateHandle.Id> skips)
  337.                     throws IOException {
  338.         ObjectLoader ldr = openLooseObject(curs, objectId);
  339.         if (ldr != null) {
  340.             return ldr;
  341.         }
  342.         skips = addMe(skips);
  343.         for (AlternateHandle alt : myAlternates()) {
  344.             if (!skips.contains(alt.getId())) {
  345.                 ldr = alt.db.openLooseFromSelfOrAlternate(curs, objectId, skips);
  346.                 if (ldr != null) {
  347.                     return ldr;
  348.                 }
  349.             }
  350.         }
  351.         return null;
  352.     }

  353.     ObjectLoader openPackedObject(WindowCursor curs, AnyObjectId objectId) {
  354.         return packed.open(curs, objectId);
  355.     }

  356.     @Override
  357.     ObjectLoader openLooseObject(WindowCursor curs, AnyObjectId id)
  358.             throws IOException {
  359.         return loose.open(curs, id);
  360.     }

  361.     @Override
  362.     long getObjectSize(WindowCursor curs, AnyObjectId id) throws IOException {
  363.         long sz = getObjectSizeWithoutRestoring(curs, id);
  364.         if (0 > sz && restoreFromSelfOrAlternate(id, null)) {
  365.             sz = getObjectSizeWithoutRestoring(curs, id);
  366.         }
  367.         return sz;
  368.     }

  369.     private long getObjectSizeWithoutRestoring(WindowCursor curs,
  370.             AnyObjectId id) throws IOException {
  371.         if (loose.hasCached(id)) {
  372.             long len = loose.getSize(curs, id);
  373.             if (0 <= len) {
  374.                 return len;
  375.             }
  376.         }
  377.         long len = getPackedSizeFromSelfOrAlternate(curs, id, null);
  378.         if (0 <= len) {
  379.             return len;
  380.         }
  381.         return getLooseSizeFromSelfOrAlternate(curs, id, null);
  382.     }

  383.     private long getPackedSizeFromSelfOrAlternate(WindowCursor curs,
  384.             AnyObjectId id, Set<AlternateHandle.Id> skips) {
  385.         long len = packed.getSize(curs, id);
  386.         if (0 <= len) {
  387.             return len;
  388.         }
  389.         skips = addMe(skips);
  390.         for (AlternateHandle alt : myAlternates()) {
  391.             if (!skips.contains(alt.getId())) {
  392.                 len = alt.db.getPackedSizeFromSelfOrAlternate(curs, id, skips);
  393.                 if (0 <= len) {
  394.                     return len;
  395.                 }
  396.             }
  397.         }
  398.         return -1;
  399.     }

  400.     private long getLooseSizeFromSelfOrAlternate(WindowCursor curs,
  401.             AnyObjectId id, Set<AlternateHandle.Id> skips) throws IOException {
  402.         long len = loose.getSize(curs, id);
  403.         if (0 <= len) {
  404.             return len;
  405.         }
  406.         skips = addMe(skips);
  407.         for (AlternateHandle alt : myAlternates()) {
  408.             if (!skips.contains(alt.getId())) {
  409.                 len = alt.db.getLooseSizeFromSelfOrAlternate(curs, id, skips);
  410.                 if (0 <= len) {
  411.                     return len;
  412.                 }
  413.             }
  414.         }
  415.         return -1;
  416.     }

  417.     @Override
  418.     void selectObjectRepresentation(PackWriter packer, ObjectToPack otp,
  419.             WindowCursor curs) throws IOException {
  420.         selectObjectRepresentation(packer, otp, curs, null);
  421.     }

  422.     private void selectObjectRepresentation(PackWriter packer, ObjectToPack otp,
  423.             WindowCursor curs, Set<AlternateHandle.Id> skips) throws IOException {
  424.         packed.selectRepresentation(packer, otp, curs);

  425.         skips = addMe(skips);
  426.         for (AlternateHandle h : myAlternates()) {
  427.             if (!skips.contains(h.getId())) {
  428.                 h.db.selectObjectRepresentation(packer, otp, curs, skips);
  429.             }
  430.         }
  431.     }

  432.     private boolean restoreFromSelfOrAlternate(AnyObjectId objectId,
  433.             Set<AlternateHandle.Id> skips) {
  434.         if (restoreFromSelf(objectId)) {
  435.             return true;
  436.         }

  437.         skips = addMe(skips);
  438.         for (AlternateHandle alt : myAlternates()) {
  439.             if (!skips.contains(alt.getId())) {
  440.                 if (alt.db.restoreFromSelfOrAlternate(objectId, skips)) {
  441.                     return true;
  442.                 }
  443.             }
  444.         }
  445.         return false;
  446.     }

  447.     private boolean restoreFromSelf(AnyObjectId objectId) {
  448.         Pack preservedPack = preserved.getPack(objectId);
  449.         if (preservedPack == null) {
  450.             return false;
  451.         }
  452.         PackFile preservedFile = new PackFile(preservedPack.getPackFile());
  453.         // Restore the index last since the set will be considered for use once
  454.         // the index appears.
  455.         for (PackExt ext : PackExt.values()) {
  456.             if (!INDEX.equals(ext)) {
  457.                 restore(preservedFile.create(ext));
  458.             }
  459.         }
  460.         restore(preservedFile.create(INDEX));
  461.         return true;
  462.     }

  463.     private boolean restore(PackFile preservedPack) {
  464.         PackFile restored = preservedPack
  465.                 .createForDirectory(packed.getDirectory());
  466.         try {
  467.             Files.createLink(restored.toPath(), preservedPack.toPath());
  468.         } catch (IOException e) {
  469.             return false;
  470.         }
  471.         return true;
  472.     }

  473.     @Override
  474.     InsertLooseObjectResult insertUnpackedObject(File tmp, ObjectId id,
  475.             boolean createDuplicate) throws IOException {
  476.         // If the object is already in the repository, remove temporary file.
  477.         //
  478.         if (loose.hasCached(id)) {
  479.             FileUtils.delete(tmp, FileUtils.RETRY);
  480.             return InsertLooseObjectResult.EXISTS_LOOSE;
  481.         }
  482.         if (!createDuplicate && has(id)) {
  483.             FileUtils.delete(tmp, FileUtils.RETRY);
  484.             return InsertLooseObjectResult.EXISTS_PACKED;
  485.         }
  486.         return loose.insert(tmp, id);
  487.     }

  488.     @Override
  489.     Config getConfig() {
  490.         return config;
  491.     }

  492.     @Override
  493.     FS getFS() {
  494.         return fs;
  495.     }

  496.     @Override
  497.     public Set<ObjectId> getShallowCommits() throws IOException {
  498.         if (shallowFile == null || !shallowFile.isFile())
  499.             return Collections.emptySet();

  500.         if (shallowFileSnapshot == null
  501.                 || shallowFileSnapshot.isModified(shallowFile)) {
  502.             try {
  503.                 shallowCommitsIds = FileUtils.readWithRetries(shallowFile,
  504.                         f -> {
  505.                             FileSnapshot newSnapshot = FileSnapshot.save(f);
  506.                             HashSet<ObjectId> result = new HashSet<>();
  507.                             try (BufferedReader reader = open(f)) {
  508.                                 String line;
  509.                                 while ((line = reader.readLine()) != null) {
  510.                                     if (!ObjectId.isId(line)) {
  511.                                         throw new IOException(
  512.                                                 MessageFormat.format(JGitText
  513.                                                         .get().badShallowLine,
  514.                                                         f.getAbsolutePath(),
  515.                                                         line));

  516.                                     }
  517.                                     result.add(ObjectId.fromString(line));
  518.                                 }
  519.                             }
  520.                             shallowFileSnapshot = newSnapshot;
  521.                             return result;
  522.                         });
  523.             } catch (IOException e) {
  524.                 throw e;
  525.             } catch (Exception e) {
  526.                 throw new IOException(
  527.                         MessageFormat.format(JGitText.get().readShallowFailed,
  528.                                 shallowFile.getAbsolutePath()),
  529.                         e);
  530.             }
  531.         }

  532.         return shallowCommitsIds;
  533.     }

  534.     @Override
  535.     public void setShallowCommits(Set<ObjectId> shallowCommits) throws IOException {
  536.         this.shallowCommitsIds = shallowCommits;
  537.         LockFile lock = new LockFile(shallowFile);
  538.         if (!lock.lock()) {
  539.             throw new IOException(MessageFormat.format(JGitText.get().lockError,
  540.                     shallowFile.getAbsolutePath()));
  541.         }

  542.         try {
  543.             if (shallowCommits.isEmpty()) {
  544.                 if (shallowFile.isFile()) {
  545.                     shallowFile.delete();
  546.                 }
  547.             } else {
  548.                 try (OutputStream out = lock.getOutputStream()) {
  549.                     for (ObjectId shallowCommit : shallowCommits) {
  550.                         byte[] buf = new byte[Constants.OBJECT_ID_STRING_LENGTH + 1];
  551.                         shallowCommit.copyTo(buf, 0);
  552.                         buf[Constants.OBJECT_ID_STRING_LENGTH] = '\n';
  553.                         out.write(buf);
  554.                     }
  555.                 } finally {
  556.                     lock.commit();
  557.                 }
  558.             }
  559.         } finally {
  560.             lock.unlock();
  561.         }

  562.         if (shallowCommits.isEmpty()) {
  563.             shallowFileSnapshot = FileSnapshot.DIRTY;
  564.         } else {
  565.             shallowFileSnapshot = FileSnapshot.save(shallowFile);
  566.         }
  567.     }

  568.     void closeAllPackHandles(File packFile) {
  569.         // if the packfile already exists (because we are rewriting a
  570.         // packfile for the same set of objects maybe with different
  571.         // PackConfig) then make sure we get rid of all handles on the file.
  572.         // Windows will not allow for rename otherwise.
  573.         if (packFile.exists()) {
  574.             for (Pack p : packed.getPacks()) {
  575.                 if (packFile.getPath().equals(p.getPackFile().getPath())) {
  576.                     p.close();
  577.                     break;
  578.                 }
  579.             }
  580.         }
  581.     }

  582.     AlternateHandle[] myAlternates() {
  583.         AlternateHandle[] alt = alternates.get();
  584.         if (alt == null) {
  585.             synchronized (alternates) {
  586.                 alt = alternates.get();
  587.                 if (alt == null) {
  588.                     try {
  589.                         alt = loadAlternates();
  590.                     } catch (IOException e) {
  591.                         alt = new AlternateHandle[0];
  592.                     }
  593.                     alternates.set(alt);
  594.                 }
  595.             }
  596.         }
  597.         return alt;
  598.     }

  599.     Set<AlternateHandle.Id> addMe(Set<AlternateHandle.Id> skips) {
  600.         if (skips == null) {
  601.             skips = new HashSet<>();
  602.         }
  603.         skips.add(handle.getId());
  604.         return skips;
  605.     }

  606.     private AlternateHandle[] loadAlternates() throws IOException {
  607.         final List<AlternateHandle> l = new ArrayList<>(4);
  608.         try (BufferedReader br = open(alternatesFile)) {
  609.             String line;
  610.             while ((line = br.readLine()) != null) {
  611.                 l.add(openAlternate(line));
  612.             }
  613.         }
  614.         return l.toArray(new AlternateHandle[0]);
  615.     }

  616.     private static BufferedReader open(File f)
  617.             throws IOException, FileNotFoundException {
  618.         return Files.newBufferedReader(f.toPath(), UTF_8);
  619.     }

  620.     private AlternateHandle openAlternate(String location)
  621.             throws IOException {
  622.         final File objdir = fs.resolve(objects, location);
  623.         return openAlternate(objdir);
  624.     }

  625.     private AlternateHandle openAlternate(File objdir) throws IOException {
  626.         final File parent = objdir.getParentFile();
  627.         if (FileKey.isGitRepository(parent, fs)) {
  628.             FileKey key = FileKey.exact(parent, fs);
  629.             FileRepository db = (FileRepository) RepositoryCache.open(key);
  630.             return new AlternateRepository(db);
  631.         }

  632.         ObjectDirectory db = new ObjectDirectory(config, objdir, null, fs, null);
  633.         return new AlternateHandle(db);
  634.     }

  635.     /**
  636.      * Compute the location of a loose object file.
  637.      */
  638.     @Override
  639.     public File fileFor(AnyObjectId objectId) {
  640.         return loose.fileFor(objectId);
  641.     }

  642.     static class AlternateHandle {
  643.         static class Id {
  644.             private final String alternateId;

  645.             public Id(File object) {
  646.                 String id = null;
  647.                 try {
  648.                     // resolve symbolic links to their final target:
  649.                     id = object.toPath().toRealPath().normalize().toString();
  650.                 } catch (Exception ignored) {
  651.                     // id == null
  652.                 }
  653.                 this.alternateId = id;
  654.             }

  655.             @Override
  656.             public boolean equals(Object o) {
  657.                 if (o == this) {
  658.                     return true;
  659.                 }
  660.                 if (o == null || !(o instanceof Id)) {
  661.                     return false;
  662.                 }
  663.                 Id aId = (Id) o;
  664.                 return Objects.equals(alternateId, aId.alternateId);
  665.             }

  666.             @Override
  667.             public int hashCode() {
  668.                 if (alternateId == null) {
  669.                     return 1;
  670.                 }
  671.                 return alternateId.hashCode();
  672.             }
  673.         }

  674.         final ObjectDirectory db;

  675.         private AlternateHandle.Id id;

  676.         AlternateHandle(ObjectDirectory db) {
  677.             this.db = db;
  678.         }

  679.         void close() {
  680.             db.close();
  681.         }

  682.         public synchronized Id getId() {
  683.             if (id == null) {
  684.                 id = new AlternateHandle.Id(db.objects);
  685.             }
  686.             return id;
  687.         }
  688.     }

  689.     static class AlternateRepository extends AlternateHandle {
  690.         final FileRepository repository;

  691.         AlternateRepository(FileRepository r) {
  692.             super(r.getObjectDatabase());
  693.             repository = r;
  694.         }

  695.         @Override
  696.         void close() {
  697.             repository.close();
  698.         }
  699.     }

  700.     /** {@inheritDoc} */
  701.     @Override
  702.     public ObjectDatabase newCachedDatabase() {
  703.         return newCachedFileObjectDatabase();
  704.     }

  705.     CachedObjectDirectory newCachedFileObjectDatabase() {
  706.         return new CachedObjectDirectory(this);
  707.     }

  708.     AlternateHandle.Id getAlternateId() {
  709.         return handle.getId();
  710.     }
  711. }