gitutil: migrate to BuildKit GitCLI API

Signed-off-by: CrazyMax <1951866+crazy-max@users.noreply.github.com>
This commit is contained in:
CrazyMax
2026-04-09 14:57:38 +02:00
parent 3124b3c839
commit 720f91fdd4
10 changed files with 135 additions and 157 deletions
+20 -10
View File
@@ -1,15 +1,17 @@
package gittestutil
import (
"context"
"os"
"strings"
"testing"
"github.com/docker/buildx/util/gitutil"
"github.com/pkg/errors"
"github.com/stretchr/testify/require"
)
func GitInit(c *gitutil.Git, tb testing.TB) {
func GitInit(c *gitutil.GitCLI, tb testing.TB) {
tb.Helper()
out, err := fakeGit(c, "init")
require.NoError(tb, err)
@@ -19,48 +21,48 @@ func GitInit(c *gitutil.Git, tb testing.TB) {
_, _ = fakeGit(c, "branch", "-D", "master")
}
func GitCommit(c *gitutil.Git, tb testing.TB, msg string) {
func GitCommit(c *gitutil.GitCLI, tb testing.TB, msg string) {
tb.Helper()
out, err := fakeGit(c, "commit", "--allow-empty", "-m", msg)
require.NoError(tb, err)
require.Contains(tb, out, "main", msg)
}
func GitTag(c *gitutil.Git, tb testing.TB, tag string) {
func GitTag(c *gitutil.GitCLI, tb testing.TB, tag string) {
tb.Helper()
out, err := fakeGit(c, "tag", tag)
require.NoError(tb, err)
require.Empty(tb, out)
}
func GitTagAnnotated(c *gitutil.Git, tb testing.TB, tag, message string) {
func GitTagAnnotated(c *gitutil.GitCLI, tb testing.TB, tag, message string) {
tb.Helper()
out, err := fakeGit(c, "tag", "-a", tag, "-m", message)
require.NoError(tb, err)
require.Empty(tb, out)
}
func GitCheckoutBranch(c *gitutil.Git, tb testing.TB, name string) {
func GitCheckoutBranch(c *gitutil.GitCLI, tb testing.TB, name string) {
tb.Helper()
out, err := fakeGit(c, "checkout", "-b", name)
require.NoError(tb, err)
require.Empty(tb, out)
}
func GitAdd(c *gitutil.Git, tb testing.TB, files ...string) {
func GitAdd(c *gitutil.GitCLI, tb testing.TB, files ...string) {
tb.Helper()
args := append([]string{"add"}, files...)
_, err := fakeGit(c, args...)
require.NoError(tb, err)
}
func GitSetRemote(c *gitutil.Git, tb testing.TB, name string, url string) {
func GitSetRemote(c *gitutil.GitCLI, tb testing.TB, name string, url string) {
tb.Helper()
_, err := fakeGit(c, "remote", "add", name, url)
require.NoError(tb, err)
}
func GitSetMainUpstream(c *gitutil.Git, tb testing.TB, remote, target string) {
func GitSetMainUpstream(c *gitutil.GitCLI, tb testing.TB, remote, target string) {
tb.Helper()
_, err := fakeGit(c, "fetch", "--depth", "1", remote, target)
require.NoError(tb, err)
@@ -81,7 +83,7 @@ func Mktmp(tb testing.TB) string {
return folder
}
func fakeGit(c *gitutil.Git, args ...string) (string, error) {
func fakeGit(c *gitutil.GitCLI, args ...string) (string, error) {
allArgs := []string{
"-c", "user.name=buildx",
"-c", "user.email=buildx@docker.com",
@@ -90,7 +92,15 @@ func fakeGit(c *gitutil.Git, args ...string) (string, error) {
"-c", "log.showSignature=false",
}
allArgs = append(allArgs, args...)
return c.Run(allArgs...)
return clean(c.Run(context.TODO(), allArgs...))
}
func clean(dt []byte, err error) (string, error) {
out := strings.ReplaceAll(strings.Split(string(dt), "\n")[0], "'", "")
if err != nil {
err = errors.New(strings.TrimSuffix(err.Error(), "\n"))
}
return out, err
}
func IsAmbiguousArgument(err error) bool {
+3 -3
View File
@@ -24,7 +24,7 @@ func WithAccessToken(token string) GitServeOpt {
}
}
func GitServeHTTP(c *gitutil.Git, t testing.TB, opts ...GitServeOpt) (url string) {
func GitServeHTTP(c *gitutil.GitCLI, t testing.TB, opts ...GitServeOpt) (url string) {
t.Helper()
gitUpdateServerInfo(c, t)
ctx, cancel := context.WithCancelCause(context.TODO())
@@ -38,7 +38,7 @@ func GitServeHTTP(c *gitutil.Git, t testing.TB, opts ...GitServeOpt) (url string
done := make(chan struct{})
name := "test.git"
dir, err := c.GitDir()
dir, err := c.GitDir(context.TODO())
if err != nil {
cancel(err)
}
@@ -93,7 +93,7 @@ func GitServeHTTP(c *gitutil.Git, t testing.TB, opts ...GitServeOpt) (url string
return fmt.Sprintf("http://%s/%s", addr, name)
}
func gitUpdateServerInfo(c *gitutil.Git, tb testing.TB) {
func gitUpdateServerInfo(c *gitutil.GitCLI, tb testing.TB) {
tb.Helper()
_, err := fakeGit(c, "update-server-info")
require.NoError(tb, err)
+42 -95
View File
@@ -1,122 +1,98 @@
package gitutil
import (
"bytes"
"context"
"net/url"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/docker/buildx/util/osutil"
bkgitutil "github.com/moby/buildkit/util/gitutil"
"github.com/pkg/errors"
)
// Git represents an active git object
type Git struct {
ctx context.Context
wd string
gitpath string
// GitCLI represents an active git object.
type GitCLI struct {
bkgitutil.GitCLI
}
// Option provides a variadic option for configuring the git client.
type Option func(b *Git)
// New initializes a new git client.
func New(opts ...bkgitutil.Option) (*GitCLI, error) {
cli := bkgitutil.NewGitCLI(append(opts, bkgitutil.WithHostGitConfig())...)
// WithContext sets context.
func WithContext(ctx context.Context) Option {
return func(b *Git) {
b.ctx = ctx
}
}
// WithWorkingDir sets working directory.
func WithWorkingDir(wd string) Option {
return func(b *Git) {
b.wd = wd
}
}
// New initializes a new git client
func New(opts ...Option) (*Git, error) {
var err error
c := &Git{
ctx: context.Background(),
}
for _, opt := range opts {
opt(c)
}
c.gitpath, err = gitPath(c.wd)
gitpath, err := gitPath(cli.Dir())
if err != nil {
return nil, err
}
return c, nil
cli = cli.New(
bkgitutil.WithGitBinary(gitpath),
bkgitutil.WithArgs("-c", "log.showSignature=false"),
)
return &GitCLI{*cli}, nil
}
func (c *Git) IsInsideWorkTree() bool {
out, err := c.Run("rev-parse", "--is-inside-work-tree")
func (cli *GitCLI) IsInsideWorkTree(ctx context.Context) bool {
out, err := cli.clean(cli.Run(ctx, "rev-parse", "--is-inside-work-tree"))
return out == "true" && err == nil
}
func (c *Git) IsDirty() bool {
out, err := c.Run("status", "--porcelain", "--ignored")
return strings.TrimSpace(out) != "" || err != nil
func (cli *GitCLI) IsDirty(ctx context.Context) bool {
out, err := cli.Run(ctx, "status", "--porcelain", "--ignored")
return strings.TrimSpace(string(out)) != "" || err != nil
}
func (c *Git) RootDir() (string, error) {
root, err := c.Run("rev-parse", "--show-toplevel")
func (cli *GitCLI) WorkTree(ctx context.Context) (string, error) {
root, err := cli.GitCLI.WorkTree(ctx)
if err != nil {
return "", err
}
return osutil.SanitizePath(root), nil
}
func (c *Git) GitDir() (string, error) {
dir, err := c.RootDir()
func (cli *GitCLI) GitDir(ctx context.Context) (string, error) {
dir, err := cli.WorkTree(ctx)
if err != nil {
return "", err
}
return filepath.Join(dir, ".git"), nil
}
func (c *Git) RemoteURL() (string, error) {
// Try default remote based on remote tracking branch
if remote, err := c.currentRemote(); err == nil && remote != "" {
if ru, err := c.clean(c.run("remote", "get-url", remote)); err == nil && ru != "" {
func (cli *GitCLI) RemoteURL(ctx context.Context) (string, error) {
// Try default remote based on remote tracking branch.
if remote, err := cli.currentRemote(ctx); err == nil && remote != "" {
if ru, err := cli.clean(cli.Run(ctx, "remote", "get-url", remote)); err == nil && ru != "" {
return stripCredentials(ru), nil
}
}
// Next try to get the remote URL from the origin remote first
if ru, err := c.clean(c.run("remote", "get-url", "origin")); err == nil && ru != "" {
// Next try to get the remote URL from the origin remote first.
if ru, err := cli.clean(cli.Run(ctx, "remote", "get-url", "origin")); err == nil && ru != "" {
return stripCredentials(ru), nil
}
// If that fails, try to get the remote URL from the upstream remote
if ru, err := c.clean(c.run("remote", "get-url", "upstream")); err == nil && ru != "" {
// If that fails, try to get the remote URL from the upstream remote.
if ru, err := cli.clean(cli.Run(ctx, "remote", "get-url", "upstream")); err == nil && ru != "" {
return stripCredentials(ru), nil
}
return "", errors.New("no remote URL found for either origin or upstream")
}
func (c *Git) FullCommit() (string, error) {
return c.clean(c.run("show", "--format=%H", "HEAD", "--quiet", "--"))
func (cli *GitCLI) FullCommit(ctx context.Context) (string, error) {
return cli.clean(cli.Run(ctx, "show", "--format=%H", "HEAD", "--quiet", "--"))
}
func (c *Git) ShortCommit() (string, error) {
return c.clean(c.run("show", "--format=%h", "HEAD", "--quiet", "--"))
func (cli *GitCLI) ShortCommit(ctx context.Context) (string, error) {
return cli.clean(cli.Run(ctx, "show", "--format=%h", "HEAD", "--quiet", "--"))
}
func (c *Git) Tag() (string, error) {
func (cli *GitCLI) Tag(ctx context.Context) (string, error) {
var tag string
var err error
for _, fn := range []func() (string, error){
func() (string, error) {
return c.clean(c.run("tag", "--points-at", "HEAD", "--sort", "-version:creatordate"))
return cli.clean(cli.Run(ctx, "tag", "--points-at", "HEAD", "--sort", "-version:creatordate"))
},
func() (string, error) {
return c.clean(c.run("describe", "--tags", "--abbrev=0"))
return cli.clean(cli.Run(ctx, "describe", "--tags", "--abbrev=0"))
},
} {
tag, err = fn()
@@ -127,36 +103,8 @@ func (c *Git) Tag() (string, error) {
return tag, err
}
func (c *Git) Run(args ...string) (string, error) {
return c.clean(c.run(args...))
}
func (c *Git) run(args ...string) (string, error) {
var extraArgs = []string{
"-c", "log.showSignature=false",
}
args = append(extraArgs, args...)
cmd := exec.CommandContext(c.ctx, c.gitpath, args...)
if c.wd != "" {
cmd.Dir = c.wd
}
// Override the locale to ensure consistent output
cmd.Env = append(os.Environ(), "LC_ALL=C")
stdout := bytes.Buffer{}
stderr := bytes.Buffer{}
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
return "", errors.New(stderr.String())
}
return stdout.String(), nil
}
func (c *Git) clean(out string, err error) (string, error) {
func (cli *GitCLI) clean(dt []byte, err error) (string, error) {
out := string(dt)
out = strings.ReplaceAll(strings.Split(out, "\n")[0], "'", "")
if err != nil {
err = errors.New(strings.TrimSuffix(err.Error(), "\n"))
@@ -164,16 +112,15 @@ func (c *Git) clean(out string, err error) (string, error) {
return out, err
}
func (c *Git) currentRemote() (string, error) {
symref, err := c.Run("symbolic-ref", "-q", "HEAD")
func (cli *GitCLI) currentRemote(ctx context.Context) (string, error) {
symref, err := cli.clean(cli.Run(ctx, "symbolic-ref", "-q", "HEAD"))
if err != nil {
return "", err
}
if symref == "" {
return "", nil
}
// git for-each-ref --format='%(upstream:remotename)'
remote, err := c.Run("for-each-ref", "--format=%(upstream:remotename)", symref)
remote, err := cli.clean(cli.Run(ctx, "for-each-ref", "--format=%(upstream:remotename)", symref))
if err != nil {
return "", err
}
+22 -12
View File
@@ -1,6 +1,8 @@
package gitutil_test
import (
"context"
"strings"
"testing"
"github.com/docker/buildx/util/gitutil"
@@ -9,6 +11,7 @@ import (
)
func TestGit(t *testing.T) {
ctx := context.TODO()
gittestutil.Mktmp(t)
c, err := gitutil.New()
require.NoError(t, err)
@@ -16,17 +19,18 @@ func TestGit(t *testing.T) {
gittestutil.GitInit(c, t)
gittestutil.GitCommit(c, t, "bar")
out, err := c.Run("status")
out, err := c.Run(ctx, "status")
require.NoError(t, err)
require.NotEmpty(t, out)
out, err = c.Run("not-exist")
out, err = c.Run(ctx, "not-exist")
require.Error(t, err)
require.Empty(t, out)
require.Equal(t, "git: 'not-exist' is not a git command. See 'git --help'.", err.Error())
require.Contains(t, err.Error(), "git: 'not-exist' is not a git command. See 'git --help'.")
}
func TestGitFullCommit(t *testing.T) {
ctx := context.TODO()
gittestutil.Mktmp(t)
c, err := gitutil.New()
require.NoError(t, err)
@@ -34,12 +38,13 @@ func TestGitFullCommit(t *testing.T) {
gittestutil.GitInit(c, t)
gittestutil.GitCommit(c, t, "bar")
out, err := c.FullCommit()
out, err := c.FullCommit(ctx)
require.NoError(t, err)
require.Equal(t, 40, len(out))
}
func TestGitShortCommit(t *testing.T) {
ctx := context.TODO()
gittestutil.Mktmp(t)
c, err := gitutil.New()
require.NoError(t, err)
@@ -47,38 +52,41 @@ func TestGitShortCommit(t *testing.T) {
gittestutil.GitInit(c, t)
gittestutil.GitCommit(c, t, "bar")
out, err := c.ShortCommit()
out, err := c.ShortCommit(ctx)
require.NoError(t, err)
require.Equal(t, 7, len(out))
}
func TestGitFullCommitErr(t *testing.T) {
ctx := context.TODO()
gittestutil.Mktmp(t)
c, err := gitutil.New()
require.NoError(t, err)
gittestutil.GitInit(c, t)
_, err = c.FullCommit()
_, err = c.FullCommit(ctx)
require.Error(t, err)
require.True(t, gitutil.IsUnknownRevision(err))
require.False(t, gittestutil.IsAmbiguousArgument(err))
}
func TestGitShortCommitErr(t *testing.T) {
ctx := context.TODO()
gittestutil.Mktmp(t)
c, err := gitutil.New()
require.NoError(t, err)
gittestutil.GitInit(c, t)
_, err = c.ShortCommit()
_, err = c.ShortCommit(ctx)
require.Error(t, err)
require.True(t, gitutil.IsUnknownRevision(err))
require.False(t, gittestutil.IsAmbiguousArgument(err))
}
func TestGitTagsPointsAt(t *testing.T) {
ctx := context.TODO()
gittestutil.Mktmp(t)
c, err := gitutil.New()
require.NoError(t, err)
@@ -89,12 +97,13 @@ func TestGitTagsPointsAt(t *testing.T) {
gittestutil.GitCommit(c, t, "foo")
gittestutil.GitTag(c, t, "v0.9.0")
out, err := c.Run("tag", "--points-at", "HEAD", "--sort", "-version:creatordate")
out, err := c.Run(ctx, "tag", "--points-at", "HEAD", "--sort", "-version:creatordate")
require.NoError(t, err)
require.Equal(t, "v0.9.0", out)
require.Equal(t, "v0.9.0", strings.TrimSpace(string(out)))
}
func TestGitDescribeTags(t *testing.T) {
ctx := context.TODO()
gittestutil.Mktmp(t)
c, err := gitutil.New()
require.NoError(t, err)
@@ -105,12 +114,13 @@ func TestGitDescribeTags(t *testing.T) {
gittestutil.GitCommit(c, t, "foo")
gittestutil.GitTag(c, t, "v0.9.0")
out, err := c.Run("describe", "--tags", "--abbrev=0")
out, err := c.Run(ctx, "describe", "--tags", "--abbrev=0")
require.NoError(t, err)
require.Equal(t, "v0.9.0", out)
require.Equal(t, "v0.9.0", strings.TrimSpace(string(out)))
}
func TestGitRemoteURL(t *testing.T) {
ctx := context.TODO()
type remote struct {
name string
url string
@@ -218,7 +228,7 @@ func TestGitRemoteURL(t *testing.T) {
}
}
ru, err := c.RemoteURL()
ru, err := c.RemoteURL(ctx)
if tt.fail {
require.Error(t, err)
return