View Javadoc
1   /*
2    * Copyright (C) 2010, Google Inc. and others
3    *
4    * This program and the accompanying materials are made available under the
5    * terms of the Eclipse Distribution License v. 1.0 which is available at
6    * https://www.eclipse.org/org/documents/edl-v10.php.
7    *
8    * SPDX-License-Identifier: BSD-3-Clause
9    */
10  
11  package org.eclipse.jgit.storage.file;
12  
13  import java.io.File;
14  import java.io.IOException;
15  
16  import org.eclipse.jgit.errors.RepositoryNotFoundException;
17  import org.eclipse.jgit.internal.storage.file.FileRepository;
18  import org.eclipse.jgit.lib.BaseRepositoryBuilder;
19  import org.eclipse.jgit.lib.Repository;
20  
21  /**
22   * Constructs a {@link org.eclipse.jgit.internal.storage.file.FileRepository}.
23   * <p>
24   * Applications must set one of {@link #setGitDir(File)} or
25   * {@link #setWorkTree(File)}, or use {@link #readEnvironment()} or
26   * {@link #findGitDir()} in order to configure the minimum property set
27   * necessary to open a repository.
28   * <p>
29   * Single repository applications trying to be compatible with other Git
30   * implementations are encouraged to use a model such as:
31   *
32   * <pre>
33   * new FileRepositoryBuilder() //
34   * 		.setGitDir(gitDirArgument) // --git-dir if supplied, no-op if null
35   * 		.readEnvironment() // scan environment GIT_* variables
36   * 		.findGitDir() // scan up the file system tree
37   * 		.build()
38   * </pre>
39   */
40  public class FileRepositoryBuilder extends
41  		BaseRepositoryBuilder<FileRepositoryBuilder, Repository> {
42  	/**
43  	 * {@inheritDoc}
44  	 * <p>
45  	 * Create a repository matching the configuration in this builder.
46  	 * <p>
47  	 * If an option was not set, the build method will try to default the option
48  	 * based on other options. If insufficient information is available, an
49  	 * exception is thrown to the caller.
50  	 *
51  	 * @since 3.0
52  	 */
53  	@Override
54  	public Repository build() throws IOException {
55  		FileRepository repo = new FileRepository(setup());
56  		if (isMustExist() && !repo.getObjectDatabase().exists())
57  			throw new RepositoryNotFoundException(getGitDir());
58  		return repo;
59  	}
60  
61  	/**
62  	 * Convenience factory method to construct a
63  	 * {@link org.eclipse.jgit.internal.storage.file.FileRepository}.
64  	 *
65  	 * @param gitDir
66  	 *            {@code GIT_DIR}, the repository meta directory.
67  	 * @return a repository matching this configuration.
68  	 * @throws java.io.IOException
69  	 *             the repository could not be accessed to configure the rest of
70  	 *             the builder's parameters.
71  	 * @since 3.0
72  	 */
73  	public static Repository create(File gitDir) throws IOException {
74  		return new FileRepositoryBuilder().setGitDir(gitDir).readEnvironment()
75  				.build();
76  	}
77  }