0

I am trying to check the status of a particular file in a git repo using go-git library.

This is the code I am attempting to run:

    repo, err := git.PlainOpen(fullPathToRepo)
    if err != nil {
        return false, fmt.Errorf("ERROR: Unable to open repository %s\n%s", fullPathToRepo, err)
    }

    workTree, err := repo.Worktree()
    if err != nil {
        return false, fmt.Errorf("ERROR: Unable to open worktree for repository %s\n%s", fullPathToRepo, err)
    }
    workTreeStatus, err := workTree.Status()
    if err != nil {
        return false, fmt.Errorf("ERROR: Unable to retrieve worktree status for repository %s\n%s", fullPathToRepo, err)
    }
    fmt.Printf("%q\n", workTreeStatus.File("releases/filename").Worktree)
    fmt.Printf("%q\n", workTreeStatus.File("/Users/panteliskaramolegkos/myrepo/filename/releases/faros.yaml").Worktree)
    return workTreeStatus.IsClean(), nil

i.e. I am attempting to use both the full as also the relevant (to the repo) path to the file I want to check.

In both cases what is printed out is the following:

`?`
`?`

According to the documentation however, this corresponds to an Untracked file.

The specific file is properly committed and checked in.

Why am I getting the wrong status code?

pkaramol
  • 16,451
  • 43
  • 149
  • 324

1 Answers1

0

Workaround:

var fileStatusMapping = map[git.StatusCode]string{
        git.Unmodified:         "",
        git.Untracked:          "Untracked",
        git.Modified:           "Modified",
        git.Added:              "Added",
        git.Deleted:            "Deleted",
        git.Renamed:            "Renamed",
        git.Copied:             "Copied",
        git.UpdatedButUnmerged: "Updated",
}

func (r *Repo) FileStatus(filename string) (string, string, error) {
        w, err := r.worktree()
        if err != nil {
                return "", "", err
        }
        s, err := w.Status()
        if err != nil {
                return "", "", err
        }
        if s != nil {
                var untracked bool
                if s.IsUntracked(filename) {
                        untracked = true
                }
                fileStatus := s.File(filename)
                if !untracked && fileStatus.Staging == git.Untracked &&
                        fileStatus.Worktree == git.Untracked {
                        fileStatus.Staging = git.Unmodified
                        fileStatus.Worktree = git.Unmodified
                }
                return fileStatusMapping[fileStatus.Staging], fileStatusMapping[fileStatus.Worktree], nil
        }
        return "", "", nil
}

NOTE: s.IsUntracked() called before s.File() on purpose