Skip to content

Commit

Permalink
pkg/vcs: parse git diffs
Browse files Browse the repository at this point in the history
Provide a functionality to extract the files affected by a git patch.
  • Loading branch information
a-nogikh committed Oct 21, 2024
1 parent 0d02c13 commit ade32c2
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
11 changes: 11 additions & 0 deletions pkg/vcs/git.go
Original file line number Diff line number Diff line change
Expand Up @@ -654,3 +654,14 @@ func (git *git) PushCommit(repo, commit string) error {
}
return nil
}

var fileNameRe = regexp.MustCompile(`(?m)^diff.* b\/([^\s]+)`)

// ParseGitDiff extracts the files modified in the git patch.
func ParseGitDiff(patch []byte) []string {
var files []string
for _, match := range fileNameRe.FindAllStringSubmatch(string(patch), -1) {
files = append(files, match[1])
}
return files
}
22 changes: 22 additions & 0 deletions pkg/vcs/git_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -462,3 +462,25 @@ func TestGitFetchShortHash(t *testing.T) {
_, err := local.CheckoutCommit(remoteRepoDir, refCommit.Hash[:12])
assert.NoError(t, err)
}

func TestParseGitDiff(t *testing.T) {
files := ParseGitDiff([]byte(`diff --git a/a.txt b/a.txt
index 4c5fd91..8fe1e32 100644
--- a/a.txt
+++ b/a.txt
@@ -1 +1 @@
-First file
+First file!
diff --git a/b.txt b/b.txt
new file mode 100644
index 0000000..f8a9677
--- /dev/null
+++ b/b.txt
@@ -0,0 +1 @@
+Second file.
diff --git a/c/c.txt b/c/c.txt
new file mode 100644
index 0000000..e69de29
`))
assert.ElementsMatch(t, files, []string{"a.txt", "b.txt", "c/c.txt"})
}

0 comments on commit ade32c2

Please sign in to comment.