Interface GitRepository
- All Superinterfaces:
AutoCloseable
A handle to an opened repository. Must be closed after use. Implementations are not thread-safe: use one
instance per thread and serialise write operations on the same repository.
All paths are relative to the work tree and use / as separator. Failures are reported as
GitException with a message that can be shown to the user.
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final intThe default number of unchanged lines around a change indiff(DiffTarget, String). -
Method Summary
Modifier and TypeMethodDescriptionvoidAbandons a merge in progress and restores the state before it.voidAdds a remote with the usual fetch rule (+refs/heads/*:refs/remotes/<name>/*).intWrites the files of a commit as a Zip archive (git archivesemantics): only what is committed, no.gitfolder, nothing untracked or ignored, file contents byte for byte.The backups of this kind, newest first.blame(String commitId, String path, BlameOptions options) Who last changed every line of a file as it is in a commit (feature 47): the commit, the author, the time and the line it came from.branches()All local and remote-tracking branches.voidSwitches to an existing local branch.checkoutRemoteBranch(String remote, String branch) Checks out a branch of a remote, the waygit checkout <branch>does when only the remote has it: if a local branch of the same name exists it is checked out, otherwise it is created at the remote-tracking branch and set to track it.cherryPick(List<String> commitIds, boolean recordOrigin, boolean noCommit, int mainline) Copies commits onto the current branch, one after the other (asgit cherry-pick).voidclose()Commits the index.commitDetails(String commitId) Message body and changed files of one commit.commitEmpty(String message) Commits even though nothing is staged: the new commit has the same files as its parent, and none at all when it is the first commit of the repository.commitsAhead(String upstream) The commits of the current branch that are not inupstream, oldest first, without merge commits: what a rebase ontoupstreamwould replay.commitsBetween(String base, String tip) The commits oftipthat are not inbase, oldest first, without merge commits: what mergingtipintobasebrings in.commitStats(int maxCount) The commits reachable from HEAD, newest first, at mostmaxCount, each with the files it changed and the lines added and removed (renames are not followed: a renamed file is one deleted and one added).A value of the effective git configuration (repository, global, system), e.g.conflictVersions(String path) The versions of a conflicting file (stages 1, 2 and 3 of the index).default <T> TconsistentReads(Supplier<T> reads) Runs a group of reads that belong together (for example everything a screen shows).createBackup(String kind, String message) Writes a backup of the working tree: a commit holding every file that is not ignored, changed or untracked ones included, with the checked-out commit as its parent, kept by the new refrefs/stemma/<kind>/<time>.voidcreateBranch(String name, String startPoint, boolean checkout) Creates a branch.voidCreates a tag.Name of the checked-out branch, or empty when HEAD is detached.voiddeleteBackup(String ref) Removes a backup (refas inBackupInfo.ref()); its commit goes away with the next garbage collection.voiddeleteBranch(String name, boolean force) Deletes a local branch.voiddeleteRemoteBranch(String remote, String branch) Deletes a branch on a remote (git push <remote> --delete <branch>); the local branch stays.voiddeleteRemoteTag(String remote, String tag) Deletes a tag on the remote (git push <remote> :refs/tags/<tag>); the local tag stays.voidDeletes a tag; the commit it pointed to stays.diff(DiffTarget target, String path) The diff of one file, seeFileDiff.default FileDiffdiff(DiffTarget target, String path, int contextLines) Asdiff(DiffTarget, String), withcontextLinesunchanged lines before and after each change (0 shows the changed lines only).voiddiscard(Collection<String> paths) Throws away local changes of the given paths: tracked files return to their state in HEAD (staged and unstaged changes), new files are deleted.voiddiscardLines(String path, Set<String> lineKeys) Throws away single changes of the working tree (feature 50): the lines ofdiff(Unstaged, path)that are named go back to what the index has (an added line is removed, a removed one is put back).voidDownloads new objects and updates the remote-tracking branches.Optional<byte[]> fileAtCommit(String commitId, String path) The content of a file as it is in a commit, byte for byte (no line-ending conversion).fileHistory(String path, boolean follow, int maxCount) The commits that changed a file or a folder (feature 46), newest first, reachable from HEAD.The paths of all files of a commit, sorted, with/as separator; no folders.history(int maxCount) The history as the graph shows it: commits reachable from HEAD, any local or remote-tracking branch or any tag, newest first, never a parent before one of its children.log(int maxCount) Commits reachable from HEAD, newest first, at mostmaxCountentries.Mergesbranch(local or remote-tracking) into the current branch.booleanWhether a merge is in progress (conflicts waiting to be resolved).pull()Fetches and merges the upstream branch into the current branch.default voidPushes a local branch.voidPushes a local branch, possibly overwriting the remote branch.voidPushes one tag.voidPushes all local tags that the remote does not have yet.Replays the commits of the current branch on top ofonto(a branch, tag or commit).voidGives up: the branch is back where it was before the rebase.Carries on after the conflicts of the current step are resolved and staged.booleanWhether a rebase is waiting for conflicts to be resolved (or forrebaseContinue()).rebaseInteractive(String onto, List<RebaseStep> steps) An interactive rebase: replays the commits as the to-do list says, in that order, on top ofonto.Leaves out the commit that caused the conflict and carries on.remotes()The configured remotes.remoteTags(String remote) The names of the tags that a remote has (asks the remote: a network call).voidremoveRemote(String name) Removes a remote together with its remote-tracking branches.voidrenameBranch(String oldName, String newName) Renames a local branch, also the current one.voidrenameRemote(String oldName, String newName) Renames a remote: its configuration, its remote-tracking branches and the upstream settings of local branches that follow it move along.voidMoves the current branch totarget(asgit reset);modesays what happens to the index and the files.Makes a new commit for each given commit that undoes its changes (asgit revert), messageRevert "…".The id of the repository's oldest root commit (the smallest id if there are several): the same on every clone of the repository, so it can identify the repository across computers.voidGives up: the branch and the working tree are as they were before the series started.Carries on after the conflicts of the current step are resolved and staged.Which series of commits (cherry-pick or revert) waits for conflicts to be resolved,SequenceKind.NONEif none.Leaves out the commit that caused the conflict (its changes are thrown away) and carries on.voidSets a value in the repository's own configuration.voidsetRemoteUrl(String name, String url) Changes the URL used to fetch from and push to a remote.squashLast(int count, String message) Replaces the lastcountcommits of the current branch by one commit with the same combined changes (the equivalent ofgit reset --soft HEAD~countfollowed by a commit).voidstage(Collection<String> paths) Stages additions, modifications and deletions of the given paths (git add -A -- paths).voidstageHunks(String path, Set<String> hunkKeys) Stages some hunks of a file: the index gets those changes ofdiff(Unstaged, path)whose hunks are named byhunkKeys(seeHunks.keyOf(java.lang.String)); the other changes stay unstaged.voidstageLines(String path, Set<String> lineKeys) Stages single lines of a file (feature 50): the index gets the added and removed lines ofdiff(Unstaged, path)whose keys are named bylineKeys(seeHunks.ChangeLine); every other change stays unstaged.voidstashApply(int index) Applies stashindexand keeps it on the stash.voidstashBranch(int index, String branch) Makes a new branch at the commit the stash was made on, checks it out, applies the stash there and removes it from the stash (git stash branch).stashDetails(int index) The files of stashindex, for showing it like a commit.voidstashDrop(int index) Removes stashindexwithout applying it.stashes()The stash, newest first.voidstashPop(int index) Applies stashindexand removes it from the stash.default voidSaves the local changes on the stash and cleans the working tree.voidstashPush(String message, StashOptions options) Saves local changes on the stash and cleans them from the working tree (as far asoptionssay).status()Working tree and index status.tags()All tags, with annotated tags peeled to their commit.tracking()Upstream relation of the current branch; empty if the branch has no upstream (or HEAD is detached).voidunsetConfig(String key) Removes a value from the repository's own configuration.voidunstage(Collection<String> paths) Removes the given paths from the index, keeping the working tree (git reset -- paths).voidunstageHunks(String path, Set<String> hunkKeys) Unstages some hunks of a file: the index loses those changes ofdiff(Staged, path)whose hunks are named byhunkKeys; the working tree is not touched.voidunstageLines(String path, Set<String> lineKeys) Unstages single lines: the index loses those changes ofdiff(Staged, path)whose lines are named; the working tree stays as it is.voiduntrack(Collection<String> paths) Stops tracking the files without touching them on the disk (git rm --cached): they leave the index, so the next commit deletes them from the repository, and they are untracked files in the working tree afterwards.The directories of the working tree that a file watcher should watch (feature 53): every directory that Git does not ignore, as a path relative to the work tree with/as separator, sorted; the work tree itself is the empty string.workTree()Root directory of the work tree.
-
Field Details
-
DEFAULT_CONTEXT
static final int DEFAULT_CONTEXTThe default number of unchanged lines around a change indiff(DiffTarget, String).- See Also:
-
-
Method Details
-
workTree
Path workTree()Root directory of the work tree. -
currentBranch
Name of the checked-out branch, or empty when HEAD is detached. -
branches
List<BranchInfo> branches()All local and remote-tracking branches. -
log
Commits reachable from HEAD, newest first, at mostmaxCountentries. Empty for unborn branches. -
history
The history as the graph shows it: commits reachable from HEAD, any local or remote-tracking branch or any tag, newest first, never a parent before one of its children. At mostmaxCountentries. -
commitStats
The commits reachable from HEAD, newest first, at mostmaxCount, each with the files it changed and the lines added and removed (renames are not followed: a renamed file is one deleted and one added). Empty without commits. -
status
List<StatusEntry> status()Working tree and index status. -
tags
All tags, with annotated tags peeled to their commit. -
stashes
The stash, newest first. -
remotes
List<RemoteInfo> remotes()The configured remotes. -
watchableDirectories
The directories of the working tree that a file watcher should watch (feature 53): every directory that Git does not ignore, as a path relative to the work tree with/as separator, sorted; the work tree itself is the empty string. Ignored directories are not entered (anode_modulesortargetfolder costs nothing), and neither are.gitand nested repositories. Empty directories are included. -
tracking
Optional<TrackingInfo> tracking()Upstream relation of the current branch; empty if the branch has no upstream (or HEAD is detached). -
commitDetails
Message body and changed files of one commit. -
diff
The diff of one file, seeFileDiff. -
diff
Asdiff(DiffTarget, String), withcontextLinesunchanged lines before and after each change (0 shows the changed lines only). Hunk staging works with the default context; a diff with another context is for reading. -
mergeInProgress
boolean mergeInProgress()Whether a merge is in progress (conflicts waiting to be resolved). -
config
A value of the effective git configuration (repository, global, system), e.g.user.name. -
stage
Stages additions, modifications and deletions of the given paths (git add -A -- paths). -
unstage
Removes the given paths from the index, keeping the working tree (git reset -- paths). -
untrack
Stops tracking the files without touching them on the disk (git rm --cached): they leave the index, so the next commit deletes them from the repository, and they are untracked files in the working tree afterwards. Used to ignore a file that Git already knows. -
commit
Commits the index.- Parameters:
message- the complete message (summary, blank line, description)amend- replace the last commit instead of adding a new one- Returns:
- the id of the new commit
- Throws:
GitException- if nothing is staged, the author identity is unknown, or signing fails
-
commitEmpty
Commits even though nothing is staged: the new commit has the same files as its parent, and none at all when it is the first commit of the repository. Used for the initial commit of a new repository, so that branches can exist.- Parameters:
message- the complete message- Returns:
- the id of the new commit
- Throws:
GitException- if the message is empty, the author identity is unknown, or signing fails
-
discard
Throws away local changes of the given paths: tracked files return to their state in HEAD (staged and unstaged changes), new files are deleted. Irreversible. -
reset
Moves the current branch totarget(asgit reset);modesays what happens to the index and the files. With a detached HEAD, HEAD itself moves.- Parameters:
target- a commit id, branch or tag- Throws:
GitException- iftargetis unknown, the repository has no commit, or a merge is in progress
-
createBackup
Writes a backup of the working tree: a commit holding every file that is not ignored, changed or untracked ones included, with the checked-out commit as its parent, kept by the new refrefs/stemma/<kind>/<time>. Neither the branch, nor the index, nor the files change. Used before something that throws changes away; to get them back,reset(commitId, HARD)and thenreset(headId, MIXED).- Parameters:
kind- one word, e.g.resetmessage- what it is for; the first line becomes the subject- Returns:
- the backup
- Throws:
GitException- if the repository has no commit yet, or the author identity is unknown
-
backups
The backups of this kind, newest first. -
deleteBackup
Removes a backup (refas inBackupInfo.ref()); its commit goes away with the next garbage collection. -
stashPush
Saves the local changes on the stash and cleans the working tree. -
stashPush
Saves local changes on the stash and cleans them from the working tree (as far asoptionssay).- Parameters:
message-nullor blank for git's own description- Throws:
GitException- if there is nothing to stash, or the options needCapability.STASH_OPTIONS, which this backend does not have
-
stashApply
void stashApply(int index) Applies stashindexand keeps it on the stash. On conflicts the files carry them and the stash stays. -
stashBranch
Makes a new branch at the commit the stash was made on, checks it out, applies the stash there and removes it from the stash (git stash branch). If applying conflicts, the branch exists and the stash stays.- Throws:
GitException- if the name is not valid or taken, or local changes are in the way of the checkout
-
stashDetails
The files of stashindex, for showing it like a commit. -
stashPop
void stashPop(int index) Applies stashindexand removes it from the stash. On conflicts it stays on the stash. -
stashDrop
void stashDrop(int index) Removes stashindexwithout applying it. -
renameBranch
Renames a local branch, also the current one. Its configuration (upstream) and its reflog move with it; a remote is not touched.- Throws:
GitException- ifoldNameis not a branch,newNameis taken or not a valid branch name
-
deleteRemoteBranch
Deletes a branch on a remote (git push <remote> --delete <branch>); the local branch stays.- Parameters:
branch- the branch name on that remote, without the remote prefix
-
checkout
Switches to an existing local branch. Fails if local changes would be overwritten. -
checkoutRemoteBranch
Checks out a branch of a remote, the waygit checkout <branch>does when only the remote has it: if a local branch of the same name exists it is checked out, otherwise it is created at the remote-tracking branch and set to track it.- Parameters:
remote- the remote's name, e.g.originbranch- the branch name on that remote, without the remote prefix, e.g.feature/login- Returns:
- the name of the local branch that is now checked out
- Throws:
GitException- if the remote-tracking branch does not exist, or local changes would be overwritten
-
createBranch
Creates a branch.- Parameters:
startPoint- commit id or ref to start at;nullfor HEADcheckout- switch to the new branch
-
deleteBranch
Deletes a local branch. Refuses to delete the current branch, or an unmerged one unlessforce. -
merge
Mergesbranch(local or remote-tracking) into the current branch. -
abortMerge
void abortMerge()Abandons a merge in progress and restores the state before it. -
rootCommitId
The id of the repository's oldest root commit (the smallest id if there are several): the same on every clone of the repository, so it can identify the repository across computers. Empty if there are no commits yet. -
consistentReads
Runs a group of reads that belong together (for example everything a screen shows). Nothing may change the repository while it runs; in return a backend may answer the reads from one another's results instead of asking git again and again. The default simply runsreads. -
rebaseInProgress
boolean rebaseInProgress()Whether a rebase is waiting for conflicts to be resolved (or forrebaseContinue()). -
commitsAhead
The commits of the current branch that are not inupstream, oldest first, without merge commits: what a rebase ontoupstreamwould replay. -
commitsBetween
The commits oftipthat are not inbase, oldest first, without merge commits: what mergingtipintobasebrings in.- Throws:
GitException- if one of them is not a branch or commit
-
rebase
Replays the commits of the current branch on top ofonto(a branch, tag or commit).- Throws:
GitException- if the working tree has uncommitted changes, a merge or rebase is in progress, HEAD is detached, orontois unknown
-
rebaseInteractive
An interactive rebase: replays the commits as the to-do list says, in that order, on top ofonto.- Parameters:
steps- the commits to replay, oldest first, each with its action; commits that are not listed are dropped. The first step that is not dropped cannot be a squash or fixup.- Throws:
GitException- asrebase(java.lang.String), or if the list does not make sense
-
rebaseContinue
RebaseResult rebaseContinue()Carries on after the conflicts of the current step are resolved and staged. -
rebaseSkip
RebaseResult rebaseSkip()Leaves out the commit that caused the conflict and carries on. -
rebaseAbort
void rebaseAbort()Gives up: the branch is back where it was before the rebase. -
sequenceInProgress
SequenceKind sequenceInProgress()Which series of commits (cherry-pick or revert) waits for conflicts to be resolved,SequenceKind.NONEif none. -
cherryPick
SequenceResult cherryPick(List<String> commitIds, boolean recordOrigin, boolean noCommit, int mainline) Copies commits onto the current branch, one after the other (asgit cherry-pick). The author, the date and the message of each commit are kept; the committer is the current identity. A commit that changes nothing (it is on the branch already) is skipped. On a conflict it stops: resolve and stage the files, thensequenceContinue().- Parameters:
commitIds- the commits in the order to apply them (oldest first)recordOrigin- add the line(cherry picked from commit …)to each message (-x)noCommit- only change the working tree and the index and make no commit; for exactly one commit. A conflict undoes everything and is reported as an errormainline- for a merge commit: the number (1, 2, …) of the parent whose side is kept as the base; ignored for others- Throws:
GitException- if a series is in progress, a merge or rebase is in progress, tracked files have uncommitted changes, a commit is unknown, or a merge commit is given withoutmainline
-
revert
Makes a new commit for each given commit that undoes its changes (asgit revert), messageRevert "…". Parameters and conflicts as forcherryPick(java.util.List<java.lang.String>, boolean, boolean, int).- Parameters:
commitIds- the commits in the order to revert them (newest first is the natural order)
-
sequenceContinue
SequenceResult sequenceContinue()Carries on after the conflicts of the current step are resolved and staged. -
sequenceSkip
SequenceResult sequenceSkip()Leaves out the commit that caused the conflict (its changes are thrown away) and carries on. -
sequenceAbort
void sequenceAbort()Gives up: the branch and the working tree are as they were before the series started. -
archive
Writes the files of a commit as a Zip archive (git archivesemantics): only what is committed, no.gitfolder, nothing untracked or ignored, file contents byte for byte.- Parameters:
topFolder- the folder inside the archive that holds everything (the repository name), or empty for none- Returns:
- the number of files in the archive
- Throws:
GitException- if the commit does not exist or the file cannot be written
-
fileAtCommit
The content of a file as it is in a commit, byte for byte (no line-ending conversion).- Returns:
- empty if the commit has no such file
- Throws:
GitException- if the commit does not exist
-
blame
Who last changed every line of a file as it is in a commit (feature 47): the commit, the author, the time and the line it came from. Follows the file across renames. Slow on a big file with a long history, so call it off the UI thread.- Parameters:
commitId- the commit whose version of the file is blamedoptions- what to ignore- Returns:
- one entry per line of the file, in the order of the file; empty for an empty file
- Throws:
GitException- if the commit does not exist or has no such file
-
fileHistory
The commits that changed a file or a folder (feature 46), newest first, reachable from HEAD. Withfollowa file is followed across renames, and each entry says which name the file had in that commit; for a folder, or withoutfollow, only that path counts. Merge commits are listed likegit log -- pathdoes: those that are not the same as one of their parents at this path.- Parameters:
follow- follow a single file across renames (not for a folder)maxCount- at most this many commits- Returns:
- empty for an unborn branch or a path that never existed
-
filesAt
The paths of all files of a commit, sorted, with/as separator; no folders.- Throws:
GitException- if the commit does not exist
-
conflictVersions
The versions of a conflicting file (stages 1, 2 and 3 of the index).- Throws:
GitException- if the file has no conflict
-
stageHunks
Stages some hunks of a file: the index gets those changes ofdiff(Unstaged, path)whose hunks are named byhunkKeys(seeHunks.keyOf(java.lang.String)); the other changes stay unstaged. The path may be a file that is not tracked yet.- Throws:
GitException- if the file is binary, deleted, has no newline at its end, a hunk is not (any more) part of the diff, or the index cannot be written
-
unstageHunks
Unstages some hunks of a file: the index loses those changes ofdiff(Staged, path)whose hunks are named byhunkKeys; the working tree is not touched. -
stageLines
Stages single lines of a file (feature 50): the index gets the added and removed lines ofdiff(Unstaged, path)whose keys are named bylineKeys(seeHunks.ChangeLine); every other change stays unstaged. Works on the bytes, so line endings and a last line without a line feed are kept.- Throws:
GitException- if the file is binary, has conflicts, a key is not (any more) in the diff, or the choice would join two lines because the file has no line feed at its end
-
unstageLines
Unstages single lines: the index loses those changes ofdiff(Staged, path)whose lines are named; the working tree stays as it is. -
discardLines
Throws away single changes of the working tree (feature 50): the lines ofdiff(Unstaged, path)that are named go back to what the index has (an added line is removed, a removed one is put back). The file in the working tree is rewritten; nothing is kept, so the caller makes the backup that it wants (seecreateBackup(java.lang.String, java.lang.String)).- Throws:
GitException- asstageLines(java.lang.String, java.util.Set<java.lang.String>), and if Git converts the line endings of this file (the lines of the diff are not those of the file)
-
squashLast
Replaces the lastcountcommits of the current branch by one commit with the same combined changes (the equivalent ofgit reset --soft HEAD~countfollowed by a commit). The new commit is made by the current user. Rewrites history: commits that were already published will need a force-push.- Parameters:
message- the message of the new commit; blank = the summaries of the squashed commits, listed- Returns:
- the id of the new commit
- Throws:
GitException- ifcountis less than 2 or reaches the first commit, a merge commit is among the commits, changes are staged, or a merge is in progress
-
createTag
Creates a tag.- Parameters:
commitId- the commit to tag;nullfor HEADmessage- tag message;nullor blank creates a lightweight tag, otherwise an annotated one
-
deleteTag
Deletes a tag; the commit it pointed to stays.- Parameters:
name- the tag name (withoutrefs/tags/)
-
fetch
Downloads new objects and updates the remote-tracking branches.remote == null: all remotes. -
pull
MergeResult pull()Fetches and merges the upstream branch into the current branch. -
push
Pushes a local branch.- Parameters:
remote- remote name, e.g.origin;nullfor the branch's upstream remotebranch- local branch;nullfor the current branchsetUpstream- remember the remote branch as upstream- Throws:
GitException- if the remote rejects the push (for example non-fast-forward)
-
push
Pushes a local branch, possibly overwriting the remote branch.- Parameters:
force- what may be overwritten, seePushForce- Throws:
GitException- if the remote rejects the push, or the lease cannot be set up because the remote-tracking branch is unknown (the branch was never pushed or fetched)
-
pushTag
Pushes one tag.- Parameters:
remote- remote name;nullfor the remote of the current branch (elseoriginor the only remote)- Throws:
GitException- if the remote has a tag of that name that points to another commit, or the push fails
-
pushTags
Pushes all local tags that the remote does not have yet. A tag that exists there with another commit is rejected and reported, nothing is overwritten.- Parameters:
remote- remote name;nullas forpushTag(java.lang.String, java.lang.String)
-
remoteTags
The names of the tags that a remote has (asks the remote: a network call).- Parameters:
remote- remote name;nullas forpushTag(java.lang.String, java.lang.String)
-
deleteRemoteTag
Deletes a tag on the remote (git push <remote> :refs/tags/<tag>); the local tag stays.- Parameters:
remote- remote name;nullas forpushTag(java.lang.String, java.lang.String)
-
setConfig
Sets a value in the repository's own configuration. -
unsetConfig
Removes a value from the repository's own configuration. Not an error if it is not set. -
addRemote
Adds a remote with the usual fetch rule (+refs/heads/*:refs/remotes/<name>/*). -
setRemoteUrl
Changes the URL used to fetch from and push to a remote. -
renameRemote
Renames a remote: its configuration, its remote-tracking branches and the upstream settings of local branches that follow it move along. -
removeRemote
Removes a remote together with its remote-tracking branches. -
close
void close()- Specified by:
closein interfaceAutoCloseable
-