mugit/internal/git/archive.go (view raw)
| 1 | package git |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | "io" |
| 7 | "regexp" |
| 8 | "strings" |
| 9 | ) |
| 10 | |
| 11 | // ArchiveTar generates a tarball of a git ref. |
| 12 | func (g *Repo) ArchiveTar(ctx context.Context, ref string, out io.Writer) error { |
| 13 | if !isValidRef(ref) { |
| 14 | return fmt.Errorf("invalid ref: %s", ref) |
| 15 | } |
| 16 | |
| 17 | if err := gitCmd(ctx, cmdOpts{ |
| 18 | Cmd: []string{"archive", "--format=tar.gz", ref}, |
| 19 | RepoDir: g.path, |
| 20 | Stdout: out, |
| 21 | }); err != nil { |
| 22 | return fmt.Errorf("git archive %s: %w", ref, err) |
| 23 | } |
| 24 | |
| 25 | return nil |
| 26 | } |
| 27 | |
| 28 | func (g *Repo) UploadArchive(ctx context.Context, in io.Reader, out io.Writer) error { |
| 29 | if err := gitCmd(ctx, cmdOpts{ |
| 30 | Cmd: []string{"upload-archive"}, |
| 31 | RepoDir: g.path, |
| 32 | Stdin: in, |
| 33 | Stdout: out, |
| 34 | Stderr: out, |
| 35 | }); err != nil { |
| 36 | return fmt.Errorf("git-upload-archive: %w", err) |
| 37 | } |
| 38 | return nil |
| 39 | } |
| 40 | |
| 41 | var isValidRefRe = regexp.MustCompile(`^[a-zA-Z0-9._/-]+$`) |
| 42 | |
| 43 | func isValidRef(ref string) bool { |
| 44 | if ref == "" || strings.Contains(ref, "..") { |
| 45 | return false |
| 46 | } |
| 47 | return isValidRefRe.MatchString(ref) |
| 48 | } |