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

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