From 8217737525f05b28359c17abeb0423ee3437c049 Mon Sep 17 00:00:00 2001 From: Petr Fedchenkov Date: Wed, 7 Sep 2022 11:25:44 +0300 Subject: [PATCH] Append dirty tag with content hash To be able to identify successive file changes without commit, we should use their hash in tag alongside with dirty flag (-dirty-). Signed-off-by: Petr Fedchenkov --- src/cmd/linuxkit/pkglib/git.go | 29 +++++++++++++++++++++++++++++ src/cmd/linuxkit/pkglib/pkglib.go | 10 +++++++++- 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/src/cmd/linuxkit/pkglib/git.go b/src/cmd/linuxkit/pkglib/git.go index 6286c8a1b..b51faeeed 100644 --- a/src/cmd/linuxkit/pkglib/git.go +++ b/src/cmd/linuxkit/pkglib/git.go @@ -3,10 +3,13 @@ package pkglib // Thin wrappers around git CLI invocations import ( + "bufio" + "crypto/sha256" "fmt" "io" "os" "os/exec" + "path/filepath" "regexp" "strings" @@ -83,6 +86,32 @@ func (g git) isWorkTree(pkg string) (bool, error) { return false, fmt.Errorf("unexpected output from git rev-parse --is-inside-work-tree: %s", tf) } +func (g git) contentHash() (string, error) { + hash := sha256.New() + out, err := g.commandStdout(nil, "ls-files") + if err != nil { + return "", err + } + scanner := bufio.NewScanner(strings.NewReader(strings.TrimSpace(out))) + for scanner.Scan() { + f, err := os.Open(filepath.Join(g.dir, scanner.Text())) + if err != nil { + return "", err + } + if _, err := io.Copy(hash, f); err != nil { + _ = f.Close() + return "", err + } + if err = f.Close(); err != nil { + return "", err + } + } + if err = scanner.Err(); err != nil { + return "", err + } + return fmt.Sprintf("%x", hash.Sum(nil)), nil +} + func (g git) treeHash(pkg, commit string) (string, error) { // we have to check if pkg is at the top level of the git tree, // if that's the case we need to use tree hash from the commit itself diff --git a/src/cmd/linuxkit/pkglib/pkglib.go b/src/cmd/linuxkit/pkglib/pkglib.go index b66925290..5ddf43bd7 100644 --- a/src/cmd/linuxkit/pkglib/pkglib.go +++ b/src/cmd/linuxkit/pkglib/pkglib.go @@ -250,7 +250,15 @@ func NewFromCLI(fs *flag.FlagSet, args ...string) ([]Pkg, error) { } if dirty { - pkgHash += "-dirty" + contentHash, err := git.contentHash() + if err != nil { + return nil, err + } + if len(contentHash) < 7 { + return nil, fmt.Errorf("unexpected hash len: %d", len(contentHash)) + } + // construct -dirty- tag + pkgHash += fmt.Sprintf("-dirty-%s", contentHash[0:7]) } } }