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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  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.JGitText;
  61. import org.eclipse.jgit.errors.ConfigInvalidException;
  62. import org.eclipse.jgit.lib.RepositoryCache.FileKey;
  63. import org.eclipse.jgit.storage.file.FileBasedConfig;
  64. import org.eclipse.jgit.storage.file.FileRepository;
  65. import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
  66. import org.eclipse.jgit.util.FS;
  67. import org.eclipse.jgit.util.SystemReader;
  68. /**
  69. * Base builder to customize repository construction.
  70. * <p>
  71. * Repository implementations may subclass this builder in order to add custom
  72. * repository detection methods.
  73. *
  74. * @param <B>
  75. * type of the repository builder.
  76. * @param <R>
  77. * type of the repository that is constructed.
  78. * @see RepositoryBuilder
  79. * @see FileRepositoryBuilder
  80. */
  81. public class BaseRepositoryBuilder<B extends BaseRepositoryBuilder, R extends Repository> {
  82. private FS fs;
  83. private File gitDir;
  84. private File objectDirectory;
  85. private List<File> alternateObjectDirectories;
  86. private File indexFile;
  87. private File workTree;
  88. /** Directories limiting the search for a Git repository. */
  89. private List<File> ceilingDirectories;
  90. /** True only if the caller wants to force bare behavior. */
  91. private boolean bare;
  92. /** Configuration file of target repository, lazily loaded if required. */
  93. private Config config;
  94. /**
  95. * Set the file system abstraction needed by this repository.
  96. *
  97. * @param fs
  98. * the abstraction.
  99. * @return {@code this} (for chaining calls).
  100. */
  101. public B setFS(FS fs) {
  102. this.fs = fs;
  103. return self();
  104. }
  105. /** @return the file system abstraction, or null if not set. */
  106. public FS getFS() {
  107. return fs;
  108. }
  109. /**
  110. * Set the Git directory storing the repository metadata.
  111. * <p>
  112. * The meta directory stores the objects, references, and meta files like
  113. * {@code MERGE_HEAD}, or the index file. If {@code null} the path is
  114. * assumed to be {@code workTree/.git}.
  115. *
  116. * @param gitDir
  117. * {@code GIT_DIR}, the repository meta directory.
  118. * @return {@code this} (for chaining calls).
  119. */
  120. public B setGitDir(File gitDir) {
  121. this.gitDir = gitDir;
  122. this.config = null;
  123. return self();
  124. }
  125. /** @return the meta data directory; null if not set. */
  126. public File getGitDir() {
  127. return gitDir;
  128. }
  129. /**
  130. * Set the directory storing the repository's objects.
  131. *
  132. * @param objectDirectory
  133. * {@code GIT_OBJECT_DIRECTORY}, the directory where the
  134. * repository's object files are stored.
  135. * @return {@code this} (for chaining calls).
  136. */
  137. public B setObjectDirectory(File objectDirectory) {
  138. this.objectDirectory = objectDirectory;
  139. return self();
  140. }
  141. /** @return the object directory; null if not set. */
  142. public File getObjectDirectory() {
  143. return objectDirectory;
  144. }
  145. /**
  146. * Add an alternate object directory to the search list.
  147. * <p>
  148. * This setting handles one alternate directory at a time, and is provided
  149. * to support {@code GIT_ALTERNATE_OBJECT_DIRECTORIES}.
  150. *
  151. * @param other
  152. * another objects directory to search after the standard one.
  153. * @return {@code this} (for chaining calls).
  154. */
  155. public B addAlternateObjectDirectory(File other) {
  156. if (other != null) {
  157. if (alternateObjectDirectories == null)
  158. alternateObjectDirectories = new LinkedList<File>();
  159. alternateObjectDirectories.add(other);
  160. }
  161. return self();
  162. }
  163. /**
  164. * Add alternate object directories to the search list.
  165. * <p>
  166. * This setting handles several alternate directories at once, and is
  167. * provided to support {@code GIT_ALTERNATE_OBJECT_DIRECTORIES}.
  168. *
  169. * @param inList
  170. * other object directories to search after the standard one. The
  171. * collection's contents is copied to an internal list.
  172. * @return {@code this} (for chaining calls).
  173. */
  174. public B addAlternateObjectDirectories(Collection<File> inList) {
  175. if (inList != null) {
  176. for (File path : inList)
  177. addAlternateObjectDirectory(path);
  178. }
  179. return self();
  180. }
  181. /**
  182. * Add alternate object directories to the search list.
  183. * <p>
  184. * This setting handles several alternate directories at once, and is
  185. * provided to support {@code GIT_ALTERNATE_OBJECT_DIRECTORIES}.
  186. *
  187. * @param inList
  188. * other object directories to search after the standard one. The
  189. * array's contents is copied to an internal list.
  190. * @return {@code this} (for chaining calls).
  191. */
  192. public B addAlternateObjectDirectories(File[] inList) {
  193. if (inList != null) {
  194. for (File path : inList)
  195. addAlternateObjectDirectory(path);
  196. }
  197. return self();
  198. }
  199. /** @return ordered array of alternate directories; null if non were set. */
  200. public File[] getAlternateObjectDirectories() {
  201. final List<File> alts = alternateObjectDirectories;
  202. if (alts == null)
  203. return null;
  204. return alts.toArray(new File[alts.size()]);
  205. }
  206. /**
  207. * Force the repository to be treated as bare (have no working directory).
  208. * <p>
  209. * If bare the working directory aspects of the repository won't be
  210. * configured, and will not be accessible.
  211. *
  212. * @return {@code this} (for chaining calls).
  213. */
  214. public B setBare() {
  215. setIndexFile(null);
  216. setWorkTree(null);
  217. bare = true;
  218. return self();
  219. }
  220. /** @return true if this repository was forced bare by {@link #setBare()}. */
  221. public boolean isBare() {
  222. return bare;
  223. }
  224. /**
  225. * Set the top level directory of the working files.
  226. *
  227. * @param workTree
  228. * {@code GIT_WORK_TREE}, the working directory of the checkout.
  229. * @return {@code this} (for chaining calls).
  230. */
  231. public B setWorkTree(File workTree) {
  232. this.workTree = workTree;
  233. return self();
  234. }
  235. /** @return the work tree directory, or null if not set. */
  236. public File getWorkTree() {
  237. return workTree;
  238. }
  239. /**
  240. * Set the local index file that is caching checked out file status.
  241. * <p>
  242. * The location of the index file tracking the status information for each
  243. * checked out file in {@code workTree}. This may be null to assume the
  244. * default {@code gitDiir/index}.
  245. *
  246. * @param indexFile
  247. * {@code GIT_INDEX_FILE}, the index file location.
  248. * @return {@code this} (for chaining calls).
  249. */
  250. public B setIndexFile(File indexFile) {
  251. this.indexFile = indexFile;
  252. return self();
  253. }
  254. /** @return the index file location, or null if not set. */
  255. public File getIndexFile() {
  256. return indexFile;
  257. }
  258. /**
  259. * Read standard Git environment variables and configure from those.
  260. * <p>
  261. * This method tries to read the standard Git environment variables, such as
  262. * {@code GIT_DIR} and {@code GIT_WORK_TREE} to configure this builder
  263. * instance. If an environment variable is set, it overrides the value
  264. * already set in this builder.
  265. *
  266. * @return {@code this} (for chaining calls).
  267. */
  268. public B readEnvironment() {
  269. return readEnvironment(SystemReader.getInstance());
  270. }
  271. /**
  272. * Read standard Git environment variables and configure from those.
  273. * <p>
  274. * This method tries to read the standard Git environment variables, such as
  275. * {@code GIT_DIR} and {@code GIT_WORK_TREE} to configure this builder
  276. * instance. If a property is already set in the builder, the environment
  277. * variable is not used.
  278. *
  279. * @param sr
  280. * the SystemReader abstraction to access the environment.
  281. * @return {@code this} (for chaining calls).
  282. */
  283. public B readEnvironment(SystemReader sr) {
  284. if (getGitDir() == null) {
  285. String val = sr.getenv(GIT_DIR_KEY);
  286. if (val != null)
  287. setGitDir(new File(val));
  288. }
  289. if (getObjectDirectory() == null) {
  290. String val = sr.getenv(GIT_OBJECT_DIRECTORY_KEY);
  291. if (val != null)
  292. setObjectDirectory(new File(val));
  293. }
  294. if (getAlternateObjectDirectories() == null) {
  295. String val = sr.getenv(GIT_ALTERNATE_OBJECT_DIRECTORIES_KEY);
  296. if (val != null) {
  297. for (String path : val.split(File.pathSeparator))
  298. addAlternateObjectDirectory(new File(path));
  299. }
  300. }
  301. if (getWorkTree() == null) {
  302. String val = sr.getenv(GIT_WORK_TREE_KEY);
  303. if (val != null)
  304. setWorkTree(new File(val));
  305. }
  306. if (getIndexFile() == null) {
  307. String val = sr.getenv(GIT_INDEX_FILE_KEY);
  308. if (val != null)
  309. setIndexFile(new File(val));
  310. }
  311. if (ceilingDirectories == null) {
  312. String val = sr.getenv(GIT_CEILING_DIRECTORIES_KEY);
  313. if (val != null) {
  314. for (String path : val.split(File.pathSeparator))
  315. addCeilingDirectory(new File(path));
  316. }
  317. }
  318. return self();
  319. }
  320. /**
  321. * Add a ceiling directory to the search limit list.
  322. * <p>
  323. * This setting handles one ceiling directory at a time, and is provided to
  324. * support {@code GIT_CEILING_DIRECTORIES}.
  325. *
  326. * @param root
  327. * a path to stop searching at; its parent will not be searched.
  328. * @return {@code this} (for chaining calls).
  329. */
  330. public B addCeilingDirectory(File root) {
  331. if (root != null) {
  332. if (ceilingDirectories == null)
  333. ceilingDirectories = new LinkedList<File>();
  334. ceilingDirectories.add(root);
  335. }
  336. return self();
  337. }
  338. /**
  339. * Add ceiling directories to the search list.
  340. * <p>
  341. * This setting handles several ceiling directories at once, and is provided
  342. * to support {@code GIT_CEILING_DIRECTORIES}.
  343. *
  344. * @param inList
  345. * directory paths to stop searching at. The collection's
  346. * contents is copied to an internal list.
  347. * @return {@code this} (for chaining calls).
  348. */
  349. public B addCeilingDirectories(Collection<File> inList) {
  350. if (inList != null) {
  351. for (File path : inList)
  352. addCeilingDirectory(path);
  353. }
  354. return self();
  355. }
  356. /**
  357. * Add ceiling directories to the search list.
  358. * <p>
  359. * This setting handles several ceiling directories at once, and is provided
  360. * to support {@code GIT_CEILING_DIRECTORIES}.
  361. *
  362. * @param inList
  363. * directory paths to stop searching at. The array's contents is
  364. * copied to an internal list.
  365. * @return {@code this} (for chaining calls).
  366. */
  367. public B addCeilingDirectories(File[] inList) {
  368. if (inList != null) {
  369. for (File path : inList)
  370. addCeilingDirectory(path);
  371. }
  372. return self();
  373. }
  374. /**
  375. * Configure {@code GIT_DIR} by searching up the file system.
  376. * <p>
  377. * Starts from the current working directory of the JVM and scans up through
  378. * the directory tree until a Git repository is found. Success can be
  379. * determined by checking for {@code getGitDir() != null}.
  380. * <p>
  381. * The search can be limited to specific spaces of the local filesystem by
  382. * {@link #addCeilingDirectory(File)}, or inheriting the list through a
  383. * prior call to {@link #readEnvironment()}.
  384. *
  385. * @return {@code this} (for chaining calls).
  386. */
  387. public B findGitDir() {
  388. if (getGitDir() == null)
  389. findGitDir(new File("").getAbsoluteFile());
  390. return self();
  391. }
  392. /**
  393. * Configure {@code GIT_DIR} by searching up the file system.
  394. * <p>
  395. * Starts from the supplied directory path and scans up through the parent
  396. * directory tree until a Git repository is found. Success can be determined
  397. * by checking for {@code getGitDir() != null}.
  398. * <p>
  399. * The search can be limited to specific spaces of the local filesystem by
  400. * {@link #addCeilingDirectory(File)}, or inheriting the list through a
  401. * prior call to {@link #readEnvironment()}.
  402. *
  403. * @param current
  404. * directory to begin searching in.
  405. * @return {@code this} (for chaining calls).
  406. */
  407. public B findGitDir(File current) {
  408. if (getGitDir() == null) {
  409. FS tryFS = safeFS();
  410. while (current != null) {
  411. File dir = new File(current, DOT_GIT);
  412. if (FileKey.isGitRepository(dir, tryFS)) {
  413. setGitDir(dir);
  414. break;
  415. }
  416. current = current.getParentFile();
  417. if (current != null && ceilingDirectories != null
  418. && ceilingDirectories.contains(current))
  419. break;
  420. }
  421. }
  422. return self();
  423. }
  424. /**
  425. * Guess and populate all parameters not already defined.
  426. * <p>
  427. * If an option was not set, the setup method will try to default the option
  428. * based on other options. If insufficient information is available, an
  429. * exception is thrown to the caller.
  430. *
  431. * @return {@code this}
  432. * @throws IllegalArgumentException
  433. * insufficient parameters were set, or some parameters are
  434. * incompatible with one another.
  435. * @throws IOException
  436. * the repository could not be accessed to configure the rest of
  437. * the builder's parameters.
  438. */
  439. public B setup() throws IllegalArgumentException, IOException {
  440. requireGitDirOrWorkTree();
  441. setupGitDir();
  442. setupWorkTree();
  443. setupInternals();
  444. return self();
  445. }
  446. /**
  447. * Create a repository matching the configuration in this builder.
  448. * <p>
  449. * If an option was not set, the build method will try to default the option
  450. * based on other options. If insufficient information is available, an
  451. * exception is thrown to the caller.
  452. *
  453. * @return a repository matching this configuration.
  454. * @throws IllegalArgumentException
  455. * insufficient parameters were set.
  456. * @throws IOException
  457. * the repository could not be accessed to configure the rest of
  458. * the builder's parameters.
  459. */
  460. @SuppressWarnings("unchecked")
  461. public R build() throws IOException {
  462. return (R) new FileRepository(setup());
  463. }
  464. /** Require either {@code gitDir} or {@code workTree} to be set. */
  465. protected void requireGitDirOrWorkTree() {
  466. if (getGitDir() == null && getWorkTree() == null)
  467. throw new IllegalArgumentException(
  468. JGitText.get().eitherGitDirOrWorkTreeRequired);
  469. }
  470. /**
  471. * Perform standard gitDir initialization.
  472. *
  473. * @throws IOException
  474. * the repository could not be accessed
  475. */
  476. protected void setupGitDir() throws IOException {
  477. // No gitDir? Try to assume its under the workTree.
  478. //
  479. if (getGitDir() == null && getWorkTree() != null)
  480. setGitDir(new File(getWorkTree(), DOT_GIT));
  481. }
  482. /**
  483. * Perform standard work-tree initialization.
  484. * <p>
  485. * This is a method typically invoked inside of {@link #setup()}, near the
  486. * end after the repository has been identified and its configuration is
  487. * available for inspection.
  488. *
  489. * @throws IOException
  490. * the repository configuration could not be read.
  491. */
  492. protected void setupWorkTree() throws IOException {
  493. if (getFS() == null)
  494. setFS(FS.DETECTED);
  495. // If we aren't bare, we should have a work tree.
  496. //
  497. if (!isBare() && getWorkTree() == null)
  498. setWorkTree(guessWorkTreeOrFail());
  499. if (!isBare()) {
  500. // If after guessing we're still not bare, we must have
  501. // a metadata directory to hold the repository. Assume
  502. // its at the work tree.
  503. //
  504. if (getGitDir() == null)
  505. setGitDir(getWorkTree().getParentFile());
  506. if (getIndexFile() == null)
  507. setIndexFile(new File(getGitDir(), "index"));
  508. }
  509. }
  510. /**
  511. * Configure the internal implementation details of the repository.
  512. *
  513. * @throws IOException
  514. * the repository could not be accessed
  515. */
  516. protected void setupInternals() throws IOException {
  517. if (getObjectDirectory() == null && getGitDir() != null)
  518. setObjectDirectory(safeFS().resolve(getGitDir(), "objects"));
  519. }
  520. /**
  521. * Get the cached repository configuration, loading if not yet available.
  522. *
  523. * @return the configuration of the repository.
  524. * @throws IOException
  525. * the configuration is not available, or is badly formed.
  526. */
  527. protected Config getConfig() throws IOException {
  528. if (config == null)
  529. config = loadConfig();
  530. return config;
  531. }
  532. /**
  533. * Parse and load the repository specific configuration.
  534. * <p>
  535. * The default implementation reads {@code gitDir/config}, or returns an
  536. * empty configuration if gitDir was not set.
  537. *
  538. * @return the repository's configuration.
  539. * @throws IOException
  540. * the configuration is not available.
  541. */
  542. protected Config loadConfig() throws IOException {
  543. if (getGitDir() != null) {
  544. // We only want the repository's configuration file, and not
  545. // the user file, as these parameters must be unique to this
  546. // repository and not inherited from other files.
  547. //
  548. File path = safeFS().resolve(getGitDir(), "config");
  549. FileBasedConfig cfg = new FileBasedConfig(path, safeFS());
  550. try {
  551. cfg.load();
  552. } catch (ConfigInvalidException err) {
  553. throw new IllegalArgumentException(MessageFormat.format(
  554. JGitText.get().repositoryConfigFileInvalid, path
  555. .getAbsolutePath(), err.getMessage()));
  556. }
  557. return cfg;
  558. } else {
  559. return new Config();
  560. }
  561. }
  562. private File guessWorkTreeOrFail() throws IOException {
  563. final Config cfg = getConfig();
  564. // If set, core.worktree wins.
  565. //
  566. String path = cfg.getString(CONFIG_CORE_SECTION, null,
  567. CONFIG_KEY_WORKTREE);
  568. if (path != null)
  569. return safeFS().resolve(getGitDir(), path);
  570. // If core.bare is set, honor its value. Assume workTree is
  571. // the parent directory of the repository.
  572. //
  573. if (cfg.getString(CONFIG_CORE_SECTION, null, CONFIG_KEY_BARE) != null) {
  574. if (cfg.getBoolean(CONFIG_CORE_SECTION, CONFIG_KEY_BARE, true)) {
  575. setBare();
  576. return null;
  577. }
  578. return getGitDir().getParentFile();
  579. }
  580. if (getGitDir().getName().equals(DOT_GIT)) {
  581. // No value for the "bare" flag, but gitDir is named ".git",
  582. // use the parent of the directory
  583. //
  584. return getGitDir().getParentFile();
  585. }
  586. // We have to assume we are bare.
  587. //
  588. setBare();
  589. return null;
  590. }
  591. /** @return the configured FS, or {@link FS#DETECTED}. */
  592. protected FS safeFS() {
  593. return getFS() != null ? getFS() : FS.DETECTED;
  594. }
  595. /** @return {@code this} */
  596. @SuppressWarnings("unchecked")
  597. protected final B self() {
  598. return (B) this;
  599. }
  600. }