This repository has been archived on 2026-11-27. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
w10k/internal/deploy/git.go
T
unkin-agent 01fa51110b Harden module installs against untrusted Puppetfiles
- reject option-like :git URLs and refs; pass -- before git positionals
- link modules without following symlinks; reject nested module paths
- judge worktree completeness by an out-of-tree done file
- key git mirrors by URL hash and forge releases by forge base
- bound every git and forge call with the -j semaphore
2026-11-08 17:52:07 +11:00

72 lines
2.2 KiB
Go

package deploy
import (
"bytes"
"context"
"fmt"
"os"
"os/exec"
"strings"
)
func runGit(ctx context.Context, dir string, args ...string) (string, error) {
cmd := exec.CommandContext(ctx, "git", args...)
cmd.Dir = dir
cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0")
var out, errb bytes.Buffer
cmd.Stdout, cmd.Stderr = &out, &errb
if err := cmd.Run(); err != nil {
return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(errb.String()))
}
return strings.TrimSpace(out.String()), nil
}
// git holds a -j slot only for the subprocess itself, so callers never nest slots.
func (d *Deployer) git(ctx context.Context, dir string, args ...string) (out string, err error) {
err = d.limit(func() error {
out, err = d.runGit(ctx, dir, args...)
return err
})
return out, err
}
func (d *Deployer) syncMirror(ctx context.Context, mirror, url string, refspecs ...string) error {
if _, err := os.Stat(mirror); os.IsNotExist(err) {
if _, err := d.git(ctx, "", "init", "-q", "--bare", "--", mirror); err != nil {
return err
}
}
args := append([]string{"fetch", "-q", "--prune", "--force", "--", url}, refspecs...)
_, err := d.git(ctx, mirror, args...)
return err
}
func (d *Deployer) branches(ctx context.Context, mirror string) (map[string]string, error) {
out, err := d.git(ctx, mirror, "for-each-ref", "--format=%(objectname) %(refname)", "refs/heads/")
if err != nil {
return nil, err
}
m := map[string]string{}
for _, l := range strings.Split(out, "\n") {
sha, ref, ok := strings.Cut(l, " ")
if ok {
m[strings.TrimPrefix(ref, "refs/heads/")] = sha
}
}
return m, nil
}
func (d *Deployer) revParse(ctx context.Context, mirror string, candidates ...string) (string, error) {
for _, c := range candidates {
if sha, err := d.git(ctx, mirror, "rev-parse", "--verify", "--quiet", "--end-of-options", c+"^{commit}"); err == nil {
return sha, nil
}
}
return "", fmt.Errorf("cannot resolve %s", strings.Join(candidates, " or "))
}
func (d *Deployer) removeWorktree(ctx context.Context, mirror, path string) error {
_, _ = d.git(ctx, mirror, "worktree", "remove", "--force", "--", path)
return os.RemoveAll(path)
}