mugit/internal/git/gitx/archive.go (view raw)
| 1 | package gitx |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | "io" |
| 7 | "os/exec" |
| 8 | "regexp" |
| 9 | "strings" |
| 10 | ) |
| 11 | |
| 12 | // ArchiveTar generates a tarball of a git ref. |
| 13 | func ArchiveTar(ctx context.Context, repoDir, ref string, out io.Writer) error { |
| 14 | if !isValidRef(ref) { |
| 15 | return fmt.Errorf("invalid ref: %s", ref) |
| 16 | } |
| 17 | |
| 18 | cmd := exec.CommandContext(ctx, "git", "archive", "--format=tar.gz", ref) |
| 19 | cmd.Dir = repoDir |
| 20 | cmd.Env = gitEnv |
| 21 | cmd.Stdout = out |
| 22 | cmd.Stderr = io.Discard |
| 23 | |
| 24 | if err := cmd.Run(); err != nil { |
| 25 | return fmt.Errorf("git archive %s: %w", ref, err) |
| 26 | } |
| 27 | |
| 28 | return nil |
| 29 | } |
| 30 | |
| 31 | func isValidRef(ref string) bool { |
| 32 | if ref == "" || strings.Contains(ref, "..") { |
| 33 | return false |
| 34 | } |
| 35 | matched, _ := regexp.MatchString(`^[a-zA-Z0-9._/-]+$`, ref) |
| 36 | return matched |
| 37 | } |