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

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