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