From f9bc8b0c9b9a9a56687c5086e372d0be689ebd01 Mon Sep 17 00:00:00 2001 From: Brian McGee Date: Thu, 8 Aug 2024 09:52:29 +0100 Subject: [PATCH] fix(git): gracefully handle a file in the index but not in the filesystem This can happen if a user removes a file from the filesystem and that change hasn't been staged yet. We log a warning when this happens and continue. Signed-off-by: Brian McGee --- cli/format_test.go | 8 ++++++-- walk/git.go | 8 +++++++- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/cli/format_test.go b/cli/format_test.go index 1d6d75dd..b8532c38 100644 --- a/cli/format_test.go +++ b/cli/format_test.go @@ -530,14 +530,18 @@ func TestGitWorktree(t *testing.T) { as.NoError(err) run(32, 32, 32, 0) - // remove python directory + // remove python directory from the worktree as.NoError(wt.RemoveGlob("python/*")) run(28, 28, 28, 0) + // remove nixpkgs.toml from the filesystem but leave it in the index + as.NoError(os.Remove(filepath.Join(tempDir, "nixpkgs.toml"))) + run(27, 27, 27, 0) + // walk with filesystem instead of git _, err = cmd(t, "-c", "--config-file", configPath, "--tree-root", tempDir, "--walk", "filesystem") as.NoError(err) - assertStats(t, as, 61, 61, 61, 0) + assertStats(t, as, 60, 60, 60, 0) } func TestPathsArg(t *testing.T) { diff --git a/walk/git.go b/walk/git.go index 4dc91967..f0c5b52e 100644 --- a/walk/git.go +++ b/walk/git.go @@ -13,6 +13,7 @@ import ( ) type gitWalker struct { + log *log.Logger root string paths chan string repo *git.Repository @@ -59,7 +60,11 @@ func (g gitWalker) Walk(ctx context.Context, fn WalkFunc) error { path := filepath.Join(g.root, entry.Name) info, err := os.Lstat(path) - if err != nil { + if os.IsNotExist(err) { + // the underlying file might have been removed without the change being staged yet + g.log.Warnf("Path %s is in the index but appears to have been removed from the filesystem", path) + continue + } else if err != nil { return fmt.Errorf("failed to stat %s: %w", path, err) } @@ -136,6 +141,7 @@ func NewGit(root string, paths chan string) (Walker, error) { return nil, fmt.Errorf("failed to open git repo: %w", err) } return &gitWalker{ + log: log.WithPrefix("walker[git]"), root: root, paths: paths, repo: repo,