internal/control/mirrorcmd.go
176 lines · 5682 bytes
1package control
2
3import (
4 "bufio"
5 "errors"
6 "fmt"
7 "io"
8 "strconv"
9 "strings"
10
11 "gitbay.org/gitbay/internal/policy"
12 "gitbay.org/gitbay/internal/protocol"
13 "gitbay.org/gitbay/internal/store"
14 "gitbay.org/gitbay/internal/webhook"
15)
16
17func init() {
18 register(Command{Path: []string{"repo", "mirror", "add"},
19 NeedsRecentSignIn: true,
20 Summary: "mirror to or from a remote",
21 Usage: "repo mirror add <owner/name> <https-url> --direction push|pull [--username <u>] [--token-stdin]",
22 Flags: []Flag{
23 {"--direction", "push|pull", "which way the mirror syncs", ""},
24 {"--username", "<u>", "the remote's username", ""},
25 {"--token-stdin", "", "read a credential token from stdin", ""},
26 },
27 Examples: []string{"repo mirror add krz/gitbay https://github.com/krazywarez/gitbay.git --direction push"},
28 ReadsStdin: true, Run: runMirrorAdd})
29 register(Command{Path: []string{"repo", "mirror", "list"},
30 Summary: "list mirrors with sync status",
31 Usage: "repo mirror list <owner/name>",
32 Examples: []string{"repo mirror list krz/gitbay"},
33 ReadOnly: true, Run: runMirrorList})
34 register(Command{Path: []string{"repo", "mirror", "remove"},
35 Summary: "remove a mirror",
36 Usage: "repo mirror remove <owner/name> <id>",
37 Examples: []string{"repo mirror remove krz/gitbay 3"},
38 Run: runMirrorRemove})
39 register(Command{Path: []string{"repo", "mirror", "sync"},
40 Summary: "schedule an immediate sync",
41 Usage: "repo mirror sync <owner/name>",
42 Examples: []string{"repo mirror sync krz/gitbay"},
43 Run: runMirrorSync})
44}
45
46func runMirrorAdd(c *Ctx, args []string) int {
47 f, err := c.parseArgs(args, flagSpec{Values: []string{"--direction", "--username"}, Bools: []string{"--token-stdin"}, MaxPos: 2,
48 Usage: "repo mirror add <owner/name> <url> --direction push|pull [--username <u>] [--token-stdin]"})
49 if err != nil {
50 return c.fail(protocol.ExitUsage, "%v", err)
51 }
52 path, urlArg := f.pos(0), f.pos(1)
53 direction, username, tokenStdin := f.Value("--direction"), f.Value("--username"), f.Has("--token-stdin")
54 if path == "" || urlArg == "" || (direction != "push" && direction != "pull") {
55 return c.usage()
56 }
57 // The worker's git process dials this URL from the server: same SSRF
58 // surface as a webhook target, same rules.
59 if err := webhook.ValidateURL(urlArg, c.Cfg.Webhooks.AllowLocal); err != nil {
60 return c.failInput(err)
61 }
62 repo, code := resolveRepo(c, path, policy.CanAdmin)
63 if code >= 0 {
64 return code
65 }
66 token := ""
67 if tokenStdin {
68 line, err := bufio.NewReader(io.LimitReader(c.Stdin, 4096)).ReadString('\n')
69 if err != nil && line == "" {
70 return c.fail(protocol.ExitUsage, "--token-stdin given but stdin held no token")
71 }
72 token = strings.TrimSpace(line)
73 }
74 id, err := c.Store.AddMirror(repo.ID, direction, urlArg, username, token)
75 if err != nil {
76 if errors.Is(err, store.ErrExists) {
77 return c.fail(protocol.ExitUsage, "that mirror already exists")
78 }
79 return c.fail(protocol.ExitFailure, "%v", err)
80 }
81 note := ""
82 if direction == "pull" {
83 note = "; local pushes are now refused — refs come from the upstream"
84 }
85 return c.emit(map[string]any{"id": id, "direction": direction, "url": urlArg}, func(w io.Writer) {
86 fmt.Fprintf(w, "mirror %d added (%s %s)%s\n", id, direction, urlArg, note)
87 })
88}
89
90func runMirrorList(c *Ctx, args []string) int {
91 if len(args) != 1 {
92 return c.usage()
93 }
94 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
95 if code >= 0 {
96 return code
97 }
98 ms, err := c.Store.ListMirrors(repo.ID)
99 if err != nil {
100 return c.fail(protocol.ExitFailure, "%v", err)
101 }
102 type out struct {
103 ID int64 `json:"id"`
104 Direction string `json:"direction"`
105 URL string `json:"url"`
106 Username string `json:"username,omitempty"`
107 Pending bool `json:"pending"`
108 LastSync string `json:"last_sync,omitempty"`
109 LastError string `json:"last_error,omitempty"`
110 }
111 var ds []out
112 for _, m := range ms {
113 // The token never leaves the server, in any encoding.
114 ds = append(ds, out{m.ID, m.Direction, m.URL, m.Username, m.Dirty, m.LastSync, m.LastError})
115 }
116 return c.emit(ds, func(w io.Writer) {
117 tb := c.table(w, "ID", "DIRECTION", "URL", "LAST", "STATUS")
118 for _, d := range ds {
119 status := "ok"
120 if d.Pending {
121 status = "pending"
122 }
123 if d.LastError != "" {
124 status = "error: " + d.LastError
125 }
126 tb.row(cRef(fmt.Sprintf("%d", d.ID)), cText(d.Direction), cText(d.URL), cText("last "+orDash(d.LastSync)), cState(status))
127 }
128 tb.flush()
129 })
130}
131
132func orDash(s string) string {
133 if s == "" {
134 return "-"
135 }
136 return s
137}
138
139func runMirrorRemove(c *Ctx, args []string) int {
140 if len(args) != 2 {
141 return c.usage()
142 }
143 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
144 if code >= 0 {
145 return code
146 }
147 id, err := strconv.ParseInt(args[1], 10, 64)
148 if err != nil {
149 return c.fail(protocol.ExitUsage, "bad mirror id %q", args[1])
150 }
151 if err := c.Store.RemoveMirror(repo.ID, id); err != nil {
152 if errors.Is(err, store.ErrNotFound) {
153 return c.fail(protocol.ExitNotFound, "no mirror %d on %s", id, repo.Path())
154 }
155 return c.fail(protocol.ExitFailure, "%v", err)
156 }
157 return c.emit(map[string]any{"removed": id}, func(w io.Writer) {
158 fmt.Fprintf(w, "removed mirror %d\n", id)
159 })
160}
161
162func runMirrorSync(c *Ctx, args []string) int {
163 if len(args) != 1 {
164 return c.usage()
165 }
166 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
167 if code >= 0 {
168 return code
169 }
170 if err := c.Store.MarkMirrorsDirty(repo.ID, ""); err != nil {
171 return c.fail(protocol.ExitFailure, "%v", err)
172 }
173 return c.emit(map[string]string{"sync": "scheduled"}, func(w io.Writer) {
174 fmt.Fprintln(w, "sync scheduled; check repo mirror list for the outcome")
175 })
176}