How to check for uncommitted changes in the working area using go-git

65 views Asked by At

I'm currently working on a web editor integrated with Git using the go-git library. I'm looking for a way to programmatically check for modifications in the working area before adding files to a commit.

I've gone through the go-git documentation, and the closest thing I found is the Patch API. However, it seems to be geared towards showing the changes between two commits rather than changes in the working area that haven't been committed yet.

I'm curious to know if go-git supports the behavior of identifying and viewing modifications in the working area before they are added to a commit. If it does, could someone provide guidance or a clue on how to achieve this using the library?

1

There are 1 answers

2
Brian Wagner On

Yes, go-git allows you to check the status of the repo. This file holds that code: https://github.com/go-git/go-git/blob/master/status.go

The main doc page does not show this piece. But if we extend the example there, it's something like this:

r, err := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
    URL: "https://github.com/go-git/go-billy",
})
CheckIfError(err)

wt, err := r.Worktree()
CheckIfError(err)

st, _ := wt.Status()
if st.IsClean() {
    fmt.Println("no changes to commit")
    return
}

You can also check a file path for untracked status, with the IsUntracked() method.

Note CheckIfError is not a method in the package. Just placeholder for some error check to implement on your side.