Open dorawyy opened 6 years ago
# with a Repo's local path
FileRepositoryBuilder repositoryBuilder = new FileRepositoryBuilder();
Repository repository = repositoryBuilder.setGitDir(new File("/path/to/repo/.git"))
.readEnvironment() // scan environment GIT_* variables
.findGitDir() // scan up the file system tree
.setMustExist(true)
.build();
# with a Repo's local path
Git.open(new File("/path/to/repo/.git"))
.checkout();
Repository repository = git.getRepository();
The example shows how to check out a specific commit. This leaves you in a detatched HEAD state.
# with a Git object
git.checkout()
.setCreateBranch(true)
.setName("new-branch")
.call();
git.checkout()
.setCreateBranch(true)
.setName("new-branch")
.setStartPoint("<id-to-commit>")
.call();
# with a Repository
// find the HEAD
ObjectId lastCommitId = repository.resolve(Constants.HEAD);
// a RevWalk allows to walk over commits based on some filtering that is defined
try (RevWalk revWalk = new RevWalk(repository)) {
RevCommit commit = revWalk.parseCommit(lastCommitId);
// and using commit's tree find the path
RevTree tree = commit.getTree();
System.out.println("Having tree: " + tree);
// now try to find a specific file
try (TreeWalk treeWalk = new TreeWalk(repository)) {
treeWalk.addTree(tree);
treeWalk.setRecursive(true);
treeWalk.setFilter(PathFilter.create("README.md"));
if (!treeWalk.next()) {
throw new IllegalStateException("Did not find expected file 'README.md'");
}
ObjectId objectId = treeWalk.getObjectId(0);
ObjectLoader loader = repository.open(objectId);
// and then one can the loader to read the file
loader.copyTo(System.out);
}
revWalk.dispose();
}
References
Add Maven Dependencies
API
Repository
A Repository holds all objects and refs used for managing source code. To build a repo, you invoke flavors of
RepositoryBuiilder
:Git Objects
All objects are represented by a
SHA-1
id in the Git object model. In JGit, this is represented by theAnyObjectId
andObjectId
classes.There are four types of objects in the Git object model:
blob
: is used to store file datatree
: can be thought of as a dir, it references other trees and blobscommit
: a commit points to a single treetag
: marks a commit as special; generally used to mark specific releases To resolve an object from a repo, simply pass in the right revision stringRef
A
Ref
is a variable that holds a single object identifier. The object identifier can be valid Git object (blob, tree, commit, tag). For example, to query for the references to head, you can simply callRevWalk
A
RevWalk
walks a commit graph and produces the matching commits in orderRevCommit
A
RevCommit
represents a commit in the Git object model. To parse a commit, simply use aRevWalk
instance:RevTag
A
RevTag
represents a tag in the Git object model. to parse a tag, simply use aRevWalk
instance:RevTree
A
RevTree
represents a tree in the Git object model. To parse a tree, simply use aRevWalk
instance: