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.

BaseRepositoryBuilder.java 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  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. }
  104. int pathStart = 8;
  105. int lineEnd = RawParseUtils.nextLF(content, pathStart);
  106. while (content[lineEnd - 1] == '\n' ||
  107. (content[lineEnd - 1] == '\r'
  108. && SystemReader.getInstance().isWindows())) {
  109. lineEnd--;
  110. }
  111. if (lineEnd == pathStart) {
  112. throw new IOException(MessageFormat.format(
  113. JGitText.get().invalidGitdirRef, dotGit.getAbsolutePath()));
  114. }
  115. String gitdirPath = RawParseUtils.decode(content, pathStart, lineEnd);
  116. File gitdirFile = fs.resolve(workTree, gitdirPath);
  117. if (gitdirFile.isAbsolute()) {
  118. return gitdirFile;
  119. }
  120. return new File(workTree, gitdirPath).getCanonicalFile();
  121. }
  122. private FS fs;
  123. private File gitDir;
  124. private File objectDirectory;
  125. private List<File> alternateObjectDirectories;
  126. private File indexFile;
  127. private File workTree;
  128. /** Directories limiting the search for a Git repository. */
  129. private List<File> ceilingDirectories;
  130. /** True only if the caller wants to force bare behavior. */
  131. private boolean bare;
  132. /** True if the caller requires the repository to exist. */
  133. private boolean mustExist;
  134. /** Configuration file of target repository, lazily loaded if required. */
  135. private Config config;
  136. /**
  137. * Set the file system abstraction needed by this repository.
  138. *
  139. * @param fs
  140. * the abstraction.
  141. * @return {@code this} (for chaining calls).
  142. */
  143. public B setFS(FS fs) {
  144. this.fs = fs;
  145. return self();
  146. }
  147. /**
  148. * Get the file system abstraction, or null if not set.
  149. *
  150. * @return the file system abstraction, or null if not set.
  151. */
  152. public FS getFS() {
  153. return fs;
  154. }
  155. /**
  156. * Set the Git directory storing the repository metadata.
  157. * <p>
  158. * The meta directory stores the objects, references, and meta files like
  159. * {@code MERGE_HEAD}, or the index file. If {@code null} the path is
  160. * assumed to be {@code workTree/.git}.
  161. *
  162. * @param gitDir
  163. * {@code GIT_DIR}, the repository meta directory.
  164. * @return {@code this} (for chaining calls).
  165. */
  166. public B setGitDir(File gitDir) {
  167. this.gitDir = gitDir;
  168. this.config = null;
  169. return self();
  170. }
  171. /**
  172. * Get the meta data directory; null if not set.
  173. *
  174. * @return the meta data directory; null if not set.
  175. */
  176. public File getGitDir() {
  177. return gitDir;
  178. }
  179. /**
  180. * Set the directory storing the repository's objects.
  181. *
  182. * @param objectDirectory
  183. * {@code GIT_OBJECT_DIRECTORY}, the directory where the
  184. * repository's object files are stored.
  185. * @return {@code this} (for chaining calls).
  186. */
  187. public B setObjectDirectory(File objectDirectory) {
  188. this.objectDirectory = objectDirectory;
  189. return self();
  190. }
  191. /**
  192. * Get the object directory; null if not set.
  193. *
  194. * @return the object directory; null if not set.
  195. */
  196. public File getObjectDirectory() {
  197. return objectDirectory;
  198. }
  199. /**
  200. * Add an alternate object directory to the search list.
  201. * <p>
  202. * This setting handles one alternate directory at a time, and is provided
  203. * to support {@code GIT_ALTERNATE_OBJECT_DIRECTORIES}.
  204. *
  205. * @param other
  206. * another objects directory to search after the standard one.
  207. * @return {@code this} (for chaining calls).
  208. */
  209. public B addAlternateObjectDirectory(File other) {
  210. if (other != null) {
  211. if (alternateObjectDirectories == null)
  212. alternateObjectDirectories = new LinkedList<>();
  213. alternateObjectDirectories.add(other);
  214. }
  215. return self();
  216. }
  217. /**
  218. * Add alternate object directories to the search list.
  219. * <p>
  220. * This setting handles several alternate directories at once, and is
  221. * provided to support {@code GIT_ALTERNATE_OBJECT_DIRECTORIES}.
  222. *
  223. * @param inList
  224. * other object directories to search after the standard one. The
  225. * collection's contents is copied to an internal list.
  226. * @return {@code this} (for chaining calls).
  227. */
  228. public B addAlternateObjectDirectories(Collection<File> inList) {
  229. if (inList != null) {
  230. for (File path : inList)
  231. addAlternateObjectDirectory(path);
  232. }
  233. return self();
  234. }
  235. /**
  236. * Add alternate object directories to the search list.
  237. * <p>
  238. * This setting handles several alternate directories at once, and is
  239. * provided to support {@code GIT_ALTERNATE_OBJECT_DIRECTORIES}.
  240. *
  241. * @param inList
  242. * other object directories to search after the standard one. The
  243. * array's contents is copied to an internal list.
  244. * @return {@code this} (for chaining calls).
  245. */
  246. public B addAlternateObjectDirectories(File[] inList) {
  247. if (inList != null) {
  248. for (File path : inList)
  249. addAlternateObjectDirectory(path);
  250. }
  251. return self();
  252. }
  253. /**
  254. * Get ordered array of alternate directories; null if non were set.
  255. *
  256. * @return ordered array of alternate directories; null if non were set.
  257. */
  258. public File[] getAlternateObjectDirectories() {
  259. final List<File> alts = alternateObjectDirectories;
  260. if (alts == null)
  261. return null;
  262. return alts.toArray(new File[0]);
  263. }
  264. /**
  265. * Force the repository to be treated as bare (have no working directory).
  266. * <p>
  267. * If bare the working directory aspects of the repository won't be
  268. * configured, and will not be accessible.
  269. *
  270. * @return {@code this} (for chaining calls).
  271. */
  272. public B setBare() {
  273. setIndexFile(null);
  274. setWorkTree(null);
  275. bare = true;
  276. return self();
  277. }
  278. /**
  279. * Whether this repository was forced bare by {@link #setBare()}.
  280. *
  281. * @return true if this repository was forced bare by {@link #setBare()}.
  282. */
  283. public boolean isBare() {
  284. return bare;
  285. }
  286. /**
  287. * Require the repository to exist before it can be opened.
  288. *
  289. * @param mustExist
  290. * true if it must exist; false if it can be missing and created
  291. * after being built.
  292. * @return {@code this} (for chaining calls).
  293. */
  294. public B setMustExist(boolean mustExist) {
  295. this.mustExist = mustExist;
  296. return self();
  297. }
  298. /**
  299. * Whether the repository must exist before being opened.
  300. *
  301. * @return true if the repository must exist before being opened.
  302. */
  303. public boolean isMustExist() {
  304. return mustExist;
  305. }
  306. /**
  307. * Set the top level directory of the working files.
  308. *
  309. * @param workTree
  310. * {@code GIT_WORK_TREE}, the working directory of the checkout.
  311. * @return {@code this} (for chaining calls).
  312. */
  313. public B setWorkTree(File workTree) {
  314. this.workTree = workTree;
  315. return self();
  316. }
  317. /**
  318. * Get the work tree directory, or null if not set.
  319. *
  320. * @return the work tree directory, or null if not set.
  321. */
  322. public File getWorkTree() {
  323. return workTree;
  324. }
  325. /**
  326. * Set the local index file that is caching checked out file status.
  327. * <p>
  328. * The location of the index file tracking the status information for each
  329. * checked out file in {@code workTree}. This may be null to assume the
  330. * default {@code gitDiir/index}.
  331. *
  332. * @param indexFile
  333. * {@code GIT_INDEX_FILE}, the index file location.
  334. * @return {@code this} (for chaining calls).
  335. */
  336. public B setIndexFile(File indexFile) {
  337. this.indexFile = indexFile;
  338. return self();
  339. }
  340. /**
  341. * Get the index file location, or null if not set.
  342. *
  343. * @return the index file location, or null if not set.
  344. */
  345. public File getIndexFile() {
  346. return indexFile;
  347. }
  348. /**
  349. * Read standard Git environment variables and configure from those.
  350. * <p>
  351. * This method tries to read the standard Git environment variables, such as
  352. * {@code GIT_DIR} and {@code GIT_WORK_TREE} to configure this builder
  353. * instance. If an environment variable is set, it overrides the value
  354. * already set in this builder.
  355. *
  356. * @return {@code this} (for chaining calls).
  357. */
  358. public B readEnvironment() {
  359. return readEnvironment(SystemReader.getInstance());
  360. }
  361. /**
  362. * Read standard Git environment variables and configure from those.
  363. * <p>
  364. * This method tries to read the standard Git environment variables, such as
  365. * {@code GIT_DIR} and {@code GIT_WORK_TREE} to configure this builder
  366. * instance. If a property is already set in the builder, the environment
  367. * variable is not used.
  368. *
  369. * @param sr
  370. * the SystemReader abstraction to access the environment.
  371. * @return {@code this} (for chaining calls).
  372. */
  373. public B readEnvironment(SystemReader sr) {
  374. if (getGitDir() == null) {
  375. String val = sr.getenv(GIT_DIR_KEY);
  376. if (val != null)
  377. setGitDir(new File(val));
  378. }
  379. if (getObjectDirectory() == null) {
  380. String val = sr.getenv(GIT_OBJECT_DIRECTORY_KEY);
  381. if (val != null)
  382. setObjectDirectory(new File(val));
  383. }
  384. if (getAlternateObjectDirectories() == null) {
  385. String val = sr.getenv(GIT_ALTERNATE_OBJECT_DIRECTORIES_KEY);
  386. if (val != null) {
  387. for (String path : val.split(File.pathSeparator))
  388. addAlternateObjectDirectory(new File(path));
  389. }
  390. }
  391. if (getWorkTree() == null) {
  392. String val = sr.getenv(GIT_WORK_TREE_KEY);
  393. if (val != null)
  394. setWorkTree(new File(val));
  395. }
  396. if (getIndexFile() == null) {
  397. String val = sr.getenv(GIT_INDEX_FILE_KEY);
  398. if (val != null)
  399. setIndexFile(new File(val));
  400. }
  401. if (ceilingDirectories == null) {
  402. String val = sr.getenv(GIT_CEILING_DIRECTORIES_KEY);
  403. if (val != null) {
  404. for (String path : val.split(File.pathSeparator))
  405. addCeilingDirectory(new File(path));
  406. }
  407. }
  408. return self();
  409. }
  410. /**
  411. * Add a ceiling directory to the search limit list.
  412. * <p>
  413. * This setting handles one ceiling directory at a time, and is provided to
  414. * support {@code GIT_CEILING_DIRECTORIES}.
  415. *
  416. * @param root
  417. * a path to stop searching at; its parent will not be searched.
  418. * @return {@code this} (for chaining calls).
  419. */
  420. public B addCeilingDirectory(File root) {
  421. if (root != null) {
  422. if (ceilingDirectories == null)
  423. ceilingDirectories = new LinkedList<>();
  424. ceilingDirectories.add(root);
  425. }
  426. return self();
  427. }
  428. /**
  429. * Add ceiling directories to the search list.
  430. * <p>
  431. * This setting handles several ceiling directories at once, and is provided
  432. * to support {@code GIT_CEILING_DIRECTORIES}.
  433. *
  434. * @param inList
  435. * directory paths to stop searching at. The collection's
  436. * contents is copied to an internal list.
  437. * @return {@code this} (for chaining calls).
  438. */
  439. public B addCeilingDirectories(Collection<File> inList) {
  440. if (inList != null) {
  441. for (File path : inList)
  442. addCeilingDirectory(path);
  443. }
  444. return self();
  445. }
  446. /**
  447. * Add ceiling directories to the search list.
  448. * <p>
  449. * This setting handles several ceiling directories at once, and is provided
  450. * to support {@code GIT_CEILING_DIRECTORIES}.
  451. *
  452. * @param inList
  453. * directory paths to stop searching at. The array's contents is
  454. * copied to an internal list.
  455. * @return {@code this} (for chaining calls).
  456. */
  457. public B addCeilingDirectories(File[] inList) {
  458. if (inList != null) {
  459. for (File path : inList)
  460. addCeilingDirectory(path);
  461. }
  462. return self();
  463. }
  464. /**
  465. * Configure {@code GIT_DIR} by searching up the file system.
  466. * <p>
  467. * Starts from the current working directory of the JVM and scans up through
  468. * the directory tree until a Git repository is found. Success can be
  469. * determined by checking for {@code getGitDir() != null}.
  470. * <p>
  471. * The search can be limited to specific spaces of the local filesystem by
  472. * {@link #addCeilingDirectory(File)}, or inheriting the list through a
  473. * prior call to {@link #readEnvironment()}.
  474. *
  475. * @return {@code this} (for chaining calls).
  476. */
  477. public B findGitDir() {
  478. if (getGitDir() == null)
  479. findGitDir(new File("").getAbsoluteFile()); //$NON-NLS-1$
  480. return self();
  481. }
  482. /**
  483. * Configure {@code GIT_DIR} by searching up the file system.
  484. * <p>
  485. * Starts from the supplied directory path and scans up through the parent
  486. * directory tree until a Git repository is found. Success can be determined
  487. * by checking for {@code getGitDir() != null}.
  488. * <p>
  489. * The search can be limited to specific spaces of the local filesystem by
  490. * {@link #addCeilingDirectory(File)}, or inheriting the list through a
  491. * prior call to {@link #readEnvironment()}.
  492. *
  493. * @param current
  494. * directory to begin searching in.
  495. * @return {@code this} (for chaining calls).
  496. */
  497. public B findGitDir(File current) {
  498. if (getGitDir() == null) {
  499. FS tryFS = safeFS();
  500. while (current != null) {
  501. File dir = new File(current, DOT_GIT);
  502. if (FileKey.isGitRepository(dir, tryFS)) {
  503. setGitDir(dir);
  504. break;
  505. } else if (dir.isFile()) {
  506. try {
  507. setGitDir(getSymRef(current, dir, tryFS));
  508. break;
  509. } catch (IOException ignored) {
  510. // Continue searching if gitdir ref isn't found
  511. }
  512. } else if (FileKey.isGitRepository(current, tryFS)) {
  513. setGitDir(current);
  514. break;
  515. }
  516. current = current.getParentFile();
  517. if (current != null && ceilingDirectories != null
  518. && ceilingDirectories.contains(current))
  519. break;
  520. }
  521. }
  522. return self();
  523. }
  524. /**
  525. * Guess and populate all parameters not already defined.
  526. * <p>
  527. * If an option was not set, the setup method will try to default the option
  528. * based on other options. If insufficient information is available, an
  529. * exception is thrown to the caller.
  530. *
  531. * @return {@code this}
  532. * @throws java.lang.IllegalArgumentException
  533. * insufficient parameters were set, or some parameters are
  534. * incompatible with one another.
  535. * @throws java.io.IOException
  536. * the repository could not be accessed to configure the rest of
  537. * the builder's parameters.
  538. */
  539. public B setup() throws IllegalArgumentException, IOException {
  540. requireGitDirOrWorkTree();
  541. setupGitDir();
  542. setupWorkTree();
  543. setupInternals();
  544. return self();
  545. }
  546. /**
  547. * Create a repository matching the configuration in this builder.
  548. * <p>
  549. * If an option was not set, the build method will try to default the option
  550. * based on other options. If insufficient information is available, an
  551. * exception is thrown to the caller.
  552. *
  553. * @return a repository matching this configuration. The caller is
  554. * responsible to close the repository instance when it is no longer
  555. * needed.
  556. * @throws java.lang.IllegalArgumentException
  557. * insufficient parameters were set.
  558. * @throws java.io.IOException
  559. * the repository could not be accessed to configure the rest of
  560. * the builder's parameters.
  561. */
  562. @SuppressWarnings({ "unchecked", "resource" })
  563. public R build() throws IOException {
  564. R repo = (R) new FileRepository(setup());
  565. if (isMustExist() && !repo.getObjectDatabase().exists())
  566. throw new RepositoryNotFoundException(getGitDir());
  567. return repo;
  568. }
  569. /**
  570. * Require either {@code gitDir} or {@code workTree} to be set.
  571. */
  572. protected void requireGitDirOrWorkTree() {
  573. if (getGitDir() == null && getWorkTree() == null)
  574. throw new IllegalArgumentException(
  575. JGitText.get().eitherGitDirOrWorkTreeRequired);
  576. }
  577. /**
  578. * Perform standard gitDir initialization.
  579. *
  580. * @throws java.io.IOException
  581. * the repository could not be accessed
  582. */
  583. protected void setupGitDir() throws IOException {
  584. // No gitDir? Try to assume its under the workTree or a ref to another
  585. // location
  586. if (getGitDir() == null && getWorkTree() != null) {
  587. File dotGit = new File(getWorkTree(), DOT_GIT);
  588. if (!dotGit.isFile())
  589. setGitDir(dotGit);
  590. else
  591. setGitDir(getSymRef(getWorkTree(), dotGit, safeFS()));
  592. }
  593. }
  594. /**
  595. * Perform standard work-tree initialization.
  596. * <p>
  597. * This is a method typically invoked inside of {@link #setup()}, near the
  598. * end after the repository has been identified and its configuration is
  599. * available for inspection.
  600. *
  601. * @throws java.io.IOException
  602. * the repository configuration could not be read.
  603. */
  604. protected void setupWorkTree() throws IOException {
  605. if (getFS() == null)
  606. setFS(FS.DETECTED);
  607. // If we aren't bare, we should have a work tree.
  608. //
  609. if (!isBare() && getWorkTree() == null)
  610. setWorkTree(guessWorkTreeOrFail());
  611. if (!isBare()) {
  612. // If after guessing we're still not bare, we must have
  613. // a metadata directory to hold the repository. Assume
  614. // its at the work tree.
  615. //
  616. if (getGitDir() == null)
  617. setGitDir(getWorkTree().getParentFile());
  618. if (getIndexFile() == null)
  619. setIndexFile(new File(getGitDir(), "index")); //$NON-NLS-1$
  620. }
  621. }
  622. /**
  623. * Configure the internal implementation details of the repository.
  624. *
  625. * @throws java.io.IOException
  626. * the repository could not be accessed
  627. */
  628. protected void setupInternals() throws IOException {
  629. if (getObjectDirectory() == null && getGitDir() != null)
  630. setObjectDirectory(safeFS().resolve(getGitDir(), Constants.OBJECTS));
  631. }
  632. /**
  633. * Get the cached repository configuration, loading if not yet available.
  634. *
  635. * @return the configuration of the repository.
  636. * @throws java.io.IOException
  637. * the configuration is not available, or is badly formed.
  638. */
  639. protected Config getConfig() throws IOException {
  640. if (config == null)
  641. config = loadConfig();
  642. return config;
  643. }
  644. /**
  645. * Parse and load the repository specific configuration.
  646. * <p>
  647. * The default implementation reads {@code gitDir/config}, or returns an
  648. * empty configuration if gitDir was not set.
  649. *
  650. * @return the repository's configuration.
  651. * @throws java.io.IOException
  652. * the configuration is not available.
  653. */
  654. protected Config loadConfig() throws IOException {
  655. if (getGitDir() != null) {
  656. // We only want the repository's configuration file, and not
  657. // the user file, as these parameters must be unique to this
  658. // repository and not inherited from other files.
  659. //
  660. File path = safeFS().resolve(getGitDir(), Constants.CONFIG);
  661. FileBasedConfig cfg = new FileBasedConfig(path, safeFS());
  662. try {
  663. cfg.load();
  664. } catch (ConfigInvalidException err) {
  665. throw new IllegalArgumentException(MessageFormat.format(
  666. JGitText.get().repositoryConfigFileInvalid, path
  667. .getAbsolutePath(), err.getMessage()));
  668. }
  669. return cfg;
  670. }
  671. return new Config();
  672. }
  673. private File guessWorkTreeOrFail() throws IOException {
  674. final Config cfg = getConfig();
  675. // If set, core.worktree wins.
  676. //
  677. String path = cfg.getString(CONFIG_CORE_SECTION, null,
  678. CONFIG_KEY_WORKTREE);
  679. if (path != null)
  680. return safeFS().resolve(getGitDir(), path).getCanonicalFile();
  681. // If core.bare is set, honor its value. Assume workTree is
  682. // the parent directory of the repository.
  683. //
  684. if (cfg.getString(CONFIG_CORE_SECTION, null, CONFIG_KEY_BARE) != null) {
  685. if (cfg.getBoolean(CONFIG_CORE_SECTION, CONFIG_KEY_BARE, true)) {
  686. setBare();
  687. return null;
  688. }
  689. return getGitDir().getParentFile();
  690. }
  691. if (getGitDir().getName().equals(DOT_GIT)) {
  692. // No value for the "bare" flag, but gitDir is named ".git",
  693. // use the parent of the directory
  694. //
  695. return getGitDir().getParentFile();
  696. }
  697. // We have to assume we are bare.
  698. //
  699. setBare();
  700. return null;
  701. }
  702. /**
  703. * Get the configured FS, or {@link FS#DETECTED}.
  704. *
  705. * @return the configured FS, or {@link FS#DETECTED}.
  706. */
  707. protected FS safeFS() {
  708. return getFS() != null ? getFS() : FS.DETECTED;
  709. }
  710. /**
  711. * Get this object
  712. *
  713. * @return {@code this}
  714. */
  715. @SuppressWarnings("unchecked")
  716. protected final B self() {
  717. return (B) this;
  718. }
  719. }