all repos

mugit @ 6e946c765fdb85e2e5bff06348dfa84643358aad

🐮 git server that your cow will love

mugit/internal/git/archive.go (view raw)

Oleksandr Smirnov Oleksandr Smirnov
olexsmir@gmail.com
git: improve ergonomics of method that is only used 4 times, 2 months ago
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 := g.gitCmd(ctx, cmdOpts{
18
		Cmd:    []string{"archive", "--format=tar.gz", ref},
19
		Stdout: out,
20
	}); err != nil {
21
		return fmt.Errorf("git archive %s: %w", ref, err)
22
	}
23
24
	return nil
25
}
26
27
func (g *Repo) UploadArchive(ctx context.Context, in io.Reader, out io.Writer) error {
28
	if err := g.gitCmd(ctx, cmdOpts{
29
		Cmd:    []string{"upload-archive"},
30
		Stdin:  in,
31
		Stdout: out,
32
		Stderr: out,
33
	}); err != nil {
34
		return fmt.Errorf("git-upload-archive: %w", err)
35
	}
36
	return nil
37
}
38
39
var isValidRefRe = regexp.MustCompile(`^[a-zA-Z0-9._/-]+$`)
40
41
func isValidRef(ref string) bool {
42
	if ref == "" || strings.Contains(ref, "..") {
43
		return false
44
	}
45
	return isValidRefRe.MatchString(ref)
46
}