|
| 1 | +package com.baeldung.jgit; |
| 2 | + |
| 3 | +import com.baeldung.jgit.helper.Helper; |
| 4 | +import org.eclipse.jgit.api.Git; |
| 5 | +import org.eclipse.jgit.api.errors.GitAPIException; |
| 6 | +import org.eclipse.jgit.lib.Ref; |
| 7 | +import org.eclipse.jgit.lib.Repository; |
| 8 | +import org.eclipse.jgit.storage.file.FileRepositoryBuilder; |
| 9 | +import java.io.File; |
| 10 | +import java.io.IOException; |
| 11 | + |
| 12 | +/** |
| 13 | + * Simple snippet which shows how to open an existing repository |
| 14 | + * |
| 15 | + * |
| 16 | + */ |
| 17 | +public class OpenRepository { |
| 18 | + |
| 19 | + public static void main(String[] args) throws IOException, GitAPIException { |
| 20 | + // first create a test-repository, the return is including the .get directory here! |
| 21 | + File repoDir = createSampleGitRepo(); |
| 22 | + |
| 23 | + // now open the resulting repository with a FileRepositoryBuilder |
| 24 | + FileRepositoryBuilder builder = new FileRepositoryBuilder(); |
| 25 | + try (Repository repository = builder.setGitDir(repoDir) |
| 26 | + .readEnvironment() // scan environment GIT_* variables |
| 27 | + .findGitDir() // scan up the file system tree |
| 28 | + .build()) { |
| 29 | + System.out.println("Having repository: " + repository.getDirectory()); |
| 30 | + |
| 31 | + // the Ref holds an ObjectId for any type of object (tree, commit, blob, tree) |
| 32 | + Ref head = repository.exactRef("refs/heads/master"); |
| 33 | + System.out.println("Ref of refs/heads/master: " + head); |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + private static File createSampleGitRepo() throws IOException, GitAPIException { |
| 38 | + try (Repository repository = Helper.createNewRepository()) { |
| 39 | + System.out.println("Temporary repository at " + repository.getDirectory()); |
| 40 | + |
| 41 | + // create the file |
| 42 | + File myfile = new File(repository.getDirectory().getParent(), "testfile"); |
| 43 | + if(!myfile.createNewFile()) { |
| 44 | + throw new IOException("Could not create file " + myfile); |
| 45 | + } |
| 46 | + |
| 47 | + // run the add-call |
| 48 | + try (Git git = new Git(repository)) { |
| 49 | + git.add() |
| 50 | + .addFilepattern("testfile") |
| 51 | + .call(); |
| 52 | + |
| 53 | + |
| 54 | + // and then commit the changes |
| 55 | + git.commit() |
| 56 | + .setMessage("Added testfile") |
| 57 | + .call(); |
| 58 | + } |
| 59 | + |
| 60 | + System.out.println("Added file " + myfile + " to repository at " + repository.getDirectory()); |
| 61 | + |
| 62 | + return repository.getDirectory(); |
| 63 | + } |
| 64 | + } |
| 65 | +} |
0 commit comments