BaseRepositoryBuilder.java

  1. /*
  2.  * Copyright (C) 2010, 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.lib;

  44. import static org.eclipse.jgit.lib.ConfigConstants.CONFIG_CORE_SECTION;
  45. import static org.eclipse.jgit.lib.ConfigConstants.CONFIG_KEY_BARE;
  46. import static org.eclipse.jgit.lib.ConfigConstants.CONFIG_KEY_WORKTREE;
  47. import static org.eclipse.jgit.lib.Constants.DOT_GIT;
  48. import static org.eclipse.jgit.lib.Constants.GIT_ALTERNATE_OBJECT_DIRECTORIES_KEY;
  49. import static org.eclipse.jgit.lib.Constants.GIT_CEILING_DIRECTORIES_KEY;
  50. import static org.eclipse.jgit.lib.Constants.GIT_DIR_KEY;
  51. import static org.eclipse.jgit.lib.Constants.GIT_INDEX_FILE_KEY;
  52. import static org.eclipse.jgit.lib.Constants.GIT_OBJECT_DIRECTORY_KEY;
  53. import static org.eclipse.jgit.lib.Constants.GIT_WORK_TREE_KEY;

  54. import java.io.File;
  55. import java.io.IOException;
  56. import java.text.MessageFormat;
  57. import java.util.Collection;
  58. import java.util.LinkedList;
  59. import java.util.List;

  60. import org.eclipse.jgit.errors.ConfigInvalidException;
  61. import org.eclipse.jgit.errors.RepositoryNotFoundException;
  62. import org.eclipse.jgit.internal.JGitText;
  63. import org.eclipse.jgit.internal.storage.file.FileRepository;
  64. import org.eclipse.jgit.lib.RepositoryCache.FileKey;
  65. import org.eclipse.jgit.storage.file.FileBasedConfig;
  66. import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
  67. import org.eclipse.jgit.util.FS;
  68. import org.eclipse.jgit.util.IO;
  69. import org.eclipse.jgit.util.RawParseUtils;
  70. import org.eclipse.jgit.util.SystemReader;

  71. /**
  72.  * Base builder to customize repository construction.
  73.  * <p>
  74.  * Repository implementations may subclass this builder in order to add custom
  75.  * repository detection methods.
  76.  *
  77.  * @param <B>
  78.  *            type of the repository builder.
  79.  * @param <R>
  80.  *            type of the repository that is constructed.
  81.  * @see RepositoryBuilder
  82.  * @see FileRepositoryBuilder
  83.  */
  84. public class BaseRepositoryBuilder<B extends BaseRepositoryBuilder, R extends Repository> {
  85.     private static boolean isSymRef(byte[] ref) {
  86.         if (ref.length < 9)
  87.             return false;
  88.         return /**/ref[0] == 'g' //
  89.                 && ref[1] == 'i' //
  90.                 && ref[2] == 't' //
  91.                 && ref[3] == 'd' //
  92.                 && ref[4] == 'i' //
  93.                 && ref[5] == 'r' //
  94.                 && ref[6] == ':' //
  95.                 && ref[7] == ' ';
  96.     }

  97.     private static File getSymRef(File workTree, File dotGit, FS fs)
  98.             throws IOException {
  99.         byte[] content = IO.readFully(dotGit);
  100.         if (!isSymRef(content))
  101.             throw new IOException(MessageFormat.format(
  102.                     JGitText.get().invalidGitdirRef, dotGit.getAbsolutePath()));

  103.         int pathStart = 8;
  104.         int lineEnd = RawParseUtils.nextLF(content, pathStart);
  105.         while (content[lineEnd - 1] == '\n' ||
  106.                (content[lineEnd - 1] == '\r' && SystemReader.getInstance().isWindows()))
  107.             lineEnd--;
  108.         if (lineEnd == pathStart)
  109.             throw new IOException(MessageFormat.format(
  110.                     JGitText.get().invalidGitdirRef, dotGit.getAbsolutePath()));

  111.         String gitdirPath = RawParseUtils.decode(content, pathStart, lineEnd);
  112.         File gitdirFile = fs.resolve(workTree, gitdirPath);
  113.         if (gitdirFile.isAbsolute())
  114.             return gitdirFile;
  115.         else
  116.             return new File(workTree, gitdirPath).getCanonicalFile();
  117.     }

  118.     private FS fs;

  119.     private File gitDir;

  120.     private File objectDirectory;

  121.     private List<File> alternateObjectDirectories;

  122.     private File indexFile;

  123.     private File workTree;

  124.     /** Directories limiting the search for a Git repository. */
  125.     private List<File> ceilingDirectories;

  126.     /** True only if the caller wants to force bare behavior. */
  127.     private boolean bare;

  128.     /** True if the caller requires the repository to exist. */
  129.     private boolean mustExist;

  130.     /** Configuration file of target repository, lazily loaded if required. */
  131.     private Config config;

  132.     /**
  133.      * Set the file system abstraction needed by this repository.
  134.      *
  135.      * @param fs
  136.      *            the abstraction.
  137.      * @return {@code this} (for chaining calls).
  138.      */
  139.     public B setFS(FS fs) {
  140.         this.fs = fs;
  141.         return self();
  142.     }

  143.     /**
  144.      * Get the file system abstraction, or null if not set.
  145.      *
  146.      * @return the file system abstraction, or null if not set.
  147.      */
  148.     public FS getFS() {
  149.         return fs;
  150.     }

  151.     /**
  152.      * Set the Git directory storing the repository metadata.
  153.      * <p>
  154.      * The meta directory stores the objects, references, and meta files like
  155.      * {@code MERGE_HEAD}, or the index file. If {@code null} the path is
  156.      * assumed to be {@code workTree/.git}.
  157.      *
  158.      * @param gitDir
  159.      *            {@code GIT_DIR}, the repository meta directory.
  160.      * @return {@code this} (for chaining calls).
  161.      */
  162.     public B setGitDir(File gitDir) {
  163.         this.gitDir = gitDir;
  164.         this.config = null;
  165.         return self();
  166.     }

  167.     /**
  168.      * Get the meta data directory; null if not set.
  169.      *
  170.      * @return the meta data directory; null if not set.
  171.      */
  172.     public File getGitDir() {
  173.         return gitDir;
  174.     }

  175.     /**
  176.      * Set the directory storing the repository's objects.
  177.      *
  178.      * @param objectDirectory
  179.      *            {@code GIT_OBJECT_DIRECTORY}, the directory where the
  180.      *            repository's object files are stored.
  181.      * @return {@code this} (for chaining calls).
  182.      */
  183.     public B setObjectDirectory(File objectDirectory) {
  184.         this.objectDirectory = objectDirectory;
  185.         return self();
  186.     }

  187.     /**
  188.      * Get the object directory; null if not set.
  189.      *
  190.      * @return the object directory; null if not set.
  191.      */
  192.     public File getObjectDirectory() {
  193.         return objectDirectory;
  194.     }

  195.     /**
  196.      * Add an alternate object directory to the search list.
  197.      * <p>
  198.      * This setting handles one alternate directory at a time, and is provided
  199.      * to support {@code GIT_ALTERNATE_OBJECT_DIRECTORIES}.
  200.      *
  201.      * @param other
  202.      *            another objects directory to search after the standard one.
  203.      * @return {@code this} (for chaining calls).
  204.      */
  205.     public B addAlternateObjectDirectory(File other) {
  206.         if (other != null) {
  207.             if (alternateObjectDirectories == null)
  208.                 alternateObjectDirectories = new LinkedList<>();
  209.             alternateObjectDirectories.add(other);
  210.         }
  211.         return self();
  212.     }

  213.     /**
  214.      * Add alternate object directories to the search list.
  215.      * <p>
  216.      * This setting handles several alternate directories at once, and is
  217.      * provided to support {@code GIT_ALTERNATE_OBJECT_DIRECTORIES}.
  218.      *
  219.      * @param inList
  220.      *            other object directories to search after the standard one. The
  221.      *            collection's contents is copied to an internal list.
  222.      * @return {@code this} (for chaining calls).
  223.      */
  224.     public B addAlternateObjectDirectories(Collection<File> inList) {
  225.         if (inList != null) {
  226.             for (File path : inList)
  227.                 addAlternateObjectDirectory(path);
  228.         }
  229.         return self();
  230.     }

  231.     /**
  232.      * Add alternate object directories to the search list.
  233.      * <p>
  234.      * This setting handles several alternate directories at once, and is
  235.      * provided to support {@code GIT_ALTERNATE_OBJECT_DIRECTORIES}.
  236.      *
  237.      * @param inList
  238.      *            other object directories to search after the standard one. The
  239.      *            array's contents is copied to an internal list.
  240.      * @return {@code this} (for chaining calls).
  241.      */
  242.     public B addAlternateObjectDirectories(File[] inList) {
  243.         if (inList != null) {
  244.             for (File path : inList)
  245.                 addAlternateObjectDirectory(path);
  246.         }
  247.         return self();
  248.     }

  249.     /**
  250.      * Get ordered array of alternate directories; null if non were set.
  251.      *
  252.      * @return ordered array of alternate directories; null if non were set.
  253.      */
  254.     public File[] getAlternateObjectDirectories() {
  255.         final List<File> alts = alternateObjectDirectories;
  256.         if (alts == null)
  257.             return null;
  258.         return alts.toArray(new File[0]);
  259.     }

  260.     /**
  261.      * Force the repository to be treated as bare (have no working directory).
  262.      * <p>
  263.      * If bare the working directory aspects of the repository won't be
  264.      * configured, and will not be accessible.
  265.      *
  266.      * @return {@code this} (for chaining calls).
  267.      */
  268.     public B setBare() {
  269.         setIndexFile(null);
  270.         setWorkTree(null);
  271.         bare = true;
  272.         return self();
  273.     }

  274.     /**
  275.      * Whether this repository was forced bare by {@link #setBare()}.
  276.      *
  277.      * @return true if this repository was forced bare by {@link #setBare()}.
  278.      */
  279.     public boolean isBare() {
  280.         return bare;
  281.     }

  282.     /**
  283.      * Require the repository to exist before it can be opened.
  284.      *
  285.      * @param mustExist
  286.      *            true if it must exist; false if it can be missing and created
  287.      *            after being built.
  288.      * @return {@code this} (for chaining calls).
  289.      */
  290.     public B setMustExist(boolean mustExist) {
  291.         this.mustExist = mustExist;
  292.         return self();
  293.     }

  294.     /**
  295.      * Whether the repository must exist before being opened.
  296.      *
  297.      * @return true if the repository must exist before being opened.
  298.      */
  299.     public boolean isMustExist() {
  300.         return mustExist;
  301.     }

  302.     /**
  303.      * Set the top level directory of the working files.
  304.      *
  305.      * @param workTree
  306.      *            {@code GIT_WORK_TREE}, the working directory of the checkout.
  307.      * @return {@code this} (for chaining calls).
  308.      */
  309.     public B setWorkTree(File workTree) {
  310.         this.workTree = workTree;
  311.         return self();
  312.     }

  313.     /**
  314.      * Get the work tree directory, or null if not set.
  315.      *
  316.      * @return the work tree directory, or null if not set.
  317.      */
  318.     public File getWorkTree() {
  319.         return workTree;
  320.     }

  321.     /**
  322.      * Set the local index file that is caching checked out file status.
  323.      * <p>
  324.      * The location of the index file tracking the status information for each
  325.      * checked out file in {@code workTree}. This may be null to assume the
  326.      * default {@code gitDiir/index}.
  327.      *
  328.      * @param indexFile
  329.      *            {@code GIT_INDEX_FILE}, the index file location.
  330.      * @return {@code this} (for chaining calls).
  331.      */
  332.     public B setIndexFile(File indexFile) {
  333.         this.indexFile = indexFile;
  334.         return self();
  335.     }

  336.     /**
  337.      * Get the index file location, or null if not set.
  338.      *
  339.      * @return the index file location, or null if not set.
  340.      */
  341.     public File getIndexFile() {
  342.         return indexFile;
  343.     }

  344.     /**
  345.      * Read standard Git environment variables and configure from those.
  346.      * <p>
  347.      * This method tries to read the standard Git environment variables, such as
  348.      * {@code GIT_DIR} and {@code GIT_WORK_TREE} to configure this builder
  349.      * instance. If an environment variable is set, it overrides the value
  350.      * already set in this builder.
  351.      *
  352.      * @return {@code this} (for chaining calls).
  353.      */
  354.     public B readEnvironment() {
  355.         return readEnvironment(SystemReader.getInstance());
  356.     }

  357.     /**
  358.      * Read standard Git environment variables and configure from those.
  359.      * <p>
  360.      * This method tries to read the standard Git environment variables, such as
  361.      * {@code GIT_DIR} and {@code GIT_WORK_TREE} to configure this builder
  362.      * instance. If a property is already set in the builder, the environment
  363.      * variable is not used.
  364.      *
  365.      * @param sr
  366.      *            the SystemReader abstraction to access the environment.
  367.      * @return {@code this} (for chaining calls).
  368.      */
  369.     public B readEnvironment(SystemReader sr) {
  370.         if (getGitDir() == null) {
  371.             String val = sr.getenv(GIT_DIR_KEY);
  372.             if (val != null)
  373.                 setGitDir(new File(val));
  374.         }

  375.         if (getObjectDirectory() == null) {
  376.             String val = sr.getenv(GIT_OBJECT_DIRECTORY_KEY);
  377.             if (val != null)
  378.                 setObjectDirectory(new File(val));
  379.         }

  380.         if (getAlternateObjectDirectories() == null) {
  381.             String val = sr.getenv(GIT_ALTERNATE_OBJECT_DIRECTORIES_KEY);
  382.             if (val != null) {
  383.                 for (String path : val.split(File.pathSeparator))
  384.                     addAlternateObjectDirectory(new File(path));
  385.             }
  386.         }

  387.         if (getWorkTree() == null) {
  388.             String val = sr.getenv(GIT_WORK_TREE_KEY);
  389.             if (val != null)
  390.                 setWorkTree(new File(val));
  391.         }

  392.         if (getIndexFile() == null) {
  393.             String val = sr.getenv(GIT_INDEX_FILE_KEY);
  394.             if (val != null)
  395.                 setIndexFile(new File(val));
  396.         }

  397.         if (ceilingDirectories == null) {
  398.             String val = sr.getenv(GIT_CEILING_DIRECTORIES_KEY);
  399.             if (val != null) {
  400.                 for (String path : val.split(File.pathSeparator))
  401.                     addCeilingDirectory(new File(path));
  402.             }
  403.         }

  404.         return self();
  405.     }

  406.     /**
  407.      * Add a ceiling directory to the search limit list.
  408.      * <p>
  409.      * This setting handles one ceiling directory at a time, and is provided to
  410.      * support {@code GIT_CEILING_DIRECTORIES}.
  411.      *
  412.      * @param root
  413.      *            a path to stop searching at; its parent will not be searched.
  414.      * @return {@code this} (for chaining calls).
  415.      */
  416.     public B addCeilingDirectory(File root) {
  417.         if (root != null) {
  418.             if (ceilingDirectories == null)
  419.                 ceilingDirectories = new LinkedList<>();
  420.             ceilingDirectories.add(root);
  421.         }
  422.         return self();
  423.     }

  424.     /**
  425.      * Add ceiling directories to the search list.
  426.      * <p>
  427.      * This setting handles several ceiling directories at once, and is provided
  428.      * to support {@code GIT_CEILING_DIRECTORIES}.
  429.      *
  430.      * @param inList
  431.      *            directory paths to stop searching at. The collection's
  432.      *            contents is copied to an internal list.
  433.      * @return {@code this} (for chaining calls).
  434.      */
  435.     public B addCeilingDirectories(Collection<File> inList) {
  436.         if (inList != null) {
  437.             for (File path : inList)
  438.                 addCeilingDirectory(path);
  439.         }
  440.         return self();
  441.     }

  442.     /**
  443.      * Add ceiling directories to the search list.
  444.      * <p>
  445.      * This setting handles several ceiling directories at once, and is provided
  446.      * to support {@code GIT_CEILING_DIRECTORIES}.
  447.      *
  448.      * @param inList
  449.      *            directory paths to stop searching at. The array's contents is
  450.      *            copied to an internal list.
  451.      * @return {@code this} (for chaining calls).
  452.      */
  453.     public B addCeilingDirectories(File[] inList) {
  454.         if (inList != null) {
  455.             for (File path : inList)
  456.                 addCeilingDirectory(path);
  457.         }
  458.         return self();
  459.     }

  460.     /**
  461.      * Configure {@code GIT_DIR} by searching up the file system.
  462.      * <p>
  463.      * Starts from the current working directory of the JVM and scans up through
  464.      * the directory tree until a Git repository is found. Success can be
  465.      * determined by checking for {@code getGitDir() != null}.
  466.      * <p>
  467.      * The search can be limited to specific spaces of the local filesystem by
  468.      * {@link #addCeilingDirectory(File)}, or inheriting the list through a
  469.      * prior call to {@link #readEnvironment()}.
  470.      *
  471.      * @return {@code this} (for chaining calls).
  472.      */
  473.     public B findGitDir() {
  474.         if (getGitDir() == null)
  475.             findGitDir(new File("").getAbsoluteFile()); //$NON-NLS-1$
  476.         return self();
  477.     }

  478.     /**
  479.      * Configure {@code GIT_DIR} by searching up the file system.
  480.      * <p>
  481.      * Starts from the supplied directory path and scans up through the parent
  482.      * directory tree until a Git repository is found. Success can be determined
  483.      * by checking for {@code getGitDir() != null}.
  484.      * <p>
  485.      * The search can be limited to specific spaces of the local filesystem by
  486.      * {@link #addCeilingDirectory(File)}, or inheriting the list through a
  487.      * prior call to {@link #readEnvironment()}.
  488.      *
  489.      * @param current
  490.      *            directory to begin searching in.
  491.      * @return {@code this} (for chaining calls).
  492.      */
  493.     public B findGitDir(File current) {
  494.         if (getGitDir() == null) {
  495.             FS tryFS = safeFS();
  496.             while (current != null) {
  497.                 File dir = new File(current, DOT_GIT);
  498.                 if (FileKey.isGitRepository(dir, tryFS)) {
  499.                     setGitDir(dir);
  500.                     break;
  501.                 } else if (dir.isFile()) {
  502.                     try {
  503.                         setGitDir(getSymRef(current, dir, tryFS));
  504.                         break;
  505.                     } catch (IOException ignored) {
  506.                         // Continue searching if gitdir ref isn't found
  507.                     }
  508.                 } else if (FileKey.isGitRepository(current, tryFS)) {
  509.                     setGitDir(current);
  510.                     break;
  511.                 }

  512.                 current = current.getParentFile();
  513.                 if (current != null && ceilingDirectories != null
  514.                         && ceilingDirectories.contains(current))
  515.                     break;
  516.             }
  517.         }
  518.         return self();
  519.     }

  520.     /**
  521.      * Guess and populate all parameters not already defined.
  522.      * <p>
  523.      * If an option was not set, the setup method will try to default the option
  524.      * based on other options. If insufficient information is available, an
  525.      * exception is thrown to the caller.
  526.      *
  527.      * @return {@code this}
  528.      * @throws java.lang.IllegalArgumentException
  529.      *             insufficient parameters were set, or some parameters are
  530.      *             incompatible with one another.
  531.      * @throws java.io.IOException
  532.      *             the repository could not be accessed to configure the rest of
  533.      *             the builder's parameters.
  534.      */
  535.     public B setup() throws IllegalArgumentException, IOException {
  536.         requireGitDirOrWorkTree();
  537.         setupGitDir();
  538.         setupWorkTree();
  539.         setupInternals();
  540.         return self();
  541.     }

  542.     /**
  543.      * Create a repository matching the configuration in this builder.
  544.      * <p>
  545.      * If an option was not set, the build method will try to default the option
  546.      * based on other options. If insufficient information is available, an
  547.      * exception is thrown to the caller.
  548.      *
  549.      * @return a repository matching this configuration. The caller is
  550.      *         responsible to close the repository instance when it is no longer
  551.      *         needed.
  552.      * @throws java.lang.IllegalArgumentException
  553.      *             insufficient parameters were set.
  554.      * @throws java.io.IOException
  555.      *             the repository could not be accessed to configure the rest of
  556.      *             the builder's parameters.
  557.      */
  558.     @SuppressWarnings({ "unchecked", "resource" })
  559.     public R build() throws IOException {
  560.         R repo = (R) new FileRepository(setup());
  561.         if (isMustExist() && !repo.getObjectDatabase().exists())
  562.             throw new RepositoryNotFoundException(getGitDir());
  563.         return repo;
  564.     }

  565.     /**
  566.      * Require either {@code gitDir} or {@code workTree} to be set.
  567.      */
  568.     protected void requireGitDirOrWorkTree() {
  569.         if (getGitDir() == null && getWorkTree() == null)
  570.             throw new IllegalArgumentException(
  571.                     JGitText.get().eitherGitDirOrWorkTreeRequired);
  572.     }

  573.     /**
  574.      * Perform standard gitDir initialization.
  575.      *
  576.      * @throws java.io.IOException
  577.      *             the repository could not be accessed
  578.      */
  579.     protected void setupGitDir() throws IOException {
  580.         // No gitDir? Try to assume its under the workTree or a ref to another
  581.         // location
  582.         if (getGitDir() == null && getWorkTree() != null) {
  583.             File dotGit = new File(getWorkTree(), DOT_GIT);
  584.             if (!dotGit.isFile())
  585.                 setGitDir(dotGit);
  586.             else
  587.                 setGitDir(getSymRef(getWorkTree(), dotGit, safeFS()));
  588.         }
  589.     }

  590.     /**
  591.      * Perform standard work-tree initialization.
  592.      * <p>
  593.      * This is a method typically invoked inside of {@link #setup()}, near the
  594.      * end after the repository has been identified and its configuration is
  595.      * available for inspection.
  596.      *
  597.      * @throws java.io.IOException
  598.      *             the repository configuration could not be read.
  599.      */
  600.     protected void setupWorkTree() throws IOException {
  601.         if (getFS() == null)
  602.             setFS(FS.DETECTED);

  603.         // If we aren't bare, we should have a work tree.
  604.         //
  605.         if (!isBare() && getWorkTree() == null)
  606.             setWorkTree(guessWorkTreeOrFail());

  607.         if (!isBare()) {
  608.             // If after guessing we're still not bare, we must have
  609.             // a metadata directory to hold the repository. Assume
  610.             // its at the work tree.
  611.             //
  612.             if (getGitDir() == null)
  613.                 setGitDir(getWorkTree().getParentFile());
  614.             if (getIndexFile() == null)
  615.                 setIndexFile(new File(getGitDir(), "index")); //$NON-NLS-1$
  616.         }
  617.     }

  618.     /**
  619.      * Configure the internal implementation details of the repository.
  620.      *
  621.      * @throws java.io.IOException
  622.      *             the repository could not be accessed
  623.      */
  624.     protected void setupInternals() throws IOException {
  625.         if (getObjectDirectory() == null && getGitDir() != null)
  626.             setObjectDirectory(safeFS().resolve(getGitDir(), "objects")); //$NON-NLS-1$
  627.     }

  628.     /**
  629.      * Get the cached repository configuration, loading if not yet available.
  630.      *
  631.      * @return the configuration of the repository.
  632.      * @throws java.io.IOException
  633.      *             the configuration is not available, or is badly formed.
  634.      */
  635.     protected Config getConfig() throws IOException {
  636.         if (config == null)
  637.             config = loadConfig();
  638.         return config;
  639.     }

  640.     /**
  641.      * Parse and load the repository specific configuration.
  642.      * <p>
  643.      * The default implementation reads {@code gitDir/config}, or returns an
  644.      * empty configuration if gitDir was not set.
  645.      *
  646.      * @return the repository's configuration.
  647.      * @throws java.io.IOException
  648.      *             the configuration is not available.
  649.      */
  650.     protected Config loadConfig() throws IOException {
  651.         if (getGitDir() != null) {
  652.             // We only want the repository's configuration file, and not
  653.             // the user file, as these parameters must be unique to this
  654.             // repository and not inherited from other files.
  655.             //
  656.             File path = safeFS().resolve(getGitDir(), Constants.CONFIG);
  657.             FileBasedConfig cfg = new FileBasedConfig(path, safeFS());
  658.             try {
  659.                 cfg.load();
  660.             } catch (ConfigInvalidException err) {
  661.                 throw new IllegalArgumentException(MessageFormat.format(
  662.                         JGitText.get().repositoryConfigFileInvalid, path
  663.                                 .getAbsolutePath(), err.getMessage()));
  664.             }
  665.             return cfg;
  666.         } else {
  667.             return new Config();
  668.         }
  669.     }

  670.     private File guessWorkTreeOrFail() throws IOException {
  671.         final Config cfg = getConfig();

  672.         // If set, core.worktree wins.
  673.         //
  674.         String path = cfg.getString(CONFIG_CORE_SECTION, null,
  675.                 CONFIG_KEY_WORKTREE);
  676.         if (path != null)
  677.             return safeFS().resolve(getGitDir(), path).getCanonicalFile();

  678.         // If core.bare is set, honor its value. Assume workTree is
  679.         // the parent directory of the repository.
  680.         //
  681.         if (cfg.getString(CONFIG_CORE_SECTION, null, CONFIG_KEY_BARE) != null) {
  682.             if (cfg.getBoolean(CONFIG_CORE_SECTION, CONFIG_KEY_BARE, true)) {
  683.                 setBare();
  684.                 return null;
  685.             }
  686.             return getGitDir().getParentFile();
  687.         }

  688.         if (getGitDir().getName().equals(DOT_GIT)) {
  689.             // No value for the "bare" flag, but gitDir is named ".git",
  690.             // use the parent of the directory
  691.             //
  692.             return getGitDir().getParentFile();
  693.         }

  694.         // We have to assume we are bare.
  695.         //
  696.         setBare();
  697.         return null;
  698.     }

  699.     /**
  700.      * Get the configured FS, or {@link FS#DETECTED}.
  701.      *
  702.      * @return the configured FS, or {@link FS#DETECTED}.
  703.      */
  704.     protected FS safeFS() {
  705.         return getFS() != null ? getFS() : FS.DETECTED;
  706.     }

  707.     /**
  708.      * Get this object
  709.      *
  710.      * @return {@code this}
  711.      */
  712.     @SuppressWarnings("unchecked")
  713.     protected final B self() {
  714.         return (B) this;
  715.     }
  716. }