root: make TestLicenseHeaders skip files unknown to git

The license header test walked the whole tree, so scratch files,
worktrees, and other untracked local files made "go test ." fail in a
developer checkout. Ask git for the set of tracked files and only
check those, falling back to checking everything (as before) when the
tree is not a git checkout, such as in a release tarball.

Fixes #20740

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
Change-Id: I9f3a7c21e5b804d6a2f4c8e19d7b53a6e0c412fd
This commit is contained in:
Brad Fitzpatrick authored and Brad Fitzpatrick committed 2026-08-04 10:47:35 +01:00
1 parent 91c1bbecb1
commit 12e4462ba3
1 file changed
+25
+25
View File
@@ -8,6 +8,7 @@ import (
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
@@ -15,6 +16,24 @@ import (
"tailscale.com/util/set"
)
// gitTrackedFiles returns the set of files known to git in the current
// directory tree, or nil if the tree is not a git checkout or git is
// unavailable.
func gitTrackedFiles(t *testing.T) set.Set[string] {
out, err := exec.Command("git", "ls-files", "-z").Output()
if err != nil {
t.Logf("git ls-files failed (%v); checking all files", err)
return nil
}
tracked := set.Set[string]{}
for f := range strings.SplitSeq(string(out), "\x00") {
if f != "" {
tracked.Add(f)
}
}
return tracked
}
func normalizeLineEndings(b []byte) []byte {
return bytes.ReplaceAll(b, []byte("\r\n"), []byte("\n"))
}
@@ -47,10 +66,16 @@ func TestLicenseHeaders(t *testing.T) {
"k8s-operator/apis/v1alpha1/zz_generated.deepcopy.go",
)
tracked := gitTrackedFiles(t)
err := filepath.Walk(".", func(path string, fi os.FileInfo, err error) error {
if err != nil {
return fmt.Errorf("path %s: %v", path, err)
}
if tracked != nil && !fi.IsDir() && !tracked.Contains(filepath.ToSlash(path)) {
// Ignore files not known to git (scratch files, etc).
return nil
}
if exceptions.Contains(filepath.ToSlash(path)) {
return nil
}