8356
Wx
www-xonecas-io / files
www-xonecas-io / internal / store / store.go
2.2 KB
1// Package store mirrors remote git repositories into local bare repos: branches and tags only. 2package store 3 4import ( 5 "errors" 6 "fmt" 7 "io/fs" 8 "os" 9 "os/exec" 10 "path/filepath" 11 "strings" 12) 13 14// Dir is where url's mirror lives under root: root/host/owner/name.git. 15func Dir(root, url string) string { 16 if _, rest, ok := strings.Cut(url, "://"); ok { 17 url = rest 18 } 19 return filepath.Join(root, strings.TrimSuffix(url, ".git")+".git") 20} 21 22// Sync creates url's mirror under root if it is missing, then fetches into it. 23// It returns "new", "updated", "same", or "hosted" for a repo the site hosts. 24func Sync(root, url string) (string, error) { 25 dir := Dir(root, url) 26 state := "updated" 27 if _, err := os.Stat(dir); errors.Is(err, fs.ErrNotExist) { 28 state = "new" 29 for _, args := range [][]string{ 30 {"init", "--bare", "--quiet", dir}, 31 {"--git-dir", dir, "remote", "add", "origin", url}, 32 {"--git-dir", dir, "config", "remote.origin.fetch", "+refs/heads/*:refs/heads/*"}, 33 {"--git-dir", dir, "config", "--add", "remote.origin.fetch", "+refs/tags/*:refs/tags/*"}, 34 } { 35 if _, err := git(args...); err != nil { 36 return "", err 37 } 38 } 39 } 40 if state != "new" && Hosted(dir) { 41 return "hosted", nil // pushes fill it, so there is nothing to fetch 42 } 43 before, _ := git("--git-dir", dir, "for-each-ref") 44 if _, err := git("--git-dir", dir, "fetch", "--prune", "--quiet", "origin"); err != nil { 45 return "", err 46 } 47 // HEAD follows the remote's default branch, so the site shows the branch the remote shows. 48 if head, err := git("ls-remote", "--symref", url, "HEAD"); err == nil && strings.HasPrefix(head, "ref: ") { 49 ref, _, _ := strings.Cut(strings.TrimPrefix(head, "ref: "), "\t") 50 if _, err := git("--git-dir", dir, "symbolic-ref", "HEAD", ref); err != nil { 51 return "", err 52 } 53 } 54 after, err := git("--git-dir", dir, "for-each-ref") 55 if state == "updated" && before == after { 56 state = "same" 57 } 58 return state, err 59} 60 61func git(args ...string) (string, error) { 62 cmd := exec.Command("git", args...) 63 cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0") 64 out, err := cmd.CombinedOutput() 65 if err != nil { 66 return "", fmt.Errorf("git %s: %w\n%s", strings.Join(args, " "), err, out) 67 } 68 return strings.TrimSpace(string(out)), nil 69}