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