Commit 12160cbe00
Verified · cmc ci/build: success ci/quality: success ci/test: success
Layout: unified · split
Changed files (10)
- cmd/gitbay/ergonomics.go added +450
- cmd/gitbay/ergonomics_test.go added +130
- cmd/gitbay/local.go +16 −4
- cmd/gitbay/main.go +110 −62
- internal/control/flags.go +45 −14
- internal/control/flags_test.go +26
- internal/control/mr.go +2 −2
- internal/control/refsupdated.go +42
- internal/hookd/hookd.go +4 −3
- internal/hookd/pushhints_test.go added +74
cmd/gitbay/ergonomics.go added +450
| @@ -0,0 +1,450 @@ | |||
| 1 | package main | ||
| 2 | |||
| 3 | import ( | ||
| 4 | "encoding/json" | ||
| 5 | "fmt" | ||
| 6 | "net/url" | ||
| 7 | "os" | ||
| 8 | "os/exec" | ||
| 9 | "path/filepath" | ||
| 10 | "runtime" | ||
| 11 | "slices" | ||
| 12 | "strconv" | ||
| 13 | "strings" | ||
| 14 | |||
| 15 | "github.com/spf13/cobra" | ||
| 16 | "golang.org/x/term" | ||
| 17 | |||
| 18 | "gitbay.org/gitbay/internal/cliconfig" | ||
| 19 | "gitbay.org/gitbay/internal/protocol" | ||
| 20 | "gitbay.org/gitbay/internal/toolpath" | ||
| 21 | ) | ||
| 22 | |||
| 23 | // parseNumberArg parses a positive integer, optionally prefixed with | ||
| 24 | // prefix ("#" for issues, "!" for MRs). | ||
| 25 | func parseNumberArg(s, prefix string) (string, bool) { | ||
| 26 | if prefix != "" { | ||
| 27 | s = strings.TrimPrefix(s, prefix) | ||
| 28 | } | ||
| 29 | if s == "" { | ||
| 30 | return "", false | ||
| 31 | } | ||
| 32 | n, err := strconv.ParseInt(s, 10, 64) | ||
| 33 | if err != nil || n < 1 { | ||
| 34 | return "", false | ||
| 35 | } | ||
| 36 | return strconv.FormatInt(n, 10), true | ||
| 37 | } | ||
| 38 | |||
| 39 | // withDefault attaches default list/show routing to a noun group so | ||
| 40 | // `gitbay issue` lists, `gitbay issue 42` (or `#42`) shows, and | ||
| 41 | // `gitbay issue --state all` lists with flags. Explicit `--help` / `-h` | ||
| 42 | // still prints the server's noun help. | ||
| 43 | func withDefault(cmd *cobra.Command, listOpts, showOpts passOpts, numPrefix string) *cobra.Command { | ||
| 44 | cmd.DisableFlagParsing = true | ||
| 45 | cmd.Args = cobra.ArbitraryArgs | ||
| 46 | cmd.RunE = func(c *cobra.Command, args []string) error { | ||
| 47 | if slices.Contains(args, "--help") || slices.Contains(args, "-h") { | ||
| 48 | return c.Help() | ||
| 49 | } | ||
| 50 | cliBase := cliPathOf(c) | ||
| 51 | if len(args) >= 1 { | ||
| 52 | if num, ok := parseNumberArg(args[0], numPrefix); ok { | ||
| 53 | cp := append([]string{num}, args[1:]...) | ||
| 54 | os.Exit(runPass(showOpts, cliBase+" show", cp)) | ||
| 55 | } | ||
| 56 | } | ||
| 57 | if len(args) >= 2 && !strings.HasPrefix(args[0], "-") && strings.Contains(args[0], "/") { | ||
| 58 | if num, ok := parseNumberArg(args[1], numPrefix); ok { | ||
| 59 | cp := slices.Clone(args) | ||
| 60 | cp[1] = num | ||
| 61 | os.Exit(runPass(showOpts, cliBase+" show", cp)) | ||
| 62 | } | ||
| 63 | } | ||
| 64 | os.Exit(runPass(listOpts, cliBase+" list", args)) | ||
| 65 | return nil | ||
| 66 | } | ||
| 67 | return cmd | ||
| 68 | } | ||
| 69 | |||
| 70 | // withRepoDefault attaches default routing to `gitbay repo`: inside a | ||
| 71 | // clone (or with an explicit owner/name), `gitbay repo` shows the repo; | ||
| 72 | // otherwise it lists repositories. | ||
| 73 | func withRepoDefault(cmd *cobra.Command) *cobra.Command { | ||
| 74 | cmd.DisableFlagParsing = true | ||
| 75 | cmd.Args = cobra.ArbitraryArgs | ||
| 76 | cmd.RunE = func(c *cobra.Command, args []string) error { | ||
| 77 | if slices.Contains(args, "--help") || slices.Contains(args, "-h") { | ||
| 78 | return c.Help() | ||
| 79 | } | ||
| 80 | showOpts := passOpts{server: []string{"repo", "show"}, needsRepo: true} | ||
| 81 | listOpts := passOpts{server: []string{"repo", "list"}} | ||
| 82 | if len(args) > 0 && !strings.HasPrefix(args[0], "-") && strings.Contains(args[0], "/") { | ||
| 83 | os.Exit(runPass(showOpts, "repo show", args)) | ||
| 84 | } | ||
| 85 | if len(args) == 0 { | ||
| 86 | if t, err := resolveTarget(); err == nil && t.repo != "" { | ||
| 87 | os.Exit(runPass(showOpts, "repo show", nil)) | ||
| 88 | } | ||
| 89 | } | ||
| 90 | os.Exit(runPass(listOpts, "repo list", args)) | ||
| 91 | return nil | ||
| 92 | } | ||
| 93 | return cmd | ||
| 94 | } | ||
| 95 | |||
| 96 | // hasPositionalAfterRepo reports whether args (whose args[0] is already | ||
| 97 | // the repository path) contains a positional argument after args[0]. | ||
| 98 | func hasPositionalAfterRepo(args []string) bool { | ||
| 99 | if len(args) <= 1 { | ||
| 100 | return false | ||
| 101 | } | ||
| 102 | for i := 1; i < len(args); i++ { | ||
| 103 | a := args[i] | ||
| 104 | if a == "--" { | ||
| 105 | return i+1 < len(args) | ||
| 106 | } | ||
| 107 | if strings.HasPrefix(a, "--") { | ||
| 108 | if !strings.Contains(a, "=") && flagTakesValue(a) { | ||
| 109 | i++ | ||
| 110 | } | ||
| 111 | continue | ||
| 112 | } | ||
| 113 | if len(a) == 2 && a[0] == '-' { | ||
| 114 | if shortFlagTakesValue(a) { | ||
| 115 | i++ | ||
| 116 | } | ||
| 117 | continue | ||
| 118 | } | ||
| 119 | return true | ||
| 120 | } | ||
| 121 | return false | ||
| 122 | } | ||
| 123 | |||
| 124 | // flagTakesValue reports whether a long flag in mr/build commands consumes | ||
| 125 | // the following argument. Boolean flags return false. | ||
| 126 | func flagTakesValue(f string) bool { | ||
| 127 | switch f { | ||
| 128 | case "--json", "--draft", "--when-ready", "--cancel", "--follow", | ||
| 129 | "--approve", "--request-changes", "--comment", "--discard", | ||
| 130 | "--pending", "--old", "--all", "--no-color": | ||
| 131 | return false | ||
| 132 | } | ||
| 133 | return true | ||
| 134 | } | ||
| 135 | |||
| 136 | func shortFlagTakesValue(f string) bool { | ||
| 137 | switch f { | ||
| 138 | case "-d": | ||
| 139 | return false | ||
| 140 | case "-t", "-m", "-b", "-s", "-l", "-a", "-f", "-n": | ||
| 141 | return true | ||
| 142 | } | ||
| 143 | return false | ||
| 144 | } | ||
| 145 | |||
| 146 | // stripLeadingNumberPrefix normalizes "#42" or "!12" at args[1] (right | ||
| 147 | // after the repo path) to plain digits. | ||
| 148 | func stripLeadingNumberPrefix(args []string, prefix string) []string { | ||
| 149 | if prefix == "" || len(args) < 2 { | ||
| 150 | return args | ||
| 151 | } | ||
| 152 | if num, ok := parseNumberArg(args[1], prefix); ok && num != args[1] { | ||
| 153 | cp := slices.Clone(args) | ||
| 154 | cp[1] = num | ||
| 155 | return cp | ||
| 156 | } | ||
| 157 | return args | ||
| 158 | } | ||
| 159 | |||
| 160 | // inferBranchMR resolves the open MR number for the currently checked-out | ||
| 161 | // branch in t.repo. | ||
| 162 | func inferBranchMR(t target) (string, error) { | ||
| 163 | br := currentBranch() | ||
| 164 | if br == "" { | ||
| 165 | return "", fmt.Errorf("not on a branch; pass an MR number") | ||
| 166 | } | ||
| 167 | out, code := sshCapture(t, []string{"mr", "list", t.repo, "--state", "open", "--json"}) | ||
| 168 | if code != 0 { | ||
| 169 | return "", fmt.Errorf("could not list open MRs for %s", t.repo) | ||
| 170 | } | ||
| 171 | var env struct { | ||
| 172 | Data []struct { | ||
| 173 | Number int64 `json:"number"` | ||
| 174 | Source string `json:"source"` | ||
| 175 | } `json:"data"` | ||
| 176 | } | ||
| 177 | if err := json.Unmarshal([]byte(out), &env); err != nil { | ||
| 178 | return "", fmt.Errorf("reading open MRs: %w", err) | ||
| 179 | } | ||
| 180 | for _, mr := range env.Data { | ||
| 181 | if mr.Source == br { | ||
| 182 | return strconv.FormatInt(mr.Number, 10), nil | ||
| 183 | } | ||
| 184 | } | ||
| 185 | return "", fmt.Errorf("no open MR for branch %q; pass <n> or run: gitbay mr create", br) | ||
| 186 | } | ||
| 187 | |||
| 188 | // inferLatestBuild resolves the most recent build number for the current | ||
| 189 | // branch (or repository) in t.repo. | ||
| 190 | func inferLatestBuild(t target) (string, error) { | ||
| 191 | argv := []string{"build", "list", t.repo, "--limit", "1", "--json"} | ||
| 192 | if br := currentBranch(); br != "" { | ||
| 193 | argv = []string{"build", "list", t.repo, "--ref", br, "--limit", "1", "--json"} | ||
| 194 | } | ||
| 195 | out, code := sshCapture(t, argv) | ||
| 196 | if code != 0 { | ||
| 197 | return "", fmt.Errorf("could not list builds for %s", t.repo) | ||
| 198 | } | ||
| 199 | var env struct { | ||
| 200 | Data struct { | ||
| 201 | Items []struct { | ||
| 202 | Number int64 `json:"number"` | ||
| 203 | } `json:"items"` | ||
| 204 | } `json:"data"` | ||
| 205 | } | ||
| 206 | if err := json.Unmarshal([]byte(out), &env); err != nil || len(env.Data.Items) == 0 { | ||
| 207 | // Fall back to latest build on any ref when branch has no builds yet. | ||
| 208 | if br := currentBranch(); br != "" { | ||
| 209 | out2, code2 := sshCapture(t, []string{"build", "list", t.repo, "--limit", "1", "--json"}) | ||
| 210 | if code2 == 0 && json.Unmarshal([]byte(out2), &env) == nil && len(env.Data.Items) > 0 { | ||
| 211 | return strconv.FormatInt(env.Data.Items[0].Number, 10), nil | ||
| 212 | } | ||
| 213 | } | ||
| 214 | return "", fmt.Errorf("no builds found for %s; pass a build number", t.repo) | ||
| 215 | } | ||
| 216 | return strconv.FormatInt(env.Data.Items[0].Number, 10), nil | ||
| 217 | } | ||
| 218 | |||
| 219 | // headCommitTitleBody returns the checked-out commit's subject and body, | ||
| 220 | // or empty strings outside a git repo. | ||
| 221 | func headCommitTitleBody() (string, string) { | ||
| 222 | subj, err := exec.Command(toolpath.Look("git"), "log", "-1", "--format=%s").Output() | ||
| 223 | if err != nil { | ||
| 224 | return "", "" | ||
| 225 | } | ||
| 226 | body, _ := exec.Command(toolpath.Look("git"), "log", "-1", "--format=%b").Output() | ||
| 227 | return strings.TrimSpace(string(subj)), strings.TrimSpace(string(body)) | ||
| 228 | } | ||
| 229 | |||
| 230 | // splitTitleAndBody extracts the first non-comment, non-blank line as | ||
| 231 | // title and the remaining non-comment lines as body. | ||
| 232 | func splitTitleAndBody(raw string) (title, body string) { | ||
| 233 | var kept []string | ||
| 234 | for _, line := range strings.Split(raw, "\n") { | ||
| 235 | if strings.HasPrefix(line, "#") { | ||
| 236 | continue | ||
| 237 | } | ||
| 238 | kept = append(kept, line) | ||
| 239 | } | ||
| 240 | start := 0 | ||
| 241 | for start < len(kept) && strings.TrimSpace(kept[start]) == "" { | ||
| 242 | start++ | ||
| 243 | } | ||
| 244 | if start >= len(kept) { | ||
| 245 | return "", "" | ||
| 246 | } | ||
| 247 | title = strings.TrimSpace(kept[start]) | ||
| 248 | rest := strings.TrimSpace(strings.Join(kept[start+1:], "\n")) | ||
| 249 | return title, rest | ||
| 250 | } | ||
| 251 | |||
| 252 | // maybeTitleAndBodyEditor opens $EDITOR when --title/-t is missing on | ||
| 253 | // issue create or mr create, letting the user write title on line 1 and | ||
| 254 | // body below. If no editor is configured or stdin is not a terminal, | ||
| 255 | // falls back to prefillTitle when available. | ||
| 256 | func maybeTitleAndBodyEditor(args []string, kind, prefillTitle, prefillBody string) ([]string, *strings.Reader, bool, error) { | ||
| 257 | if hasFlag(args, "--title") || hasFlag(args, "-t") { | ||
| 258 | return args, nil, true, nil | ||
| 259 | } | ||
| 260 | editor := os.Getenv("EDITOR") | ||
| 261 | if hasBodyFlag(args) || !term.IsTerminal(int(os.Stdin.Fd())) || editor == "" { | ||
| 262 | if prefillTitle != "" { | ||
| 263 | return append(args, "--title", prefillTitle), nil, true, nil | ||
| 264 | } | ||
| 265 | return args, nil, true, nil | ||
| 266 | } | ||
| 267 | f, err := os.CreateTemp("", "gitbay-"+kind+"-*.md") | ||
| 268 | if err != nil { | ||
| 269 | return nil, nil, false, err | ||
| 270 | } | ||
| 271 | defer os.Remove(f.Name()) | ||
| 272 | if prefillTitle != "" { | ||
| 273 | fmt.Fprintf(f, "%s\n", prefillTitle) | ||
| 274 | } | ||
| 275 | if prefillBody != "" { | ||
| 276 | fmt.Fprintf(f, "\n%s\n", strings.TrimRight(prefillBody, "\n")) | ||
| 277 | } | ||
| 278 | fmt.Fprintf(f, "\n# First line is the %s title; leave a blank line and write the body below.\n# Lines starting with '#' are ignored. Save an empty file to abort.\n", kind) | ||
| 279 | f.Close() | ||
| 280 | |||
| 281 | ed := exec.Command(toolpath.Look("sh"), "-c", editor+" "+shellQuote(f.Name())) | ||
| 282 | ed.Stdin, ed.Stdout, ed.Stderr = os.Stdin, os.Stdout, os.Stderr | ||
| 283 | if err := ed.Run(); err != nil { | ||
| 284 | return nil, nil, false, fmt.Errorf("editor: %w", err) | ||
| 285 | } | ||
| 286 | raw, err := os.ReadFile(f.Name()) | ||
| 287 | if err != nil { | ||
| 288 | return nil, nil, false, err | ||
| 289 | } | ||
| 290 | title, body := splitTitleAndBody(string(raw)) | ||
| 291 | if title == "" { | ||
| 292 | fmt.Fprintln(os.Stderr, "gitbay: aborted (empty title)") | ||
| 293 | return nil, nil, false, nil | ||
| 294 | } | ||
| 295 | args = append(args, "--title", title) | ||
| 296 | if body == "" { | ||
| 297 | return args, nil, true, nil | ||
| 298 | } | ||
| 299 | return append(args, "--file", "-"), strings.NewReader(body + "\n"), true, nil | ||
| 300 | } | ||
| 301 | |||
| 302 | // instanceBaseURL derives the web base URL for an instance. | ||
| 303 | func instanceBaseURL(inst cliconfig.Instance) string { | ||
| 304 | scheme := "https" | ||
| 305 | if inst.Host == "localhost" || inst.Host == "127.0.0.1" || strings.HasSuffix(inst.Host, ".local") { | ||
| 306 | scheme = "http" | ||
| 307 | } | ||
| 308 | return scheme + "://" + inst.Host | ||
| 309 | } | ||
| 310 | |||
| 311 | // resolveOpenURL maps `gitbay open` arguments to a web URL on the target | ||
| 312 | // instance. inferMR and inferBuild are injected for testability. | ||
| 313 | func resolveOpenURL(t target, args []string, branch string, stat func(string) (os.FileInfo, error), inferMR, inferBuild func() (string, error)) (string, error) { | ||
| 314 | base := instanceBaseURL(t.inst) | ||
| 315 | if len(args) == 0 { | ||
| 316 | if t.repo == "" { | ||
| 317 | return base + "/", nil | ||
| 318 | } | ||
| 319 | return base + "/" + t.repo, nil | ||
| 320 | } | ||
| 321 | arg := args[0] | ||
| 322 | repo := t.repo | ||
| 323 | |||
| 324 | // Explicit owner/name as first argument. | ||
| 325 | if !strings.HasPrefix(arg, "#") && !strings.HasPrefix(arg, "!") && strings.Count(arg, "/") == 1 { | ||
| 326 | if _, err := stat(arg); err != nil { | ||
| 327 | repo = arg | ||
| 328 | args = args[1:] | ||
| 329 | if len(args) == 0 { | ||
| 330 | return base + "/" + repo, nil | ||
| 331 | } | ||
| 332 | arg = args[0] | ||
| 333 | } | ||
| 334 | } | ||
| 335 | |||
| 336 | if repo == "" { | ||
| 337 | return "", fmt.Errorf("no repository given and none inferable: pass <owner/name> or run inside a clone") | ||
| 338 | } | ||
| 339 | |||
| 340 | if num, ok := parseNumberArg(arg, "#"); ok && strings.HasPrefix(arg, "#") { | ||
| 341 | return fmt.Sprintf("%s/%s/issues/%s", base, repo, num), nil | ||
| 342 | } | ||
| 343 | if num, ok := parseNumberArg(arg, "!"); ok && strings.HasPrefix(arg, "!") { | ||
| 344 | return fmt.Sprintf("%s/%s/mrs/%s", base, repo, num), nil | ||
| 345 | } | ||
| 346 | switch arg { | ||
| 347 | case "issues", "mrs", "builds", "releases", "wiki", "settings": | ||
| 348 | return fmt.Sprintf("%s/%s/%s", base, repo, arg), nil | ||
| 349 | case "mr": | ||
| 350 | if len(args) > 1 { | ||
| 351 | if num, ok := parseNumberArg(args[1], "!"); ok { | ||
| 352 | return fmt.Sprintf("%s/%s/mrs/%s", base, repo, num), nil | ||
| 353 | } | ||
| 354 | } | ||
| 355 | if inferMR != nil { | ||
| 356 | if num, err := inferMR(); err == nil { | ||
| 357 | return fmt.Sprintf("%s/%s/mrs/%s", base, repo, num), nil | ||
| 358 | } | ||
| 359 | } | ||
| 360 | return fmt.Sprintf("%s/%s/mrs", base, repo), nil | ||
| 361 | case "build": | ||
| 362 | if len(args) > 1 { | ||
| 363 | if num, ok := parseNumberArg(args[1], ""); ok { | ||
| 364 | return fmt.Sprintf("%s/%s/builds/%s", base, repo, num), nil | ||
| 365 | } | ||
| 366 | } | ||
| 367 | if inferBuild != nil { | ||
| 368 | if num, err := inferBuild(); err == nil { | ||
| 369 | return fmt.Sprintf("%s/%s/builds/%s", base, repo, num), nil | ||
| 370 | } | ||
| 371 | } | ||
| 372 | return fmt.Sprintf("%s/%s/builds", base, repo), nil | ||
| 373 | } | ||
| 374 | |||
| 375 | // File or directory path, optionally with :line. | ||
| 376 | pathPart, linePart, hasLine := strings.Cut(arg, ":") | ||
| 377 | cleanPath := filepath.ToSlash(filepath.Clean(pathPart)) | ||
| 378 | fi, err := stat(pathPart) | ||
| 379 | if err == nil { | ||
| 380 | ref := branch | ||
| 381 | if ref == "" { | ||
| 382 | ref = "HEAD" | ||
| 383 | } | ||
| 384 | kind := "blob" | ||
| 385 | if fi.IsDir() { | ||
| 386 | kind = "tree" | ||
| 387 | } | ||
| 388 | u := fmt.Sprintf("%s/%s/%s/%s/%s", base, repo, kind, url.PathEscape(ref), cleanPath) | ||
| 389 | if hasLine && linePart != "" { | ||
| 390 | if n, err := strconv.Atoi(linePart); err == nil && n > 0 { | ||
| 391 | u += fmt.Sprintf("#L%d", n) | ||
| 392 | } | ||
| 393 | } | ||
| 394 | return u, nil | ||
| 395 | } | ||
| 396 | |||
| 397 | return "", fmt.Errorf("cannot resolve %q (use #N, !N, mr, build [N], issues|mrs|builds|releases|wiki|settings, owner/name, or a file path)", arg) | ||
| 398 | } | ||
| 399 | |||
| 400 | func openCmd() *cobra.Command { | ||
| 401 | c := local("open", "open the repository, issue, MR, build, or file in your browser", cmdOpen) | ||
| 402 | c.Aliases = []string{"browse"} | ||
| 403 | return c | ||
| 404 | } | ||
| 405 | |||
| 406 | func cmdOpen(args []string) int { | ||
| 407 | printOnly := false | ||
| 408 | var rest []string | ||
| 409 | for _, a := range args { | ||
| 410 | if a == "--print" || a == "-p" { | ||
| 411 | printOnly = true | ||
| 412 | continue | ||
| 413 | } | ||
| 414 | rest = append(rest, a) | ||
| 415 | } | ||
| 416 | t, err := resolveTarget() | ||
| 417 | if err != nil { | ||
| 418 | fmt.Fprintln(os.Stderr, "gitbay:", err) | ||
| 419 | return protocol.ExitFailure | ||
| 420 | } | ||
| 421 | u, err := resolveOpenURL(t, rest, currentBranch(), os.Stat, | ||
| 422 | func() (string, error) { return inferBranchMR(t) }, | ||
| 423 | func() (string, error) { return inferLatestBuild(t) }, | ||
| 424 | ) | ||
| 425 | if err != nil { | ||
| 426 | fmt.Fprintln(os.Stderr, "gitbay:", err) | ||
| 427 | return protocol.ExitUsage | ||
| 428 | } | ||
| 429 | if printOnly { | ||
| 430 | fmt.Println(u) | ||
| 431 | return 0 | ||
| 432 | } | ||
| 433 | if err := openBrowser(u); err != nil { | ||
| 434 | fmt.Fprintln(os.Stderr, "gitbay: opening browser:", err) | ||
| 435 | fmt.Println(u) | ||
| 436 | return protocol.ExitFailure | ||
| 437 | } | ||
| 438 | return 0 | ||
| 439 | } | ||
| 440 | |||
| 441 | func openBrowser(u string) error { | ||
| 442 | switch runtime.GOOS { | ||
| 443 | case "darwin": | ||
| 444 | return exec.Command("open", u).Start() | ||
| 445 | case "windows": | ||
| 446 | return exec.Command("cmd", "/c", "start", "", u).Start() | ||
| 447 | default: | ||
| 448 | return exec.Command("xdg-open", u).Start() | ||
| 449 | } | ||
| 450 | } | ||
cmd/gitbay/ergonomics_test.go added +130
| @@ -0,0 +1,130 @@ | |||
| 1 | package main | ||
| 2 | |||
| 3 | import ( | ||
| 4 | "os" | ||
| 5 | "path/filepath" | ||
| 6 | "slices" | ||
| 7 | "testing" | ||
| 8 | |||
| 9 | "gitbay.org/gitbay/internal/cliconfig" | ||
| 10 | ) | ||
| 11 | |||
| 12 | func TestParseNumberArg(t *testing.T) { | ||
| 13 | cases := []struct { | ||
| 14 | in, prefix, want string | ||
| 15 | ok bool | ||
| 16 | }{ | ||
| 17 | {"42", "#", "42", true}, | ||
| 18 | {"#42", "#", "42", true}, | ||
| 19 | {"!12", "!", "12", true}, | ||
| 20 | {"#12", "!", "", false}, | ||
| 21 | {"0", "#", "", false}, | ||
| 22 | {"-1", "#", "", false}, | ||
| 23 | {"abc", "", "", false}, | ||
| 24 | } | ||
| 25 | for _, tc := range cases { | ||
| 26 | got, ok := parseNumberArg(tc.in, tc.prefix) | ||
| 27 | if got != tc.want || ok != tc.ok { | ||
| 28 | t.Errorf("parseNumberArg(%q, %q) = (%q, %v), want (%q, %v)", tc.in, tc.prefix, got, ok, tc.want, tc.ok) | ||
| 29 | } | ||
| 30 | } | ||
| 31 | } | ||
| 32 | |||
| 33 | func TestHasPositionalAfterRepo(t *testing.T) { | ||
| 34 | cases := []struct { | ||
| 35 | args []string | ||
| 36 | want bool | ||
| 37 | }{ | ||
| 38 | {[]string{"krz/gitbay"}, false}, | ||
| 39 | {[]string{"krz/gitbay", "--strategy", "ff"}, false}, | ||
| 40 | {[]string{"krz/gitbay", "--when-ready", "--json"}, false}, | ||
| 41 | {[]string{"krz/gitbay", "-m", "looks good"}, false}, | ||
| 42 | {[]string{"krz/gitbay", "42"}, true}, | ||
| 43 | {[]string{"krz/gitbay", "--strategy", "ff", "42"}, true}, | ||
| 44 | {[]string{"krz/gitbay", "--strategy=ff", "42"}, true}, | ||
| 45 | {[]string{"krz/gitbay", "--follow"}, false}, | ||
| 46 | } | ||
| 47 | for _, tc := range cases { | ||
| 48 | if got := hasPositionalAfterRepo(tc.args); got != tc.want { | ||
| 49 | t.Errorf("hasPositionalAfterRepo(%v) = %v, want %v", tc.args, got, tc.want) | ||
| 50 | } | ||
| 51 | } | ||
| 52 | } | ||
| 53 | |||
| 54 | func TestStripLeadingNumberPrefix(t *testing.T) { | ||
| 55 | got := stripLeadingNumberPrefix([]string{"krz/gitbay", "#42", "--json"}, "#") | ||
| 56 | if !slices.Equal(got, []string{"krz/gitbay", "42", "--json"}) { | ||
| 57 | t.Errorf("got %v", got) | ||
| 58 | } | ||
| 59 | got = stripLeadingNumberPrefix([]string{"krz/gitbay", "!7"}, "!") | ||
| 60 | if !slices.Equal(got, []string{"krz/gitbay", "7"}) { | ||
| 61 | t.Errorf("got %v", got) | ||
| 62 | } | ||
| 63 | } | ||
| 64 | |||
| 65 | func TestSplitTitleAndBody(t *testing.T) { | ||
| 66 | raw := "# comment\n\nFix the thing\n\nMore details\n# ignored\nSecond line\n" | ||
| 67 | title, body := splitTitleAndBody(raw) | ||
| 68 | if title != "Fix the thing" || body != "More details\nSecond line" { | ||
| 69 | t.Errorf("got title=%q body=%q", title, body) | ||
| 70 | } | ||
| 71 | title, body = splitTitleAndBody("# only comments\n\n") | ||
| 72 | if title != "" || body != "" { | ||
| 73 | t.Errorf("empty: got title=%q body=%q", title, body) | ||
| 74 | } | ||
| 75 | } | ||
| 76 | |||
| 77 | func TestShortFlagHelpers(t *testing.T) { | ||
| 78 | if !usesStdin([]string{"-f", "-"}) || !usesStdin([]string{"--file=-"}) { | ||
| 79 | t.Errorf("usesStdin should recognize -f - and --file=-") | ||
| 80 | } | ||
| 81 | if !hasBodyFlag([]string{"-b", "hi"}) || !hasBodyFlag([]string{"-m", "hi"}) || !hasBodyFlag([]string{"--body=hi"}) { | ||
| 82 | t.Errorf("hasBodyFlag should recognize -b, -m, and --body=") | ||
| 83 | } | ||
| 84 | } | ||
| 85 | |||
| 86 | func TestResolveOpenURL(t *testing.T) { | ||
| 87 | tmp := t.TempDir() | ||
| 88 | filePath := filepath.Join(tmp, "main.go") | ||
| 89 | if err := os.WriteFile(filePath, []byte("package main\n"), 0o644); err != nil { | ||
| 90 | t.Fatal(err) | ||
| 91 | } | ||
| 92 | dirPath := filepath.Join(tmp, "sub") | ||
| 93 | if err := os.Mkdir(dirPath, 0o755); err != nil { | ||
| 94 | t.Fatal(err) | ||
| 95 | } | ||
| 96 | |||
| 97 | tgt := target{inst: cliconfig.Instance{Host: "gitbay.org"}, repo: "krz/gitbay"} | ||
| 98 | inferMR := func() (string, error) { return "42", nil } | ||
| 99 | inferBuild := func() (string, error) { return "99", nil } | ||
| 100 | |||
| 101 | cases := []struct { | ||
| 102 | t target | ||
| 103 | args []string | ||
| 104 | want string | ||
| 105 | }{ | ||
| 106 | {target{inst: cliconfig.Instance{Host: "gitbay.org"}}, nil, "https://gitbay.org/"}, | ||
| 107 | {tgt, nil, "https://gitbay.org/krz/gitbay"}, | ||
| 108 | {tgt, []string{"#15"}, "https://gitbay.org/krz/gitbay/issues/15"}, | ||
| 109 | {tgt, []string{"!8"}, "https://gitbay.org/krz/gitbay/mrs/8"}, | ||
| 110 | {tgt, []string{"issues"}, "https://gitbay.org/krz/gitbay/issues"}, | ||
| 111 | {tgt, []string{"mr"}, "https://gitbay.org/krz/gitbay/mrs/42"}, | ||
| 112 | {tgt, []string{"mr", "!7"}, "https://gitbay.org/krz/gitbay/mrs/7"}, | ||
| 113 | {tgt, []string{"build"}, "https://gitbay.org/krz/gitbay/builds/99"}, | ||
| 114 | {tgt, []string{"build", "12"}, "https://gitbay.org/krz/gitbay/builds/12"}, | ||
| 115 | {tgt, []string{"cmc/other", "#3"}, "https://gitbay.org/cmc/other/issues/3"}, | ||
| 116 | {tgt, []string{filePath + ":10"}, "https://gitbay.org/krz/gitbay/blob/feat/" + filepath.ToSlash(filePath) + "#L10"}, | ||
| 117 | {tgt, []string{dirPath}, "https://gitbay.org/krz/gitbay/tree/feat/" + filepath.ToSlash(dirPath)}, | ||
| 118 | {target{inst: cliconfig.Instance{Host: "localhost"}, repo: "a/b"}, nil, "http://localhost/a/b"}, | ||
| 119 | } | ||
| 120 | for _, tc := range cases { | ||
| 121 | got, err := resolveOpenURL(tc.t, tc.args, "feat", os.Stat, inferMR, inferBuild) | ||
| 122 | if err != nil { | ||
| 123 | t.Errorf("resolveOpenURL(%v): %v", tc.args, err) | ||
| 124 | continue | ||
| 125 | } | ||
| 126 | if got != tc.want { | ||
| 127 | t.Errorf("resolveOpenURL(%v) = %q, want %q", tc.args, got, tc.want) | ||
| 128 | } | ||
| 129 | } | ||
| 130 | } | ||
cmd/gitbay/local.go +16 −4
| @@ -21,7 +21,9 @@ import ( | |||
| 21 | // hasBodyFlag reports whether args already carry body/message input. | 21 | // hasBodyFlag reports whether args already carry body/message input. |
| 22 | func hasBodyFlag(args []string) bool { | 22 | func hasBodyFlag(args []string) bool { |
| 23 | for _, a := range args { | 23 | for _, a := range args { |
| 24 | if a == "--body" || a == "--message" || a == "--file" { | 24 | if a == "--body" || a == "-b" || strings.HasPrefix(a, "--body=") || |
| 25 | a == "--message" || a == "-m" || strings.HasPrefix(a, "--message=") || | ||
| 26 | a == "--file" || a == "-f" || strings.HasPrefix(a, "--file=") { | ||
| 25 | return true | 27 | return true |
| 26 | } | 28 | } |
| 27 | } | 29 | } |
| @@ -333,11 +335,10 @@ func hasFlag(args []string, flag string) bool { | |||
| 333 | // signs with; the server is never asked to vouch for a commit it did not | 335 | // signs with; the server is never asked to vouch for a commit it did not |
| 334 | // receive already signed (#175). | 336 | // receive already signed (#175). |
| 335 | func cmdMRRebase(args []string) int { | 337 | func cmdMRRebase(args []string) int { |
| 336 | if len(args) != 1 { | 338 | if len(args) > 1 { |
| 337 | fmt.Fprintln(os.Stderr, "usage: gitbay mr rebase <n>") | 339 | fmt.Fprintln(os.Stderr, "usage: gitbay mr rebase [<n>]") |
| 338 | return protocol.ExitUsage | 340 | return protocol.ExitUsage |
| 339 | } | 341 | } |
| 340 | n := args[0] | ||
| 341 | // Cheapest check first: a dirty tree stops the rebase anyway, and | 342 | // Cheapest check first: a dirty tree stops the rebase anyway, and |
| 342 | // saying so costs no round trip. | 343 | // saying so costs no round trip. |
| 343 | if dirty, err := worktreeDirty(); err != nil { | 344 | if dirty, err := worktreeDirty(); err != nil { |
| @@ -356,6 +357,17 @@ func cmdMRRebase(args []string) int { | |||
| 356 | fmt.Fprintln(os.Stderr, "gitbay: run this in a clone of the repository the merge request targets") | 357 | fmt.Fprintln(os.Stderr, "gitbay: run this in a clone of the repository the merge request targets") |
| 357 | return protocol.ExitUsage | 358 | return protocol.ExitUsage |
| 358 | } | 359 | } |
| 360 | var n string | ||
| 361 | if len(args) == 1 { | ||
| 362 | n = strings.TrimPrefix(args[0], "!") | ||
| 363 | } else { | ||
| 364 | var err error | ||
| 365 | n, err = inferBranchMR(t) | ||
| 366 | if err != nil { | ||
| 367 | fmt.Fprintln(os.Stderr, "gitbay:", err) | ||
| 368 | return protocol.ExitNotFound | ||
| 369 | } | ||
| 370 | } | ||
| 359 | out, code := captureSSH(t, []string{"mr", "show", t.repo, n, "--json"}) | 371 | out, code := captureSSH(t, []string{"mr", "show", t.repo, n, "--json"}) |
| 360 | if code != 0 { | 372 | if code != 0 { |
| 361 | return code | 373 | return code |
cmd/gitbay/main.go +110 −62
| @@ -48,14 +48,14 @@ func newRoot() *cobra.Command { | |||
| 48 | pass("set", passOpts{server: []string{"status", "set"}, needsRepo: true}), | 48 | pass("set", passOpts{server: []string{"status", "set"}, needsRepo: true}), |
| 49 | pass("list", passOpts{server: []string{"status", "list"}, needsRepo: true}), | 49 | pass("list", passOpts{server: []string{"status", "list"}, needsRepo: true}), |
| 50 | ), | 50 | ), |
| 51 | group("build", "CI builds", | 51 | withDefault(group("build", "CI builds", |
| 52 | pass("list", passOpts{server: []string{"build", "list"}, needsRepo: true}), | 52 | pass("list", passOpts{server: []string{"build", "list"}, needsRepo: true}), |
| 53 | pass("show", passOpts{server: []string{"build", "show"}, needsRepo: true}), | 53 | pass("show", passOpts{server: []string{"build", "show"}, needsRepo: true, inferBuild: true}), |
| 54 | pass("log", passOpts{server: []string{"build", "log"}, needsRepo: true}), | 54 | pass("log", passOpts{server: []string{"build", "log"}, needsRepo: true, inferBuild: true}), |
| 55 | pass("jobs", passOpts{server: []string{"build", "jobs"}, needsRepo: true}), | 55 | pass("jobs", passOpts{server: []string{"build", "jobs"}, needsRepo: true}), |
| 56 | pass("trigger", passOpts{server: []string{"build", "trigger"}, needsRepo: true}), | 56 | pass("trigger", passOpts{server: []string{"build", "trigger"}, needsRepo: true}), |
| 57 | pass("cancel", passOpts{server: []string{"build", "cancel"}, needsRepo: true}), | 57 | pass("cancel", passOpts{server: []string{"build", "cancel"}, needsRepo: true}), |
| 58 | ), | 58 | ), passOpts{server: []string{"build", "list"}, needsRepo: true}, passOpts{server: []string{"build", "show"}, needsRepo: true, inferBuild: true}, ""), |
| 59 | withShort(pass("dashboard", passOpts{server: []string{"dashboard"}}), "pinned repos, open MRs, assigned issues, recent builds"), | 59 | withShort(pass("dashboard", passOpts{server: []string{"dashboard"}}), "pinned repos, open MRs, assigned issues, recent builds"), |
| 60 | pass("feed", passOpts{server: []string{"feed"}}), | 60 | pass("feed", passOpts{server: []string{"feed"}}), |
| 61 | withShort(pass("explore", passOpts{server: []string{"explore"}}), "public repositories on this instance"), | 61 | withShort(pass("explore", passOpts{server: []string{"explore"}}), "public repositories on this instance"), |
| @@ -105,6 +105,7 @@ func newRoot() *cobra.Command { | |||
| 105 | issueCmd(), | 105 | issueCmd(), |
| 106 | milestoneCmd(), | 106 | milestoneCmd(), |
| 107 | mrCmd(), | 107 | mrCmd(), |
| 108 | openCmd(), | ||
| 108 | releaseCmd(), | 109 | releaseCmd(), |
| 109 | migrateCmd(), | 110 | migrateCmd(), |
| 110 | webCmd(), | 111 | webCmd(), |
| @@ -181,7 +182,7 @@ type rootSection struct { | |||
| 181 | } | 182 | } |
| 182 | 183 | ||
| 183 | var rootSections = []rootSection{ | 184 | var rootSections = []rootSection{ |
| 184 | {"WORK", []string{"issue", "mr", "build", "release", "milestone", "label", "search", "query"}}, | 185 | {"WORK", []string{"issue", "mr", "build", "release", "milestone", "label", "search", "query", "open"}}, |
| 185 | {"REPOSITORIES", []string{"repo", "wiki", "status", "webhook", "init"}}, | 186 | {"REPOSITORIES", []string{"repo", "wiki", "status", "webhook", "init"}}, |
| 186 | {"YOU", []string{"dashboard", "feed", "notifications", "auth", "profile", "snippet", "web"}}, | 187 | {"YOU", []string{"dashboard", "feed", "notifications", "auth", "profile", "snippet", "web"}}, |
| 187 | {"INSTANCE", []string{"org", "explore", "register", "migrate", "remote", "admin", "audit", "man"}}, | 188 | {"INSTANCE", []string{"org", "explore", "register", "migrate", "remote", "admin", "audit", "man"}}, |
| @@ -245,6 +246,9 @@ type passOpts struct { | |||
| 245 | stdinSecret bool | 246 | stdinSecret bool |
| 246 | editor string // open $EDITOR for a body when none given | 247 | editor string // open $EDITOR for a body when none given |
| 247 | inferSource bool // --source defaults to the checked-out branch inside a clone | 248 | inferSource bool // --source defaults to the checked-out branch inside a clone |
| 249 | inferMR bool // <n> defaults to the current branch's open MR inside a clone | ||
| 250 | inferBuild bool // <n> defaults to the latest build for the current branch inside a clone | ||
| 251 | numPrefix string // optional leading "#" or "!" stripped from args[1] | ||
| 248 | } | 252 | } |
| 249 | 253 | ||
| 250 | // pass builds a passthrough command. Flags are parsed by the server, which | 254 | // pass builds a passthrough command. Flags are parsed by the server, which |
| @@ -323,6 +327,23 @@ func runPass(o passOpts, cliPath string, args []string) int { | |||
| 323 | fmt.Fprintln(os.Stderr, "gitbay:", err) | 327 | fmt.Fprintln(os.Stderr, "gitbay:", err) |
| 324 | return protocol.ExitUsage | 328 | return protocol.ExitUsage |
| 325 | } | 329 | } |
| 330 | args = stripLeadingNumberPrefix(args, o.numPrefix) | ||
| 331 | } | ||
| 332 | if o.inferMR && !explicitRepo && !hasPositionalAfterRepo(args) { | ||
| 333 | num, err := inferBranchMR(t) | ||
| 334 | if err != nil { | ||
| 335 | fmt.Fprintln(os.Stderr, "gitbay:", err) | ||
| 336 | return protocol.ExitNotFound | ||
| 337 | } | ||
| 338 | args = slices.Insert(args, 1, num) | ||
| 339 | } | ||
| 340 | if o.inferBuild && !explicitRepo && !hasPositionalAfterRepo(args) { | ||
| 341 | num, err := inferLatestBuild(t) | ||
| 342 | if err != nil { | ||
| 343 | fmt.Fprintln(os.Stderr, "gitbay:", err) | ||
| 344 | return protocol.ExitNotFound | ||
| 345 | } | ||
| 346 | args = slices.Insert(args, 1, num) | ||
| 326 | } | 347 | } |
| 327 | // Inside a clone, the branch you are on is the one you mean (#101). | 348 | // Inside a clone, the branch you are on is the one you mean (#101). |
| 328 | // Only when the repository was inferred from the clone too: naming | 349 | // Only when the repository was inferred from the clone too: naming |
| @@ -335,23 +356,46 @@ func runPass(o passOpts, cliPath string, args []string) int { | |||
| 335 | 356 | ||
| 336 | var stdin io.Reader = strings.NewReader("") | 357 | var stdin io.Reader = strings.NewReader("") |
| 337 | if o.editor != "" { | 358 | if o.editor != "" { |
| 338 | // Issue bodies prefill from the repo's .gitbay/issue-template*.md. | 359 | // Issue/MR create can take both title and body from $EDITOR when |
| 339 | var prefill func() string | 360 | // --title/-t is omitted; MR create prefills from HEAD commit. |
| 340 | if o.editor == "issue" && len(args) > 0 && strings.Contains(args[0], "/") { | 361 | if (o.editor == "issue" || o.editor == "merge request") && !hasFlag(args, "--title") && !hasFlag(args, "-t") { |
| 341 | repoPath := args[0] | 362 | var preTitle, preBody string |
| 342 | prefill = func() string { return fetchIssueTemplate(t, repoPath) } | 363 | if o.editor == "merge request" && !explicitRepo { |
| 343 | } | 364 | preTitle, preBody = headCommitTitleBody() |
| 344 | extended, body, ok, err := maybeEditor(args, o.editor, prefill) | 365 | } else if o.editor == "issue" && len(args) > 0 && strings.Contains(args[0], "/") { |
| 345 | if err != nil { | 366 | preBody = fetchIssueTemplate(t, args[0]) |
| 346 | fmt.Fprintln(os.Stderr, "gitbay:", err) | 367 | } |
| 347 | return protocol.ExitFailure | 368 | extended, body, ok, err := maybeTitleAndBodyEditor(args, o.editor, preTitle, preBody) |
| 348 | } | 369 | if err != nil { |
| 349 | if !ok { | 370 | fmt.Fprintln(os.Stderr, "gitbay:", err) |
| 350 | return protocol.ExitFailure | 371 | return protocol.ExitFailure |
| 351 | } | 372 | } |
| 352 | args = extended | 373 | if !ok { |
| 353 | if body != nil { | 374 | return protocol.ExitFailure |
| 354 | stdin = body | 375 | } |
| 376 | args = extended | ||
| 377 | if body != nil { | ||
| 378 | stdin = body | ||
| 379 | } | ||
| 380 | } else { | ||
| 381 | // Issue bodies prefill from the repo's .gitbay/issue-template*.md. | ||
| 382 | var prefill func() string | ||
| 383 | if o.editor == "issue" && len(args) > 0 && strings.Contains(args[0], "/") { | ||
| 384 | repoPath := args[0] | ||
| 385 | prefill = func() string { return fetchIssueTemplate(t, repoPath) } | ||
| 386 | } | ||
| 387 | extended, body, ok, err := maybeEditor(args, o.editor, prefill) | ||
| 388 | if err != nil { | ||
| 389 | fmt.Fprintln(os.Stderr, "gitbay:", err) | ||
| 390 | return protocol.ExitFailure | ||
| 391 | } | ||
| 392 | if !ok { | ||
| 393 | return protocol.ExitFailure | ||
| 394 | } | ||
| 395 | args = extended | ||
| 396 | if body != nil { | ||
| 397 | stdin = body | ||
| 398 | } | ||
| 355 | } | 399 | } |
| 356 | } | 400 | } |
| 357 | if stdin == nil || isEmptyReader(stdin) { | 401 | if stdin == nil || isEmptyReader(stdin) { |
| @@ -380,10 +424,10 @@ func isEmptyReader(r io.Reader) bool { | |||
| 380 | // usesStdin reports whether the arguments request stdin content. | 424 | // usesStdin reports whether the arguments request stdin content. |
| 381 | func usesStdin(args []string) bool { | 425 | func usesStdin(args []string) bool { |
| 382 | for i, a := range args { | 426 | for i, a := range args { |
| 383 | if slices.Contains([]string{"--file", "--key", "--secret"}, a) && i+1 < len(args) && args[i+1] == "-" { | 427 | if slices.Contains([]string{"--file", "-f", "--key", "--secret"}, a) && i+1 < len(args) && args[i+1] == "-" { |
| 384 | return true | 428 | return true |
| 385 | } | 429 | } |
| 386 | if a == "--token-stdin" { | 430 | if a == "--file=-" || a == "--key=-" || a == "--secret=-" || a == "--token-stdin" { |
| 387 | return true | 431 | return true |
| 388 | } | 432 | } |
| 389 | } | 433 | } |
| @@ -545,7 +589,7 @@ func authCmd() *cobra.Command { | |||
| 545 | } | 589 | } |
| 546 | 590 | ||
| 547 | func repoCmd() *cobra.Command { | 591 | func repoCmd() *cobra.Command { |
| 548 | return group("repo", "create and manage repositories", | 592 | return withRepoDefault(group("repo", "create and manage repositories", |
| 549 | pass("create", passOpts{server: []string{"repo", "create"}}), | 593 | pass("create", passOpts{server: []string{"repo", "create"}}), |
| 550 | pass("list", passOpts{server: []string{"repo", "list"}}), | 594 | pass("list", passOpts{server: []string{"repo", "list"}}), |
| 551 | pass("show", passOpts{server: []string{"repo", "show"}, needsRepo: true}), | 595 | pass("show", passOpts{server: []string{"repo", "show"}, needsRepo: true}), |
| @@ -658,24 +702,26 @@ func repoCmd() *cobra.Command { | |||
| 658 | pass("website", passOpts{server: []string{"repo", "settings", "website"}, needsRepo: true}), | 702 | pass("website", passOpts{server: []string{"repo", "settings", "website"}, needsRepo: true}), |
| 659 | pass("git-daemon", passOpts{server: []string{"repo", "settings", "git-daemon"}, needsRepo: true}), | 703 | pass("git-daemon", passOpts{server: []string{"repo", "settings", "git-daemon"}, needsRepo: true}), |
| 660 | ), | 704 | ), |
| 661 | ) | 705 | )) |
| 662 | } | 706 | } |
| 663 | 707 | ||
| 664 | func issueCmd() *cobra.Command { | 708 | func issueCmd() *cobra.Command { |
| 665 | return group("issue", "issues", | 709 | listOpts := passOpts{server: []string{"issue", "list"}, needsRepo: true, crossRepo: []string{"--query", "--q"}} |
| 710 | showOpts := passOpts{server: []string{"issue", "show"}, needsRepo: true, numPrefix: "#"} | ||
| 711 | return withDefault(group("issue", "issues", | ||
| 666 | pass("create", passOpts{server: []string{"issue", "create"}, needsRepo: true, stdinOK: true, editor: "issue"}), | 712 | pass("create", passOpts{server: []string{"issue", "create"}, needsRepo: true, stdinOK: true, editor: "issue"}), |
| 667 | pass("list", passOpts{server: []string{"issue", "list"}, needsRepo: true, crossRepo: []string{"--query", "--q"}}), | 713 | pass("list", listOpts), |
| 668 | pass("show", passOpts{server: []string{"issue", "show"}, needsRepo: true}), | 714 | pass("show", showOpts), |
| 669 | pass("comment", passOpts{server: []string{"issue", "comment"}, needsRepo: true, stdinOK: true, editor: "comment"}), | 715 | pass("comment", passOpts{server: []string{"issue", "comment"}, needsRepo: true, stdinOK: true, editor: "comment", numPrefix: "#"}), |
| 670 | pass("close", passOpts{server: []string{"issue", "close"}, needsRepo: true}), | 716 | pass("close", passOpts{server: []string{"issue", "close"}, needsRepo: true, numPrefix: "#"}), |
| 671 | pass("reopen", passOpts{server: []string{"issue", "reopen"}, needsRepo: true}), | 717 | pass("reopen", passOpts{server: []string{"issue", "reopen"}, needsRepo: true, numPrefix: "#"}), |
| 672 | pass("label", passOpts{server: []string{"issue", "label"}, needsRepo: true}), | 718 | pass("label", passOpts{server: []string{"issue", "label"}, needsRepo: true, numPrefix: "#"}), |
| 673 | pass("assign", passOpts{server: []string{"issue", "assign"}, needsRepo: true}), | 719 | pass("assign", passOpts{server: []string{"issue", "assign"}, needsRepo: true, numPrefix: "#"}), |
| 674 | pass("react", passOpts{server: []string{"issue", "react"}, needsRepo: true}), | 720 | pass("react", passOpts{server: []string{"issue", "react"}, needsRepo: true, numPrefix: "#"}), |
| 675 | pass("edit", passOpts{server: []string{"issue", "edit"}, needsRepo: true, stdinOK: true}), | 721 | pass("edit", passOpts{server: []string{"issue", "edit"}, needsRepo: true, stdinOK: true, numPrefix: "#"}), |
| 676 | pass("milestone", passOpts{server: []string{"issue", "milestone"}, needsRepo: true}), | 722 | pass("milestone", passOpts{server: []string{"issue", "milestone"}, needsRepo: true, numPrefix: "#"}), |
| 677 | pass("templates", passOpts{server: []string{"issue", "templates"}, needsRepo: true}), | 723 | pass("templates", passOpts{server: []string{"issue", "templates"}, needsRepo: true}), |
| 678 | ) | 724 | ), listOpts, showOpts, "#") |
| 679 | } | 725 | } |
| 680 | 726 | ||
| 681 | func releaseCmd() *cobra.Command { | 727 | func releaseCmd() *cobra.Command { |
| @@ -704,34 +750,36 @@ func milestoneCmd() *cobra.Command { | |||
| 704 | } | 750 | } |
| 705 | 751 | ||
| 706 | func mrCmd() *cobra.Command { | 752 | func mrCmd() *cobra.Command { |
| 707 | review := pass("review", passOpts{server: []string{"mr", "review"}, needsRepo: true}) | 753 | listOpts := passOpts{server: []string{"mr", "list"}, needsRepo: true, crossRepo: []string{"--query", "--q"}} |
| 708 | review.AddCommand(pass("request", passOpts{server: []string{"mr", "review", "request"}, needsRepo: true})) | 754 | showOpts := passOpts{server: []string{"mr", "show"}, needsRepo: true, inferMR: true, numPrefix: "!"} |
| 709 | return group("mr", "merge requests", | 755 | review := pass("review", passOpts{server: []string{"mr", "review"}, needsRepo: true, inferMR: true, numPrefix: "!"}) |
| 756 | review.AddCommand(pass("request", passOpts{server: []string{"mr", "review", "request"}, needsRepo: true, inferMR: true, numPrefix: "!"})) | ||
| 757 | return withDefault(group("mr", "merge requests", | ||
| 710 | pass("create", passOpts{server: []string{"mr", "create"}, needsRepo: true, stdinOK: true, editor: "merge request", inferSource: true}), | 758 | pass("create", passOpts{server: []string{"mr", "create"}, needsRepo: true, stdinOK: true, editor: "merge request", inferSource: true}), |
| 711 | pass("list", passOpts{server: []string{"mr", "list"}, needsRepo: true, crossRepo: []string{"--query", "--q"}}), | 759 | pass("list", listOpts), |
| 712 | pass("show", passOpts{server: []string{"mr", "show"}, needsRepo: true}), | 760 | pass("show", showOpts), |
| 713 | pass("diff", passOpts{server: []string{"mr", "diff"}, needsRepo: true}), | 761 | pass("diff", passOpts{server: []string{"mr", "diff"}, needsRepo: true, inferMR: true, numPrefix: "!"}), |
| 714 | local("checkout", "fetch and check out the MR head locally: gitbay mr checkout <n>", cmdMRCheckout), | 762 | local("checkout", "fetch and check out the MR head locally: gitbay mr checkout <n>", cmdMRCheckout), |
| 715 | local("rebase", "replay the MR's branch onto its target and re-push: gitbay mr rebase <n>", cmdMRRebase), | 763 | local("rebase", "replay the MR's branch onto its target and re-push: gitbay mr rebase [<n>]", cmdMRRebase), |
| 716 | pass("comment", passOpts{server: []string{"mr", "comment"}, needsRepo: true, stdinOK: true, editor: "comment"}), | 764 | pass("comment", passOpts{server: []string{"mr", "comment"}, needsRepo: true, stdinOK: true, editor: "comment", inferMR: true, numPrefix: "!"}), |
| 717 | pass("react", passOpts{server: []string{"mr", "react"}, needsRepo: true}), | 765 | pass("react", passOpts{server: []string{"mr", "react"}, needsRepo: true, inferMR: true, numPrefix: "!"}), |
| 718 | pass("diff-comment", passOpts{server: []string{"mr", "diff-comment"}, needsRepo: true, stdinOK: true, editor: "comment"}), | 766 | pass("diff-comment", passOpts{server: []string{"mr", "diff-comment"}, needsRepo: true, stdinOK: true, editor: "comment", inferMR: true, numPrefix: "!"}), |
| 719 | pass("threads", passOpts{server: []string{"mr", "threads"}, needsRepo: true}), | 767 | pass("threads", passOpts{server: []string{"mr", "threads"}, needsRepo: true, inferMR: true, numPrefix: "!"}), |
| 720 | pass("resolve", passOpts{server: []string{"mr", "resolve"}, needsRepo: true}), | 768 | pass("resolve", passOpts{server: []string{"mr", "resolve"}, needsRepo: true, numPrefix: "!"}), |
| 721 | mrApplySuggestionCmd(), | 769 | mrApplySuggestionCmd(), |
| 722 | pass("unresolve", passOpts{server: []string{"mr", "unresolve"}, needsRepo: true}), | 770 | pass("unresolve", passOpts{server: []string{"mr", "unresolve"}, needsRepo: true, numPrefix: "!"}), |
| 723 | review, | 771 | review, |
| 724 | pass("merge", passOpts{server: []string{"mr", "merge"}, needsRepo: true}), | 772 | pass("merge", passOpts{server: []string{"mr", "merge"}, needsRepo: true, inferMR: true, numPrefix: "!"}), |
| 725 | pass("close", passOpts{server: []string{"mr", "close"}, needsRepo: true}), | 773 | pass("close", passOpts{server: []string{"mr", "close"}, needsRepo: true, inferMR: true, numPrefix: "!"}), |
| 726 | pass("revisions", passOpts{server: []string{"mr", "revisions"}, needsRepo: true}), | 774 | pass("revisions", passOpts{server: []string{"mr", "revisions"}, needsRepo: true, inferMR: true, numPrefix: "!"}), |
| 727 | pass("range-diff", passOpts{server: []string{"mr", "range-diff"}, needsRepo: true}), | 775 | pass("range-diff", passOpts{server: []string{"mr", "range-diff"}, needsRepo: true, inferMR: true, numPrefix: "!"}), |
| 728 | pass("draft", passOpts{server: []string{"mr", "draft"}, needsRepo: true}), | 776 | pass("draft", passOpts{server: []string{"mr", "draft"}, needsRepo: true, inferMR: true, numPrefix: "!"}), |
| 729 | pass("ready", passOpts{server: []string{"mr", "ready"}, needsRepo: true}), | 777 | pass("ready", passOpts{server: []string{"mr", "ready"}, needsRepo: true, inferMR: true, numPrefix: "!"}), |
| 730 | pass("edit", passOpts{server: []string{"mr", "edit"}, needsRepo: true, stdinOK: true}), | 778 | pass("edit", passOpts{server: []string{"mr", "edit"}, needsRepo: true, stdinOK: true, inferMR: true, numPrefix: "!"}), |
| 731 | pass("label", passOpts{server: []string{"mr", "label"}, needsRepo: true}), | 779 | pass("label", passOpts{server: []string{"mr", "label"}, needsRepo: true, inferMR: true, numPrefix: "!"}), |
| 732 | pass("milestone", passOpts{server: []string{"mr", "milestone"}, needsRepo: true}), | 780 | pass("milestone", passOpts{server: []string{"mr", "milestone"}, needsRepo: true, inferMR: true, numPrefix: "!"}), |
| 733 | pass("retarget", passOpts{server: []string{"mr", "retarget"}, needsRepo: true}), | 781 | pass("retarget", passOpts{server: []string{"mr", "retarget"}, needsRepo: true, numPrefix: "!"}), |
| 734 | ) | 782 | ), listOpts, showOpts, "!") |
| 735 | } | 783 | } |
| 736 | 784 | ||
| 737 | // importCmd passes repo import through with stdin wired for --token-stdin. | 785 | // importCmd passes repo import through with stdin wired for --token-stdin. |
internal/control/flags.go +45 −14
| @@ -35,9 +35,25 @@ func (f flags) Has(name string) bool { return f.seen[name] } | |||
| 35 | // List is every value given for a repeatable flag, in order. | 35 | // List is every value given for a repeatable flag, in order. |
| 36 | func (f flags) List(name string) []string { return f.multi[name] } | 36 | func (f flags) List(name string) []string { return f.multi[name] } |
| 37 | 37 | ||
| 38 | // shortFlags maps common single-letter aliases to their canonical long | ||
| 39 | // names. An alias only fires when the command's spec declares that long | ||
| 40 | // flag, so commands without it never misread a positional like "-n". | ||
| 41 | var shortFlags = map[string]string{ | ||
| 42 | "-t": "--title", | ||
| 43 | "-m": "--message", | ||
| 44 | "-b": "--body", | ||
| 45 | "-s": "--state", | ||
| 46 | "-l": "--label", | ||
| 47 | "-a": "--assignee", | ||
| 48 | "-d": "--draft", | ||
| 49 | "-f": "--file", | ||
| 50 | "-n": "--limit", | ||
| 51 | } | ||
| 52 | |||
| 38 | // parseFlags reads args against spec. A flag must be one the spec names; | 53 | // parseFlags reads args against spec. A flag must be one the spec names; |
| 39 | // a value flag consumes the next argument verbatim, "-" included; "--" | 54 | // a value flag consumes the next argument verbatim, "-" included (or the |
| 40 | // ends flag parsing. The error, when there is one, is the usage message. | 55 | // part after "=" in --flag=value); "--" ends flag parsing. The error, |
| 56 | // when there is one, is the usage message. | ||
| 41 | func parseFlags(args []string, spec flagSpec) (flags, error) { | 57 | func parseFlags(args []string, spec flagSpec) (flags, error) { |
| 42 | f := flags{vals: map[string]string{}, multi: map[string][]string{}, seen: map[string]bool{}} | 58 | f := flags{vals: map[string]string{}, multi: map[string][]string{}, seen: map[string]bool{}} |
| 43 | kind := map[string]byte{} | 59 | kind := map[string]byte{} |
| @@ -64,26 +80,41 @@ func parseFlags(args []string, spec flagSpec) (flags, error) { | |||
| 64 | onlyPos = true | 80 | onlyPos = true |
| 65 | continue | 81 | continue |
| 66 | } | 82 | } |
| 83 | if !onlyPos && len(a) == 2 && a[0] == '-' && a[1] != '-' { | ||
| 84 | if long, ok := shortFlags[a]; ok && kind[long] != 0 { | ||
| 85 | a = long | ||
| 86 | } | ||
| 87 | } | ||
| 67 | if !onlyPos && strings.HasPrefix(a, "--") { | 88 | if !onlyPos && strings.HasPrefix(a, "--") { |
| 68 | switch kind[a] { | 89 | name, eqVal, hasEq := strings.Cut(a, "=") |
| 90 | switch kind[name] { | ||
| 69 | case 'b': | 91 | case 'b': |
| 70 | f.seen[a] = true | 92 | if hasEq { |
| 93 | return f, usage("%s does not take a value", name) | ||
| 94 | } | ||
| 95 | f.seen[name] = true | ||
| 71 | case 'v', 'm': | 96 | case 'v', 'm': |
| 72 | if i+1 >= len(args) { | 97 | var val string |
| 73 | return f, usage("%s requires a value", a) | 98 | if hasEq { |
| 99 | val = eqVal | ||
| 100 | } else { | ||
| 101 | if i+1 >= len(args) { | ||
| 102 | return f, usage("%s requires a value", name) | ||
| 103 | } | ||
| 104 | val = args[i+1] | ||
| 105 | i++ | ||
| 74 | } | 106 | } |
| 75 | f.seen[a] = true | 107 | f.seen[name] = true |
| 76 | if kind[a] == 'v' { | 108 | if kind[name] == 'v' { |
| 77 | f.vals[a] = args[i+1] | 109 | f.vals[name] = val |
| 78 | } else { | 110 | } else { |
| 79 | f.multi[a] = append(f.multi[a], args[i+1]) | 111 | f.multi[name] = append(f.multi[name], val) |
| 80 | } | 112 | } |
| 81 | i++ | ||
| 82 | default: | 113 | default: |
| 83 | if near := nearestFlag(a, kind); near != "" { | 114 | if near := nearestFlag(name, kind); near != "" { |
| 84 | return f, usage("unknown flag %q; did you mean %s?", a, near) | 115 | return f, usage("unknown flag %q; did you mean %s?", name, near) |
| 85 | } | 116 | } |
| 86 | return f, usage("unknown flag %q", a) | 117 | return f, usage("unknown flag %q", name) |
| 87 | } | 118 | } |
| 88 | continue | 119 | continue |
| 89 | } | 120 | } |
internal/control/flags_test.go +26
| @@ -30,6 +30,32 @@ func TestParseFlags(t *testing.T) { | |||
| 30 | if err != nil || strings.Join(f.Pos, " ") != "--title x" || f.Has("--title") { | 30 | if err != nil || strings.Join(f.Pos, " ") != "--title x" || f.Has("--title") { |
| 31 | t.Fatalf("-- handling: %v %+v", err, f) | 31 | t.Fatalf("-- handling: %v %+v", err, f) |
| 32 | } | 32 | } |
| 33 | |||
| 34 | // Short flags and --flag=value forms. | ||
| 35 | shortSpec := flagSpec{ | ||
| 36 | Values: []string{"--title", "--state", "--file", "--limit"}, | ||
| 37 | Multi: []string{"--label"}, | ||
| 38 | Bools: []string{"--draft"}, | ||
| 39 | MaxPos: 1, | ||
| 40 | } | ||
| 41 | f, err = parseFlags([]string{"a/b", "-t", "hello", "-s", "all", "-l", "bug", "-l", "ux", "-d", "-f", "-", "-n", "10"}, shortSpec) | ||
| 42 | if err != nil { | ||
| 43 | t.Fatalf("short flags: %v", err) | ||
| 44 | } | ||
| 45 | if f.Value("--title") != "hello" || f.Value("--state") != "all" || f.Value("--file") != "-" || | ||
| 46 | f.Value("--limit") != "10" || !f.Has("--draft") || strings.Join(f.List("--label"), ",") != "bug,ux" { | ||
| 47 | t.Fatalf("short flags parsed wrong: %+v", f) | ||
| 48 | } | ||
| 49 | f, err = parseFlags([]string{"a/b", "--title=hello=world", "--label=bug", "--label=ux"}, shortSpec) | ||
| 50 | if err != nil { | ||
| 51 | t.Fatalf("--flag=value: %v", err) | ||
| 52 | } | ||
| 53 | if f.Value("--title") != "hello=world" || strings.Join(f.List("--label"), ",") != "bug,ux" { | ||
| 54 | t.Fatalf("--flag=value parsed wrong: %+v", f) | ||
| 55 | } | ||
| 56 | if _, err := parseFlags([]string{"a/b", "--draft=true"}, shortSpec); err == nil { | ||
| 57 | t.Errorf("expected error for --bool=value") | ||
| 58 | } | ||
| 33 | } | 59 | } |
| 34 | 60 | ||
| 35 | func TestNearestFlag(t *testing.T) { | 61 | func TestNearestFlag(t *testing.T) { |
internal/control/mr.go +2 −2
| @@ -64,10 +64,10 @@ func init() { | |||
| 64 | Run: runRequireSigned}) | 64 | Run: runRequireSigned}) |
| 65 | register(Command{Path: []string{"mr", "create"}, | 65 | register(Command{Path: []string{"mr", "create"}, |
| 66 | Summary: "open a merge request", | 66 | Summary: "open a merge request", |
| 67 | Usage: "mr create <target owner/name> --source [owner/name:]<branch> --target <branch> --title <t> [--body <b> | --file -] [--format md|org] [--draft]", | 67 | Usage: "mr create <target owner/name> --source [owner/name:]<branch> [--target <branch>] --title <t> [--body <b> | --file -] [--format md|org] [--draft]", |
| 68 | Flags: []Flag{ | 68 | Flags: []Flag{ |
| 69 | {"--source", "[owner/name:]<branch>", "the branch to merge, from a fork with owner/name:", ""}, | 69 | {"--source", "[owner/name:]<branch>", "the branch to merge, from a fork with owner/name:", ""}, |
| 70 | {"--target", "<branch>", "the branch to merge into", ""}, | 70 | {"--target", "<branch>", "the branch to merge into", "default branch"}, |
| 71 | {"--title", "<t>", "the merge request's title", ""}, | 71 | {"--title", "<t>", "the merge request's title", ""}, |
| 72 | {"--body", "<b>", "the merge request's body", ""}, | 72 | {"--body", "<b>", "the merge request's body", ""}, |
| 73 | {"--file", "-", "read the body from stdin", ""}, | 73 | {"--file", "-", "read the body from stdin", ""}, |
internal/control/refsupdated.go +42
| @@ -5,6 +5,7 @@ import ( | |||
| 5 | "fmt" | 5 | "fmt" |
| 6 | "io" | 6 | "io" |
| 7 | "log/slog" | 7 | "log/slog" |
| 8 | "net/url" | ||
| 8 | "path" | 9 | "path" |
| 9 | "strings" | 10 | "strings" |
| 10 | "time" | 11 | "time" |
| @@ -271,3 +272,44 @@ func cutHeads(ref string) (string, bool) { | |||
| 271 | } | 272 | } |
| 272 | return "", false | 273 | return "", false |
| 273 | } | 274 | } |
| 275 | |||
| 276 | // PushHints formats post-receive hints for non-default branches in updates: | ||
| 277 | // a link to any open merge request for that branch, or the CLI command and | ||
| 278 | // web URL to open one. | ||
| 279 | func PushHints(st *store.Store, cfg config.Config, repoID int64, updates []policy.RefUpdate) string { | ||
| 280 | repo, err := st.RepoByID(repoID) | ||
| 281 | if err != nil { | ||
| 282 | return "" | ||
| 283 | } | ||
| 284 | site := strings.TrimRight(cfg.Server.SiteURL, "/") | ||
| 285 | var lines []string | ||
| 286 | for _, u := range updates { | ||
| 287 | branch, ok := cutHeads(u.Ref) | ||
| 288 | if !ok || u.IsDelete || branch == repo.DefaultBranch { | ||
| 289 | continue | ||
| 290 | } | ||
| 291 | mrs, err := st.OpenMRsBySource(repoID, branch) | ||
| 292 | if err == nil && len(mrs) > 0 { | ||
| 293 | for _, mr := range mrs { | ||
| 294 | target := repo | ||
| 295 | if mr.RepoID != repo.ID { | ||
| 296 | if r, err := st.RepoByID(mr.RepoID); err == nil { | ||
| 297 | target = r | ||
| 298 | } | ||
| 299 | } | ||
| 300 | if site != "" { | ||
| 301 | lines = append(lines, fmt.Sprintf("open merge request !%d: %s/%s/mrs/%d", mr.Number, site, target.Path(), mr.Number)) | ||
| 302 | } else { | ||
| 303 | lines = append(lines, fmt.Sprintf("open merge request !%d (%s)", mr.Number, target.Path())) | ||
| 304 | } | ||
| 305 | } | ||
| 306 | continue | ||
| 307 | } | ||
| 308 | lines = append(lines, fmt.Sprintf("create a merge request for %s:", branch)) | ||
| 309 | lines = append(lines, fmt.Sprintf(" gitbay mr create --source %s", shellWord(branch))) | ||
| 310 | if site != "" { | ||
| 311 | lines = append(lines, fmt.Sprintf(" %s/%s/mrs/new?source=%s", site, repo.Path(), url.QueryEscape(branch))) | ||
| 312 | } | ||
| 313 | } | ||
| 314 | return strings.Join(lines, "\n") | ||
| 315 | } | ||
internal/hookd/hookd.go +4 −3
| @@ -152,8 +152,8 @@ func (s *Server) handle(conn net.Conn) { | |||
| 152 | preReceiveStarted(req.Token) | 152 | preReceiveStarted(req.Token) |
| 153 | s.preReceive(req, dec, enc) | 153 | s.preReceive(req, dec, enc) |
| 154 | case "post-receive": | 154 | case "post-receive": |
| 155 | s.postReceive(req) | 155 | msg := s.postReceive(req) |
| 156 | enc.Encode(Response{Allow: true}) | 156 | enc.Encode(Response{Allow: true, Message: msg}) |
| 157 | default: | 157 | default: |
| 158 | enc.Encode(Response{Allow: false, Message: fmt.Sprintf("unknown hook %q", req.Hook)}) | 158 | enc.Encode(Response{Allow: false, Message: fmt.Sprintf("unknown hook %q", req.Hook)}) |
| 159 | } | 159 | } |
| @@ -346,8 +346,9 @@ func (s *Server) releaseAnchors(repo store.Repo, updates []policy.RefUpdate) str | |||
| 346 | 346 | ||
| 347 | // postReceive runs the ref-update work for a push; see | 347 | // postReceive runs the ref-update work for a push; see |
| 348 | // control.RefsUpdated, which server-side writes to a branch share. | 348 | // control.RefsUpdated, which server-side writes to a branch share. |
| 349 | func (s *Server) postReceive(req Request) { | 349 | func (s *Server) postReceive(req Request) string { |
| 350 | control.RefsUpdated(s.st, s.cfg, req.RepoID, req.UserID, req.Scope, req.Updates) | 350 | control.RefsUpdated(s.st, s.cfg, req.RepoID, req.UserID, req.Scope, req.Updates) |
| 351 | return control.PushHints(s.st, s.cfg, req.RepoID, req.Updates) | ||
| 351 | } | 352 | } |
| 352 | 353 | ||
| 353 | // Ask sends one request from the hook process to the daemon. stream is | 354 | // Ask sends one request from the hook process to the daemon. stream is |
internal/hookd/pushhints_test.go added +74
| @@ -0,0 +1,74 @@ | |||
| 1 | package hookd | ||
| 2 | |||
| 3 | import ( | ||
| 4 | "path/filepath" | ||
| 5 | "strings" | ||
| 6 | "testing" | ||
| 7 | |||
| 8 | "gitbay.org/gitbay/internal/config" | ||
| 9 | "gitbay.org/gitbay/internal/control" | ||
| 10 | "gitbay.org/gitbay/internal/policy" | ||
| 11 | "gitbay.org/gitbay/internal/store" | ||
| 12 | ) | ||
| 13 | |||
| 14 | func TestPushHints(t *testing.T) { | ||
| 15 | root := t.TempDir() | ||
| 16 | st, err := store.Open(filepath.Join(root, "gitbay.db")) | ||
| 17 | if err != nil { | ||
| 18 | t.Fatal(err) | ||
| 19 | } | ||
| 20 | defer st.Close() | ||
| 21 | |||
| 22 | if err := st.MigrateUp(); err != nil { | ||
| 23 | t.Fatal(err) | ||
| 24 | } | ||
| 25 | uid, err := st.CreateUser("alice", true) | ||
| 26 | if err != nil { | ||
| 27 | t.Fatal(err) | ||
| 28 | } | ||
| 29 | repoID, err := st.CreateRepo("user", uid, "app", "public") | ||
| 30 | if err != nil { | ||
| 31 | t.Fatal(err) | ||
| 32 | } | ||
| 33 | var cfg config.Config | ||
| 34 | cfg.Server.Root = root | ||
| 35 | cfg.Server.SiteURL = "https://gitbay.org" | ||
| 36 | |||
| 37 | // Default branch push produces no hint. | ||
| 38 | got := control.PushHints(st, cfg, repoID, []policy.RefUpdate{ | ||
| 39 | {Ref: "refs/heads/main", Old: strings.Repeat("0", 40), New: strings.Repeat("a", 40)}, | ||
| 40 | }) | ||
| 41 | if got != "" { | ||
| 42 | t.Fatalf("default branch hint = %q, want empty", got) | ||
| 43 | } | ||
| 44 | |||
| 45 | // Feature branch without an MR suggests creating one. | ||
| 46 | got = control.PushHints(st, cfg, repoID, []policy.RefUpdate{ | ||
| 47 | {Ref: "refs/heads/feat-x", Old: strings.Repeat("0", 40), New: strings.Repeat("a", 40)}, | ||
| 48 | }) | ||
| 49 | if !strings.Contains(got, "gitbay mr create --source feat-x") || | ||
| 50 | !strings.Contains(got, "https://gitbay.org/alice/app/mrs/new?source=feat-x") { | ||
| 51 | t.Fatalf("new branch hint = %q", got) | ||
| 52 | } | ||
| 53 | |||
| 54 | // Branch deletion produces no hint. | ||
| 55 | got = control.PushHints(st, cfg, repoID, []policy.RefUpdate{ | ||
| 56 | {Ref: "refs/heads/feat-x", Old: strings.Repeat("a", 40), New: strings.Repeat("0", 40), IsDelete: true}, | ||
| 57 | }) | ||
| 58 | if got != "" { | ||
| 59 | t.Fatalf("delete hint = %q, want empty", got) | ||
| 60 | } | ||
| 61 | |||
| 62 | // Branch with an open MR prints the existing MR URL. | ||
| 63 | n, err := st.CreateMR(repoID, uid, repoID, "feat-x", "main", "my feat", "", strings.Repeat("a", 40), "md", false) | ||
| 64 | if err != nil { | ||
| 65 | t.Fatal(err) | ||
| 66 | } | ||
| 67 | got = control.PushHints(st, cfg, repoID, []policy.RefUpdate{ | ||
| 68 | {Ref: "refs/heads/feat-x", Old: strings.Repeat("a", 40), New: strings.Repeat("b", 40)}, | ||
| 69 | }) | ||
| 70 | want := "open merge request !1: https://gitbay.org/alice/app/mrs/1" | ||
| 71 | if n != 1 || got != want { | ||
| 72 | t.Fatalf("open MR hint = %q, want %q", got, want) | ||
| 73 | } | ||
| 74 | } | ||