Qlty config and code cleanup !593
53 files changed, +1736 −1891
Layout: unified · split
.qlty/qlty.toml +20
| @@ -64,3 +64,23 @@ set.ignored = true | |||
| 64 | match.plugins = ["osv-scanner"] | 64 | match.plugins = ["osv-scanner"] |
| 65 | match.rules = ["osv-scanner:GO-2026-5932"] | 65 | match.rules = ["osv-scanner:GO-2026-5932"] |
| 66 | set.ignored = true | 66 | set.ignored = true |
| 67 | |||
| 68 | |||
| 69 | # Early returns are guard clauses, which keep the happy path unindented. | ||
| 70 | [smells.return_statements] | ||
| 71 | enabled = false | ||
| 72 | |||
| 73 | # Function and file complexity are left to review rather than counted. | ||
| 74 | [smells.function_complexity] | ||
| 75 | enabled = false | ||
| 76 | |||
| 77 | [smells.file_complexity] | ||
| 78 | enabled = false | ||
| 79 | |||
| 80 | # Six or seven parameters is ordinary for an unexported Go helper. | ||
| 81 | [smells.function_parameters] | ||
| 82 | threshold = 8 | ||
| 83 | |||
| 84 | # The store's hand-written queries each scan their rows in the same loop. | ||
| 85 | [language.go.smells.duplication] | ||
| 86 | filter_patterns = ["(import_declaration _)", "(for_statement (call_expression function: (selector_expression field: (field_identifier) @_f)) (#eq? @_f \"Next\"))"] | ||
cmd/gitbay/main.go +16 −26
| @@ -8,6 +8,7 @@ import ( | |||
| 8 | "fmt" | 8 | "fmt" |
| 9 | "io" | 9 | "io" |
| 10 | "os" | 10 | "os" |
| 11 | "slices" | ||
| 11 | "strings" | 12 | "strings" |
| 12 | 13 | ||
| 13 | "github.com/spf13/cobra" | 14 | "github.com/spf13/cobra" |
| @@ -379,7 +380,7 @@ func isEmptyReader(r io.Reader) bool { | |||
| 379 | // usesStdin reports whether the arguments request stdin content. | 380 | // usesStdin reports whether the arguments request stdin content. |
| 380 | func usesStdin(args []string) bool { | 381 | func usesStdin(args []string) bool { |
| 381 | for i, a := range args { | 382 | for i, a := range args { |
| 382 | if (a == "--file" || a == "--key" || a == "--secret") && i+1 < len(args) && args[i+1] == "-" { | 383 | if slices.Contains([]string{"--file", "--key", "--secret"}, a) && i+1 < len(args) && args[i+1] == "-" { |
| 383 | return true | 384 | return true |
| 384 | } | 385 | } |
| 385 | if a == "--token-stdin" { | 386 | if a == "--token-stdin" { |
| @@ -475,27 +476,33 @@ func local(use, short string, fn func(args []string) int) *cobra.Command { | |||
| 475 | } | 476 | } |
| 476 | } | 477 | } |
| 477 | 478 | ||
| 478 | func authCmd() *cobra.Command { | 479 | // runWithStdin runs the server command with the args and what, read |
| 479 | keysAdd := pass("add", passOpts{server: []string{"keys", "add"}, alwaysStdin: true, stdinWhat: "an SSH public key"}) | 480 | // from stdin, as its payload. |
| 480 | // keys add always reads stdin on the server; wire it through directly. | 481 | func runWithStdin(server []string, what string) func(*cobra.Command, []string) error { |
| 481 | keysAdd.RunE = func(cmd *cobra.Command, args []string) error { | 482 | return func(cmd *cobra.Command, args []string) error { |
| 482 | cliPath := cliPathOf(cmd) | 483 | cliPath := cliPathOf(cmd) |
| 483 | for _, a := range args { | 484 | for _, a := range args { |
| 484 | if a == "--help" || a == "-h" { | 485 | if a == "--help" || a == "-h" { |
| 485 | os.Exit(runServerHelp(passOpts{server: []string{"keys", "add"}}, cliPath)) | 486 | os.Exit(runServerHelp(passOpts{server: server}, cliPath)) |
| 486 | } | 487 | } |
| 487 | } | 488 | } |
| 488 | t, err := resolveTarget() | 489 | t, err := resolveTarget() |
| 489 | if err != nil { | 490 | if err != nil { |
| 490 | return err | 491 | return err |
| 491 | } | 492 | } |
| 492 | in, err := stdinPayload(os.Stdin, "an SSH public key", false) | 493 | in, err := stdinPayload(os.Stdin, what, false) |
| 493 | if err != nil { | 494 | if err != nil { |
| 494 | return err | 495 | return err |
| 495 | } | 496 | } |
| 496 | os.Exit(runSSH(t, withCLIPath(cliPath, "keys add", append([]string{"keys", "add"}, args...)), in)) | 497 | os.Exit(runSSH(t, withCLIPath(cliPath, strings.Join(server, " "), slices.Concat(server, args)), in)) |
| 497 | return nil | 498 | return nil |
| 498 | } | 499 | } |
| 500 | } | ||
| 501 | |||
| 502 | func authCmd() *cobra.Command { | ||
| 503 | keysAdd := pass("add", passOpts{server: []string{"keys", "add"}, alwaysStdin: true, stdinWhat: "an SSH public key"}) | ||
| 504 | // keys add always reads stdin on the server; wire it through directly. | ||
| 505 | keysAdd.RunE = runWithStdin([]string{"keys", "add"}, "an SSH public key") | ||
| 499 | pgpAdd := &cobra.Command{ | 506 | pgpAdd := &cobra.Command{ |
| 500 | Use: "add", Short: "register an OpenPGP public key (armored, on stdin)", | 507 | Use: "add", Short: "register an OpenPGP public key (armored, on stdin)", |
| 501 | Annotations: map[string]string{ | 508 | Annotations: map[string]string{ |
| @@ -504,24 +511,7 @@ func authCmd() *cobra.Command { | |||
| 504 | stdinWhat: "an armored OpenPGP public key", | 511 | stdinWhat: "an armored OpenPGP public key", |
| 505 | }, | 512 | }, |
| 506 | DisableFlagParsing: true, | 513 | DisableFlagParsing: true, |
| 507 | RunE: func(cmd *cobra.Command, args []string) error { | 514 | RunE: runWithStdin([]string{"pgp", "add"}, "an armored OpenPGP public key"), |
| 508 | cliPath := cliPathOf(cmd) | ||
| 509 | for _, a := range args { | ||
| 510 | if a == "--help" || a == "-h" { | ||
| 511 | os.Exit(runServerHelp(passOpts{server: []string{"pgp", "add"}}, cliPath)) | ||
| 512 | } | ||
| 513 | } | ||
| 514 | t, err := resolveTarget() | ||
| 515 | if err != nil { | ||
| 516 | return err | ||
| 517 | } | ||
| 518 | in, err := stdinPayload(os.Stdin, "an armored OpenPGP public key", false) | ||
| 519 | if err != nil { | ||
| 520 | return err | ||
| 521 | } | ||
| 522 | os.Exit(runSSH(t, withCLIPath(cliPath, "pgp add", append([]string{"pgp", "add"}, args...)), in)) | ||
| 523 | return nil | ||
| 524 | }, | ||
| 525 | } | 515 | } |
| 526 | tokens := group("token", "API tokens (minted over SSH, used with the JSON API)", | 516 | tokens := group("token", "API tokens (minted over SSH, used with the JSON API)", |
| 527 | pass("create", passOpts{server: []string{"token", "create"}}), | 517 | pass("create", passOpts{server: []string{"token", "create"}}), |
cmd/gitbayd/system.go +1 −1
| @@ -101,7 +101,7 @@ func shellCmd() *cobra.Command { | |||
| 101 | } | 101 | } |
| 102 | // Each forced command is its own process, so there is no | 102 | // Each forced command is its own process, so there is no |
| 103 | // shared pack or push budget in system mode. | 103 | // shared pack or push budget in system mode. |
| 104 | code := sshd.Exec(cfg, st, nil, nil, user, key, control.ParseTerm(os.Getenv("GITBAY_TERM")), cmdline, os.Stdin, os.Stdout, os.Stderr, nil, nil, nil) | 104 | code := sshd.Exec(sshd.Backend{Cfg: cfg, St: st}, user, key, control.ParseTerm(os.Getenv("GITBAY_TERM")), cmdline, sshd.Streams{Stdin: os.Stdin, Stdout: os.Stdout, Stderr: os.Stderr}) |
| 105 | st.Close() | 105 | st.Close() |
| 106 | os.Exit(code) | 106 | os.Exit(code) |
| 107 | return nil | 107 | return nil |
internal/config/config.go +13 −4
| @@ -463,8 +463,7 @@ func (m MailInbound) validate() []error { | |||
| 463 | errs = append(errs, fmt.Errorf("mail.inbound.trusted_authserv_id %q must be a bare host name such as mx.google.com", id)) | 463 | errs = append(errs, fmt.Errorf("mail.inbound.trusted_authserv_id %q must be a bare host name such as mx.google.com", id)) |
| 464 | } | 464 | } |
| 465 | if a := m.ReplyAddress; a != "" { | 465 | if a := m.ReplyAddress; a != "" { |
| 466 | local, domain, ok := strings.Cut(a, "@") | 466 | if !bareAddress(a) { |
| 467 | if !ok || local == "" || domain == "" || strings.ContainsAny(a, "+ <>\"\r\n") || strings.Contains(domain, "@") { | ||
| 468 | errs = append(errs, fmt.Errorf("mail.inbound.reply_address %q must be a bare address such as reply@example.org, with no + in it", a)) | 467 | errs = append(errs, fmt.Errorf("mail.inbound.reply_address %q must be a bare address such as reply@example.org, with no + in it", a)) |
| 469 | } | 468 | } |
| 470 | } | 469 | } |
| @@ -682,8 +681,8 @@ func (c Config) Validate() error { | |||
| 682 | errs = append(errs, fmt.Errorf("registration.pending_expiry %q must be a positive duration such as 168h", c.Registration.PendingExpiry)) | 681 | errs = append(errs, fmt.Errorf("registration.pending_expiry %q must be a positive duration such as 168h", c.Registration.PendingExpiry)) |
| 683 | } | 682 | } |
| 684 | } | 683 | } |
| 685 | if c.Limits.MaxReposPerUser < 0 || c.Limits.MaxBytesPerUser < 0 || c.Limits.MaxSnippetsPerUser < 0 || | 684 | if min(c.Limits.MaxReposPerUser, c.Limits.MaxSnippetsPerUser, c.Limits.MaxOrgsPerUser, c.Limits.MaxReposPerOrg) < 0 || |
| 686 | c.Limits.MaxOrgsPerUser < 0 || c.Limits.MaxReposPerOrg < 0 || c.Limits.MaxBytesPerOrg < 0 { | 685 | min(c.Limits.MaxBytesPerUser, c.Limits.MaxBytesPerOrg) < 0 { |
| 687 | errs = append(errs, errors.New("limits.max_repos_per_user, max_bytes_per_user, max_snippets_per_user, max_orgs_per_user, max_repos_per_org and max_bytes_per_org must not be negative")) | 686 | errs = append(errs, errors.New("limits.max_repos_per_user, max_bytes_per_user, max_snippets_per_user, max_orgs_per_user, max_repos_per_org and max_bytes_per_org must not be negative")) |
| 688 | } | 687 | } |
| 689 | for _, w := range []struct{ name, val string }{ | 688 | for _, w := range []struct{ name, val string }{ |
| @@ -855,3 +854,13 @@ func (h HTTP) TrustedProxyNets() ([]*net.IPNet, error) { | |||
| 855 | } | 854 | } |
| 856 | return nets, nil | 855 | return nets, nil |
| 857 | } | 856 | } |
| 857 | |||
| 858 | // bareAddress reports whether a is local@domain and nothing else: no +, | ||
| 859 | // spaces, angle brackets, quotes or line breaks. | ||
| 860 | func bareAddress(a string) bool { | ||
| 861 | local, domain, ok := strings.Cut(a, "@") | ||
| 862 | if !ok || local == "" || domain == "" { | ||
| 863 | return false | ||
| 864 | } | ||
| 865 | return !strings.ContainsAny(a, "+ <>\"\r\n") && !strings.Contains(domain, "@") | ||
| 866 | } | ||
internal/control/admin.go +184 −169
| @@ -210,225 +210,240 @@ func runAdminUserShow(c *Ctx, args []string) int { | |||
| 210 | return c.fail(protocol.ExitFailure, "%v", err) | 210 | return c.fail(protocol.ExitFailure, "%v", err) |
| 211 | } | 211 | } |
| 212 | 212 | ||
| 213 | type keyOut struct { | 213 | d, err := adminUserShowData(c, u, row) |
| 214 | Fingerprint string `json:"fingerprint"` | 214 | if err != nil { |
| 215 | Algo string `json:"algo"` | 215 | return c.fail(protocol.ExitFailure, "%v", err) |
| 216 | Scope string `json:"scope"` | ||
| 217 | Label string `json:"label"` | ||
| 218 | CreatedAt string `json:"created_at"` | ||
| 219 | LastUsedAt string `json:"last_used_at,omitempty"` | ||
| 220 | } | ||
| 221 | type emailOut struct { | ||
| 222 | Address string `json:"address"` | ||
| 223 | Verified bool `json:"verified"` | ||
| 224 | VerifiedBy string `json:"verified_by,omitempty"` // smtp | admin | ||
| 225 | Primary bool `json:"primary"` | ||
| 226 | } | ||
| 227 | type pgpOut struct { | ||
| 228 | Fingerprint string `json:"fingerprint"` | ||
| 229 | ExpiresAt *time.Time `json:"expires_at,omitempty"` | ||
| 230 | RevokedAt *time.Time `json:"revoked_at,omitempty"` | ||
| 231 | } | ||
| 232 | type orgOut struct { | ||
| 233 | Org string `json:"org"` | ||
| 234 | Role string `json:"role"` | ||
| 235 | } | ||
| 236 | type tokenOut struct { | ||
| 237 | Name string `json:"name"` | ||
| 238 | Scope string `json:"scope"` | ||
| 239 | CreatedAt string `json:"created_at"` | ||
| 240 | ExpiresAt *time.Time `json:"expires_at,omitempty"` | ||
| 241 | LastUsedAt *time.Time `json:"last_used_at,omitempty"` | ||
| 242 | } | 216 | } |
| 243 | type out struct { | 217 | return c.emitView(d, func(w io.Writer) { writeAdminUserShow(c, w, d) }, |
| 244 | adminUserOut | 218 | func() screen { return adminUserScreen(c, d) }) |
| 245 | Keys []keyOut `json:"keys"` | 219 | } |
| 246 | Emails []emailOut `json:"emails"` | 220 | |
| 247 | PGPKeys []pgpOut `json:"pgp_keys"` | 221 | type adminKeyOut struct { |
| 248 | Orgs []orgOut `json:"orgs"` | 222 | Fingerprint string `json:"fingerprint"` |
| 249 | Repos int64 `json:"repos"` | 223 | Algo string `json:"algo"` |
| 250 | RepoLimit int64 `json:"repo_limit"` // 0 unlimited | 224 | Scope string `json:"scope"` |
| 251 | ByteLimit int64 `json:"byte_limit"` // 0 unlimited | 225 | Label string `json:"label"` |
| 252 | APITokens []tokenOut `json:"api_tokens"` | 226 | CreatedAt string `json:"created_at"` |
| 253 | WebSessions int64 `json:"web_sessions"` | 227 | LastUsedAt string `json:"last_used_at,omitempty"` |
| 254 | DeleteAfter string `json:"delete_after,omitempty"` // a scheduled self-deletion | 228 | } |
| 255 | } | 229 | type adminEmailOut struct { |
| 256 | d := out{adminUserOut: adminUserRow(row), | 230 | Address string `json:"address"` |
| 257 | Keys: []keyOut{}, Emails: []emailOut{}, PGPKeys: []pgpOut{}, Orgs: []orgOut{}, APITokens: []tokenOut{}} | 231 | Verified bool `json:"verified"` |
| 232 | VerifiedBy string `json:"verified_by,omitempty"` // smtp | admin | ||
| 233 | Primary bool `json:"primary"` | ||
| 234 | } | ||
| 235 | type adminPGPOut struct { | ||
| 236 | Fingerprint string `json:"fingerprint"` | ||
| 237 | ExpiresAt *time.Time `json:"expires_at,omitempty"` | ||
| 238 | RevokedAt *time.Time `json:"revoked_at,omitempty"` | ||
| 239 | } | ||
| 240 | type adminOrgOut struct { | ||
| 241 | Org string `json:"org"` | ||
| 242 | Role string `json:"role"` | ||
| 243 | } | ||
| 244 | type adminTokenOut struct { | ||
| 245 | Name string `json:"name"` | ||
| 246 | Scope string `json:"scope"` | ||
| 247 | CreatedAt string `json:"created_at"` | ||
| 248 | ExpiresAt *time.Time `json:"expires_at,omitempty"` | ||
| 249 | LastUsedAt *time.Time `json:"last_used_at,omitempty"` | ||
| 250 | } | ||
| 251 | type adminUserShowOut struct { | ||
| 252 | adminUserOut | ||
| 253 | Keys []adminKeyOut `json:"keys"` | ||
| 254 | Emails []adminEmailOut `json:"emails"` | ||
| 255 | PGPKeys []adminPGPOut `json:"pgp_keys"` | ||
| 256 | Orgs []adminOrgOut `json:"orgs"` | ||
| 257 | Repos int64 `json:"repos"` | ||
| 258 | RepoLimit int64 `json:"repo_limit"` // 0 unlimited | ||
| 259 | ByteLimit int64 `json:"byte_limit"` // 0 unlimited | ||
| 260 | APITokens []adminTokenOut `json:"api_tokens"` | ||
| 261 | WebSessions int64 `json:"web_sessions"` | ||
| 262 | DeleteAfter string `json:"delete_after,omitempty"` // a scheduled self-deletion | ||
| 263 | } | ||
| 264 | |||
| 265 | // adminUserShowData is everything `admin user show` reports about a user. | ||
| 266 | func adminUserShowData(c *Ctx, u store.User, row store.AdminUser) (adminUserShowOut, error) { | ||
| 267 | d := adminUserShowOut{adminUserOut: adminUserRow(row), | ||
| 268 | Keys: []adminKeyOut{}, Emails: []adminEmailOut{}, PGPKeys: []adminPGPOut{}, Orgs: []adminOrgOut{}, APITokens: []adminTokenOut{}} | ||
| 258 | 269 | ||
| 259 | keys, err := c.Store.ListSSHKeys(u.ID) | 270 | keys, err := c.Store.ListSSHKeys(u.ID) |
| 260 | if err != nil { | 271 | if err != nil { |
| 261 | return c.fail(protocol.ExitFailure, "%v", err) | 272 | return d, err |
| 262 | } | 273 | } |
| 263 | for _, k := range keys { | 274 | for _, k := range keys { |
| 264 | d.Keys = append(d.Keys, keyOut{k.Fingerprint, k.Algo, k.Scope, k.Label, k.CreatedAt, k.LastUsedAt}) | 275 | d.Keys = append(d.Keys, adminKeyOut{k.Fingerprint, k.Algo, k.Scope, k.Label, k.CreatedAt, k.LastUsedAt}) |
| 265 | } | 276 | } |
| 266 | emails, err := c.Store.ListEmails(u.ID) | 277 | emails, err := c.Store.ListEmails(u.ID) |
| 267 | if err != nil { | 278 | if err != nil { |
| 268 | return c.fail(protocol.ExitFailure, "%v", err) | 279 | return d, err |
| 269 | } | 280 | } |
| 270 | for _, e := range emails { | 281 | for _, e := range emails { |
| 271 | d.Emails = append(d.Emails, emailOut{e.Address, e.Verified, e.VerifiedBy, e.Primary}) | 282 | d.Emails = append(d.Emails, adminEmailOut{e.Address, e.Verified, e.VerifiedBy, e.Primary}) |
| 272 | } | 283 | } |
| 273 | pgp, err := c.Store.ListPGPKeys(u.ID) | 284 | pgp, err := c.Store.ListPGPKeys(u.ID) |
| 274 | if err != nil { | 285 | if err != nil { |
| 275 | return c.fail(protocol.ExitFailure, "%v", err) | 286 | return d, err |
| 276 | } | 287 | } |
| 277 | for _, k := range pgp { | 288 | for _, k := range pgp { |
| 278 | d.PGPKeys = append(d.PGPKeys, pgpOut{k.Fingerprint, k.ExpiresAt, k.RevokedAt}) | 289 | d.PGPKeys = append(d.PGPKeys, adminPGPOut{k.Fingerprint, k.ExpiresAt, k.RevokedAt}) |
| 279 | } | 290 | } |
| 280 | orgs, err := c.Store.ListOrgsForUser(u.ID) | 291 | orgs, err := c.Store.ListOrgsForUser(u.ID) |
| 281 | if err != nil { | 292 | if err != nil { |
| 282 | return c.fail(protocol.ExitFailure, "%v", err) | 293 | return d, err |
| 283 | } | 294 | } |
| 284 | for _, m := range orgs { | 295 | for _, m := range orgs { |
| 285 | d.Orgs = append(d.Orgs, orgOut{m.Username, m.Role}) | 296 | d.Orgs = append(d.Orgs, adminOrgOut{m.Username, m.Role}) |
| 286 | } | 297 | } |
| 287 | if d.Repos, err = c.Store.OwnedRepoCount("user", u.ID); err != nil { | 298 | if d.Repos, err = c.Store.OwnedRepoCount("user", u.ID); err != nil { |
| 288 | return c.fail(protocol.ExitFailure, "%v", err) | 299 | return d, err |
| 289 | } | 300 | } |
| 290 | d.RepoLimit = RepoLimit(c.Store, limitsOf(c), "user", u.ID) | 301 | d.RepoLimit = RepoLimit(c.Store, limitsOf(c), "user", u.ID) |
| 291 | d.ByteLimit = ByteLimit(c.Store, limitsOf(c), "user", u.ID) | 302 | d.ByteLimit = ByteLimit(c.Store, limitsOf(c), "user", u.ID) |
| 292 | tokens, err := c.Store.ListAPITokens(u.ID) | 303 | tokens, err := c.Store.ListAPITokens(u.ID) |
| 293 | if err != nil { | 304 | if err != nil { |
| 294 | return c.fail(protocol.ExitFailure, "%v", err) | 305 | return d, err |
| 295 | } | 306 | } |
| 296 | for _, t := range tokens { | 307 | for _, t := range tokens { |
| 297 | d.APITokens = append(d.APITokens, tokenOut{t.Name, t.Scope, t.CreatedAt, t.ExpiresAt, t.LastUsedAt}) | 308 | d.APITokens = append(d.APITokens, adminTokenOut{t.Name, t.Scope, t.CreatedAt, t.ExpiresAt, t.LastUsedAt}) |
| 298 | } | 309 | } |
| 299 | if d.WebSessions, err = c.Store.WebSessionCount(u.ID); err != nil { | 310 | if d.WebSessions, err = c.Store.WebSessionCount(u.ID); err != nil { |
| 300 | return c.fail(protocol.ExitFailure, "%v", err) | 311 | return d, err |
| 301 | } | 312 | } |
| 302 | d.DeleteAfter = u.DeleteAfter | 313 | d.DeleteAfter = u.DeleteAfter |
| 314 | return d, nil | ||
| 315 | } | ||
| 303 | 316 | ||
| 304 | return c.emitView(d, func(w io.Writer) { | 317 | // writeAdminUserShow is `admin user show` as text. |
| 305 | admin := "" | 318 | func writeAdminUserShow(c *Ctx, w io.Writer, d adminUserShowOut) { |
| 306 | if d.Admin { | 319 | admin := "" |
| 307 | admin = "yes" | 320 | if d.Admin { |
| 308 | } | 321 | admin = "yes" |
| 309 | v := c.view(w) | 322 | } |
| 310 | v.title(d.Username, "", d.State) | 323 | v := c.view(w) |
| 311 | v.fields( | 324 | v.title(d.Username, "", d.State) |
| 312 | "admin", admin, | 325 | v.fields( |
| 313 | "created", c.when(d.CreatedAt), | 326 | "admin", admin, |
| 314 | "last seen", c.when(d.LastSeen), | 327 | "created", c.when(d.CreatedAt), |
| 315 | "repos", fmt.Sprintf("%d", d.Repos), | 328 | "last seen", c.when(d.LastSeen), |
| 316 | "web sessions", fmt.Sprintf("%d", d.WebSessions), | 329 | "repos", fmt.Sprintf("%d", d.Repos), |
| 317 | "deletes at", c.when(d.DeleteAfter), | 330 | "web sessions", fmt.Sprintf("%d", d.WebSessions), |
| 318 | ) | 331 | "deletes at", c.when(d.DeleteAfter), |
| 319 | if len(d.Keys) > 0 { | 332 | ) |
| 320 | v.section("keys") | 333 | if len(d.Keys) > 0 { |
| 321 | tk := c.table(w, "FINGERPRINT", "ALGO", "SCOPE", "LAST USED") | 334 | v.section("keys") |
| 322 | for _, k := range d.Keys { | 335 | tk := c.table(w, "FINGERPRINT", "ALGO", "SCOPE", "LAST USED") |
| 323 | tk.row(cFlex(k.Fingerprint), cText(k.Algo), cState(k.Scope), cAge(k.LastUsedAt)) | ||
| 324 | } | ||
| 325 | tk.flush() | ||
| 326 | } | ||
| 327 | if len(d.Emails) > 0 { | ||
| 328 | v.section("emails") | ||
| 329 | te := c.table(w, "ADDRESS", "STATE") | ||
| 330 | for _, e := range d.Emails { | ||
| 331 | state := "unverified" | ||
| 332 | if e.Verified { | ||
| 333 | state = "verified by " + e.VerifiedBy | ||
| 334 | } | ||
| 335 | cells := []cell{cRef(e.Address), cState(state)} | ||
| 336 | if e.Primary { | ||
| 337 | cells = c.note(cells, 1, "primary", "primary") | ||
| 338 | } | ||
| 339 | te.row(cells...) | ||
| 340 | } | ||
| 341 | te.flush() | ||
| 342 | } | ||
| 343 | if len(d.PGPKeys) > 0 { | ||
| 344 | v.section("pgp keys") | ||
| 345 | tp := c.table(w, "FINGERPRINT") | ||
| 346 | for _, k := range d.PGPKeys { | ||
| 347 | tp.row(cFlex(k.Fingerprint)) | ||
| 348 | } | ||
| 349 | tp.flush() | ||
| 350 | } | ||
| 351 | if len(d.Orgs) > 0 { | ||
| 352 | v.section("orgs") | ||
| 353 | to := c.table(w, "ORG", "ROLE") | ||
| 354 | for _, o := range d.Orgs { | ||
| 355 | to.row(cRef(o.Org), cState(o.Role)) | ||
| 356 | } | ||
| 357 | to.flush() | ||
| 358 | } | ||
| 359 | if len(d.APITokens) > 0 { | ||
| 360 | v.section("api tokens") | ||
| 361 | tt := c.table(w, "NAME", "SCOPE", "LAST USED") | ||
| 362 | for _, t := range d.APITokens { | ||
| 363 | used := "" | ||
| 364 | if t.LastUsedAt != nil { | ||
| 365 | used = t.LastUsedAt.UTC().Format(time.RFC3339Nano) | ||
| 366 | } | ||
| 367 | tt.row(cRef(t.Name), cState(t.Scope), cAge(used)) | ||
| 368 | } | ||
| 369 | tt.flush() | ||
| 370 | } | ||
| 371 | }, func() screen { | ||
| 372 | s := screen{} | ||
| 373 | user := []cell{cRef(d.Username), cState(d.State)} | ||
| 374 | if d.Admin { | ||
| 375 | user = append(user, cMeta("admin")) | ||
| 376 | } | ||
| 377 | seen := "never seen" | ||
| 378 | if d.LastSeen != "" { | ||
| 379 | seen = "seen " + relAge(d.LastSeen, termNow()) | ||
| 380 | } | ||
| 381 | s.fields = []field{ | ||
| 382 | {"User", user}, | ||
| 383 | {"Seen", []cell{cText(seen), cMeta("created " + relAge(d.CreatedAt, termNow()))}}, | ||
| 384 | {"Repos", []cell{cText(strconv.FormatInt(d.Repos, 10))}}, | ||
| 385 | {"Sessions", []cell{cText(strconv.FormatInt(d.WebSessions, 10))}}, | ||
| 386 | } | ||
| 387 | keys := section{title: "Keys", n: len(d.Keys)} | ||
| 388 | for _, k := range d.Keys { | 336 | for _, k := range d.Keys { |
| 389 | keys.rows = append(keys.rows, rowOf(cFlexRef(k.Fingerprint), cState(k.Scope), cMeta(k.Algo, "used "+relAge(k.LastUsedAt, termNow())))) | 337 | tk.row(cFlex(k.Fingerprint), cText(k.Algo), cState(k.Scope), cAge(k.LastUsedAt)) |
| 390 | } | 338 | } |
| 391 | emails := section{title: "Emails", n: len(d.Emails)} | 339 | tk.flush() |
| 340 | } | ||
| 341 | if len(d.Emails) > 0 { | ||
| 342 | v.section("emails") | ||
| 343 | te := c.table(w, "ADDRESS", "STATE") | ||
| 392 | for _, e := range d.Emails { | 344 | for _, e := range d.Emails { |
| 393 | state, primary := "unverified", "" | 345 | state := "unverified" |
| 394 | if e.Verified { | 346 | if e.Verified { |
| 395 | state = "verified" | 347 | state = "verified by " + e.VerifiedBy |
| 396 | } | 348 | } |
| 349 | cells := []cell{cRef(e.Address), cState(state)} | ||
| 397 | if e.Primary { | 350 | if e.Primary { |
| 398 | primary = "primary" | 351 | cells = c.note(cells, 1, "primary", "primary") |
| 399 | } | 352 | } |
| 400 | emails.rows = append(emails.rows, rowOf(cRef(e.Address), cState(state), cMeta(primary, e.VerifiedBy))) | 353 | te.row(cells...) |
| 401 | } | 354 | } |
| 402 | pgp := section{title: "PGP keys", n: len(d.PGPKeys)} | 355 | te.flush() |
| 356 | } | ||
| 357 | if len(d.PGPKeys) > 0 { | ||
| 358 | v.section("pgp keys") | ||
| 359 | tp := c.table(w, "FINGERPRINT") | ||
| 403 | for _, k := range d.PGPKeys { | 360 | for _, k := range d.PGPKeys { |
| 404 | pgp.rows = append(pgp.rows, rowOf(cFlexRef(k.Fingerprint))) | 361 | tp.row(cFlex(k.Fingerprint)) |
| 405 | } | 362 | } |
| 406 | orgs := section{title: "Orgs", n: len(d.Orgs)} | 363 | tp.flush() |
| 364 | } | ||
| 365 | if len(d.Orgs) > 0 { | ||
| 366 | v.section("orgs") | ||
| 367 | to := c.table(w, "ORG", "ROLE") | ||
| 407 | for _, o := range d.Orgs { | 368 | for _, o := range d.Orgs { |
| 408 | orgs.rows = append(orgs.rows, rowOf(cLink(o.Org, c.siteURL(o.Org)), cState(o.Role))) | 369 | to.row(cRef(o.Org), cState(o.Role)) |
| 409 | } | 370 | } |
| 410 | tokens := section{title: "API tokens", n: len(d.APITokens)} | 371 | to.flush() |
| 411 | for _, tk := range d.APITokens { | 372 | } |
| 373 | if len(d.APITokens) > 0 { | ||
| 374 | v.section("api tokens") | ||
| 375 | tt := c.table(w, "NAME", "SCOPE", "LAST USED") | ||
| 376 | for _, t := range d.APITokens { | ||
| 412 | used := "" | 377 | used := "" |
| 413 | if tk.LastUsedAt != nil { | 378 | if t.LastUsedAt != nil { |
| 414 | used = "used " + relAge(tk.LastUsedAt.UTC().Format(time.RFC3339Nano), termNow()) | 379 | used = t.LastUsedAt.UTC().Format(time.RFC3339Nano) |
| 415 | } | 380 | } |
| 416 | tokens.rows = append(tokens.rows, rowOf(cRef(tk.Name), cState(tk.Scope), cMeta(used))) | 381 | tt.row(cRef(t.Name), cState(t.Scope), cAge(used)) |
| 417 | } | ||
| 418 | s.sections = []section{keys, emails, pgp, orgs, tokens} | ||
| 419 | role, state := "promote", "disable" | ||
| 420 | if d.Admin { | ||
| 421 | role = "demote" | ||
| 422 | } | ||
| 423 | if d.State == "disabled" { | ||
| 424 | state = "enable" | ||
| 425 | } | 382 | } |
| 426 | s.actions = []action{ | 383 | tt.flush() |
| 427 | {"Manage", []string{"admin", "user", role, d.Username}}, | 384 | } |
| 428 | {"Manage", []string{"admin", "user", state, d.Username}}, | 385 | } |
| 429 | } | 386 | |
| 430 | return s | 387 | func adminUserScreen(c *Ctx, d adminUserShowOut) screen { |
| 431 | }) | 388 | s := screen{} |
| 389 | user := []cell{cRef(d.Username), cState(d.State)} | ||
| 390 | if d.Admin { | ||
| 391 | user = append(user, cMeta("admin")) | ||
| 392 | } | ||
| 393 | seen := "never seen" | ||
| 394 | if d.LastSeen != "" { | ||
| 395 | seen = "seen " + relAge(d.LastSeen, termNow()) | ||
| 396 | } | ||
| 397 | s.fields = []field{ | ||
| 398 | {"User", user}, | ||
| 399 | {"Seen", []cell{cText(seen), cMeta("created " + relAge(d.CreatedAt, termNow()))}}, | ||
| 400 | {"Repos", []cell{cText(strconv.FormatInt(d.Repos, 10))}}, | ||
| 401 | {"Sessions", []cell{cText(strconv.FormatInt(d.WebSessions, 10))}}, | ||
| 402 | } | ||
| 403 | keys := section{title: "Keys", n: len(d.Keys)} | ||
| 404 | for _, k := range d.Keys { | ||
| 405 | keys.rows = append(keys.rows, rowOf(cFlexRef(k.Fingerprint), cState(k.Scope), cMeta(k.Algo, "used "+relAge(k.LastUsedAt, termNow())))) | ||
| 406 | } | ||
| 407 | emails := section{title: "Emails", n: len(d.Emails)} | ||
| 408 | for _, e := range d.Emails { | ||
| 409 | state, primary := "unverified", "" | ||
| 410 | if e.Verified { | ||
| 411 | state = "verified" | ||
| 412 | } | ||
| 413 | if e.Primary { | ||
| 414 | primary = "primary" | ||
| 415 | } | ||
| 416 | emails.rows = append(emails.rows, rowOf(cRef(e.Address), cState(state), cMeta(primary, e.VerifiedBy))) | ||
| 417 | } | ||
| 418 | pgp := section{title: "PGP keys", n: len(d.PGPKeys)} | ||
| 419 | for _, k := range d.PGPKeys { | ||
| 420 | pgp.rows = append(pgp.rows, rowOf(cFlexRef(k.Fingerprint))) | ||
| 421 | } | ||
| 422 | orgs := section{title: "Orgs", n: len(d.Orgs)} | ||
| 423 | for _, o := range d.Orgs { | ||
| 424 | orgs.rows = append(orgs.rows, rowOf(cLink(o.Org, c.siteURL(o.Org)), cState(o.Role))) | ||
| 425 | } | ||
| 426 | tokens := section{title: "API tokens", n: len(d.APITokens)} | ||
| 427 | for _, tk := range d.APITokens { | ||
| 428 | used := "" | ||
| 429 | if tk.LastUsedAt != nil { | ||
| 430 | used = "used " + relAge(tk.LastUsedAt.UTC().Format(time.RFC3339Nano), termNow()) | ||
| 431 | } | ||
| 432 | tokens.rows = append(tokens.rows, rowOf(cRef(tk.Name), cState(tk.Scope), cMeta(used))) | ||
| 433 | } | ||
| 434 | s.sections = []section{keys, emails, pgp, orgs, tokens} | ||
| 435 | role, state := "promote", "disable" | ||
| 436 | if d.Admin { | ||
| 437 | role = "demote" | ||
| 438 | } | ||
| 439 | if d.State == "disabled" { | ||
| 440 | state = "enable" | ||
| 441 | } | ||
| 442 | s.actions = []action{ | ||
| 443 | {"Manage", []string{"admin", "user", role, d.Username}}, | ||
| 444 | {"Manage", []string{"admin", "user", state, d.Username}}, | ||
| 445 | } | ||
| 446 | return s | ||
| 432 | } | 447 | } |
| 433 | 448 | ||
| 434 | func runAdminUserPromote(c *Ctx, args []string) int { return setAdmin(c, args, true) } | 449 | func runAdminUserPromote(c *Ctx, args []string) int { return setAdmin(c, args, true) } |
internal/control/dashboard.go +176 −160
| @@ -101,215 +101,231 @@ func runDashboard(c *Ctx, args []string) int { | |||
| 101 | if len(args) != 0 { | 101 | if len(args) != 0 { |
| 102 | return c.usage() | 102 | return c.usage() |
| 103 | } | 103 | } |
| 104 | d, events, err := dashboardData(c) | ||
| 105 | if err != nil { | ||
| 106 | return c.fail(protocol.ExitFailure, "%v", err) | ||
| 107 | } | ||
| 108 | lines := FeedLines(events) | ||
| 109 | return c.emitView(d, func(w io.Writer) { writeDashboard(c, w, d, lines) }, | ||
| 110 | func() screen { return dashboardScreen(c, d, lines) }) | ||
| 111 | } | ||
| 112 | |||
| 113 | // dashboardData is the signed-in user's dashboard, with the events its | ||
| 114 | // activity was made from. | ||
| 115 | func dashboardData(c *Ctx) (DashboardOut, []store.FeedEvent, error) { | ||
| 104 | d := DashboardOut{ | 116 | d := DashboardOut{ |
| 105 | Reviews: []DashboardItem{}, Assigned: []DashboardItem{}, MRs: []DashboardItem{}, | 117 | Reviews: []DashboardItem{}, Assigned: []DashboardItem{}, MRs: []DashboardItem{}, |
| 106 | Issues: []DashboardItem{}, Pinned: []PinnedOut{}, Activity: []FeedOut{}, Builds: []DashboardBuild{}, | 118 | Issues: []DashboardItem{}, Pinned: []PinnedOut{}, Activity: []FeedOut{}, Builds: []DashboardBuild{}, |
| 107 | } | 119 | } |
| 108 | 120 | var err error | |
| 109 | pinned, err := c.Store.PinnedRepos(c.User.ID) | 121 | if d.Pinned, err = pinnedOutputs(c); err != nil { |
| 110 | if err != nil { | 122 | return d, nil, err |
| 111 | return c.fail(protocol.ExitFailure, "%v", err) | 123 | } |
| 112 | } | 124 | lists := []struct { |
| 113 | for _, r := range pinned { | 125 | into *[]DashboardItem |
| 114 | grant, err := c.Store.AccessRole(r.ID, c.User.ID) | 126 | fetch func(int64) ([]store.DashboardItem, error) |
| 127 | }{ | ||
| 128 | {&d.MRs, c.Store.DashboardMRs}, | ||
| 129 | {&d.Reviews, c.Store.ReviewQueue}, | ||
| 130 | {&d.Assigned, c.Store.AssignedIssues}, | ||
| 131 | {&d.Issues, c.Store.DashboardIssues}, | ||
| 132 | } | ||
| 133 | for _, l := range lists { | ||
| 134 | items, err := l.fetch(c.User.ID) | ||
| 115 | if err != nil { | 135 | if err != nil { |
| 116 | return c.fail(protocol.ExitFailure, "%v", err) | 136 | return d, nil, err |
| 117 | } | 137 | } |
| 118 | if !policy.CanRead(c.User, r, grant) { | 138 | for _, m := range items { |
| 119 | continue | 139 | *l.into = append(*l.into, DashboardItem{m.RepoPath, m.Number, m.Title, m.Author, m.State, m.UpdatedAt, m.Queued}) |
| 120 | } | 140 | } |
| 121 | desc := gitutil.ReadDescription(RepoDir(c.Cfg.Server.Root, r.OwnerName, r.Name)) | ||
| 122 | d.Pinned = append(d.Pinned, PinnedOut{r.Path(), r.Visibility, desc, r.Settings.Archived}) | ||
| 123 | } | ||
| 124 | |||
| 125 | mrs, err := c.Store.DashboardMRs(c.User.ID) | ||
| 126 | if err != nil { | ||
| 127 | return c.fail(protocol.ExitFailure, "%v", err) | ||
| 128 | } | ||
| 129 | for _, m := range mrs { | ||
| 130 | d.MRs = append(d.MRs, DashboardItem{m.RepoPath, m.Number, m.Title, m.Author, m.State, m.UpdatedAt, m.Queued}) | ||
| 131 | } | ||
| 132 | |||
| 133 | reviews, err := c.Store.ReviewQueue(c.User.ID) | ||
| 134 | if err != nil { | ||
| 135 | return c.fail(protocol.ExitFailure, "%v", err) | ||
| 136 | } | ||
| 137 | for _, m := range reviews { | ||
| 138 | d.Reviews = append(d.Reviews, DashboardItem{m.RepoPath, m.Number, m.Title, m.Author, m.State, m.UpdatedAt, m.Queued}) | ||
| 139 | } | ||
| 140 | |||
| 141 | assigned, err := c.Store.AssignedIssues(c.User.ID) | ||
| 142 | if err != nil { | ||
| 143 | return c.fail(protocol.ExitFailure, "%v", err) | ||
| 144 | } | ||
| 145 | for _, i := range assigned { | ||
| 146 | d.Assigned = append(d.Assigned, DashboardItem{i.RepoPath, i.Number, i.Title, i.Author, i.State, i.UpdatedAt, i.Queued}) | ||
| 147 | } | ||
| 148 | |||
| 149 | issues, err := c.Store.DashboardIssues(c.User.ID) | ||
| 150 | if err != nil { | ||
| 151 | return c.fail(protocol.ExitFailure, "%v", err) | ||
| 152 | } | ||
| 153 | for _, i := range issues { | ||
| 154 | d.Issues = append(d.Issues, DashboardItem{i.RepoPath, i.Number, i.Title, i.Author, i.State, i.UpdatedAt, i.Queued}) | ||
| 155 | } | 141 | } |
| 156 | 142 | ||
| 157 | events, err := c.Store.RecentEvents(c.User.ID, 20, 0) | 143 | events, err := c.Store.RecentEvents(c.User.ID, 20, 0) |
| 158 | if err != nil { | 144 | if err != nil { |
| 159 | return c.fail(protocol.ExitFailure, "%v", err) | 145 | return d, nil, err |
| 160 | } | 146 | } |
| 161 | d.Activity = feedOutputs(events) | 147 | d.Activity = feedOutputs(events) |
| 162 | 148 | ||
| 163 | builds, err := c.Store.RecentBuilds(c.User.ID, 20) | 149 | builds, err := c.Store.RecentBuilds(c.User.ID, 20) |
| 164 | if err != nil { | 150 | if err != nil { |
| 165 | return c.fail(protocol.ExitFailure, "%v", err) | 151 | return d, nil, err |
| 166 | } | 152 | } |
| 167 | for _, b := range builds { | 153 | for _, b := range builds { |
| 168 | d.Builds = append(d.Builds, DashboardBuild{b.RepoPath, b.Number, b.Job, b.Status, b.SHA, b.Ref, b.CreatedAt, b.FinishedAt}) | 154 | d.Builds = append(d.Builds, DashboardBuild{b.RepoPath, b.Number, b.Job, b.Status, b.SHA, b.Ref, b.CreatedAt, b.FinishedAt}) |
| 169 | } | 155 | } |
| 170 | if d.Queries, err = PinnedQueries(c.Store, c.User); err != nil { | 156 | if d.Queries, err = PinnedQueries(c.Store, c.User); err != nil { |
| 171 | return c.fail(protocol.ExitFailure, "%v", err) | 157 | return d, nil, err |
| 172 | } | 158 | } |
| 173 | d.Unread = c.Store.UnreadNotices(c.User.ID) | 159 | d.Unread = c.Store.UnreadNotices(c.User.ID) |
| 174 | if c.User.IsAdmin { | 160 | if c.User.IsAdmin { |
| 175 | d.Server = &ServerOut{Commit: buildinfo.String()} | 161 | d.Server = &ServerOut{Commit: buildinfo.String()} |
| 176 | q, err := c.Store.QueueStatus() | 162 | q, err := c.Store.QueueStatus() |
| 177 | if err != nil { | 163 | if err != nil { |
| 178 | return c.fail(protocol.ExitFailure, "%v", err) | 164 | return d, nil, err |
| 179 | } | 165 | } |
| 180 | d.Queues = &q | 166 | d.Queues = &q |
| 181 | } | 167 | } |
| 168 | return d, events, nil | ||
| 169 | } | ||
| 182 | 170 | ||
| 183 | lines := FeedLines(events) | 171 | // pinnedOutputs is the user's pinned repositories they can still read. |
| 184 | return c.emitView(d, func(w io.Writer) { | 172 | func pinnedOutputs(c *Ctx) ([]PinnedOut, error) { |
| 185 | heading := func(title string) { fmt.Fprintln(w, title) } | 173 | pinned, err := c.Store.PinnedRepos(c.User.ID) |
| 186 | section := func(title string, rows [][]cell) { | 174 | if err != nil { |
| 187 | heading(title) | 175 | return nil, err |
| 188 | if len(rows) == 0 { | 176 | } |
| 189 | fmt.Fprintln(w, " none") | 177 | out := []PinnedOut{} |
| 190 | return | 178 | for _, r := range pinned { |
| 191 | } | 179 | grant, err := c.Store.AccessRole(r.ID, c.User.ID) |
| 192 | for _, r := range rows { | 180 | if err != nil { |
| 193 | parts := make([]string, len(r)) | 181 | return nil, err |
| 194 | for i, cl := range r { | ||
| 195 | parts[i] = cl.s | ||
| 196 | if cl.kind == kindAge { | ||
| 197 | parts[i] = stamp(cl.s) | ||
| 198 | } | ||
| 199 | } | ||
| 200 | fmt.Fprintf(w, " %s\n", strings.Join(parts, "\t")) | ||
| 201 | } | ||
| 202 | } | 182 | } |
| 203 | itemRows := func(items []DashboardItem, marker string) [][]cell { | 183 | if !policy.CanRead(c.User, r, grant) { |
| 204 | rows := make([][]cell, len(items)) | 184 | continue |
| 205 | for i, item := range items { | ||
| 206 | page := "issues" | ||
| 207 | if marker == "!" { | ||
| 208 | page = "mrs" | ||
| 209 | } | ||
| 210 | ref := cLink(fmt.Sprintf("%s%s%d", item.Repo, marker, item.Number), c.siteURL(item.Repo, page, strconv.FormatInt(item.Number, 10))) | ||
| 211 | rows[i] = []cell{ref, cFlex(item.Title), cText(item.Author)} | ||
| 212 | } | ||
| 213 | return rows | ||
| 214 | } | 185 | } |
| 186 | desc := gitutil.ReadDescription(RepoDir(c.Cfg.Server.Root, r.OwnerName, r.Name)) | ||
| 187 | out = append(out, PinnedOut{r.Path(), r.Visibility, desc, r.Settings.Archived}) | ||
| 188 | } | ||
| 189 | return out, nil | ||
| 190 | } | ||
| 215 | 191 | ||
| 216 | if d.Unread > 0 { | 192 | // writeDashboard is `dashboard` as text: one section per list, then the |
| 217 | fmt.Fprintf(w, "unread notifications: %d\n", d.Unread) | 193 | // server's build and queues for an admin. |
| 218 | } | 194 | func writeDashboard(c *Ctx, w io.Writer, d DashboardOut, lines []FeedLine) { |
| 219 | section("waiting on your review:", itemRows(d.Reviews, "!")) | 195 | section := func(title string, rows [][]cell) { writeDashboardSection(w, title, rows) } |
| 220 | section("assigned to you:", itemRows(d.Assigned, "#")) | 196 | itemRows := func(items []DashboardItem, marker string) [][]cell { |
| 221 | section("open merge requests:", itemRows(d.MRs, "!")) | 197 | rows := make([][]cell, len(items)) |
| 222 | section("open issues:", itemRows(d.Issues, "#")) | 198 | for i, item := range items { |
| 223 | for _, q := range d.Queries { | 199 | page := "issues" |
| 224 | rows := make([][]cell, 0, len(q.Items)) | 200 | if marker == "!" { |
| 225 | for _, it := range q.Items { | 201 | page = "mrs" |
| 226 | rows = append(rows, []cell{cRef(it.Ref()), cFlex(it.Title), cText(it.Author)}) | ||
| 227 | } | ||
| 228 | title := fmt.Sprintf("query %s (%d):", q.Name, q.Count) | ||
| 229 | if q.Error != "" { | ||
| 230 | title = fmt.Sprintf("query %s: %s", q.Name, q.Error) | ||
| 231 | } | 202 | } |
| 232 | section(title, rows) | 203 | ref := cLink(fmt.Sprintf("%s%s%d", item.Repo, marker, item.Number), c.siteURL(item.Repo, page, strconv.FormatInt(item.Number, 10))) |
| 204 | rows[i] = []cell{ref, cFlex(item.Title), cText(item.Author)} | ||
| 233 | } | 205 | } |
| 206 | return rows | ||
| 207 | } | ||
| 234 | 208 | ||
| 235 | pinnedRows := make([][]cell, len(d.Pinned)) | 209 | if d.Unread > 0 { |
| 236 | for i, p := range d.Pinned { | 210 | fmt.Fprintf(w, "unread notifications: %d\n", d.Unread) |
| 237 | cells := []cell{cLink(p.Path, c.siteURL(p.Path)), cState(p.Visibility), cFlex(p.Description)} | 211 | } |
| 238 | if p.Archived { | 212 | section("waiting on your review:", itemRows(d.Reviews, "!")) |
| 239 | cells = c.note(cells, 1, "[archived]", "archived") | 213 | section("assigned to you:", itemRows(d.Assigned, "#")) |
| 240 | } | 214 | section("open merge requests:", itemRows(d.MRs, "!")) |
| 241 | pinnedRows[i] = cells | 215 | section("open issues:", itemRows(d.Issues, "#")) |
| 216 | for _, q := range d.Queries { | ||
| 217 | rows := make([][]cell, 0, len(q.Items)) | ||
| 218 | for _, it := range q.Items { | ||
| 219 | rows = append(rows, []cell{cRef(it.Ref()), cFlex(it.Title), cText(it.Author)}) | ||
| 242 | } | 220 | } |
| 243 | section("pinned:", pinnedRows) | 221 | title := fmt.Sprintf("query %s (%d):", q.Name, q.Count) |
| 244 | 222 | if q.Error != "" { | |
| 245 | activityRows := make([][]cell, len(lines)) | 223 | title = fmt.Sprintf("query %s: %s", q.Name, q.Error) |
| 246 | for i, l := range lines { | ||
| 247 | activityRows[i] = []cell{cAge(l.When), cFlex(l.Sentence())} | ||
| 248 | } | 224 | } |
| 249 | section("recent activity:", activityRows) | 225 | section(title, rows) |
| 226 | } | ||
| 250 | 227 | ||
| 251 | buildRows := make([][]cell, len(d.Builds)) | 228 | pinnedRows := make([][]cell, len(d.Pinned)) |
| 252 | for i, b := range d.Builds { | 229 | for i, p := range d.Pinned { |
| 253 | buildRows[i] = []cell{cLink(b.Repo, c.siteURL(b.Repo, "builds", strconv.FormatInt(b.Number, 10))), cNum(b.Number), cText(b.Job), cState(b.Status), cRef(fmt.Sprintf("%.10s", b.SHA)), cText(b.Ref)} | 230 | cells := []cell{cLink(p.Path, c.siteURL(p.Path)), cState(p.Visibility), cFlex(p.Description)} |
| 231 | if p.Archived { | ||
| 232 | cells = c.note(cells, 1, "[archived]", "archived") | ||
| 254 | } | 233 | } |
| 255 | section("builds:", buildRows) | 234 | pinnedRows[i] = cells |
| 235 | } | ||
| 236 | section("pinned:", pinnedRows) | ||
| 256 | 237 | ||
| 257 | if d.Server != nil { | 238 | activityRows := make([][]cell, len(lines)) |
| 258 | heading("server:") | 239 | for i, l := range lines { |
| 259 | fmt.Fprintf(w, " build %s\n", d.Server.Commit) | 240 | activityRows[i] = []cell{cAge(l.When), cFlex(l.Sentence())} |
| 260 | } | 241 | } |
| 261 | if q := d.Queues; q != nil { | 242 | section("recent activity:", activityRows) |
| 262 | heading("queues:") | ||
| 263 | 243 | ||
| 264 | fmt.Fprintf(w, " webhooks\tpending %d\tretrying %d\tfailed %d\n", q.Webhooks.Pending, q.Webhooks.Retrying, q.Webhooks.Failed) | 244 | buildRows := make([][]cell, len(d.Builds)) |
| 265 | twh := c.table(w, "REPO", "URL", "ATTEMPTS", "ERROR") | 245 | for i, b := range d.Builds { |
| 266 | for _, it := range q.Webhooks.Items { | 246 | buildRows[i] = []cell{cLink(b.Repo, c.siteURL(b.Repo, "builds", strconv.FormatInt(b.Number, 10))), cNum(b.Number), cText(b.Job), cState(b.Status), cRef(fmt.Sprintf("%.10s", b.SHA)), cText(b.Ref)} |
| 267 | twh.row(cRef(" "+it.Repo), cText(it.URL), cText(fmt.Sprintf("attempts %d", it.Attempts)), cText(it.LastError)) | 247 | } |
| 268 | } | 248 | section("builds:", buildRows) |
| 269 | twh.flush() | ||
| 270 | 249 | ||
| 271 | fmt.Fprintf(w, " mail\tpending %d\tretrying %d\tfailed %d\n", q.Mail.Pending, q.Mail.Retrying, q.Mail.Failed) | 250 | if d.Server != nil { |
| 272 | tma := c.table(w, "RECIPIENT", "SUBJECT", "ATTEMPTS", "ERROR") | 251 | fmt.Fprintln(w, "server:") |
| 273 | for _, it := range q.Mail.Items { | 252 | fmt.Fprintf(w, " build %s\n", d.Server.Commit) |
| 274 | tma.row(cRef(" "+it.Recipient), cText(it.Subject), cText(fmt.Sprintf("attempts %d", it.Attempts)), cText(it.LastError)) | 253 | } |
| 275 | } | 254 | if d.Queues != nil { |
| 276 | tma.flush() | 255 | writeQueues(c, w, *d.Queues) |
| 256 | } | ||
| 257 | } | ||
| 277 | 258 | ||
| 278 | // The device id, not the token: a token is never echoed. | 259 | // writeDashboardSection is a titled list of tab-separated rows, or "none". |
| 279 | fmt.Fprintf(w, " push\tpending %d\tretrying %d\tfailed %d\n", q.Push.Pending, q.Push.Retrying, q.Push.Failed) | 260 | func writeDashboardSection(w io.Writer, title string, rows [][]cell) { |
| 280 | tpu := c.table(w, "DEVICE", "TITLE", "ATTEMPTS", "ERROR") | 261 | fmt.Fprintln(w, title) |
| 281 | for _, it := range q.Push.Items { | 262 | if len(rows) == 0 { |
| 282 | tpu.row(cRef(fmt.Sprintf(" device %d", it.DeviceID)), cText(it.Title), cText(fmt.Sprintf("attempts %d", it.Attempts)), cText(it.LastError)) | 263 | fmt.Fprintln(w, " none") |
| 264 | return | ||
| 265 | } | ||
| 266 | for _, r := range rows { | ||
| 267 | parts := make([]string, len(r)) | ||
| 268 | for i, cl := range r { | ||
| 269 | parts[i] = cl.s | ||
| 270 | if cl.kind == kindAge { | ||
| 271 | parts[i] = stamp(cl.s) | ||
| 283 | } | 272 | } |
| 284 | tpu.flush() | 273 | } |
| 274 | fmt.Fprintf(w, " %s\n", strings.Join(parts, "\t")) | ||
| 275 | } | ||
| 276 | } | ||
| 285 | 277 | ||
| 286 | fmt.Fprintf(w, " mirrors\tdirty %d\terrors %d\n", q.Mirrors.Dirty, q.Mirrors.Errors) | 278 | // writeQueues is each background queue's counts and stuck items. |
| 287 | tmi := c.table(w, "REPO", "DIRECTION", "URL", "ERROR") | 279 | func writeQueues(c *Ctx, w io.Writer, q store.Queues) { |
| 288 | for _, it := range q.Mirrors.Items { | 280 | fmt.Fprintln(w, "queues:") |
| 289 | tmi.row(cRef(" "+it.Repo), cText(it.Direction), cText(it.URL), cText(it.LastError)) | ||
| 290 | } | ||
| 291 | tmi.flush() | ||
| 292 | |||
| 293 | fmt.Fprintf(w, " builds\tpending %d\trunning %d\n", q.Builds.Pending, q.Builds.Running) | ||
| 294 | tbq := c.table(w, "REPO", "#", "JOB", "STATUS") | ||
| 295 | for _, it := range q.Builds.Items { | ||
| 296 | since := it.StartedAt | ||
| 297 | if it.Status == "pending" { | ||
| 298 | since = it.CreatedAt | ||
| 299 | } | ||
| 300 | since = stamp(since) | ||
| 301 | tbq.row(cRef(" "+it.Repo), cNum(it.Number), cText(it.Job), cText(fmt.Sprintf("%s since %s", it.Status, since))) | ||
| 302 | } | ||
| 303 | tbq.flush() | ||
| 304 | 281 | ||
| 305 | fmt.Fprintf(w, " deps\terrors %d\n", q.Deps.Errors) | 282 | fmt.Fprintf(w, " webhooks\tpending %d\tretrying %d\tfailed %d\n", q.Webhooks.Pending, q.Webhooks.Retrying, q.Webhooks.Failed) |
| 306 | tde := c.table(w, "REPO", "ERROR") | 283 | twh := c.table(w, "REPO", "URL", "ATTEMPTS", "ERROR") |
| 307 | for _, it := range q.Deps.Items { | 284 | for _, it := range q.Webhooks.Items { |
| 308 | tde.row(cRef(" "+it.Repo), cText(it.LastError)) | 285 | twh.row(cRef(" "+it.Repo), cText(it.URL), cText(fmt.Sprintf("attempts %d", it.Attempts)), cText(it.LastError)) |
| 309 | } | 286 | } |
| 310 | tde.flush() | 287 | twh.flush() |
| 288 | |||
| 289 | fmt.Fprintf(w, " mail\tpending %d\tretrying %d\tfailed %d\n", q.Mail.Pending, q.Mail.Retrying, q.Mail.Failed) | ||
| 290 | tma := c.table(w, "RECIPIENT", "SUBJECT", "ATTEMPTS", "ERROR") | ||
| 291 | for _, it := range q.Mail.Items { | ||
| 292 | tma.row(cRef(" "+it.Recipient), cText(it.Subject), cText(fmt.Sprintf("attempts %d", it.Attempts)), cText(it.LastError)) | ||
| 293 | } | ||
| 294 | tma.flush() | ||
| 295 | |||
| 296 | // The device id, not the token: a token is never echoed. | ||
| 297 | fmt.Fprintf(w, " push\tpending %d\tretrying %d\tfailed %d\n", q.Push.Pending, q.Push.Retrying, q.Push.Failed) | ||
| 298 | tpu := c.table(w, "DEVICE", "TITLE", "ATTEMPTS", "ERROR") | ||
| 299 | for _, it := range q.Push.Items { | ||
| 300 | tpu.row(cRef(fmt.Sprintf(" device %d", it.DeviceID)), cText(it.Title), cText(fmt.Sprintf("attempts %d", it.Attempts)), cText(it.LastError)) | ||
| 301 | } | ||
| 302 | tpu.flush() | ||
| 303 | |||
| 304 | fmt.Fprintf(w, " mirrors\tdirty %d\terrors %d\n", q.Mirrors.Dirty, q.Mirrors.Errors) | ||
| 305 | tmi := c.table(w, "REPO", "DIRECTION", "URL", "ERROR") | ||
| 306 | for _, it := range q.Mirrors.Items { | ||
| 307 | tmi.row(cRef(" "+it.Repo), cText(it.Direction), cText(it.URL), cText(it.LastError)) | ||
| 308 | } | ||
| 309 | tmi.flush() | ||
| 310 | |||
| 311 | fmt.Fprintf(w, " builds\tpending %d\trunning %d\n", q.Builds.Pending, q.Builds.Running) | ||
| 312 | tbq := c.table(w, "REPO", "#", "JOB", "STATUS") | ||
| 313 | for _, it := range q.Builds.Items { | ||
| 314 | since := it.StartedAt | ||
| 315 | if it.Status == "pending" { | ||
| 316 | since = it.CreatedAt | ||
| 311 | } | 317 | } |
| 312 | }, func() screen { return dashboardScreen(c, d, lines) }) | 318 | since = stamp(since) |
| 319 | tbq.row(cRef(" "+it.Repo), cNum(it.Number), cText(it.Job), cText(fmt.Sprintf("%s since %s", it.Status, since))) | ||
| 320 | } | ||
| 321 | tbq.flush() | ||
| 322 | |||
| 323 | fmt.Fprintf(w, " deps\terrors %d\n", q.Deps.Errors) | ||
| 324 | tde := c.table(w, "REPO", "ERROR") | ||
| 325 | for _, it := range q.Deps.Items { | ||
| 326 | tde.row(cRef(" "+it.Repo), cText(it.LastError)) | ||
| 327 | } | ||
| 328 | tde.flush() | ||
| 313 | } | 329 | } |
| 314 | 330 | ||
| 315 | // feedDefaultLimit caps a bare `feed` call; pagination reaches further | 331 | // feedDefaultLimit caps a bare `feed` call; pagination reaches further |
internal/control/help.go +21 −11
| @@ -111,6 +111,22 @@ type helpEntry struct { | |||
| 111 | Examples []string `json:"examples,omitempty"` | 111 | Examples []string `json:"examples,omitempty"` |
| 112 | } | 112 | } |
| 113 | 113 | ||
| 114 | // aliasPaths maps each registered command path under an aliased noun to | ||
| 115 | // the path the CLI shows for it. | ||
| 116 | func aliasPaths(aliased []nounAlias) map[string]string { | ||
| 117 | paths := map[string]string{} | ||
| 118 | for _, cmd := range registry { | ||
| 119 | p := joinPath(cmd.Path) | ||
| 120 | for _, a := range aliased { | ||
| 121 | if p == a.Registered || strings.HasPrefix(p, a.Registered+" ") { | ||
| 122 | paths[p] = a.CLI + strings.TrimPrefix(p, a.Registered) | ||
| 123 | break | ||
| 124 | } | ||
| 125 | } | ||
| 126 | } | ||
| 127 | return paths | ||
| 128 | } | ||
| 129 | |||
| 114 | // runHelp lists the registry, sorted, so a noun's commands sit together. | 130 | // runHelp lists the registry, sorted, so a noun's commands sit together. |
| 115 | // Bare `help` stays one line per command. A prefix that names one command | 131 | // Bare `help` stays one line per command. A prefix that names one command |
| 116 | // exactly renders its full USAGE/FLAGS/EXAMPLES; a prefix that names a | 132 | // exactly renders its full USAGE/FLAGS/EXAMPLES; a prefix that names a |
| @@ -125,15 +141,7 @@ func runHelp(c *Ctx, args []string) int { | |||
| 125 | prefixes = append(prefixes, a.Registered) | 141 | prefixes = append(prefixes, a.Registered) |
| 126 | } | 142 | } |
| 127 | if c.CLIPath != "" { | 143 | if c.CLIPath != "" { |
| 128 | for _, cmd := range registry { | 144 | override = aliasPaths(aliased) |
| 129 | p := joinPath(cmd.Path) | ||
| 130 | for _, a := range aliased { | ||
| 131 | if p == a.Registered || strings.HasPrefix(p, a.Registered+" ") { | ||
| 132 | override[p] = a.CLI + strings.TrimPrefix(p, a.Registered) | ||
| 133 | break | ||
| 134 | } | ||
| 135 | } | ||
| 136 | } | ||
| 137 | } | 145 | } |
| 138 | } | 146 | } |
| 139 | var matched []Command | 147 | var matched []Command |
| @@ -224,8 +232,10 @@ func (c *Ctx) shownAs(registered, full string) string { | |||
| 224 | // other command's name, so it keeps its registered path. | 232 | // other command's name, so it keeps its registered path. |
| 225 | func (c *Ctx) shownBelow(registered, other string) string { | 233 | func (c *Ctx) shownBelow(registered, other string) string { |
| 226 | reg, cli, o := strings.Fields(registered), strings.Fields(c.CLIPath), strings.Fields(other) | 234 | reg, cli, o := strings.Fields(registered), strings.Fields(c.CLIPath), strings.Fields(other) |
| 227 | if len(cli) == 0 || len(reg) == 0 || len(o) < len(reg) || cli[len(cli)-1] != reg[len(reg)-1] || | 235 | if len(cli) == 0 || len(reg) == 0 || len(o) < len(reg) { |
| 228 | !slices.Equal(o[:len(reg)-1], reg[:len(reg)-1]) { | 236 | return other |
| 237 | } | ||
| 238 | if cli[len(cli)-1] != reg[len(reg)-1] || !slices.Equal(o[:len(reg)-1], reg[:len(reg)-1]) { | ||
| 229 | return other | 239 | return other |
| 230 | } | 240 | } |
| 231 | return joinPath(append(slices.Clip(cli[:len(cli)-1]), o[len(reg)-1:]...)) | 241 | return joinPath(append(slices.Clip(cli[:len(cli)-1]), o[len(reg)-1:]...)) |
internal/control/milestone.go +12 −16
| @@ -217,13 +217,7 @@ func runIssueMilestone(c *Ctx, args []string) int { | |||
| 217 | if code >= 0 { | 217 | if code >= 0 { |
| 218 | return code | 218 | return code |
| 219 | } | 219 | } |
| 220 | if code := refuseArchived(c, repo); code >= 0 { | 220 | return setItemMilestone(c, repo, args, "issue", issue.Number, func(id int64) error { |
| 221 | return code | ||
| 222 | } | ||
| 223 | if len(args) != 3 { | ||
| 224 | return c.usage() | ||
| 225 | } | ||
| 226 | return setItemMilestone(c, repo, "issue", issue.Number, args[2], func(id int64) error { | ||
| 227 | return c.Store.SetIssueMilestone(issue.ID, id) | 221 | return c.Store.SetIssueMilestone(issue.ID, id) |
| 228 | }) | 222 | }) |
| 229 | } | 223 | } |
| @@ -233,13 +227,7 @@ func runMRMilestone(c *Ctx, args []string) int { | |||
| 233 | if code >= 0 { | 227 | if code >= 0 { |
| 234 | return code | 228 | return code |
| 235 | } | 229 | } |
| 236 | if code := refuseArchived(c, repo); code >= 0 { | 230 | return setItemMilestone(c, repo, args, "mr", mr.Number, func(id int64) error { |
| 237 | return code | ||
| 238 | } | ||
| 239 | if len(args) != 3 { | ||
| 240 | return c.usage() | ||
| 241 | } | ||
| 242 | return setItemMilestone(c, repo, "mr", mr.Number, args[2], func(id int64) error { | ||
| 243 | return c.Store.SetMRMilestone(mr.ID, id) | 231 | return c.Store.SetMRMilestone(mr.ID, id) |
| 244 | }) | 232 | }) |
| 245 | } | 233 | } |
| @@ -255,8 +243,16 @@ func recordItemMilestone(c *Ctx, repo store.Repo, noun string, number, id int64, | |||
| 255 | return nil | 243 | return nil |
| 256 | } | 244 | } |
| 257 | 245 | ||
| 258 | // noun and number name what the milestone was set on, for the event. | 246 | // setItemMilestone sets the milestone args[2] titles through set. noun and |
| 259 | func setItemMilestone(c *Ctx, repo store.Repo, noun string, number int64, title string, set func(int64) error) int { | 247 | // number name what it was set on, for the event. |
| 248 | func setItemMilestone(c *Ctx, repo store.Repo, args []string, noun string, number int64, set func(int64) error) int { | ||
| 249 | if code := refuseArchived(c, repo); code >= 0 { | ||
| 250 | return code | ||
| 251 | } | ||
| 252 | if len(args) != 3 { | ||
| 253 | return c.usage() | ||
| 254 | } | ||
| 255 | title := args[2] | ||
| 260 | var id int64 | 256 | var id int64 |
| 261 | if title != "none" { | 257 | if title != "none" { |
| 262 | m, err := c.Store.MilestoneByTitle(repo, title) | 258 | m, err := c.Store.MilestoneByTitle(repo, title) |
internal/control/mirrorcmd.go +1 −20
| @@ -166,26 +166,7 @@ func orDash(s string) string { | |||
| 166 | } | 166 | } |
| 167 | 167 | ||
| 168 | func runMirrorRemove(c *Ctx, args []string) int { | 168 | func runMirrorRemove(c *Ctx, args []string) int { |
| 169 | if len(args) != 2 { | 169 | return runRepoItemAction(c, args, "mirror", c.Store.RemoveMirror, "removed", "removed mirror %d") |
| 170 | return c.usage() | ||
| 171 | } | ||
| 172 | repo, code := resolveRepo(c, args[0], policy.CanAdmin) | ||
| 173 | if code >= 0 { | ||
| 174 | return code | ||
| 175 | } | ||
| 176 | id, err := strconv.ParseInt(args[1], 10, 64) | ||
| 177 | if err != nil { | ||
| 178 | return c.fail(protocol.ExitUsage, "bad mirror id %q", args[1]) | ||
| 179 | } | ||
| 180 | if err := c.Store.RemoveMirror(repo.ID, id); err != nil { | ||
| 181 | if errors.Is(err, store.ErrNotFound) { | ||
| 182 | return c.fail(protocol.ExitNotFound, "no mirror %d on %s", id, repo.Path()) | ||
| 183 | } | ||
| 184 | return c.fail(protocol.ExitFailure, "%v", err) | ||
| 185 | } | ||
| 186 | return c.emit(map[string]any{"removed": id}, func(w io.Writer) { | ||
| 187 | fmt.Fprintf(w, "removed mirror %d\n", id) | ||
| 188 | }) | ||
| 189 | } | 170 | } |
| 190 | 171 | ||
| 191 | func runMirrorSync(c *Ctx, args []string) int { | 172 | func runMirrorSync(c *Ctx, args []string) int { |
internal/control/mr.go +687 −551
| @@ -297,40 +297,20 @@ func runRequireApprovals(c *Ctx, args []string) int { | |||
| 297 | } | 297 | } |
| 298 | 298 | ||
| 299 | func runRequireResolved(c *Ctx, args []string) int { | 299 | func runRequireResolved(c *Ctx, args []string) int { |
| 300 | if len(args) != 2 || (args[1] != "on" && args[1] != "off") { | 300 | return setRepoToggle(c, args, "require_resolved", func(s *store.RepoSettings, on bool) { s.RequireResolved = on }) |
| 301 | return c.usage() | ||
| 302 | } | ||
| 303 | repo, code := resolveRepo(c, args[0], policy.CanAdmin) | ||
| 304 | if code >= 0 { | ||
| 305 | return code | ||
| 306 | } | ||
| 307 | s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.RequireResolved = args[1] == "on" }) | ||
| 308 | if err != nil { | ||
| 309 | return c.fail(protocol.ExitFailure, "%v", err) | ||
| 310 | } | ||
| 311 | return c.emit(s, func(w io.Writer) { | ||
| 312 | fmt.Fprintf(w, "require_resolved %s on %s\n", args[1], repo.Path()) | ||
| 313 | }) | ||
| 314 | } | 301 | } |
| 315 | 302 | ||
| 316 | func runRequireCodeowners(c *Ctx, args []string) int { | 303 | func runRequireCodeowners(c *Ctx, args []string) int { |
| 317 | if len(args) != 2 || (args[1] != "on" && args[1] != "off") { | 304 | return setRepoToggle(c, args, "require_codeowners", func(s *store.RepoSettings, on bool) { s.RequireCodeowners = on }) |
| 318 | return c.usage() | ||
| 319 | } | ||
| 320 | repo, code := resolveRepo(c, args[0], policy.CanAdmin) | ||
| 321 | if code >= 0 { | ||
| 322 | return code | ||
| 323 | } | ||
| 324 | s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.RequireCodeowners = args[1] == "on" }) | ||
| 325 | if err != nil { | ||
| 326 | return c.fail(protocol.ExitFailure, "%v", err) | ||
| 327 | } | ||
| 328 | return c.emit(s, func(w io.Writer) { | ||
| 329 | fmt.Fprintf(w, "require_codeowners %s on %s\n", args[1], repo.Path()) | ||
| 330 | }) | ||
| 331 | } | 305 | } |
| 332 | 306 | ||
| 333 | func runRequireChecks(c *Ctx, args []string) int { | 307 | func runRequireChecks(c *Ctx, args []string) int { |
| 308 | return setRepoToggle(c, args, "require_checks", func(s *store.RepoSettings, on bool) { s.RequireChecks = on }) | ||
| 309 | } | ||
| 310 | |||
| 311 | // setRepoToggle is `<owner/name> on|off` for one boolean repository setting, | ||
| 312 | // reported under `name`. | ||
| 313 | func setRepoToggle(c *Ctx, args []string, name string, set func(*store.RepoSettings, bool)) int { | ||
| 334 | if len(args) != 2 || (args[1] != "on" && args[1] != "off") { | 314 | if len(args) != 2 || (args[1] != "on" && args[1] != "off") { |
| 335 | return c.usage() | 315 | return c.usage() |
| 336 | } | 316 | } |
| @@ -338,12 +318,12 @@ func runRequireChecks(c *Ctx, args []string) int { | |||
| 338 | if code >= 0 { | 318 | if code >= 0 { |
| 339 | return code | 319 | return code |
| 340 | } | 320 | } |
| 341 | s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.RequireChecks = args[1] == "on" }) | 321 | s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { set(s, args[1] == "on") }) |
| 342 | if err != nil { | 322 | if err != nil { |
| 343 | return c.fail(protocol.ExitFailure, "%v", err) | 323 | return c.fail(protocol.ExitFailure, "%v", err) |
| 344 | } | 324 | } |
| 345 | return c.emit(s, func(w io.Writer) { | 325 | return c.emit(s, func(w io.Writer) { |
| 346 | fmt.Fprintf(w, "require_checks %s on %s\n", args[1], repo.Path()) | 326 | fmt.Fprintf(w, "%s %s on %s\n", name, args[1], repo.Path()) |
| 347 | }) | 327 | }) |
| 348 | } | 328 | } |
| 349 | 329 | ||
| @@ -396,37 +376,11 @@ func runRequireContexts(c *Ctx, args []string) int { | |||
| 396 | } | 376 | } |
| 397 | 377 | ||
| 398 | func runRequireMR(c *Ctx, args []string) int { | 378 | func runRequireMR(c *Ctx, args []string) int { |
| 399 | if len(args) != 2 || (args[1] != "on" && args[1] != "off") { | 379 | return setRepoToggle(c, args, "require_mr", func(s *store.RepoSettings, on bool) { s.RequireMR = on }) |
| 400 | return c.usage() | ||
| 401 | } | ||
| 402 | repo, code := resolveRepo(c, args[0], policy.CanAdmin) | ||
| 403 | if code >= 0 { | ||
| 404 | return code | ||
| 405 | } | ||
| 406 | s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.RequireMR = args[1] == "on" }) | ||
| 407 | if err != nil { | ||
| 408 | return c.fail(protocol.ExitFailure, "%v", err) | ||
| 409 | } | ||
| 410 | return c.emit(s, func(w io.Writer) { | ||
| 411 | fmt.Fprintf(w, "require_mr %s on %s\n", args[1], repo.Path()) | ||
| 412 | }) | ||
| 413 | } | 380 | } |
| 414 | 381 | ||
| 415 | func runRequireSigned(c *Ctx, args []string) int { | 382 | func runRequireSigned(c *Ctx, args []string) int { |
| 416 | if len(args) != 2 || (args[1] != "on" && args[1] != "off") { | 383 | return setRepoToggle(c, args, "require_signed_commits", func(s *store.RepoSettings, on bool) { s.RequireSignedCommits = on }) |
| 417 | return c.usage() | ||
| 418 | } | ||
| 419 | repo, code := resolveRepo(c, args[0], policy.CanAdmin) | ||
| 420 | if code >= 0 { | ||
| 421 | return code | ||
| 422 | } | ||
| 423 | s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.RequireSignedCommits = args[1] == "on" }) | ||
| 424 | if err != nil { | ||
| 425 | return c.fail(protocol.ExitFailure, "%v", err) | ||
| 426 | } | ||
| 427 | return c.emit(s, func(w io.Writer) { | ||
| 428 | fmt.Fprintf(w, "require_signed_commits %s on %s\n", args[1], repo.Path()) | ||
| 429 | }) | ||
| 430 | } | 384 | } |
| 431 | 385 | ||
| 432 | // mrRef parses "<owner/name> <n>" and loads the MR. | 386 | // mrRef parses "<owner/name> <n>" and loads the MR. |
| @@ -758,21 +712,48 @@ func runMRShow(c *Ctx, args []string) int { | |||
| 758 | if len(args) != 2 { | 712 | if len(args) != 2 { |
| 759 | return c.usage() | 713 | return c.usage() |
| 760 | } | 714 | } |
| 761 | comments, err := c.Store.ListMRComments(mr.ID) | 715 | dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name) |
| 716 | d, err := mrShowData(c, repo, mr) | ||
| 762 | if err != nil { | 717 | if err != nil { |
| 763 | return c.fail(protocol.ExitFailure, "%v", err) | 718 | return c.fail(protocol.ExitFailure, "%v", err) |
| 764 | } | 719 | } |
| 720 | // The commits this MR carries: base..head, the diff's range. | ||
| 721 | base := mrBase(dir, mr) | ||
| 722 | d.Commits = mrCommits(dir, base, mr) | ||
| 723 | d.StackedOn, d.Stacked = stackOf(c, repo, mr) | ||
| 724 | if mr.State == "open" || mr.State == "source_gone" { | ||
| 725 | if targetSHA, err := gitutil.ResolveRef(dir, "refs/heads/"+mr.TargetRef); err == nil { | ||
| 726 | if g, err := MergeGates(c.Store, repo, mr, dir, targetSHA, mr.HeadSHA); err == nil { | ||
| 727 | d.Gates = &g | ||
| 728 | } | ||
| 729 | } | ||
| 730 | } | ||
| 731 | var files []gitutil.NumStat | ||
| 732 | if c.Term.Cols > 0 && !c.JSON && base != "" { | ||
| 733 | files, _ = gitutil.DiffNumstat(dir, base, mrHeadRef(mr.Number)) | ||
| 734 | } | ||
| 735 | return c.emitView(d, func(w io.Writer) { writeMRShow(c, w, repo, d) }, | ||
| 736 | func() screen { return mrShowScreen(c, repo, d, files) }) | ||
| 737 | } | ||
| 738 | |||
| 739 | // mrShowData is a merge request with its comments, reviews, checks and | ||
| 740 | // reactions; commits, stack and gates are filled in by the caller. | ||
| 741 | func mrShowData(c *Ctx, repo store.Repo, mr store.MR) (MRShow, error) { | ||
| 742 | comments, err := c.Store.ListMRComments(mr.ID) | ||
| 743 | if err != nil { | ||
| 744 | return MRShow{}, err | ||
| 745 | } | ||
| 765 | reviews, err := c.Store.ListMRReviews(mr.ID) | 746 | reviews, err := c.Store.ListMRReviews(mr.ID) |
| 766 | if err != nil { | 747 | if err != nil { |
| 767 | return c.fail(protocol.ExitFailure, "%v", err) | 748 | return MRShow{}, err |
| 768 | } | 749 | } |
| 769 | statuses, combined, err := c.Store.ChecksForCommit(repo.ID, mr.HeadSHA) | 750 | statuses, combined, err := c.Store.ChecksForCommit(repo.ID, mr.HeadSHA) |
| 770 | if err != nil { | 751 | if err != nil { |
| 771 | return c.fail(protocol.ExitFailure, "%v", err) | 752 | return MRShow{}, err |
| 772 | } | 753 | } |
| 773 | unresolved, err := c.Store.UnresolvedThreadCount(mr.ID) | 754 | unresolved, err := c.Store.UnresolvedThreadCount(mr.ID) |
| 774 | if err != nil { | 755 | if err != nil { |
| 775 | return c.fail(protocol.ExitFailure, "%v", err) | 756 | return MRShow{}, err |
| 776 | } | 757 | } |
| 777 | var checks []CheckOut | 758 | var checks []CheckOut |
| 778 | for _, st := range statuses { | 759 | for _, st := range statuses { |
| @@ -784,7 +765,7 @@ func runMRShow(c *Ctx, args []string) int { | |||
| 784 | } | 765 | } |
| 785 | rx, err := c.Store.ReactionCounts("mr", mr.ID, c.User.ID) | 766 | rx, err := c.Store.ReactionCounts("mr", mr.ID, c.User.ID) |
| 786 | if err != nil { | 767 | if err != nil { |
| 787 | return c.fail(protocol.ExitFailure, "%v", err) | 768 | return MRShow{}, err |
| 788 | } | 769 | } |
| 789 | var cs []commentOut | 770 | var cs []commentOut |
| 790 | for _, cm := range comments { | 771 | for _, cm := range comments { |
| @@ -795,194 +776,214 @@ func runMRShow(c *Ctx, args []string) int { | |||
| 795 | for _, r := range reviews { | 776 | for _, r := range reviews { |
| 796 | rs = append(rs, ReviewOut{r.Reviewer, r.Verdict, r.Stale, counts[r.Reviewer], r.CreatedAt}) | 777 | rs = append(rs, ReviewOut{r.Reviewer, r.Verdict, r.Stale, counts[r.Reviewer], r.CreatedAt}) |
| 797 | } | 778 | } |
| 798 | // The commits this MR carries: base..head, the diff's range. | 779 | return MRShow{mrOut: mrToOut(repo, mr, true), Checks: checks, Combined: combined, |
| 799 | var commits []CommitOut | 780 | UnresolvedThreads: unresolved, Reactions: reactionsOut(rx[0]), Comments: cs, Reviews: rs}, nil |
| 800 | dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name) | 781 | } |
| 801 | base := mr.MergedBase | 782 | |
| 783 | // mrBase is where a merge request's diff starts: the base recorded at merge, | ||
| 784 | // or the live merge base with its target. Empty when neither is known. | ||
| 785 | func mrBase(dir string, mr store.MR) string { | ||
| 786 | if mr.MergedBase != "" { | ||
| 787 | return mr.MergedBase | ||
| 788 | } | ||
| 789 | if b, err := gitutil.MergeBase(dir, "refs/heads/"+mr.TargetRef, mrHeadRef(mr.Number)); err == nil { | ||
| 790 | return b | ||
| 791 | } | ||
| 792 | return "" | ||
| 793 | } | ||
| 794 | |||
| 795 | // mrCommits is base..head with each commit's subject, when it can be read. | ||
| 796 | func mrCommits(dir, base string, mr store.MR) []CommitOut { | ||
| 802 | if base == "" { | 797 | if base == "" { |
| 803 | if b, err := gitutil.MergeBase(dir, "refs/heads/"+mr.TargetRef, mrHeadRef(mr.Number)); err == nil { | 798 | return nil |
| 804 | base = b | ||
| 805 | } | ||
| 806 | } | ||
| 807 | if base != "" { | ||
| 808 | if shas, err := gitutil.RevListRange(dir, base, mrHeadRef(mr.Number)); err == nil { | ||
| 809 | for _, sha := range shas { | ||
| 810 | subject := "" | ||
| 811 | if raw, err := gitutil.ReadCommit(dir, sha); err == nil { | ||
| 812 | if parsed, err := sig.ParseCommit(raw); err == nil { | ||
| 813 | subject = parsed.Subject | ||
| 814 | } | ||
| 815 | } | ||
| 816 | commits = append(commits, CommitOut{sha, subject}) | ||
| 817 | } | ||
| 818 | } | ||
| 819 | } | 799 | } |
| 820 | d := MRShow{mrOut: mrToOut(repo, mr, true), Checks: checks, Combined: combined, | 800 | shas, err := gitutil.RevListRange(dir, base, mrHeadRef(mr.Number)) |
| 821 | UnresolvedThreads: unresolved, Commits: commits, Reactions: reactionsOut(rx[0]), Comments: cs, Reviews: rs} | 801 | if err != nil { |
| 822 | d.StackedOn, d.Stacked = stackOf(c, repo, mr) | 802 | return nil |
| 823 | if mr.State == "open" || mr.State == "source_gone" { | 803 | } |
| 824 | if targetSHA, err := gitutil.ResolveRef(dir, "refs/heads/"+mr.TargetRef); err == nil { | 804 | var commits []CommitOut |
| 825 | if g, err := MergeGates(c.Store, repo, mr, dir, targetSHA, mr.HeadSHA); err == nil { | 805 | for _, sha := range shas { |
| 826 | d.Gates = &g | 806 | subject := "" |
| 807 | if raw, err := gitutil.ReadCommit(dir, sha); err == nil { | ||
| 808 | if parsed, err := sig.ParseCommit(raw); err == nil { | ||
| 809 | subject = parsed.Subject | ||
| 827 | } | 810 | } |
| 828 | } | 811 | } |
| 812 | commits = append(commits, CommitOut{sha, subject}) | ||
| 829 | } | 813 | } |
| 830 | var files []gitutil.NumStat | 814 | return commits |
| 831 | if c.Term.Cols > 0 && !c.JSON && base != "" { | 815 | } |
| 832 | files, _ = gitutil.DiffNumstat(dir, base, mrHeadRef(mr.Number)) | 816 | |
| 817 | // writeMRShow is `mr show` as text. | ||
| 818 | func writeMRShow(c *Ctx, w io.Writer, repo store.Repo, d MRShow) { | ||
| 819 | state := d.State | ||
| 820 | if d.Draft { | ||
| 821 | state = "draft" | ||
| 833 | } | 822 | } |
| 834 | return c.emitView(d, func(w io.Writer) { | 823 | v := c.view(w) |
| 835 | state := d.State | 824 | v.title(fmt.Sprintf("!%d", d.Number), d.Title, state) |
| 836 | if d.Draft { | 825 | v.fields(mrShowFields(c, repo, d)...) |
| 837 | state = "draft" | ||
| 838 | } | ||
| 839 | v := c.view(w) | ||
| 840 | v.title(fmt.Sprintf("!%d", d.Number), d.Title, state) | ||
| 841 | 826 | ||
| 842 | stackedOn, stacked := "", "" | 827 | v.body(d.Body, d.BodyFormat) |
| 843 | if d.StackedOn != nil { | 828 | v.reactions(d.Reactions) |
| 844 | stackedOn = fmt.Sprintf("!%d %s", d.StackedOn.Number, d.StackedOn.Title) | 829 | writeMRTables(c, w, v, d) |
| 845 | } | 830 | |
| 846 | for _, k := range d.Stacked { | 831 | events := false |
| 847 | if stacked != "" { | 832 | for _, cm := range d.Comments { |
| 848 | stacked += ", " | 833 | if cm.Kind != "system" { |
| 849 | } | 834 | continue |
| 850 | stacked += fmt.Sprintf("!%d %s", k.Number, k.Title) | ||
| 851 | } | ||
| 852 | merged, closed, superseded := "", "", "" | ||
| 853 | if d.MergedAt != "" { | ||
| 854 | merged = c.when(d.MergedAt) + byWhom(d.MergedBy) | ||
| 855 | } | ||
| 856 | if d.ClosedAt != "" { | ||
| 857 | closed = c.when(d.ClosedAt) + byWhom(d.ClosedBy) | ||
| 858 | } | ||
| 859 | if d.SupersededBy != 0 { | ||
| 860 | superseded = fmt.Sprintf("!%d", d.SupersededBy) | ||
| 861 | } | ||
| 862 | gates := "" | ||
| 863 | if g := d.Gates; g != nil { | ||
| 864 | ff := "fast-forward possible" | ||
| 865 | if !g.FastForward { | ||
| 866 | ff = "fast-forward not possible" | ||
| 867 | } | ||
| 868 | if len(g.Unmet) == 0 { | ||
| 869 | gates = "met; " + ff | ||
| 870 | } else { | ||
| 871 | gates = fmt.Sprintf("%d unmet; %s", len(g.Unmet), ff) | ||
| 872 | } | ||
| 873 | } | ||
| 874 | queued, waiting := "", "" | ||
| 875 | if q := d.Queued; q != nil { | ||
| 876 | queued = "by " + q.By | ||
| 877 | if q.Strategy != "" { | ||
| 878 | queued += " (" + q.Strategy + ")" | ||
| 879 | } | ||
| 880 | queued += ", " + c.when(q.QueuedAt) | ||
| 881 | waiting = q.Reason | ||
| 882 | } | ||
| 883 | unresolved := "" | ||
| 884 | if d.UnresolvedThreads > 0 { | ||
| 885 | unresolved = fmt.Sprintf("%d", d.UnresolvedThreads) | ||
| 886 | } | ||
| 887 | // One fields call for every one-row fact, including the unmet | ||
| 888 | // gates and the commit/check/review that only has a single row | ||
| 889 | // to show: separate calls each compute their own key width, so | ||
| 890 | // keeping them in one call keeps every key aligned. | ||
| 891 | kv := []string{ | ||
| 892 | "author", d.Author + ", " + c.when(d.CreatedAt), | ||
| 893 | "source", fmt.Sprintf("%s -> %s", d.Source, d.TargetRef), | ||
| 894 | "head", fmt.Sprintf("%.10s", d.HeadSHA), | ||
| 895 | "milestone", d.Milestone, | ||
| 896 | "labels", strings.Join(d.Labels, ", "), | ||
| 897 | "reviewers", strings.Join(d.ReviewRequests, ", "), | ||
| 898 | "stacked on", stackedOn, | ||
| 899 | "stacked", stacked, | ||
| 900 | "merged", merged, | ||
| 901 | "closed", closed, | ||
| 902 | "superseded by", superseded, | ||
| 903 | "queued to merge", queued, | ||
| 904 | "waiting on", waiting, | ||
| 905 | "unresolved threads", unresolved, | ||
| 906 | "gates", gates, | ||
| 907 | } | ||
| 908 | if g := d.Gates; g != nil { | ||
| 909 | for _, u := range g.Unmet { | ||
| 910 | kv = append(kv, "unmet", u) | ||
| 911 | } | ||
| 912 | } | ||
| 913 | if len(commits) == 1 { | ||
| 914 | kv = append(kv, "commit", fmt.Sprintf("%.10s %s", commits[0].SHA, commits[0].Subject)) | ||
| 915 | } | 835 | } |
| 916 | if len(checks) == 1 { | 836 | if !events { |
| 917 | x := checks[0] | 837 | io.WriteString(w, "\n") |
| 918 | dur := "" | 838 | events = true |
| 919 | if x.Duration != "" { | ||
| 920 | dur = " in " + x.Duration | ||
| 921 | } | ||
| 922 | kv = append(kv, "check", fmt.Sprintf("%s %s at %s%s", x.Context, x.State, c.when(x.UpdatedAt), dur)) | ||
| 923 | } | 839 | } |
| 924 | if len(rs) == 1 { | 840 | v.event(cm.Body, cm.BodyFormat, cm.CreatedAt) |
| 925 | kv = append(kv, "review", reviewLine(rs[0])+" at "+c.when(rs[0].CreatedAt)) | 841 | } |
| 842 | for _, cm := range d.Comments { | ||
| 843 | if cm.Kind == "system" { | ||
| 844 | continue | ||
| 926 | } | 845 | } |
| 927 | kv = append(kv, "url", c.siteURL(repo.Path(), "mrs", strconv.FormatInt(d.Number, 10))) | 846 | v.comment(cm.ID, cm.Author, cm.CreatedAt, cm.Body, cm.BodyFormat) |
| 928 | v.fields(kv...) | 847 | v.reactions(cm.Reactions) |
| 848 | } | ||
| 849 | } | ||
| 929 | 850 | ||
| 930 | v.body(d.Body, d.BodyFormat) | 851 | // mrShowFields is every one-row fact as key, value pairs, including the |
| 931 | v.reactions(d.Reactions) | 852 | // unmet gates and the commit/check/review that only has a single row to |
| 853 | // show: separate fields calls each compute their own key width, so keeping | ||
| 854 | // them in one call keeps every key aligned. | ||
| 855 | func mrShowFields(c *Ctx, repo store.Repo, d MRShow) []string { | ||
| 856 | stackedOn, stacked := mrStackLines(d) | ||
| 857 | merged, closed, superseded := "", "", "" | ||
| 858 | if d.MergedAt != "" { | ||
| 859 | merged = c.when(d.MergedAt) + byWhom(d.MergedBy) | ||
| 860 | } | ||
| 861 | if d.ClosedAt != "" { | ||
| 862 | closed = c.when(d.ClosedAt) + byWhom(d.ClosedBy) | ||
| 863 | } | ||
| 864 | if d.SupersededBy != 0 { | ||
| 865 | superseded = fmt.Sprintf("!%d", d.SupersededBy) | ||
| 866 | } | ||
| 867 | queued, waiting := mrQueuedLines(c, d.Queued) | ||
| 868 | unresolved := "" | ||
| 869 | if d.UnresolvedThreads > 0 { | ||
| 870 | unresolved = fmt.Sprintf("%d", d.UnresolvedThreads) | ||
| 871 | } | ||
| 872 | kv := []string{ | ||
| 873 | "author", d.Author + ", " + c.when(d.CreatedAt), | ||
| 874 | "source", fmt.Sprintf("%s -> %s", d.Source, d.TargetRef), | ||
| 875 | "head", fmt.Sprintf("%.10s", d.HeadSHA), | ||
| 876 | "milestone", d.Milestone, | ||
| 877 | "labels", strings.Join(d.Labels, ", "), | ||
| 878 | "reviewers", strings.Join(d.ReviewRequests, ", "), | ||
| 879 | "stacked on", stackedOn, | ||
| 880 | "stacked", stacked, | ||
| 881 | "merged", merged, | ||
| 882 | "closed", closed, | ||
| 883 | "superseded by", superseded, | ||
| 884 | "queued to merge", queued, | ||
| 885 | "waiting on", waiting, | ||
| 886 | "unresolved threads", unresolved, | ||
| 887 | "gates", gatesSummary(d.Gates), | ||
| 888 | } | ||
| 889 | if g := d.Gates; g != nil { | ||
| 890 | for _, u := range g.Unmet { | ||
| 891 | kv = append(kv, "unmet", u) | ||
| 892 | } | ||
| 893 | } | ||
| 894 | if len(d.Commits) == 1 { | ||
| 895 | kv = append(kv, "commit", fmt.Sprintf("%.10s %s", d.Commits[0].SHA, d.Commits[0].Subject)) | ||
| 896 | } | ||
| 897 | if len(d.Checks) == 1 { | ||
| 898 | x := d.Checks[0] | ||
| 899 | dur := "" | ||
| 900 | if x.Duration != "" { | ||
| 901 | dur = " in " + x.Duration | ||
| 902 | } | ||
| 903 | kv = append(kv, "check", fmt.Sprintf("%s %s at %s%s", x.Context, x.State, c.when(x.UpdatedAt), dur)) | ||
| 904 | } | ||
| 905 | if len(d.Reviews) == 1 { | ||
| 906 | kv = append(kv, "review", reviewLine(d.Reviews[0])+" at "+c.when(d.Reviews[0].CreatedAt)) | ||
| 907 | } | ||
| 908 | return append(kv, "url", c.siteURL(repo.Path(), "mrs", strconv.FormatInt(d.Number, 10))) | ||
| 909 | } | ||
| 932 | 910 | ||
| 933 | if len(commits) > 1 { | 911 | // mrStackLines names the merge request this one is stacked on, and those |
| 934 | v.section(fmt.Sprintf("commits (%d)", len(commits))) | 912 | // stacked on it. |
| 935 | tb := c.table(w, "SHA", "SUBJECT") | 913 | func mrStackLines(d MRShow) (stackedOn, stacked string) { |
| 936 | for _, cm := range commits { | 914 | if d.StackedOn != nil { |
| 937 | tb.row(cRef(fmt.Sprintf("%.10s", cm.SHA)), cFlex(cm.Subject)) | 915 | stackedOn = fmt.Sprintf("!%d %s", d.StackedOn.Number, d.StackedOn.Title) |
| 938 | } | 916 | } |
| 939 | tb.flush() | 917 | for _, k := range d.Stacked { |
| 918 | if stacked != "" { | ||
| 919 | stacked += ", " | ||
| 940 | } | 920 | } |
| 921 | stacked += fmt.Sprintf("!%d %s", k.Number, k.Title) | ||
| 922 | } | ||
| 923 | return stackedOn, stacked | ||
| 924 | } | ||
| 941 | 925 | ||
| 942 | if len(checks) > 1 { | 926 | // mrQueuedLines is who queued the merge, how and when, and what it waits on. |
| 943 | v.section(fmt.Sprintf("checks (%d)", len(checks))) | 927 | func mrQueuedLines(c *Ctx, q *QueuedOut) (queued, waiting string) { |
| 944 | tb := c.table(w, "CHECK", "STATE", "DURATION", "UPDATED") | 928 | if q == nil { |
| 945 | for _, x := range checks { | 929 | return "", "" |
| 946 | tb.row(cText(x.Context), cState(x.State), cText(x.Duration), cText(c.when(x.UpdatedAt))) | 930 | } |
| 947 | } | 931 | queued = "by " + q.By |
| 948 | tb.flush() | 932 | if q.Strategy != "" { |
| 949 | } | 933 | queued += " (" + q.Strategy + ")" |
| 934 | } | ||
| 935 | return queued + ", " + c.when(q.QueuedAt), q.Reason | ||
| 936 | } | ||
| 950 | 937 | ||
| 951 | if len(rs) > 1 { | 938 | // gatesSummary is "met" or the unmet count, and whether fast-forward is possible. |
| 952 | v.section(fmt.Sprintf("reviews (%d)", len(rs))) | 939 | func gatesSummary(g *GatesOut) string { |
| 953 | tb := c.table(w, "REVIEWER", "VERDICT", "WHEN") | 940 | if g == nil { |
| 954 | for _, r := range rs { | 941 | return "" |
| 955 | verdict := r.Verdict | 942 | } |
| 956 | if r.Stale { | 943 | ff := "fast-forward possible" |
| 957 | verdict += " (stale)" | 944 | if !g.FastForward { |
| 958 | } | 945 | ff = "fast-forward not possible" |
| 959 | if !r.Counts { | 946 | } |
| 960 | verdict += " (advisory)" | 947 | if len(g.Unmet) == 0 { |
| 961 | } | 948 | return "met; " + ff |
| 962 | tb.row(cText(r.Reviewer), cState(verdict), cText(c.when(r.CreatedAt))) | 949 | } |
| 963 | } | 950 | return fmt.Sprintf("%d unmet; %s", len(g.Unmet), ff) |
| 964 | tb.flush() | 951 | } |
| 965 | } | ||
| 966 | 952 | ||
| 967 | events := false | 953 | // writeMRTables lists commits, checks and reviews when there is more than |
| 968 | for _, cm := range cs { | 954 | // one of each; a single one is a field instead. |
| 969 | if cm.Kind != "system" { | 955 | func writeMRTables(c *Ctx, w io.Writer, v *view, d MRShow) { |
| 970 | continue | 956 | if len(d.Commits) > 1 { |
| 971 | } | 957 | v.section(fmt.Sprintf("commits (%d)", len(d.Commits))) |
| 972 | if !events { | 958 | tb := c.table(w, "SHA", "SUBJECT") |
| 973 | io.WriteString(w, "\n") | 959 | for _, cm := range d.Commits { |
| 974 | events = true | 960 | tb.row(cRef(fmt.Sprintf("%.10s", cm.SHA)), cFlex(cm.Subject)) |
| 975 | } | ||
| 976 | v.event(cm.Body, cm.BodyFormat, cm.CreatedAt) | ||
| 977 | } | 961 | } |
| 978 | for _, cm := range cs { | 962 | tb.flush() |
| 979 | if cm.Kind == "system" { | 963 | } |
| 980 | continue | 964 | if len(d.Checks) > 1 { |
| 965 | v.section(fmt.Sprintf("checks (%d)", len(d.Checks))) | ||
| 966 | tb := c.table(w, "CHECK", "STATE", "DURATION", "UPDATED") | ||
| 967 | for _, x := range d.Checks { | ||
| 968 | tb.row(cText(x.Context), cState(x.State), cText(x.Duration), cText(c.when(x.UpdatedAt))) | ||
| 969 | } | ||
| 970 | tb.flush() | ||
| 971 | } | ||
| 972 | if len(d.Reviews) > 1 { | ||
| 973 | v.section(fmt.Sprintf("reviews (%d)", len(d.Reviews))) | ||
| 974 | tb := c.table(w, "REVIEWER", "VERDICT", "WHEN") | ||
| 975 | for _, r := range d.Reviews { | ||
| 976 | verdict := r.Verdict | ||
| 977 | if r.Stale { | ||
| 978 | verdict += " (stale)" | ||
| 979 | } | ||
| 980 | if !r.Counts { | ||
| 981 | verdict += " (advisory)" | ||
| 981 | } | 982 | } |
| 982 | v.comment(cm.ID, cm.Author, cm.CreatedAt, cm.Body, cm.BodyFormat) | 983 | tb.row(cText(r.Reviewer), cState(verdict), cText(c.when(r.CreatedAt))) |
| 983 | v.reactions(cm.Reactions) | ||
| 984 | } | 984 | } |
| 985 | }, func() screen { return mrShowScreen(c, repo, d, files) }) | 985 | tb.flush() |
| 986 | } | ||
| 986 | } | 987 | } |
| 987 | 988 | ||
| 988 | // reviewLine renders one review as fields prose: "reviewer verdict | 989 | // reviewLine renders one review as fields prose: "reviewer verdict |
| @@ -1394,256 +1395,357 @@ func mergeMR(c *Ctx, repo store.Repo, mr store.MR, strategy string) int { | |||
| 1394 | return c.fail(protocol.ExitUsage, "MR !%d is %s", mr.Number, mr.State) | 1395 | return c.fail(protocol.ExitUsage, "MR !%d is %s", mr.Number, mr.State) |
| 1395 | } | 1396 | } |
| 1396 | 1397 | ||
| 1397 | dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name) | 1398 | p := &mergePlan{repo: repo, mr: mr, strategy: strategy} |
| 1398 | targetRef := "refs/heads/" + mr.TargetRef | 1399 | p.dir = RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name) |
| 1399 | targetSHA, err := gitutil.ResolveRef(dir, targetRef) | 1400 | p.targetRef = "refs/heads/" + mr.TargetRef |
| 1401 | var err error | ||
| 1402 | p.targetSHA, err = gitutil.ResolveRef(p.dir, p.targetRef) | ||
| 1400 | if err != nil { | 1403 | if err != nil { |
| 1401 | return c.fail(protocol.ExitFailure, "target branch %s: %v", mr.TargetRef, err) | 1404 | return c.fail(protocol.ExitFailure, "target branch %s: %v", mr.TargetRef, err) |
| 1402 | } | 1405 | } |
| 1403 | headSHA, err := gitutil.ResolveRef(dir, mrHeadRef(mr.Number)) | 1406 | p.headSHA, err = gitutil.ResolveRef(p.dir, mrHeadRef(mr.Number)) |
| 1404 | if err != nil { | 1407 | if err != nil { |
| 1405 | return c.fail(protocol.ExitFailure, "MR head ref: %v", err) | 1408 | return c.fail(protocol.ExitFailure, "MR head ref: %v", err) |
| 1406 | } | 1409 | } |
| 1407 | 1410 | ||
| 1408 | // Merge gates: draft, checks, approvals, CODEOWNERS, resolved threads, | 1411 | // Merge gates: draft, checks, approvals, CODEOWNERS, resolved threads, |
| 1409 | // all reported at once. | 1412 | // all reported at once. |
| 1410 | if code := c.reviewGates(repo, mr, dir, targetSHA, headSHA); code >= 0 { | 1413 | if code := c.reviewGates(repo, mr, p.dir, p.targetSHA, p.headSHA); code >= 0 { |
| 1411 | return code | 1414 | return code |
| 1412 | } | 1415 | } |
| 1413 | 1416 | ||
| 1414 | upToDate, err := gitutil.IsAncestor(dir, headSHA, targetSHA) | 1417 | upToDate, err := gitutil.IsAncestor(p.dir, p.headSHA, p.targetSHA) |
| 1415 | if err != nil { | 1418 | if err != nil { |
| 1416 | return c.fail(protocol.ExitFailure, "%v", err) | 1419 | return c.fail(protocol.ExitFailure, "%v", err) |
| 1417 | } | 1420 | } |
| 1418 | if upToDate { | 1421 | if upToDate { |
| 1419 | // The head is already on the target: merged by hand and pushed, or | 1422 | return c.recordAlreadyMerged(p) |
| 1420 | // a merge whose ref update landed and whose record did not. Record | ||
| 1421 | // it rather than refuse, so a merge request cannot be stuck open | ||
| 1422 | // with no way to close it as merged (#108). | ||
| 1423 | if err := c.Store.MarkMerged(mr.ID, targetSHA, headSHA, c.User.ID, ""); err != nil { | ||
| 1424 | return c.fail(protocol.ExitFailure, "%v", err) | ||
| 1425 | } | ||
| 1426 | c.Store.RecordEvent(repo.ID, c.User.ID, "mr.merged", fmt.Sprintf(`{"number":%d}`, mr.Number)) | ||
| 1427 | return c.emit(map[string]any{"number": mr.Number, "strategy": "recorded", "sha": headSHA}, func(w io.Writer) { | ||
| 1428 | fmt.Fprintf(w, "%s already contains !%d; recorded as merged at %.10s\n", mr.TargetRef, mr.Number, headSHA) | ||
| 1429 | }) | ||
| 1430 | } | 1423 | } |
| 1431 | ffPossible, err := gitutil.IsAncestor(dir, targetSHA, headSHA) | 1424 | p.ffPossible, err = gitutil.IsAncestor(p.dir, p.targetSHA, p.headSHA) |
| 1432 | if err != nil { | 1425 | if err != nil { |
| 1433 | return c.fail(protocol.ExitFailure, "%v", err) | 1426 | return c.fail(protocol.ExitFailure, "%v", err) |
| 1434 | } | 1427 | } |
| 1435 | 1428 | ||
| 1436 | // Signature policy matrix: with require_signed_commits, only | ||
| 1437 | // fast-forward is allowed — squash, rebase-replay, and merge commits | ||
| 1438 | // are all server-created and unsigned, violating the branch's own | ||
| 1439 | // policy — and every landed commit must be verified. An explicit | ||
| 1440 | // rebase when fast-forward is already possible IS a fast-forward | ||
| 1441 | // (nothing is rewritten), so it stays legal. | ||
| 1442 | if repo.Settings.RequireSignedCommits { | 1429 | if repo.Settings.RequireSignedCommits { |
| 1443 | if c.Source == queueSource && !ffPossible { | 1430 | if code := c.requireSignedMerge(p); code >= 0 { |
| 1444 | return c.fail(protocol.ExitDenied, | 1431 | return code |
| 1445 | "%s is behind %s and %s requires signed commits, so the server cannot rebase it; rebase and push, and the merge stays queued", | ||
| 1446 | mr.SourceRef, mr.TargetRef, repo.Path()) | ||
| 1447 | } | ||
| 1448 | if strategy == "merge" || strategy == "squash" || !ffPossible { | ||
| 1449 | return c.fail(protocol.ExitDenied, | ||
| 1450 | "%s requires signed commits, so only fast-forward merges are allowed; rebase %s onto %s locally, re-push, and merge again", | ||
| 1451 | repo.Path(), mr.SourceRef, mr.TargetRef) | ||
| 1452 | } | 1432 | } |
| 1453 | strategy = "ff" | 1433 | } |
| 1454 | commits, err := gitutil.RevListRange(dir, targetSHA, headSHA) | 1434 | p.chooseStrategy() |
| 1435 | if code := c.mergerIdentity(p); code >= 0 { | ||
| 1436 | return code | ||
| 1437 | } | ||
| 1438 | newSHA, code := c.mergedCommit(p) | ||
| 1439 | if code >= 0 { | ||
| 1440 | return code | ||
| 1441 | } | ||
| 1442 | stack, code := c.stackForMerge(p) | ||
| 1443 | if code >= 0 { | ||
| 1444 | return code | ||
| 1445 | } | ||
| 1446 | |||
| 1447 | // CAS so a concurrent push between our read and this write fails the | ||
| 1448 | // merge instead of silently discarding the push. | ||
| 1449 | if err := gitutil.UpdateRefCAS(p.dir, p.targetRef, newSHA, p.targetSHA); err != nil { | ||
| 1450 | return c.fail(protocol.ExitFailure, "target branch moved during merge; retry: %v", err) | ||
| 1451 | } | ||
| 1452 | if err := c.Store.MarkMerged(mr.ID, p.targetSHA, newSHA, c.User.ID, ""); err != nil { | ||
| 1453 | return c.fail(protocol.ExitFailure, "%v", err) | ||
| 1454 | } | ||
| 1455 | c.Store.RecordEvent(repo.ID, c.User.ID, "mr.merged", fmt.Sprintf(`{"number":%d,"sha":%q}`, mr.Number, newSHA)) | ||
| 1456 | MarkLandedMRs(c.Store, c.Cfg, repo, c.User.ID, mr.TargetRef, p.targetSHA, newSHA) | ||
| 1457 | c.retargetStack(p, stack) | ||
| 1458 | c.afterMerge(p, newSHA) | ||
| 1459 | return c.emit(map[string]any{"number": mr.Number, "strategy": p.strategy, "sha": newSHA}, func(w io.Writer) { | ||
| 1460 | fmt.Fprintf(w, "merged %s!%d into %s (%s) at %.10s\n", repo.Path(), mr.Number, mr.TargetRef, p.strategy, newSHA) | ||
| 1461 | }) | ||
| 1462 | } | ||
| 1463 | |||
| 1464 | // mergePlan is a merge in progress: what is merged where, how, and as whom. | ||
| 1465 | type mergePlan struct { | ||
| 1466 | repo store.Repo | ||
| 1467 | mr store.MR | ||
| 1468 | dir, targetRef string | ||
| 1469 | targetSHA, headSHA string | ||
| 1470 | ffPossible bool | ||
| 1471 | strategy, mergerEmail string | ||
| 1472 | } | ||
| 1473 | |||
| 1474 | // recordAlreadyMerged handles a head that is already on the target: merged | ||
| 1475 | // by hand and pushed, or a merge whose ref update landed and whose record | ||
| 1476 | // did not. Recording it rather than refusing means a merge request cannot be | ||
| 1477 | // stuck open with no way to close it as merged (#108). | ||
| 1478 | func (c *Ctx) recordAlreadyMerged(p *mergePlan) int { | ||
| 1479 | mr := p.mr | ||
| 1480 | if err := c.Store.MarkMerged(mr.ID, p.targetSHA, p.headSHA, c.User.ID, ""); err != nil { | ||
| 1481 | return c.fail(protocol.ExitFailure, "%v", err) | ||
| 1482 | } | ||
| 1483 | c.Store.RecordEvent(p.repo.ID, c.User.ID, "mr.merged", fmt.Sprintf(`{"number":%d}`, mr.Number)) | ||
| 1484 | return c.emit(map[string]any{"number": mr.Number, "strategy": "recorded", "sha": p.headSHA}, func(w io.Writer) { | ||
| 1485 | fmt.Fprintf(w, "%s already contains !%d; recorded as merged at %.10s\n", mr.TargetRef, mr.Number, p.headSHA) | ||
| 1486 | }) | ||
| 1487 | } | ||
| 1488 | |||
| 1489 | // requireSignedMerge applies the signature policy matrix: with | ||
| 1490 | // require_signed_commits, only fast-forward is allowed — squash, | ||
| 1491 | // rebase-replay, and merge commits are all server-created and unsigned, | ||
| 1492 | // violating the branch's own policy — and every landed commit must be | ||
| 1493 | // verified. An explicit rebase when fast-forward is already possible IS a | ||
| 1494 | // fast-forward (nothing is rewritten), so it stays legal. Returns -1 to | ||
| 1495 | // proceed, with the strategy set to fast-forward. | ||
| 1496 | func (c *Ctx) requireSignedMerge(p *mergePlan) int { | ||
| 1497 | repo, mr := p.repo, p.mr | ||
| 1498 | if c.Source == queueSource && !p.ffPossible { | ||
| 1499 | return c.fail(protocol.ExitDenied, | ||
| 1500 | "%s is behind %s and %s requires signed commits, so the server cannot rebase it; rebase and push, and the merge stays queued", | ||
| 1501 | mr.SourceRef, mr.TargetRef, repo.Path()) | ||
| 1502 | } | ||
| 1503 | if p.strategy == "merge" || p.strategy == "squash" || !p.ffPossible { | ||
| 1504 | return c.fail(protocol.ExitDenied, | ||
| 1505 | "%s requires signed commits, so only fast-forward merges are allowed; rebase %s onto %s locally, re-push, and merge again", | ||
| 1506 | repo.Path(), mr.SourceRef, mr.TargetRef) | ||
| 1507 | } | ||
| 1508 | p.strategy = "ff" | ||
| 1509 | commits, err := gitutil.RevListRange(p.dir, p.targetSHA, p.headSHA) | ||
| 1510 | if err != nil { | ||
| 1511 | return c.fail(protocol.ExitFailure, "%v", err) | ||
| 1512 | } | ||
| 1513 | for _, sha := range commits { | ||
| 1514 | state, err := c.commitSignatureState(repo, p.dir, sha) | ||
| 1455 | if err != nil { | 1515 | if err != nil { |
| 1456 | return c.fail(protocol.ExitFailure, "%v", err) | 1516 | return c.fail(protocol.ExitFailure, "%v", err) |
| 1457 | } | 1517 | } |
| 1458 | for _, sha := range commits { | 1518 | if state != "verified" { |
| 1459 | raw, err := gitutil.ReadCommit(dir, sha) | 1519 | return c.fail(protocol.ExitDenied, |
| 1460 | if err != nil { | 1520 | "%s requires signed commits: %.10s is %s", repo.Path(), sha, state) |
| 1461 | return c.fail(protocol.ExitFailure, "%v", err) | ||
| 1462 | } | ||
| 1463 | parsed, err := sigParse(raw) | ||
| 1464 | if err != nil { | ||
| 1465 | return c.fail(protocol.ExitFailure, "%v", err) | ||
| 1466 | } | ||
| 1467 | res, err := VerifyCommitCached(c.Store, repo, parsed, sha) | ||
| 1468 | if err != nil { | ||
| 1469 | return c.fail(protocol.ExitFailure, "%v", err) | ||
| 1470 | } | ||
| 1471 | if res.State != "verified" { | ||
| 1472 | return c.fail(protocol.ExitDenied, | ||
| 1473 | "%s requires signed commits: %.10s is %s", repo.Path(), sha, res.State) | ||
| 1474 | } | ||
| 1475 | } | 1521 | } |
| 1476 | } | 1522 | } |
| 1477 | if strategy == "" { | 1523 | return -1 |
| 1478 | if ffPossible { | 1524 | } |
| 1479 | strategy = "ff" | 1525 | |
| 1526 | // commitSignatureState is a commit's signature verification state, such as "verified". | ||
| 1527 | func (c *Ctx) commitSignatureState(repo store.Repo, dir, sha string) (sig.State, error) { | ||
| 1528 | raw, err := gitutil.ReadCommit(dir, sha) | ||
| 1529 | if err != nil { | ||
| 1530 | return "", err | ||
| 1531 | } | ||
| 1532 | parsed, err := sigParse(raw) | ||
| 1533 | if err != nil { | ||
| 1534 | return "", err | ||
| 1535 | } | ||
| 1536 | res, err := VerifyCommitCached(c.Store, repo, parsed, sha) | ||
| 1537 | if err != nil { | ||
| 1538 | return "", err | ||
| 1539 | } | ||
| 1540 | return res.State, nil | ||
| 1541 | } | ||
| 1542 | |||
| 1543 | // chooseStrategy fills in the default strategy: fast-forward when possible, | ||
| 1544 | // otherwise a merge commit. A rebase onto an ancestor has nothing to | ||
| 1545 | // rewrite, so it is a fast-forward, which keeps the original commits and | ||
| 1546 | // their signatures. | ||
| 1547 | func (p *mergePlan) chooseStrategy() { | ||
| 1548 | if p.strategy == "" { | ||
| 1549 | if p.ffPossible { | ||
| 1550 | p.strategy = "ff" | ||
| 1480 | } else { | 1551 | } else { |
| 1481 | strategy = "merge" | 1552 | p.strategy = "merge" |
| 1482 | } | 1553 | } |
| 1483 | } | 1554 | } |
| 1484 | if strategy == "rebase" && ffPossible { | 1555 | if p.strategy == "rebase" && p.ffPossible { |
| 1485 | // Nothing to rewrite: a rebase onto an ancestor is a fast-forward, | 1556 | p.strategy = "ff" |
| 1486 | // and taking it keeps the original commits and their signatures. | ||
| 1487 | strategy = "ff" | ||
| 1488 | } | 1557 | } |
| 1558 | } | ||
| 1489 | 1559 | ||
| 1490 | // Every server-created commit needs the merger's verified identity. | 1560 | // mergerIdentity sets the email every server-created commit is committed |
| 1491 | mergerEmail := "" | 1561 | // under: the merger's verified primary one. Returns -1 to proceed. |
| 1492 | if strategy != "ff" { | 1562 | func (c *Ctx) mergerIdentity(p *mergePlan) int { |
| 1493 | email, err := c.Store.PrimaryVerifiedEmail(c.User.ID) | 1563 | if p.strategy == "ff" { |
| 1494 | if err != nil { | 1564 | return -1 |
| 1495 | return c.fail(protocol.ExitFailure, "%v", err) | 1565 | } |
| 1496 | } | 1566 | email, err := c.Store.PrimaryVerifiedEmail(c.User.ID) |
| 1497 | if email == "" { | 1567 | if err != nil { |
| 1498 | return c.fail(protocol.ExitDenied, | 1568 | return c.fail(protocol.ExitFailure, "%v", err) |
| 1499 | "%s merges create commits carrying your identity: verify a primary email first (or use a fast-forward merge)", strategy) | 1569 | } |
| 1500 | } | 1570 | if email == "" { |
| 1501 | mergerEmail = email | 1571 | return c.fail(protocol.ExitDenied, |
| 1572 | "%s merges create commits carrying your identity: verify a primary email first (or use a fast-forward merge)", p.strategy) | ||
| 1502 | } | 1573 | } |
| 1574 | p.mergerEmail = email | ||
| 1575 | return -1 | ||
| 1576 | } | ||
| 1503 | 1577 | ||
| 1504 | var newSHA string | 1578 | // mergedCommit is the commit the target moves to under the plan's strategy. |
| 1505 | switch strategy { | 1579 | // The code is -1 unless the merge is refused. |
| 1580 | func (c *Ctx) mergedCommit(p *mergePlan) (string, int) { | ||
| 1581 | switch p.strategy { | ||
| 1506 | case "ff": | 1582 | case "ff": |
| 1507 | if !ffPossible { | 1583 | if !p.ffPossible { |
| 1508 | return c.fail(protocol.ExitUsage, | 1584 | return "", c.fail(protocol.ExitUsage, |
| 1509 | "fast-forward not possible: %s has diverged from the MR head; merge with the merge strategy, or rebase and push again", mr.TargetRef) | 1585 | "fast-forward not possible: %s has diverged from the MR head; merge with the merge strategy, or rebase and push again", p.mr.TargetRef) |
| 1510 | } | 1586 | } |
| 1511 | newSHA = headSHA | 1587 | return p.headSHA, -1 |
| 1512 | |||
| 1513 | case "merge": | 1588 | case "merge": |
| 1514 | tree, conflict, err := gitutil.MergeTree(dir, targetSHA, headSHA) | 1589 | return c.mergeCommit(p) |
| 1590 | case "squash": | ||
| 1591 | return c.squashCommit(p) | ||
| 1592 | case "rebase": | ||
| 1593 | return c.rebaseCommits(p) | ||
| 1594 | } | ||
| 1595 | return "", -1 | ||
| 1596 | } | ||
| 1597 | |||
| 1598 | // mergedTree is the tree of the target and head merged, refusing on conflict. | ||
| 1599 | func (c *Ctx) mergedTree(p *mergePlan) (string, int) { | ||
| 1600 | tree, conflict, err := gitutil.MergeTree(p.dir, p.targetSHA, p.headSHA) | ||
| 1601 | if err != nil { | ||
| 1602 | return "", c.fail(protocol.ExitFailure, "%v", err) | ||
| 1603 | } | ||
| 1604 | if conflict { | ||
| 1605 | return "", c.fail(protocol.ExitUsage, | ||
| 1606 | "merge conflicts between %s and the MR head; resolve locally and re-push", p.mr.TargetRef) | ||
| 1607 | } | ||
| 1608 | return tree, -1 | ||
| 1609 | } | ||
| 1610 | |||
| 1611 | func (c *Ctx) mergeCommit(p *mergePlan) (string, int) { | ||
| 1612 | tree, code := c.mergedTree(p) | ||
| 1613 | if code >= 0 { | ||
| 1614 | return "", code | ||
| 1615 | } | ||
| 1616 | mr := p.mr | ||
| 1617 | msg := fmt.Sprintf("Merge request !%d: %s\n\nMerged %s into %s", mr.Number, mr.Title, mr.SourceRef, mr.TargetRef) | ||
| 1618 | sha, err := gitutil.CommitTree(p.dir, tree, []string{p.targetSHA, p.headSHA}, c.User.Username, p.mergerEmail, msg) | ||
| 1619 | if err != nil { | ||
| 1620 | return "", c.fail(protocol.ExitFailure, "%v", err) | ||
| 1621 | } | ||
| 1622 | return sha, -1 | ||
| 1623 | } | ||
| 1624 | |||
| 1625 | // squashCommit is one new commit with the merged tree. Authorship credit | ||
| 1626 | // goes to the MR author (their verified identity when they have one); the | ||
| 1627 | // committer is the merger. | ||
| 1628 | func (c *Ctx) squashCommit(p *mergePlan) (string, int) { | ||
| 1629 | var tree string | ||
| 1630 | if p.ffPossible { | ||
| 1631 | t, err := gitutil.ResolveTree(p.dir, p.headSHA) | ||
| 1515 | if err != nil { | 1632 | if err != nil { |
| 1516 | return c.fail(protocol.ExitFailure, "%v", err) | 1633 | return "", c.fail(protocol.ExitFailure, "%v", err) |
| 1517 | } | 1634 | } |
| 1518 | if conflict { | 1635 | tree = t |
| 1519 | return c.fail(protocol.ExitUsage, | 1636 | } else { |
| 1520 | "merge conflicts between %s and the MR head; resolve locally and re-push", mr.TargetRef) | 1637 | t, code := c.mergedTree(p) |
| 1638 | if code >= 0 { | ||
| 1639 | return "", code | ||
| 1521 | } | 1640 | } |
| 1522 | msg := fmt.Sprintf("Merge request !%d: %s\n\nMerged %s into %s", mr.Number, mr.Title, mr.SourceRef, mr.TargetRef) | 1641 | tree = t |
| 1523 | newSHA, err = gitutil.CommitTree(dir, tree, []string{targetSHA, headSHA}, c.User.Username, mergerEmail, msg) | 1642 | } |
| 1524 | if err != nil { | 1643 | mr := p.mr |
| 1525 | return c.fail(protocol.ExitFailure, "%v", err) | 1644 | authorName, authorEmail := c.User.Username, p.mergerEmail |
| 1645 | if author, err := c.Store.UserByUsername(mr.Author); err == nil { | ||
| 1646 | if ae, err := c.Store.PrimaryVerifiedEmail(author.ID); err == nil && ae != "" { | ||
| 1647 | authorName, authorEmail = author.Username, ae | ||
| 1526 | } | 1648 | } |
| 1649 | } | ||
| 1650 | msg := fmt.Sprintf("%s (!%d)", mr.Title, mr.Number) | ||
| 1651 | if mr.Body != "" { | ||
| 1652 | msg += "\n\n" + mr.Body | ||
| 1653 | } | ||
| 1654 | sha, err := gitutil.CommitTreeIdent(p.dir, tree, []string{p.targetSHA}, | ||
| 1655 | authorName, authorEmail, "", c.User.Username, p.mergerEmail, msg) | ||
| 1656 | if err != nil { | ||
| 1657 | return "", c.fail(protocol.ExitFailure, "%v", err) | ||
| 1658 | } | ||
| 1659 | return sha, -1 | ||
| 1660 | } | ||
| 1527 | 1661 | ||
| 1528 | case "squash": | 1662 | // rebaseCommits replays the merge request's commits, oldest first, onto the |
| 1529 | // One new commit with the merged tree. Authorship credit goes to | 1663 | // target, keeping each one's author. |
| 1530 | // the MR author (their verified identity when they have one); the | 1664 | func (c *Ctx) rebaseCommits(p *mergePlan) (string, int) { |
| 1531 | // committer is the merger. | 1665 | commits, err := gitutil.RevListRange(p.dir, p.targetSHA, p.headSHA) |
| 1532 | tree := "" | 1666 | if err != nil { |
| 1533 | if ffPossible { | 1667 | return "", c.fail(protocol.ExitFailure, "%v", err) |
| 1534 | t, err := gitutil.ResolveTree(dir, headSHA) | 1668 | } |
| 1535 | if err != nil { | 1669 | slices.Reverse(commits) |
| 1536 | return c.fail(protocol.ExitFailure, "%v", err) | 1670 | onto := p.targetSHA |
| 1537 | } | 1671 | for _, sha := range commits { |
| 1538 | tree = t | 1672 | next, code := c.replayCommit(p, sha, onto) |
| 1539 | } else { | 1673 | if code >= 0 { |
| 1540 | t, conflict, err := gitutil.MergeTree(dir, targetSHA, headSHA) | 1674 | return "", code |
| 1541 | if err != nil { | ||
| 1542 | return c.fail(protocol.ExitFailure, "%v", err) | ||
| 1543 | } | ||
| 1544 | if conflict { | ||
| 1545 | return c.fail(protocol.ExitUsage, | ||
| 1546 | "merge conflicts between %s and the MR head; resolve locally and re-push", mr.TargetRef) | ||
| 1547 | } | ||
| 1548 | tree = t | ||
| 1549 | } | ||
| 1550 | authorName, authorEmail := c.User.Username, mergerEmail | ||
| 1551 | if author, err := c.Store.UserByUsername(mr.Author); err == nil { | ||
| 1552 | if ae, err := c.Store.PrimaryVerifiedEmail(author.ID); err == nil && ae != "" { | ||
| 1553 | authorName, authorEmail = author.Username, ae | ||
| 1554 | } | ||
| 1555 | } | ||
| 1556 | msg := fmt.Sprintf("%s (!%d)", mr.Title, mr.Number) | ||
| 1557 | if mr.Body != "" { | ||
| 1558 | msg += "\n\n" + mr.Body | ||
| 1559 | } | ||
| 1560 | var err error | ||
| 1561 | newSHA, err = gitutil.CommitTreeIdent(dir, tree, []string{targetSHA}, | ||
| 1562 | authorName, authorEmail, "", c.User.Username, mergerEmail, msg) | ||
| 1563 | if err != nil { | ||
| 1564 | return c.fail(protocol.ExitFailure, "%v", err) | ||
| 1565 | } | 1675 | } |
| 1676 | onto = next | ||
| 1677 | } | ||
| 1678 | return onto, -1 | ||
| 1679 | } | ||
| 1566 | 1680 | ||
| 1567 | case "rebase": | 1681 | // replayCommit applies one commit onto `onto` as a new commit with its |
| 1568 | commits, err := gitutil.RevListRange(dir, targetSHA, headSHA) | 1682 | // author, message and date, committed by the merger. |
| 1569 | if err != nil { | 1683 | func (c *Ctx) replayCommit(p *mergePlan, sha, onto string) (string, int) { |
| 1570 | return c.fail(protocol.ExitFailure, "%v", err) | 1684 | parents, err := gitutil.CommitParents(p.dir, sha) |
| 1571 | } | 1685 | if err != nil { |
| 1572 | // Oldest first. | 1686 | return "", c.fail(protocol.ExitFailure, "%v", err) |
| 1573 | for i, j := 0, len(commits)-1; i < j; i, j = i+1, j-1 { | 1687 | } |
| 1574 | commits[i], commits[j] = commits[j], commits[i] | 1688 | if len(parents) > 1 { |
| 1575 | } | 1689 | return "", c.fail(protocol.ExitUsage, |
| 1576 | onto := targetSHA | 1690 | "the MR contains merge commit %.10s; a rebase merge needs linear history — choose the merge or squash strategy", sha) |
| 1577 | for _, sha := range commits { | ||
| 1578 | parents, err := gitutil.CommitParents(dir, sha) | ||
| 1579 | if err != nil { | ||
| 1580 | return c.fail(protocol.ExitFailure, "%v", err) | ||
| 1581 | } | ||
| 1582 | if len(parents) > 1 { | ||
| 1583 | return c.fail(protocol.ExitUsage, | ||
| 1584 | "the MR contains merge commit %.10s; a rebase merge needs linear history — choose the merge or squash strategy", sha) | ||
| 1585 | } | ||
| 1586 | base := onto // root commit: replay against the new tip itself | ||
| 1587 | if len(parents) == 1 { | ||
| 1588 | base = parents[0] | ||
| 1589 | } | ||
| 1590 | tree, conflict, err := gitutil.MergeTreeOnto(dir, base, onto, sha) | ||
| 1591 | if err != nil { | ||
| 1592 | return c.fail(protocol.ExitFailure, "%v", err) | ||
| 1593 | } | ||
| 1594 | if conflict { | ||
| 1595 | return c.fail(protocol.ExitUsage, | ||
| 1596 | "commit %.10s does not apply cleanly onto %s; rebase locally and re-push", sha, mr.TargetRef) | ||
| 1597 | } | ||
| 1598 | aName, aEmail, aDate, err := gitutil.AuthorIdent(dir, sha) | ||
| 1599 | if err != nil { | ||
| 1600 | return c.fail(protocol.ExitFailure, "%v", err) | ||
| 1601 | } | ||
| 1602 | msg, err := gitutil.CommitMessage(dir, sha) | ||
| 1603 | if err != nil { | ||
| 1604 | return c.fail(protocol.ExitFailure, "%v", err) | ||
| 1605 | } | ||
| 1606 | onto, err = gitutil.CommitTreeIdent(dir, tree, []string{onto}, | ||
| 1607 | aName, aEmail, aDate, c.User.Username, mergerEmail, msg) | ||
| 1608 | if err != nil { | ||
| 1609 | return c.fail(protocol.ExitFailure, "%v", err) | ||
| 1610 | } | ||
| 1611 | } | ||
| 1612 | newSHA = onto | ||
| 1613 | } | 1691 | } |
| 1692 | base := onto // root commit: replay against the new tip itself | ||
| 1693 | if len(parents) == 1 { | ||
| 1694 | base = parents[0] | ||
| 1695 | } | ||
| 1696 | tree, conflict, err := gitutil.MergeTreeOnto(p.dir, base, onto, sha) | ||
| 1697 | if err != nil { | ||
| 1698 | return "", c.fail(protocol.ExitFailure, "%v", err) | ||
| 1699 | } | ||
| 1700 | if conflict { | ||
| 1701 | return "", c.fail(protocol.ExitUsage, | ||
| 1702 | "commit %.10s does not apply cleanly onto %s; rebase locally and re-push", sha, p.mr.TargetRef) | ||
| 1703 | } | ||
| 1704 | aName, aEmail, aDate, err := gitutil.AuthorIdent(p.dir, sha) | ||
| 1705 | if err != nil { | ||
| 1706 | return "", c.fail(protocol.ExitFailure, "%v", err) | ||
| 1707 | } | ||
| 1708 | msg, err := gitutil.CommitMessage(p.dir, sha) | ||
| 1709 | if err != nil { | ||
| 1710 | return "", c.fail(protocol.ExitFailure, "%v", err) | ||
| 1711 | } | ||
| 1712 | next, err := gitutil.CommitTreeIdent(p.dir, tree, []string{onto}, | ||
| 1713 | aName, aEmail, aDate, c.User.Username, p.mergerEmail, msg) | ||
| 1714 | if err != nil { | ||
| 1715 | return "", c.fail(protocol.ExitFailure, "%v", err) | ||
| 1716 | } | ||
| 1717 | return next, -1 | ||
| 1718 | } | ||
| 1614 | 1719 | ||
| 1615 | // A stacked merge request's diff is against this branch. After a | 1720 | // stackForMerge is the merge requests stacked on this one. A stacked merge |
| 1616 | // fast-forward or merge commit the same commits are on the target and | 1721 | // request's diff is against this branch. After a fast-forward or merge |
| 1617 | // its diff is unchanged there; after a squash or rebase they are not, | 1722 | // commit the same commits are on the target and its diff is unchanged |
| 1618 | // and the stack would carry this merge request's changes a second | 1723 | // there; after a squash or rebase they are not, and the stack would carry |
| 1619 | // time. Refuse rather than leave the stack wrong. | 1724 | // this merge request's changes a second time. Refuse rather than leave the |
| 1725 | // stack wrong. | ||
| 1726 | func (c *Ctx) stackForMerge(p *mergePlan) ([]store.MR, int) { | ||
| 1727 | mr := p.mr | ||
| 1620 | var stack []store.MR | 1728 | var stack []store.MR |
| 1621 | if mr.SourceRepoID == repo.ID { | 1729 | if mr.SourceRepoID == p.repo.ID { |
| 1622 | stack, _ = c.Store.OpenMRsByTarget(repo.ID, mr.SourceRef) | 1730 | stack, _ = c.Store.OpenMRsByTarget(p.repo.ID, mr.SourceRef) |
| 1623 | } | 1731 | } |
| 1624 | if len(stack) > 0 && (strategy == "squash" || strategy == "rebase") { | 1732 | if len(stack) > 0 && (p.strategy == "squash" || p.strategy == "rebase") { |
| 1625 | var nums []string | 1733 | var nums []string |
| 1626 | for _, k := range stack { | 1734 | for _, k := range stack { |
| 1627 | nums = append(nums, fmt.Sprintf("!%d", k.Number)) | 1735 | nums = append(nums, fmt.Sprintf("!%d", k.Number)) |
| 1628 | } | 1736 | } |
| 1629 | return c.fail(protocol.ExitUsage, | 1737 | return nil, c.fail(protocol.ExitUsage, |
| 1630 | "%s is stacked on by %s; a %s merge rewrites the commits they build on. Merge with the fast-forward or merge strategy, or merge the stack into %s first", | 1738 | "%s is stacked on by %s; a %s merge rewrites the commits they build on. Merge with the fast-forward or merge strategy, or merge the stack into %s first", |
| 1631 | fmt.Sprintf("!%d", mr.Number), strings.Join(nums, ", "), strategy, mr.SourceRef) | 1739 | fmt.Sprintf("!%d", mr.Number), strings.Join(nums, ", "), p.strategy, mr.SourceRef) |
| 1632 | } | 1740 | } |
| 1741 | return stack, -1 | ||
| 1742 | } | ||
| 1633 | 1743 | ||
| 1634 | // CAS so a concurrent push between our read and this write fails the | 1744 | // retargetStack moves the stack up: whatever targeted this branch now |
| 1635 | // merge instead of silently discarding the push. | 1745 | // targets what it merged into, reviews intact, since that diff is the one |
| 1636 | if err := gitutil.UpdateRefCAS(dir, targetRef, newSHA, targetSHA); err != nil { | 1746 | // they were of. |
| 1637 | return c.fail(protocol.ExitFailure, "target branch moved during merge; retry: %v", err) | 1747 | func (c *Ctx) retargetStack(p *mergePlan, stack []store.MR) { |
| 1638 | } | 1748 | repo, mr := p.repo, p.mr |
| 1639 | if err := c.Store.MarkMerged(mr.ID, targetSHA, newSHA, c.User.ID, ""); err != nil { | ||
| 1640 | return c.fail(protocol.ExitFailure, "%v", err) | ||
| 1641 | } | ||
| 1642 | c.Store.RecordEvent(repo.ID, c.User.ID, "mr.merged", fmt.Sprintf(`{"number":%d,"sha":%q}`, mr.Number, newSHA)) | ||
| 1643 | MarkLandedMRs(c.Store, c.Cfg, repo, c.User.ID, mr.TargetRef, targetSHA, newSHA) | ||
| 1644 | // The stack moves up: whatever targeted this branch now targets what | ||
| 1645 | // it merged into, reviews intact, since that diff is the one they | ||
| 1646 | // were of. | ||
| 1647 | for _, k := range stack { | 1749 | for _, k := range stack { |
| 1648 | if err := c.Store.RetargetKeepingReviews(k.ID, mr.TargetRef); err != nil { | 1750 | if err := c.Store.RetargetKeepingReviews(k.ID, mr.TargetRef); err != nil { |
| 1649 | continue | 1751 | continue |
| @@ -1656,14 +1758,19 @@ func mergeMR(c *Ctx, repo store.Repo, mr store.MR, strategy string) int { | |||
| 1656 | path: fmt.Sprintf("%s/mrs/%d", repo.Path(), k.Number)}) | 1758 | path: fmt.Sprintf("%s/mrs/%d", repo.Path(), k.Number)}) |
| 1657 | } | 1759 | } |
| 1658 | } | 1760 | } |
| 1761 | } | ||
| 1762 | |||
| 1763 | // afterMerge does the work a push of the target would have done. | ||
| 1764 | func (c *Ctx) afterMerge(p *mergePlan, newSHA string) { | ||
| 1765 | repo, mr := p.repo, p.mr | ||
| 1659 | // Merges bypass receive-pack, so the commit-message issue actions | 1766 | // Merges bypass receive-pack, so the commit-message issue actions |
| 1660 | // (closes #N, references) run here for the newly landed commits. The | 1767 | // (closes #N, references) run here for the newly landed commits. The |
| 1661 | // description is scanned after them, so a commit wins the attribution | 1768 | // description is scanned after them, so a commit wins the attribution |
| 1662 | // when both name the same issue. | 1769 | // when both name the same issue. |
| 1663 | if mr.TargetRef == repo.DefaultBranch { | 1770 | if mr.TargetRef == repo.DefaultBranch { |
| 1664 | ProcessCommitMessages(c.Store, dir, repo, c.User.ID, c.Scope, targetSHA, newSHA) | 1771 | ProcessCommitMessages(c.Store, p.dir, repo, c.User.ID, c.Scope, p.targetSHA, newSHA) |
| 1665 | ProcessMRDescription(c.Store, repo, mr, c.User.ID, c.Scope) | 1772 | ProcessMRDescription(c.Store, repo, mr, c.User.ID, c.Scope) |
| 1666 | RecordLandedCommits(c.Store, dir, repo, targetSHA, newSHA) | 1773 | RecordLandedCommits(c.Store, p.dir, repo, p.targetSHA, newSHA) |
| 1667 | c.Store.RequestSymbolIndex(repo.ID, false) | 1774 | c.Store.RequestSymbolIndex(repo.ID, false) |
| 1668 | } | 1775 | } |
| 1669 | // A merge moves the ref directly, so it never reaches post-receive and | 1776 | // A merge moves the ref directly, so it never reaches post-receive and |
| @@ -1671,19 +1778,16 @@ func mergeMR(c *Ctx, repo store.Repo, mr store.MR, strategy string) int { | |||
| 1671 | // subscribe to, and the branch's CI jobs, happen here instead. | 1778 | // subscribe to, and the branch's CI jobs, happen here instead. |
| 1672 | c.Store.RecordEvent(repo.ID, c.User.ID, "push", fmt.Sprintf( | 1779 | c.Store.RecordEvent(repo.ID, c.User.ID, "push", fmt.Sprintf( |
| 1673 | `{"ref":%q,"old":%q,"new":%q,"forced":false,"deleted":false}`, | 1780 | `{"ref":%q,"old":%q,"new":%q,"forced":false,"deleted":false}`, |
| 1674 | targetRef, targetSHA, newSHA)) | 1781 | p.targetRef, p.targetSHA, newSHA)) |
| 1675 | QueueBranchBuilds(c.Store, c.Cfg.Server.Root, c.Cfg.Server.SiteURL, | 1782 | QueueBranchBuilds(c.Store, c.Cfg.Server.Root, c.Cfg.Server.SiteURL, |
| 1676 | repo, c.User.ID, mr.TargetRef, targetSHA, newSHA, time.Now()) | 1783 | repo, c.User.ID, mr.TargetRef, p.targetSHA, newSHA, time.Now()) |
| 1677 | c.Store.MarkMirrorsDirty(repo.ID, "push") | 1784 | c.Store.MarkMirrorsDirty(repo.ID, "push") |
| 1678 | if parts, err := c.Store.MRParticipants(mr.ID); err == nil { | 1785 | if parts, err := c.Store.MRParticipants(mr.ID); err == nil { |
| 1679 | notify(c, parts, notice{repo: repo, kind: "mr", number: mr.Number, | 1786 | notify(c, parts, notice{repo: repo, kind: "mr", number: mr.Number, |
| 1680 | subject: mrSubject(repo, mr.Number, mr.Title), | 1787 | subject: mrSubject(repo, mr.Number, mr.Title), |
| 1681 | action: fmt.Sprintf("merged !%d into %s (%s)", mr.Number, mr.TargetRef, strategy), | 1788 | action: fmt.Sprintf("merged !%d into %s (%s)", mr.Number, mr.TargetRef, p.strategy), |
| 1682 | path: fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)}) | 1789 | path: fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)}) |
| 1683 | } | 1790 | } |
| 1684 | return c.emit(map[string]any{"number": mr.Number, "strategy": strategy, "sha": newSHA}, func(w io.Writer) { | ||
| 1685 | fmt.Fprintf(w, "merged %s!%d into %s (%s) at %.10s\n", repo.Path(), mr.Number, mr.TargetRef, strategy, newSHA) | ||
| 1686 | }) | ||
| 1687 | } | 1791 | } |
| 1688 | 1792 | ||
| 1689 | // reviewGates refuses a merge whose gates are not all met, naming every | 1793 | // reviewGates refuses a merge whose gates are not all met, naming every |
| @@ -1746,69 +1850,113 @@ func MergeGates(st *store.Store, repo store.Repo, mr store.MR, dir, targetSHA, h | |||
| 1746 | g := GatesOut{Draft: mr.Draft, ApprovalsRequired: set.RequireApprovals, | 1850 | g := GatesOut{Draft: mr.Draft, ApprovalsRequired: set.RequireApprovals, |
| 1747 | CodeownersRequired: set.RequireCodeowners, ResolvedRequired: set.RequireResolved, | 1851 | CodeownersRequired: set.RequireCodeowners, ResolvedRequired: set.RequireResolved, |
| 1748 | ChecksRequired: set.RequireChecks} | 1852 | ChecksRequired: set.RequireChecks} |
| 1853 | in := gateInputs{st: st, repo: repo, mr: mr, dir: dir, targetSHA: targetSHA, headSHA: headSHA} | ||
| 1749 | // A draft is open but not asking. This gate is unconditional — no | 1854 | // A draft is open but not asking. This gate is unconditional — no |
| 1750 | // setting turns it off — because the author said so themselves. | 1855 | // setting turns it off — because the author said so themselves. |
| 1751 | if mr.Draft { | 1856 | if mr.Draft { |
| 1752 | g.Unmet = append(g.Unmet, fmt.Sprintf("!%d is a draft; `gitbay mr ready %s %d` first", mr.Number, repo.Path(), mr.Number)) | 1857 | g.Unmet = append(g.Unmet, fmt.Sprintf("!%d is a draft; `gitbay mr ready %s %d` first", mr.Number, repo.Path(), mr.Number)) |
| 1753 | } | 1858 | } |
| 1859 | if err := in.checksGate(&g); err != nil { | ||
| 1860 | return g, err | ||
| 1861 | } | ||
| 1862 | if err := in.approvalsGate(&g); err != nil { | ||
| 1863 | return g, err | ||
| 1864 | } | ||
| 1865 | if set.RequireCodeowners { | ||
| 1866 | if err := in.codeownersGate(&g); err != nil { | ||
| 1867 | return g, err | ||
| 1868 | } | ||
| 1869 | } | ||
| 1754 | 1870 | ||
| 1755 | // Checks: with require_checks, every status the head carries must be | 1871 | n, err := st.UnresolvedThreadCount(mr.ID) |
| 1756 | // green, a head something was going to report on must carry some, and | ||
| 1757 | // every required context must have reported: one that has not is | ||
| 1758 | // pending whatever the others say (#258). Setting contexts turns | ||
| 1759 | // require_checks on; turned off again, the list is kept and unread. | ||
| 1760 | statuses, err := st.ListCommitStatuses(repo.ID, headSHA) | ||
| 1761 | if err != nil { | 1872 | if err != nil { |
| 1762 | return g, err | 1873 | return g, err |
| 1763 | } | 1874 | } |
| 1875 | g.OpenThreads = n | ||
| 1876 | if set.RequireResolved && n > 0 { | ||
| 1877 | g.Unmet = append(g.Unmet, fmt.Sprintf("%s requires review threads resolved; !%d has %d open (mr threads %s %d)", repo.Path(), mr.Number, n, repo.Path(), mr.Number)) | ||
| 1878 | } | ||
| 1879 | |||
| 1880 | if ff, err := gitutil.IsAncestor(dir, targetSHA, headSHA); err == nil { | ||
| 1881 | g.FastForward = ff | ||
| 1882 | } | ||
| 1883 | return g, nil | ||
| 1884 | } | ||
| 1885 | |||
| 1886 | // gateInputs is what MergeGates judges a merge request on. | ||
| 1887 | type gateInputs struct { | ||
| 1888 | st *store.Store | ||
| 1889 | repo store.Repo | ||
| 1890 | mr store.MR | ||
| 1891 | dir string | ||
| 1892 | targetSHA, headSHA string | ||
| 1893 | } | ||
| 1894 | |||
| 1895 | // checksGate records the head's combined status. With require_checks, every | ||
| 1896 | // status the head carries must be green, a head something was going to | ||
| 1897 | // report on must carry some, and every required context must have reported: | ||
| 1898 | // one that has not is pending whatever the others say (#258). Setting | ||
| 1899 | // contexts turns require_checks on; turned off again, the list is kept and | ||
| 1900 | // unread. | ||
| 1901 | func (in gateInputs) checksGate(g *GatesOut) error { | ||
| 1902 | statuses, err := in.st.ListCommitStatuses(in.repo.ID, in.headSHA) | ||
| 1903 | if err != nil { | ||
| 1904 | return err | ||
| 1905 | } | ||
| 1764 | g.Checks = store.CombinedStatus(statuses) | 1906 | g.Checks = store.CombinedStatus(statuses) |
| 1765 | if set.RequireChecks { | 1907 | set := in.repo.Settings |
| 1766 | reported := map[string]bool{} | 1908 | if !set.RequireChecks { |
| 1767 | for _, s := range statuses { | 1909 | return nil |
| 1768 | reported[s.Context] = true | 1910 | } |
| 1769 | } | 1911 | reported := map[string]bool{} |
| 1770 | for _, want := range set.RequiredContexts { | 1912 | for _, s := range statuses { |
| 1771 | if !reported[want] { | 1913 | reported[s.Context] = true |
| 1772 | g.ChecksMissing = append(g.ChecksMissing, want) | 1914 | } |
| 1773 | } | 1915 | for _, want := range set.RequiredContexts { |
| 1916 | if !reported[want] { | ||
| 1917 | g.ChecksMissing = append(g.ChecksMissing, want) | ||
| 1774 | } | 1918 | } |
| 1775 | if len(g.ChecksMissing) > 0 && (g.Checks == "" || g.Checks == "success") { | 1919 | } |
| 1776 | g.Checks = "pending" | 1920 | if len(g.ChecksMissing) > 0 && (g.Checks == "" || g.Checks == "success") { |
| 1921 | g.Checks = "pending" | ||
| 1922 | } | ||
| 1923 | switch g.Checks { | ||
| 1924 | case "success": | ||
| 1925 | case "": | ||
| 1926 | if checksExpected(in.st, in.repo.ID, in.dir, in.headSHA) { | ||
| 1927 | g.Unmet = append(g.Unmet, fmt.Sprintf("%s requires green checks and none were reported on %.10s", in.repo.Path(), in.headSHA)) | ||
| 1777 | } | 1928 | } |
| 1778 | switch g.Checks { | 1929 | default: |
| 1779 | case "success": | 1930 | var bad []string |
| 1780 | case "": | 1931 | for _, st := range statuses { |
| 1781 | if checksExpected(st, repo.ID, dir, headSHA) { | 1932 | if st.State != "success" { |
| 1782 | g.Unmet = append(g.Unmet, fmt.Sprintf("%s requires green checks and none were reported on %.10s", repo.Path(), headSHA)) | 1933 | bad = append(bad, st.Context+"="+st.State) |
| 1783 | } | ||
| 1784 | default: | ||
| 1785 | var bad []string | ||
| 1786 | for _, st := range statuses { | ||
| 1787 | if st.State != "success" { | ||
| 1788 | bad = append(bad, st.Context+"="+st.State) | ||
| 1789 | } | ||
| 1790 | } | 1934 | } |
| 1791 | for _, m := range g.ChecksMissing { | ||
| 1792 | bad = append(bad, m+"=missing") | ||
| 1793 | } | ||
| 1794 | g.Unmet = append(g.Unmet, fmt.Sprintf("%s requires green checks; %.10s has %s", repo.Path(), headSHA, strings.Join(bad, ", "))) | ||
| 1795 | } | 1935 | } |
| 1936 | for _, m := range g.ChecksMissing { | ||
| 1937 | bad = append(bad, m+"=missing") | ||
| 1938 | } | ||
| 1939 | g.Unmet = append(g.Unmet, fmt.Sprintf("%s requires green checks; %.10s has %s", in.repo.Path(), in.headSHA, strings.Join(bad, ", "))) | ||
| 1796 | } | 1940 | } |
| 1941 | return nil | ||
| 1942 | } | ||
| 1797 | 1943 | ||
| 1798 | reviews, err := st.ListMRReviews(mr.ID) | 1944 | // approvalsGate records approvals and change requests. The latest fresh |
| 1945 | // review per reviewer decides their stance — but only from someone the | ||
| 1946 | // repository trusts to write to it. Reviewing is open to any reader, which | ||
| 1947 | // is what makes an outside opinion on a public change possible; deciding a | ||
| 1948 | // merge gate is not the same thing, and counting every verdict let anyone | ||
| 1949 | // with an account satisfy require_approvals or block a merge indefinitely | ||
| 1950 | // (#147). | ||
| 1951 | func (in gateInputs) approvalsGate(g *GatesOut) error { | ||
| 1952 | reviews, err := in.st.ListMRReviews(in.mr.ID) | ||
| 1799 | if err != nil { | 1953 | if err != nil { |
| 1800 | return g, err | 1954 | return err |
| 1801 | } | 1955 | } |
| 1802 | // Latest fresh review per reviewer decides their stance — but only | 1956 | counts := ReviewersWhoCount(in.st, in.repo, reviews) |
| 1803 | // from someone the repository trusts to write to it. Reviewing is | ||
| 1804 | // open to any reader, which is what makes an outside opinion on a | ||
| 1805 | // public change possible; deciding a merge gate is not the same | ||
| 1806 | // thing, and counting every verdict let anyone with an account | ||
| 1807 | // satisfy require_approvals or block a merge indefinitely (#147). | ||
| 1808 | counts := ReviewersWhoCount(st, repo, reviews) | ||
| 1809 | latest := map[string]string{} | 1957 | latest := map[string]string{} |
| 1810 | for _, r := range reviews { | 1958 | for _, r := range reviews { |
| 1811 | if r.Stale || r.Reviewer == mr.Author || !counts[r.Reviewer] { | 1959 | if r.Stale || r.Reviewer == in.mr.Author || !counts[r.Reviewer] { |
| 1812 | continue | 1960 | continue |
| 1813 | } | 1961 | } |
| 1814 | latest[r.Reviewer] = r.Verdict | 1962 | latest[r.Reviewer] = r.Verdict |
| @@ -1823,91 +1971,79 @@ func MergeGates(st *store.Store, repo store.Repo, mr store.MR, dir, targetSHA, h | |||
| 1823 | } | 1971 | } |
| 1824 | slices.Sort(g.Approvals) | 1972 | slices.Sort(g.Approvals) |
| 1825 | slices.Sort(g.ChangesRequested) | 1973 | slices.Sort(g.ChangesRequested) |
| 1826 | if set.RequireApprovals > 0 { | 1974 | required := in.repo.Settings.RequireApprovals |
| 1975 | if required > 0 { | ||
| 1827 | if len(g.ChangesRequested) > 0 { | 1976 | if len(g.ChangesRequested) > 0 { |
| 1828 | g.Unmet = append(g.Unmet, fmt.Sprintf("%s requested changes on !%d; resolve their review before merging", strings.Join(g.ChangesRequested, ", "), mr.Number)) | 1977 | g.Unmet = append(g.Unmet, fmt.Sprintf("%s requested changes on !%d; resolve their review before merging", strings.Join(g.ChangesRequested, ", "), in.mr.Number)) |
| 1829 | } | 1978 | } |
| 1830 | if len(g.Approvals) < set.RequireApprovals { | 1979 | if len(g.Approvals) < required { |
| 1831 | g.Unmet = append(g.Unmet, fmt.Sprintf("%s requires %d fresh approval(s); !%d has %d", repo.Path(), set.RequireApprovals, mr.Number, len(g.Approvals))) | 1980 | g.Unmet = append(g.Unmet, fmt.Sprintf("%s requires %d fresh approval(s); !%d has %d", in.repo.Path(), required, in.mr.Number, len(g.Approvals))) |
| 1832 | } | 1981 | } |
| 1833 | } | 1982 | } |
| 1983 | return nil | ||
| 1984 | } | ||
| 1834 | 1985 | ||
| 1835 | // CODEOWNERS: every owned changed file needs an approval from one of | 1986 | // codeownersGate requires every owned changed file to have an approval from |
| 1836 | // its owners. require_codeowners is the opt-in — a repository can | 1987 | // one of its owners. require_codeowners is the opt-in — a repository can |
| 1837 | // carry the file as documentation of who to ask without it gating | 1988 | // carry the file as documentation of who to ask without it gating merges — |
| 1838 | // merges — and it does not wait on require_approvals (#99). | 1989 | // and it does not wait on require_approvals (#99). |
| 1839 | if set.RequireCodeowners { | 1990 | func (in gateInputs) codeownersGate(g *GatesOut) error { |
| 1840 | content, err := gitutil.ReadBlob(dir, "refs/heads/"+mr.TargetRef, "CODEOWNERS", 1<<20) | 1991 | target := "refs/heads/" + in.mr.TargetRef |
| 1841 | if err != nil { | 1992 | content, err := gitutil.ReadBlob(in.dir, target, "CODEOWNERS", 1<<20) |
| 1842 | content, err = gitutil.ReadBlob(dir, "refs/heads/"+mr.TargetRef, ".gitbay/CODEOWNERS", 1<<20) | 1993 | if err != nil { |
| 1843 | } | 1994 | content, err = gitutil.ReadBlob(in.dir, target, ".gitbay/CODEOWNERS", 1<<20) |
| 1844 | if err != nil || len(content) == 0 { | ||
| 1845 | g.Unmet = append(g.Unmet, fmt.Sprintf("%s requires CODEOWNERS approval but %s carries no CODEOWNERS file", repo.Path(), mr.TargetRef)) | ||
| 1846 | } else { | ||
| 1847 | rules := policy.ParseCodeowners(string(content)) | ||
| 1848 | base, err := gitutil.MergeBase(dir, targetSHA, headSHA) | ||
| 1849 | if err != nil { | ||
| 1850 | return g, err | ||
| 1851 | } | ||
| 1852 | files, err := gitutil.DiffFiles(dir, base, headSHA) | ||
| 1853 | if err != nil { | ||
| 1854 | return g, err | ||
| 1855 | } | ||
| 1856 | approved := map[string]bool{} | ||
| 1857 | for _, a := range g.Approvals { | ||
| 1858 | approved[a] = true | ||
| 1859 | } | ||
| 1860 | missing := map[string][]string{} // owner-set key -> paths | ||
| 1861 | var keys []string | ||
| 1862 | for _, f := range files { | ||
| 1863 | owners := policy.OwnersFor(rules, f) | ||
| 1864 | if owners == nil { | ||
| 1865 | continue | ||
| 1866 | } | ||
| 1867 | ok := false | ||
| 1868 | for _, o := range owners { | ||
| 1869 | if approved[o] { | ||
| 1870 | ok = true | ||
| 1871 | break | ||
| 1872 | } | ||
| 1873 | } | ||
| 1874 | if !ok { | ||
| 1875 | key := strings.Join(owners, ",") | ||
| 1876 | if _, seen := missing[key]; !seen { | ||
| 1877 | keys = append(keys, key) | ||
| 1878 | } | ||
| 1879 | missing[key] = append(missing[key], f) | ||
| 1880 | } | ||
| 1881 | } | ||
| 1882 | if len(missing) > 0 { | ||
| 1883 | slices.Sort(keys) | ||
| 1884 | var parts []string | ||
| 1885 | for _, key := range keys { | ||
| 1886 | paths := missing[key] | ||
| 1887 | g.OwnersOutstanding = append(g.OwnersOutstanding, OwnersOut{Files: paths, Owners: strings.Split(key, ",")}) | ||
| 1888 | if len(paths) > 3 { | ||
| 1889 | paths = paths[:3] | ||
| 1890 | } | ||
| 1891 | parts = append(parts, fmt.Sprintf("%s (owned by %s)", strings.Join(paths, ", "), key)) | ||
| 1892 | } | ||
| 1893 | g.Unmet = append(g.Unmet, "CODEOWNERS approval missing for: "+strings.Join(parts, "; ")) | ||
| 1894 | } | ||
| 1895 | } | ||
| 1896 | } | 1995 | } |
| 1897 | 1996 | if err != nil || len(content) == 0 { | |
| 1898 | n, err := st.UnresolvedThreadCount(mr.ID) | 1997 | g.Unmet = append(g.Unmet, fmt.Sprintf("%s requires CODEOWNERS approval but %s carries no CODEOWNERS file", in.repo.Path(), in.mr.TargetRef)) |
| 1998 | return nil | ||
| 1999 | } | ||
| 2000 | base, err := gitutil.MergeBase(in.dir, in.targetSHA, in.headSHA) | ||
| 1899 | if err != nil { | 2001 | if err != nil { |
| 1900 | return g, err | 2002 | return err |
| 1901 | } | 2003 | } |
| 1902 | g.OpenThreads = n | 2004 | files, err := gitutil.DiffFiles(in.dir, base, in.headSHA) |
| 1903 | if set.RequireResolved && n > 0 { | 2005 | if err != nil { |
| 1904 | g.Unmet = append(g.Unmet, fmt.Sprintf("%s requires review threads resolved; !%d has %d open (mr threads %s %d)", repo.Path(), mr.Number, n, repo.Path(), mr.Number)) | 2006 | return err |
| 2007 | } | ||
| 2008 | keys, missing := unapprovedOwners(policy.ParseCodeowners(string(content)), files, g.Approvals) | ||
| 2009 | if len(missing) == 0 { | ||
| 2010 | return nil | ||
| 1905 | } | 2011 | } |
| 2012 | var parts []string | ||
| 2013 | for _, key := range keys { | ||
| 2014 | paths := missing[key] | ||
| 2015 | g.OwnersOutstanding = append(g.OwnersOutstanding, OwnersOut{Files: paths, Owners: strings.Split(key, ",")}) | ||
| 2016 | if len(paths) > 3 { | ||
| 2017 | paths = paths[:3] | ||
| 2018 | } | ||
| 2019 | parts = append(parts, fmt.Sprintf("%s (owned by %s)", strings.Join(paths, ", "), key)) | ||
| 2020 | } | ||
| 2021 | g.Unmet = append(g.Unmet, "CODEOWNERS approval missing for: "+strings.Join(parts, "; ")) | ||
| 2022 | return nil | ||
| 2023 | } | ||
| 1906 | 2024 | ||
| 1907 | if ff, err := gitutil.IsAncestor(dir, targetSHA, headSHA); err == nil { | 2025 | // unapprovedOwners groups the owned files no owner has approved by their |
| 1908 | g.FastForward = ff | 2026 | // owner set, joined with commas: the sorted keys, and the paths under each. |
| 2027 | func unapprovedOwners(rules []policy.CodeownersRule, files, approvals []string) ([]string, map[string][]string) { | ||
| 2028 | approved := map[string]bool{} | ||
| 2029 | for _, a := range approvals { | ||
| 2030 | approved[a] = true | ||
| 1909 | } | 2031 | } |
| 1910 | return g, nil | 2032 | missing := map[string][]string{} // owner-set key -> paths |
| 2033 | var keys []string | ||
| 2034 | for _, f := range files { | ||
| 2035 | owners := policy.OwnersFor(rules, f) | ||
| 2036 | if owners == nil || slices.ContainsFunc(owners, func(o string) bool { return approved[o] }) { | ||
| 2037 | continue | ||
| 2038 | } | ||
| 2039 | key := strings.Join(owners, ",") | ||
| 2040 | if _, seen := missing[key]; !seen { | ||
| 2041 | keys = append(keys, key) | ||
| 2042 | } | ||
| 2043 | missing[key] = append(missing[key], f) | ||
| 2044 | } | ||
| 2045 | slices.Sort(keys) | ||
| 2046 | return keys, missing | ||
| 1911 | } | 2047 | } |
| 1912 | 2048 | ||
| 1913 | func runMRDraft(c *Ctx, args []string) int { return setMRDraft(c, args, true) } | 2049 | func runMRDraft(c *Ctx, args []string) int { return setMRDraft(c, args, true) } |
internal/control/querylang.go +1 −1
| @@ -69,7 +69,7 @@ func queryTokens(s string) (toks []string, quoted []bool, err error) { | |||
| 69 | startQuoted = true | 69 | startQuoted = true |
| 70 | } | 70 | } |
| 71 | in, have = !in, true | 71 | in, have = !in, true |
| 72 | case !in && (r == ' ' || r == '\t' || r == '\n' || r == '\r'): | 72 | case !in && strings.ContainsRune(" \t\n\r", r): |
| 73 | flush() | 73 | flush() |
| 74 | default: | 74 | default: |
| 75 | cur.WriteRune(r) | 75 | cur.WriteRune(r) |
internal/control/repo.go +22 −40
| @@ -1266,10 +1266,12 @@ func runRepoPin(c *Ctx, args []string) int { return setPinned(c, args, true) } | |||
| 1266 | func runRepoUnpin(c *Ctx, args []string) int { return setPinned(c, args, false) } | 1266 | func runRepoUnpin(c *Ctx, args []string) int { return setPinned(c, args, false) } |
| 1267 | 1267 | ||
| 1268 | func setPinned(c *Ctx, args []string, pin bool) int { | 1268 | func setPinned(c *Ctx, args []string, pin bool) int { |
| 1269 | verb := "pin" | 1269 | return setRepoMark(c, args, pin, "pinned", "unpinned", c.Store.PinRepo, c.Store.UnpinRepo) |
| 1270 | if !pin { | 1270 | } |
| 1271 | verb = "unpin" | 1271 | |
| 1272 | } | 1272 | // setRepoMark marks a repository the caller can read with mark, or clears |
| 1273 | // it with unmark; done and undone are the words the output uses. | ||
| 1274 | func setRepoMark(c *Ctx, args []string, on bool, done, undone string, mark, unmark func(userID, repoID int64) error) int { | ||
| 1273 | if len(args) != 1 { | 1275 | if len(args) != 1 { |
| 1274 | return c.usage() | 1276 | return c.usage() |
| 1275 | } | 1277 | } |
| @@ -1277,53 +1279,33 @@ func setPinned(c *Ctx, args []string, pin bool) int { | |||
| 1277 | if code >= 0 { | 1279 | if code >= 0 { |
| 1278 | return code | 1280 | return code |
| 1279 | } | 1281 | } |
| 1280 | if pin { | 1282 | word := done |
| 1281 | if err := c.Store.PinRepo(c.User.ID, repo.ID); err != nil { | 1283 | if on { |
| 1284 | if err := mark(c.User.ID, repo.ID); err != nil { | ||
| 1282 | return c.fail(protocol.ExitFailure, "%v", err) | 1285 | return c.fail(protocol.ExitFailure, "%v", err) |
| 1283 | } | 1286 | } |
| 1284 | } else if err := c.Store.UnpinRepo(c.User.ID, repo.ID); err != nil { | 1287 | } else { |
| 1285 | if errors.Is(err, store.ErrNotFound) { | 1288 | word = undone |
| 1286 | return c.fail(protocol.ExitNotFound, "%s is not pinned", repo.Path()) | 1289 | if err := unmark(c.User.ID, repo.ID); err != nil { |
| 1290 | if errors.Is(err, store.ErrNotFound) { | ||
| 1291 | return c.fail(protocol.ExitNotFound, "%s is not %s", repo.Path(), done) | ||
| 1292 | } | ||
| 1293 | return c.fail(protocol.ExitFailure, "%v", err) | ||
| 1287 | } | 1294 | } |
| 1288 | return c.fail(protocol.ExitFailure, "%v", err) | ||
| 1289 | } | 1295 | } |
| 1290 | return c.emit(map[string]string{verb + "ned": repo.Path()}, func(w io.Writer) { | 1296 | return c.emit(map[string]string{word: repo.Path()}, func(w io.Writer) { |
| 1291 | fmt.Fprintf(w, "%sned %s\n", verb, repo.Path()) | 1297 | fmt.Fprintf(w, "%s %s\n", word, repo.Path()) |
| 1292 | }) | 1298 | }) |
| 1293 | } | 1299 | } |
| 1294 | 1300 | ||
| 1295 | func runRepoBookmark(c *Ctx, args []string) int { return setBookmarked(c, args, true) } | 1301 | func runRepoBookmark(c *Ctx, args []string) int { return setBookmarked(c, args, true) } |
| 1296 | func runRepoUnbookmark(c *Ctx, args []string) int { return setBookmarked(c, args, false) } | 1302 | func runRepoUnbookmark(c *Ctx, args []string) int { return setBookmarked(c, args, false) } |
| 1297 | 1303 | ||
| 1298 | // setBookmarked mirrors setPinned. A bookmark needs only read access — | 1304 | // A bookmark needs only read access — bookmarking is something you do to |
| 1299 | // bookmarking is something you do to someone else's repository, which is | 1305 | // someone else's repository, which is the whole point of it — and a |
| 1300 | // the whole point of it — and a private repository you cannot read is | 1306 | // private repository you cannot read is not found, as everywhere. |
| 1301 | // not found, as everywhere. | ||
| 1302 | func setBookmarked(c *Ctx, args []string, on bool) int { | 1307 | func setBookmarked(c *Ctx, args []string, on bool) int { |
| 1303 | verb := "bookmark" | 1308 | return setRepoMark(c, args, on, "bookmarked", "unbookmarked", c.Store.BookmarkRepo, c.Store.UnbookmarkRepo) |
| 1304 | if !on { | ||
| 1305 | verb = "unbookmark" | ||
| 1306 | } | ||
| 1307 | if len(args) != 1 { | ||
| 1308 | return c.usage() | ||
| 1309 | } | ||
| 1310 | repo, code := resolveRepo(c, args[0], policy.CanRead) | ||
| 1311 | if code >= 0 { | ||
| 1312 | return code | ||
| 1313 | } | ||
| 1314 | if on { | ||
| 1315 | if err := c.Store.BookmarkRepo(c.User.ID, repo.ID); err != nil { | ||
| 1316 | return c.fail(protocol.ExitFailure, "%v", err) | ||
| 1317 | } | ||
| 1318 | } else if err := c.Store.UnbookmarkRepo(c.User.ID, repo.ID); err != nil { | ||
| 1319 | if errors.Is(err, store.ErrNotFound) { | ||
| 1320 | return c.fail(protocol.ExitNotFound, "%s is not bookmarked", repo.Path()) | ||
| 1321 | } | ||
| 1322 | return c.fail(protocol.ExitFailure, "%v", err) | ||
| 1323 | } | ||
| 1324 | return c.emit(map[string]string{verb + "ed": repo.Path()}, func(w io.Writer) { | ||
| 1325 | fmt.Fprintf(w, "%sed %s\n", verb, repo.Path()) | ||
| 1326 | }) | ||
| 1327 | } | 1309 | } |
| 1328 | 1310 | ||
| 1329 | // BookmarkOut is one row of `repo bookmarks`: the repository and how many | 1311 | // BookmarkOut is one row of `repo bookmarks`: the repository and how many |
internal/control/term.go +4 −2
| @@ -326,8 +326,10 @@ func (t Term) paintDiffLine(l string) string { | |||
| 326 | // "1: abc1234 = 1: def5678 subject", either side possibly "-: -------". | 326 | // "1: abc1234 = 1: def5678 subject", either side possibly "-: -------". |
| 327 | func rangePair(l string) bool { | 327 | func rangePair(l string) bool { |
| 328 | f := strings.Fields(l) | 328 | f := strings.Fields(l) |
| 329 | return len(f) >= 5 && strings.HasSuffix(f[0], ":") && strings.HasSuffix(f[3], ":") && | 329 | if len(f) < 5 || len(f[2]) != 1 { |
| 330 | strings.ContainsAny(f[2], "=!<>") && len(f[2]) == 1 | 330 | return false |
| 331 | } | ||
| 332 | return strings.HasSuffix(f[0], ":") && strings.HasSuffix(f[3], ":") && strings.ContainsAny(f[2], "=!<>") | ||
| 331 | } | 333 | } |
| 332 | 334 | ||
| 333 | // toolSGR matches the colour sequences build tools print. | 335 | // toolSGR matches the colour sequences build tools print. |
internal/control/webhook.go +12 −25
| @@ -164,6 +164,12 @@ func runWebhookList(c *Ctx, args []string) int { | |||
| 164 | } | 164 | } |
| 165 | 165 | ||
| 166 | func runWebhookRemove(c *Ctx, args []string) int { | 166 | func runWebhookRemove(c *Ctx, args []string) int { |
| 167 | return runRepoItemAction(c, args, "webhook", c.Store.RemoveWebhook, "removed", "removed webhook %d") | ||
| 168 | } | ||
| 169 | |||
| 170 | // runRepoItemAction runs act on the <owner/name> <id> in args for a repo | ||
| 171 | // admin and reports the id under key, with done as the plain line. | ||
| 172 | func runRepoItemAction(c *Ctx, args []string, noun string, act func(repoID, id int64) error, key, done string) int { | ||
| 167 | if len(args) != 2 { | 173 | if len(args) != 2 { |
| 168 | return c.usage() | 174 | return c.usage() |
| 169 | } | 175 | } |
| @@ -173,16 +179,16 @@ func runWebhookRemove(c *Ctx, args []string) int { | |||
| 173 | } | 179 | } |
| 174 | id, err := strconv.ParseInt(args[1], 10, 64) | 180 | id, err := strconv.ParseInt(args[1], 10, 64) |
| 175 | if err != nil { | 181 | if err != nil { |
| 176 | return c.fail(protocol.ExitUsage, "bad webhook id %q", args[1]) | 182 | return c.fail(protocol.ExitUsage, "bad %s id %q", noun, args[1]) |
| 177 | } | 183 | } |
| 178 | if err := c.Store.RemoveWebhook(repo.ID, id); err != nil { | 184 | if err := act(repo.ID, id); err != nil { |
| 179 | if errors.Is(err, store.ErrNotFound) { | 185 | if errors.Is(err, store.ErrNotFound) { |
| 180 | return c.fail(protocol.ExitNotFound, "no webhook %d on %s", id, repo.Path()) | 186 | return c.fail(protocol.ExitNotFound, "no %s %d on %s", noun, id, repo.Path()) |
| 181 | } | 187 | } |
| 182 | return c.fail(protocol.ExitFailure, "%v", err) | 188 | return c.fail(protocol.ExitFailure, "%v", err) |
| 183 | } | 189 | } |
| 184 | return c.emit(map[string]any{"removed": id}, func(w io.Writer) { | 190 | return c.emit(map[string]any{key: id}, func(w io.Writer) { |
| 185 | fmt.Fprintf(w, "removed webhook %d\n", id) | 191 | fmt.Fprintf(w, done+"\n", id) |
| 186 | }) | 192 | }) |
| 187 | } | 193 | } |
| 188 | 194 | ||
| @@ -265,24 +271,5 @@ func runWebhookDeliveries(c *Ctx, args []string) int { | |||
| 265 | } | 271 | } |
| 266 | 272 | ||
| 267 | func runWebhookRedeliver(c *Ctx, args []string) int { | 273 | func runWebhookRedeliver(c *Ctx, args []string) int { |
| 268 | if len(args) != 2 { | 274 | return runRepoItemAction(c, args, "delivery", c.Store.Redeliver, "requeued", "delivery %d requeued") |
| 269 | return c.usage() | ||
| 270 | } | ||
| 271 | repo, code := resolveRepo(c, args[0], policy.CanAdmin) | ||
| 272 | if code >= 0 { | ||
| 273 | return code | ||
| 274 | } | ||
| 275 | id, err := strconv.ParseInt(args[1], 10, 64) | ||
| 276 | if err != nil { | ||
| 277 | return c.fail(protocol.ExitUsage, "bad delivery id %q", args[1]) | ||
| 278 | } | ||
| 279 | if err := c.Store.Redeliver(repo.ID, id); err != nil { | ||
| 280 | if errors.Is(err, store.ErrNotFound) { | ||
| 281 | return c.fail(protocol.ExitNotFound, "no delivery %d on %s", id, repo.Path()) | ||
| 282 | } | ||
| 283 | return c.fail(protocol.ExitFailure, "%v", err) | ||
| 284 | } | ||
| 285 | return c.emit(map[string]any{"requeued": id}, func(w io.Writer) { | ||
| 286 | fmt.Fprintf(w, "delivery %d requeued\n", id) | ||
| 287 | }) | ||
| 288 | } | 275 | } |
internal/deps/python.go +33 −26
| @@ -37,35 +37,42 @@ func parsePython(read ReadFile) []Dep { | |||
| 37 | } | 37 | } |
| 38 | } | 38 | } |
| 39 | if raw, err := read("pyproject.toml"); err == nil { | 39 | if raw, err := read("pyproject.toml"); err == nil { |
| 40 | var doc struct { | 40 | pyprojectDeps(raw, add) |
| 41 | Project struct { | 41 | } |
| 42 | Dependencies []string `toml:"dependencies"` | 42 | return out |
| 43 | } `toml:"project"` | 43 | } |
| 44 | Tool struct { | 44 | |
| 45 | Poetry struct { | 45 | // pyprojectDeps adds the dependencies a pyproject.toml lists under |
| 46 | Dependencies map[string]any `toml:"dependencies"` | 46 | // [project] and [tool.poetry]. |
| 47 | DevDependencies map[string]any `toml:"dev-dependencies"` | 47 | func pyprojectDeps(raw []byte, add func(name, version string)) { |
| 48 | } `toml:"poetry"` | 48 | var doc struct { |
| 49 | } `toml:"tool"` | 49 | Project struct { |
| 50 | } | 50 | Dependencies []string `toml:"dependencies"` |
| 51 | if toml.Unmarshal(raw, &doc) == nil { | 51 | } `toml:"project"` |
| 52 | for _, spec := range doc.Project.Dependencies { | 52 | Tool struct { |
| 53 | name, version := splitPEP508(spec) | 53 | Poetry struct { |
| 54 | add(name, version) | 54 | Dependencies map[string]any `toml:"dependencies"` |
| 55 | } | 55 | DevDependencies map[string]any `toml:"dev-dependencies"` |
| 56 | poetry := doc.Tool.Poetry | 56 | } `toml:"poetry"` |
| 57 | for _, set := range []map[string]any{poetry.Dependencies, poetry.DevDependencies} { | 57 | } `toml:"tool"` |
| 58 | for name, spec := range set { | 58 | } |
| 59 | // Poetry shares Cargo's two forms: a bare string, or a | 59 | if toml.Unmarshal(raw, &doc) != nil { |
| 60 | // table that may point somewhere other than PyPI. | 60 | return |
| 61 | if req, ok := cargoRequirement(spec); ok { | 61 | } |
| 62 | add(name, req) | 62 | for _, spec := range doc.Project.Dependencies { |
| 63 | } | 63 | name, version := splitPEP508(spec) |
| 64 | } | 64 | add(name, version) |
| 65 | } | ||
| 66 | poetry := doc.Tool.Poetry | ||
| 67 | for _, set := range []map[string]any{poetry.Dependencies, poetry.DevDependencies} { | ||
| 68 | for name, spec := range set { | ||
| 69 | // Poetry shares Cargo's two forms: a bare string, or a | ||
| 70 | // table that may point somewhere other than PyPI. | ||
| 71 | if req, ok := cargoRequirement(spec); ok { | ||
| 72 | add(name, req) | ||
| 65 | } | 73 | } |
| 66 | } | 74 | } |
| 67 | } | 75 | } |
| 68 | return out | ||
| 69 | } | 76 | } |
| 70 | 77 | ||
| 71 | // splitPEP508 separates the distribution name from its version specifier, | 78 | // splitPEP508 separates the distribution name from its version specifier, |
internal/deps/version.go +4 −2
| @@ -49,7 +49,7 @@ func split(v string) ([]int, string) { | |||
| 49 | i := 0 | 49 | i := 0 |
| 50 | for i < len(v) { | 50 | for i < len(v) { |
| 51 | j := i | 51 | j := i |
| 52 | for j < len(v) && v[j] >= '0' && v[j] <= '9' { | 52 | for j < len(v) && isDigit(v[j]) { |
| 53 | j++ | 53 | j++ |
| 54 | } | 54 | } |
| 55 | if j == i { | 55 | if j == i { |
| @@ -60,7 +60,7 @@ func split(v string) ([]int, string) { | |||
| 60 | break | 60 | break |
| 61 | } | 61 | } |
| 62 | nums = append(nums, n) | 62 | nums = append(nums, n) |
| 63 | if j < len(v) && v[j] == '.' && j+1 < len(v) && v[j+1] >= '0' && v[j+1] <= '9' { | 63 | if j+1 < len(v) && v[j] == '.' && isDigit(v[j+1]) { |
| 64 | i = j + 1 | 64 | i = j + 1 |
| 65 | continue | 65 | continue |
| 66 | } | 66 | } |
| @@ -89,3 +89,5 @@ func rank(suffix string) int { | |||
| 89 | } | 89 | } |
| 90 | return -1 | 90 | return -1 |
| 91 | } | 91 | } |
| 92 | |||
| 93 | func isDigit(c byte) bool { return c >= '0' && c <= '9' } | ||
internal/httpd/diff.go +82 −73
| @@ -334,86 +334,95 @@ type diffLayout struct { | |||
| 334 | // forms are attached to the lines. | 334 | // forms are attached to the lines. |
| 335 | func splitFiles(files []diffFile) { | 335 | func splitFiles(files []diffFile) { |
| 336 | for f := range files { | 336 | for f := range files { |
| 337 | lines := files[f].Lines | 337 | files[f].Rows = splitRows(files[f].Lines) |
| 338 | var rows []splitRow | 338 | } |
| 339 | for i := 0; i < len(lines); { | 339 | } |
| 340 | ln := &lines[i] | 340 | |
| 341 | switch ln.Class { | 341 | // splitRows pairs one file's deletions with its additions, side by side. |
| 342 | case "hunk", "meta": | 342 | func splitRows(lines []diffLine) []splitRow { |
| 343 | if ln.Class == "meta" && ln.Path == "" && len(rows) > 0 && strings.HasPrefix(ln.Text, `\`) { | 343 | var rows []splitRow |
| 344 | // a marker after a context line: neither side ends in a newline | 344 | for i := 0; i < len(lines); { |
| 345 | if last := &rows[len(rows)-1]; last.Old != nil && last.Old == last.New { | 345 | ln := &lines[i] |
| 346 | last.OldNote, last.NewNote = ln.Text, ln.Text | 346 | switch ln.Class { |
| 347 | i++ | 347 | case "hunk", "meta": |
| 348 | continue | 348 | if ln.Class == "meta" && ln.Path == "" && len(rows) > 0 && strings.HasPrefix(ln.Text, `\`) { |
| 349 | } | 349 | // a marker after a context line: neither side ends in a newline |
| 350 | } | 350 | if last := &rows[len(rows)-1]; last.Old != nil && last.Old == last.New { |
| 351 | rows = append(rows, splitRow{Kind: ln.Class, Text: ln.Text}) | 351 | last.OldNote, last.NewNote = ln.Text, ln.Text |
| 352 | i++ | ||
| 353 | case "ctx": | ||
| 354 | r := splitRow{Kind: "pair", Old: ln, New: ln, Threads: ln.Threads} | ||
| 355 | if ln.Compose { | ||
| 356 | r.Compose = ln | ||
| 357 | } | ||
| 358 | rows = append(rows, r) | ||
| 359 | i++ | ||
| 360 | default: | ||
| 361 | var dels, adds []*diffLine | ||
| 362 | marker := func() string { | ||
| 363 | if i < len(lines) && lines[i].Class == "meta" && strings.HasPrefix(lines[i].Text, `\`) { | ||
| 364 | i++ | ||
| 365 | return lines[i-1].Text | ||
| 366 | } | ||
| 367 | return "" | ||
| 368 | } | ||
| 369 | var oldNote, newNote string | ||
| 370 | for i < len(lines) && lines[i].Class == "del" { | ||
| 371 | dels = append(dels, &lines[i]) | ||
| 372 | i++ | ||
| 373 | } | ||
| 374 | if len(dels) > 0 { | ||
| 375 | oldNote = marker() | ||
| 376 | } | ||
| 377 | for i < len(lines) && lines[i].Class == "add" { | ||
| 378 | adds = append(adds, &lines[i]) | ||
| 379 | i++ | 352 | i++ |
| 380 | } | ||
| 381 | if len(adds) > 0 { | ||
| 382 | newNote = marker() | ||
| 383 | } | ||
| 384 | if len(dels)+len(adds) == 0 { | ||
| 385 | i++ // an unknown class: skip rather than loop | ||
| 386 | continue | 353 | continue |
| 387 | } | 354 | } |
| 388 | first := len(rows) | 355 | } |
| 389 | for k := 0; k < len(dels) || k < len(adds); k++ { | 356 | rows = append(rows, splitRow{Kind: ln.Class, Text: ln.Text}) |
| 390 | r := splitRow{Kind: "pair"} | 357 | i++ |
| 391 | for _, l := range []*diffLine{pick(dels, k), pick(adds, k)} { | 358 | case "ctx": |
| 392 | if l == nil { | 359 | r := splitRow{Kind: "pair", Old: ln, New: ln, Threads: ln.Threads} |
| 393 | continue | 360 | if ln.Compose { |
| 394 | } | 361 | r.Compose = ln |
| 395 | if l.Class == "del" { | 362 | } |
| 396 | r.Old = l | 363 | rows = append(rows, r) |
| 397 | } else { | 364 | i++ |
| 398 | r.New = l | 365 | default: |
| 399 | } | 366 | var dels, adds []*diffLine |
| 400 | r.Threads = append(r.Threads, l.Threads...) | 367 | marker := func() string { |
| 401 | if l.Compose { | 368 | if i < len(lines) && lines[i].Class == "meta" && strings.HasPrefix(lines[i].Text, `\`) { |
| 402 | r.Compose = l | 369 | i++ |
| 403 | } | 370 | return lines[i-1].Text |
| 404 | } | ||
| 405 | rows = append(rows, r) | ||
| 406 | } | ||
| 407 | if len(dels) > 0 { | ||
| 408 | rows[first+len(dels)-1].OldNote = oldNote | ||
| 409 | } | ||
| 410 | if len(adds) > 0 { | ||
| 411 | rows[first+len(adds)-1].NewNote = newNote | ||
| 412 | } | 371 | } |
| 372 | return "" | ||
| 373 | } | ||
| 374 | var oldNote, newNote string | ||
| 375 | for i < len(lines) && lines[i].Class == "del" { | ||
| 376 | dels = append(dels, &lines[i]) | ||
| 377 | i++ | ||
| 378 | } | ||
| 379 | if len(dels) > 0 { | ||
| 380 | oldNote = marker() | ||
| 381 | } | ||
| 382 | for i < len(lines) && lines[i].Class == "add" { | ||
| 383 | adds = append(adds, &lines[i]) | ||
| 384 | i++ | ||
| 385 | } | ||
| 386 | if len(adds) > 0 { | ||
| 387 | newNote = marker() | ||
| 388 | } | ||
| 389 | if len(dels)+len(adds) == 0 { | ||
| 390 | i++ // an unknown class: skip rather than loop | ||
| 391 | continue | ||
| 392 | } | ||
| 393 | first := len(rows) | ||
| 394 | for k := 0; k < len(dels) || k < len(adds); k++ { | ||
| 395 | rows = append(rows, pairRow(pick(dels, k), pick(adds, k))) | ||
| 413 | } | 396 | } |
| 397 | if len(dels) > 0 { | ||
| 398 | rows[first+len(dels)-1].OldNote = oldNote | ||
| 399 | } | ||
| 400 | if len(adds) > 0 { | ||
| 401 | rows[first+len(adds)-1].NewNote = newNote | ||
| 402 | } | ||
| 403 | } | ||
| 404 | } | ||
| 405 | return rows | ||
| 406 | } | ||
| 407 | |||
| 408 | // pairRow is the row showing del beside add; either may be nil. | ||
| 409 | func pairRow(del, add *diffLine) splitRow { | ||
| 410 | r := splitRow{Kind: "pair"} | ||
| 411 | for _, l := range []*diffLine{del, add} { | ||
| 412 | if l == nil { | ||
| 413 | continue | ||
| 414 | } | ||
| 415 | if l.Class == "del" { | ||
| 416 | r.Old = l | ||
| 417 | } else { | ||
| 418 | r.New = l | ||
| 419 | } | ||
| 420 | r.Threads = append(r.Threads, l.Threads...) | ||
| 421 | if l.Compose { | ||
| 422 | r.Compose = l | ||
| 414 | } | 423 | } |
| 415 | files[f].Rows = rows | ||
| 416 | } | 424 | } |
| 425 | return r | ||
| 417 | } | 426 | } |
| 418 | 427 | ||
| 419 | func pick(s []*diffLine, i int) *diffLine { | 428 | func pick(s []*diffLine, i int) *diffLine { |
internal/httpd/readme.go +48 −25
| @@ -16,6 +16,37 @@ import ( | |||
| 16 | // go-org exports .org links as .html, so an .html target whose .org (or | 16 | // go-org exports .org links as .html, so an .html target whose .org (or |
| 17 | // .md) source exists in the tree maps back to the source file. | 17 | // .md) source exists in the tree maps back to the source file. |
| 18 | func rewriteRelativeLinks(rendered template.HTML, p repoPage, baseDir string) template.HTML { | 18 | func rewriteRelativeLinks(rendered template.HTML, p repoPage, baseDir string) template.HTML { |
| 19 | return rewriteRelativeTargets(rendered, func(v string, src bool) (string, bool) { | ||
| 20 | target := path.Clean(path.Join(baseDir, v)) | ||
| 21 | if strings.HasPrefix(target, "..") { | ||
| 22 | return "", false | ||
| 23 | } | ||
| 24 | if src { | ||
| 25 | return "/" + p.Repo.Path() + "/raw/" + p.Ref + "/" + target, true | ||
| 26 | } | ||
| 27 | return "/" + p.Repo.Path() + "/blob/" + p.Ref + "/" + exportSource(p, target), true | ||
| 28 | }) | ||
| 29 | } | ||
| 30 | |||
| 31 | // exportSource maps an .html target back to the .org or .md file in the | ||
| 32 | // tree it was exported from, if there is one. | ||
| 33 | func exportSource(p repoPage, target string) string { | ||
| 34 | stem, ok := strings.CutSuffix(target, ".html") | ||
| 35 | if !ok { | ||
| 36 | return target | ||
| 37 | } | ||
| 38 | for _, ext := range []string{".org", ".md"} { | ||
| 39 | if _, err := gitutil.ReadBlob(p.Dir, p.Ref, stem+ext, 1); err == nil { | ||
| 40 | return stem + ext | ||
| 41 | } | ||
| 42 | } | ||
| 43 | return target | ||
| 44 | } | ||
| 45 | |||
| 46 | // rewriteRelativeTargets passes each relative link href and img, video or | ||
| 47 | // source src in rendered to rewrite (src is true for the media), and sets | ||
| 48 | // the attribute to what it returns when ok. | ||
| 49 | func rewriteRelativeTargets(rendered template.HTML, rewrite func(v string, src bool) (string, bool)) template.HTML { | ||
| 19 | ctx := &html.Node{Type: html.ElementNode, Data: "div", DataAtom: atom.Div} | 50 | ctx := &html.Node{Type: html.ElementNode, Data: "div", DataAtom: atom.Div} |
| 20 | nodes, err := html.ParseFragment(strings.NewReader(string(rendered)), ctx) | 51 | nodes, err := html.ParseFragment(strings.NewReader(string(rendered)), ctx) |
| 21 | if err != nil { | 52 | if err != nil { |
| @@ -27,34 +58,12 @@ func rewriteRelativeLinks(rendered template.HTML, p repoPage, baseDir string) te | |||
| 27 | for i, a := range n.Attr { | 58 | for i, a := range n.Attr { |
| 28 | isHref := a.Key == "href" && n.Data == "a" | 59 | isHref := a.Key == "href" && n.Data == "a" |
| 29 | isSrc := a.Key == "src" && (n.Data == "img" || n.Data == "video" || n.Data == "source") | 60 | isSrc := a.Key == "src" && (n.Data == "img" || n.Data == "video" || n.Data == "source") |
| 30 | if !isHref && !isSrc { | 61 | if (!isHref && !isSrc) || !isRelativeTarget(a.Val) { |
| 31 | continue | ||
| 32 | } | ||
| 33 | v := a.Val | ||
| 34 | if v == "" || strings.Contains(v, "://") || strings.HasPrefix(v, "/") || | ||
| 35 | strings.HasPrefix(v, "#") || strings.HasPrefix(v, "mailto:") || | ||
| 36 | strings.HasPrefix(v, "data:") { | ||
| 37 | continue | ||
| 38 | } | ||
| 39 | target := path.Clean(path.Join(baseDir, v)) | ||
| 40 | if strings.HasPrefix(target, "..") { | ||
| 41 | continue | ||
| 42 | } | ||
| 43 | if isSrc { | ||
| 44 | n.Attr[i].Val = "/" + p.Repo.Path() + "/raw/" + p.Ref + "/" + target | ||
| 45 | continue | 62 | continue |
| 46 | } | 63 | } |
| 47 | // .html from org/markdown exports maps back to the source. | 64 | if v, ok := rewrite(a.Val, isSrc); ok { |
| 48 | if strings.HasSuffix(target, ".html") { | 65 | n.Attr[i].Val = v |
| 49 | stem := strings.TrimSuffix(target, ".html") | ||
| 50 | for _, ext := range []string{".org", ".md"} { | ||
| 51 | if _, err := gitutil.ReadBlob(p.Dir, p.Ref, stem+ext, 1); err == nil { | ||
| 52 | target = stem + ext | ||
| 53 | break | ||
| 54 | } | ||
| 55 | } | ||
| 56 | } | 66 | } |
| 57 | n.Attr[i].Val = "/" + p.Repo.Path() + "/blob/" + p.Ref + "/" + target | ||
| 58 | } | 67 | } |
| 59 | } | 68 | } |
| 60 | for c := n.FirstChild; c != nil; c = c.NextSibling { | 69 | for c := n.FirstChild; c != nil; c = c.NextSibling { |
| @@ -70,3 +79,17 @@ func rewriteRelativeLinks(rendered template.HTML, p repoPage, baseDir string) te | |||
| 70 | } | 79 | } |
| 71 | return template.HTML(out.String()) | 80 | return template.HTML(out.String()) |
| 72 | } | 81 | } |
| 82 | |||
| 83 | // isRelativeTarget is false for empty targets, absolute URLs, rooted | ||
| 84 | // paths, fragments, mailto: and data:. | ||
| 85 | func isRelativeTarget(v string) bool { | ||
| 86 | if v == "" || strings.Contains(v, "://") { | ||
| 87 | return false | ||
| 88 | } | ||
| 89 | for _, prefix := range []string{"/", "#", "mailto:", "data:"} { | ||
| 90 | if strings.HasPrefix(v, prefix) { | ||
| 91 | return false | ||
| 92 | } | ||
| 93 | } | ||
| 94 | return true | ||
| 95 | } | ||
internal/httpd/wiki.go +15 −51
| @@ -7,9 +7,6 @@ import ( | |||
| 7 | "sort" | 7 | "sort" |
| 8 | "strings" | 8 | "strings" |
| 9 | 9 | ||
| 10 | "golang.org/x/net/html" | ||
| 11 | "golang.org/x/net/html/atom" | ||
| 12 | |||
| 13 | "gitbay.org/gitbay/internal/control" | 10 | "gitbay.org/gitbay/internal/control" |
| 14 | "gitbay.org/gitbay/internal/gitutil" | 11 | "gitbay.org/gitbay/internal/gitutil" |
| 15 | "gitbay.org/gitbay/internal/store" | 12 | "gitbay.org/gitbay/internal/store" |
| @@ -229,56 +226,23 @@ func trimPageExt(target string) string { | |||
| 229 | // other relative targets (images) to the wiki raw route. Targets resolve | 226 | // other relative targets (images) to the wiki raw route. Targets resolve |
| 230 | // from the current page's folder, as wikiResolve describes. | 227 | // from the current page's folder, as wikiResolve describes. |
| 231 | func rewriteWikiLinks(rendered template.HTML, p repoPage, page string, isPage, isFile func(string) bool) template.HTML { | 228 | func rewriteWikiLinks(rendered template.HTML, p repoPage, page string, isPage, isFile func(string) bool) template.HTML { |
| 232 | ctx := &html.Node{Type: html.ElementNode, Data: "div", DataAtom: atom.Div} | ||
| 233 | nodes, err := html.ParseFragment(strings.NewReader(string(rendered)), ctx) | ||
| 234 | if err != nil { | ||
| 235 | return rendered | ||
| 236 | } | ||
| 237 | base := "/" + p.Repo.Path() + "/wiki" | 229 | base := "/" + p.Repo.Path() + "/wiki" |
| 238 | var walk func(*html.Node) | 230 | return rewriteRelativeTargets(rendered, func(v string, src bool) (string, bool) { |
| 239 | walk = func(n *html.Node) { | 231 | if src { |
| 240 | if n.Type == html.ElementNode { | 232 | target, ok := wikiResolve(page, v, isFile) |
| 241 | for i, a := range n.Attr { | 233 | return base + "/_raw/" + target, ok |
| 242 | isHref := a.Key == "href" && n.Data == "a" | ||
| 243 | isSrc := a.Key == "src" && (n.Data == "img" || n.Data == "video" || n.Data == "source") | ||
| 244 | if !isHref && !isSrc { | ||
| 245 | continue | ||
| 246 | } | ||
| 247 | v := a.Val | ||
| 248 | if v == "" || strings.Contains(v, "://") || strings.HasPrefix(v, "/") || | ||
| 249 | strings.HasPrefix(v, "#") || strings.HasPrefix(v, "mailto:") || | ||
| 250 | strings.HasPrefix(v, "data:") { | ||
| 251 | continue | ||
| 252 | } | ||
| 253 | if isSrc { | ||
| 254 | if target, ok := wikiResolve(page, v, isFile); ok { | ||
| 255 | n.Attr[i].Val = base + "/_raw/" + target | ||
| 256 | } | ||
| 257 | continue | ||
| 258 | } | ||
| 259 | // A plain link is usually to another page, but a link to | ||
| 260 | // an existing non-page file (an .svg, .txt, .pdf) must | ||
| 261 | // go to _raw the same as an image src, or it 404s | ||
| 262 | // against the page route (#283). | ||
| 263 | if target, ok := wikiResolve(page, trimPageExt(v), isPage); ok { | ||
| 264 | if raw, rok := wikiResolve(page, v, isFile); rok && isFile(raw) && !isPage(target) { | ||
| 265 | n.Attr[i].Val = base + "/_raw/" + raw | ||
| 266 | } else { | ||
| 267 | n.Attr[i].Val = base + "/" + target | ||
| 268 | } | ||
| 269 | } | ||
| 270 | } | ||
| 271 | } | 234 | } |
| 272 | for c := n.FirstChild; c != nil; c = c.NextSibling { | 235 | // A plain link is usually to another page, but a link to an |
| 273 | walk(c) | 236 | // existing non-page file (an .svg, .txt, .pdf) must go to _raw |
| 237 | // the same as an image src, or it 404s against the page route | ||
| 238 | // (#283). | ||
| 239 | target, ok := wikiResolve(page, trimPageExt(v), isPage) | ||
| 240 | if !ok { | ||
| 241 | return "", false | ||
| 274 | } | 242 | } |
| 275 | } | 243 | if raw, rok := wikiResolve(page, v, isFile); rok && isFile(raw) && !isPage(target) { |
| 276 | var out strings.Builder | 244 | return base + "/_raw/" + raw, true |
| 277 | for _, n := range nodes { | ||
| 278 | walk(n) | ||
| 279 | if err := html.Render(&out, n); err != nil { | ||
| 280 | return rendered | ||
| 281 | } | 245 | } |
| 282 | } | 246 | return base + "/" + target, true |
| 283 | return template.HTML(out.String()) | 247 | }) |
| 284 | } | 248 | } |
internal/lfs/lfs.go +4 −1
| @@ -188,7 +188,10 @@ func Verify(secret []byte, token string, now time.Time) (Grant, bool) { | |||
| 188 | repoID, err1 := strconv.ParseInt(parts[0], 10, 64) | 188 | repoID, err1 := strconv.ParseInt(parts[0], 10, 64) |
| 189 | keyID, err2 := strconv.ParseInt(parts[1], 10, 64) | 189 | keyID, err2 := strconv.ParseInt(parts[1], 10, 64) |
| 190 | exp, err3 := strconv.ParseInt(parts[4], 10, 64) | 190 | exp, err3 := strconv.ParseInt(parts[4], 10, 64) |
| 191 | if err1 != nil || err2 != nil || err3 != nil || keyID < 0 || now.Unix() > exp { | 191 | if err1 != nil || err2 != nil || err3 != nil { |
| 192 | return Grant{}, false | ||
| 193 | } | ||
| 194 | if keyID < 0 || now.Unix() > exp { | ||
| 192 | return Grant{}, false | 195 | return Grant{}, false |
| 193 | } | 196 | } |
| 194 | if (keyID == 0) != (parts[2] == "") { | 197 | if (keyID == 0) != (parts[2] == "") { |
internal/mailin/authres.go +21 −16
| @@ -83,22 +83,7 @@ func tokenize(s string) []token { | |||
| 83 | joined = false | 83 | joined = false |
| 84 | i++ | 84 | i++ |
| 85 | case c == '(': | 85 | case c == '(': |
| 86 | depth := 0 | 86 | i = commentEnd(s, i) |
| 87 | for ; i < len(s); i++ { | ||
| 88 | if s[i] == '\\' { | ||
| 89 | i++ | ||
| 90 | continue | ||
| 91 | } | ||
| 92 | if s[i] == '(' { | ||
| 93 | depth++ | ||
| 94 | } else if s[i] == ')' { | ||
| 95 | depth-- | ||
| 96 | if depth == 0 { | ||
| 97 | i++ | ||
| 98 | break | ||
| 99 | } | ||
| 100 | } | ||
| 101 | } | ||
| 102 | joined = false | 87 | joined = false |
| 103 | case c == '"': | 88 | case c == '"': |
| 104 | var b strings.Builder | 89 | var b strings.Builder |
| @@ -133,6 +118,26 @@ func tokenize(s string) []token { | |||
| 133 | return out | 118 | return out |
| 134 | } | 119 | } |
| 135 | 120 | ||
| 121 | // commentEnd is the index just past the comment opening at s[i], with | ||
| 122 | // nested parentheses and backslash escapes; past the end when unclosed. | ||
| 123 | func commentEnd(s string, i int) int { | ||
| 124 | depth := 0 | ||
| 125 | for ; i < len(s); i++ { | ||
| 126 | switch s[i] { | ||
| 127 | case '\\': | ||
| 128 | i++ | ||
| 129 | case '(': | ||
| 130 | depth++ | ||
| 131 | case ')': | ||
| 132 | depth-- | ||
| 133 | if depth == 0 { | ||
| 134 | return i + 1 | ||
| 135 | } | ||
| 136 | } | ||
| 137 | } | ||
| 138 | return i | ||
| 139 | } | ||
| 140 | |||
| 136 | // splitResults splits tokens at each ";". | 141 | // splitResults splits tokens at each ";". |
| 137 | func splitResults(ts []token) [][]token { | 142 | func splitResults(ts []token) [][]token { |
| 138 | segs := [][]token{nil} | 143 | segs := [][]token{nil} |
internal/notify/notify.go +20 −13
| @@ -50,24 +50,31 @@ func (m *Mailer) Run(ctx context.Context) { | |||
| 50 | continue | 50 | continue |
| 51 | } | 51 | } |
| 52 | for _, q := range due { | 52 | for _, q := range due { |
| 53 | if err := mail.SendReplyTo(m.Cfg, q.Recipient, q.ReplyTo, q.Subject, q.Body); err != nil { | 53 | m.deliver(q) |
| 54 | attempt := q.Attempts + 1 | ||
| 55 | if attempt >= m.MaxAttempts { | ||
| 56 | m.St.MarkMailFailed(q.ID, err.Error(), nil) | ||
| 57 | slog.Warn("notification dead-lettered", | ||
| 58 | "mail", q.ID, "attempts", attempt, "err", redactAddresses(err.Error())) | ||
| 59 | } else { | ||
| 60 | next := time.Now().Add(m.RetryBase << (attempt - 1)) | ||
| 61 | m.St.MarkMailFailed(q.ID, err.Error(), &next) | ||
| 62 | } | ||
| 63 | continue | ||
| 64 | } | ||
| 65 | m.St.MarkMailSent(q.ID) | ||
| 66 | } | 54 | } |
| 67 | } | 55 | } |
| 68 | } | 56 | } |
| 69 | } | 57 | } |
| 70 | 58 | ||
| 59 | // deliver sends one queued mail, marking it sent, due again after a | ||
| 60 | // backoff, or failed once it has had MaxAttempts. | ||
| 61 | func (m *Mailer) deliver(q store.QueuedMail) { | ||
| 62 | err := mail.SendReplyTo(m.Cfg, q.Recipient, q.ReplyTo, q.Subject, q.Body) | ||
| 63 | if err == nil { | ||
| 64 | m.St.MarkMailSent(q.ID) | ||
| 65 | return | ||
| 66 | } | ||
| 67 | attempt := q.Attempts + 1 | ||
| 68 | if attempt >= m.MaxAttempts { | ||
| 69 | m.St.MarkMailFailed(q.ID, err.Error(), nil) | ||
| 70 | slog.Warn("notification dead-lettered", | ||
| 71 | "mail", q.ID, "attempts", attempt, "err", redactAddresses(err.Error())) | ||
| 72 | return | ||
| 73 | } | ||
| 74 | next := time.Now().Add(m.RetryBase << (attempt - 1)) | ||
| 75 | m.St.MarkMailFailed(q.ID, err.Error(), &next) | ||
| 76 | } | ||
| 77 | |||
| 71 | // A relay's rejection usually quotes the address it rejected — "550 5.1.1 | 78 | // A relay's rejection usually quotes the address it rejected — "550 5.1.1 |
| 72 | // <x@y>: Recipient address rejected" — so dropping the recipient field | 79 | // <x@y>: Recipient address rejected" — so dropping the recipient field |
| 73 | // alone would not keep an address out of the log. | 80 | // alone would not keep an address out of the log. |
internal/protocol/tokenize.go +22 −25
| @@ -39,28 +39,9 @@ func Tokenize(s string) ([]string, error) { | |||
| 39 | i += end + 2 | 39 | i += end + 2 |
| 40 | case c == '"': | 40 | case c == '"': |
| 41 | inWord = true | 41 | inWord = true |
| 42 | i++ | 42 | var err error |
| 43 | closed := false | 43 | if i, err = doubleQuoted(s, i, &cur); err != nil { |
| 44 | for i < len(s) { | 44 | return nil, err |
| 45 | c = s[i] | ||
| 46 | if c == '"' { | ||
| 47 | closed = true | ||
| 48 | i++ | ||
| 49 | break | ||
| 50 | } | ||
| 51 | if c == '\\' && i+1 < len(s) { | ||
| 52 | switch s[i+1] { | ||
| 53 | case '\\', '"', '$', '`': | ||
| 54 | cur.WriteByte(s[i+1]) | ||
| 55 | i += 2 | ||
| 56 | continue | ||
| 57 | } | ||
| 58 | } | ||
| 59 | cur.WriteByte(c) | ||
| 60 | i++ | ||
| 61 | } | ||
| 62 | if !closed { | ||
| 63 | return nil, errors.New("unterminated double quote") | ||
| 64 | } | 45 | } |
| 65 | case c == '\\': | 46 | case c == '\\': |
| 66 | if i+1 >= len(s) { | 47 | if i+1 >= len(s) { |
| @@ -69,9 +50,7 @@ func Tokenize(s string) ([]string, error) { | |||
| 69 | inWord = true | 50 | inWord = true |
| 70 | cur.WriteByte(s[i+1]) | 51 | cur.WriteByte(s[i+1]) |
| 71 | i += 2 | 52 | i += 2 |
| 72 | case c == '$' || c == '`' || c == ';' || c == '&' || c == '|' || | 53 | case strings.IndexByte("$`;&|<>()*?[#~", c) >= 0: |
| 73 | c == '<' || c == '>' || c == '(' || c == ')' || c == '*' || | ||
| 74 | c == '?' || c == '[' || c == '#' || c == '~': | ||
| 75 | // Unquoted shell metacharacters are rejected outright rather | 54 | // Unquoted shell metacharacters are rejected outright rather |
| 76 | // than passed through: there is no shell here, and silently | 55 | // than passed through: there is no shell here, and silently |
| 77 | // treating them as literals would mask client quoting bugs. | 56 | // treating them as literals would mask client quoting bugs. |
| @@ -87,3 +66,21 @@ func Tokenize(s string) ([]string, error) { | |||
| 87 | } | 66 | } |
| 88 | return argv, nil | 67 | return argv, nil |
| 89 | } | 68 | } |
| 69 | |||
| 70 | // doubleQuoted writes the double-quoted string opening at s[i] to cur, | ||
| 71 | // unescaping \\, \", \$ and \`, and returns the index past its closing | ||
| 72 | // quote. | ||
| 73 | func doubleQuoted(s string, i int, cur *strings.Builder) (int, error) { | ||
| 74 | for i++; i < len(s); i++ { | ||
| 75 | c := s[i] | ||
| 76 | if c == '"' { | ||
| 77 | return i + 1, nil | ||
| 78 | } | ||
| 79 | if c == '\\' && i+1 < len(s) && strings.IndexByte("\\\"$`", s[i+1]) >= 0 { | ||
| 80 | i++ | ||
| 81 | c = s[i] | ||
| 82 | } | ||
| 83 | cur.WriteByte(c) | ||
| 84 | } | ||
| 85 | return i, errors.New("unterminated double quote") | ||
| 86 | } | ||
internal/sshd/pushlimit_test.go +8 −8
| @@ -35,8 +35,8 @@ func TestSilentPushKilledAtReceiveTimeout(t *testing.T) { | |||
| 35 | codec := make(chan int, 1) | 35 | codec := make(chan int, 1) |
| 36 | start := time.Now() | 36 | start := time.Now() |
| 37 | go func() { | 37 | go func() { |
| 38 | codec <- Exec(cfg, st, nil, pushes, alice, key, control.Term{}, "git-receive-pack alice/app", | 38 | codec <- Exec(Backend{Cfg: cfg, St: st, Pushes: pushes}, alice, key, control.Term{}, "git-receive-pack alice/app", |
| 39 | silentStdin(t), io.Discard, io.Discard, nil, nil, nil) | 39 | Streams{Stdin: silentStdin(t), Stdout: io.Discard, Stderr: io.Discard}) |
| 40 | }() | 40 | }() |
| 41 | slotTaken(t, pushes) | 41 | slotTaken(t, pushes) |
| 42 | pushEnded(t, codec, pushes, 5*time.Second) | 42 | pushEnded(t, codec, pushes, 5*time.Second) |
| @@ -66,8 +66,8 @@ func TestPushKilledAtIdleOncePackStarts(t *testing.T) { | |||
| 66 | codec := make(chan int, 1) | 66 | codec := make(chan int, 1) |
| 67 | start := time.Now() | 67 | start := time.Now() |
| 68 | go func() { | 68 | go func() { |
| 69 | codec <- Exec(cfg, st, nil, pushes, alice, key, control.Term{}, "git-receive-pack alice/app", | 69 | codec <- Exec(Backend{Cfg: cfg, St: st, Pushes: pushes}, alice, key, control.Term{}, "git-receive-pack alice/app", |
| 70 | r, io.Discard, io.Discard, nil, nil, nil) | 70 | Streams{Stdin: r, Stdout: io.Discard, Stderr: io.Discard}) |
| 71 | }() | 71 | }() |
| 72 | slotTaken(t, pushes) | 72 | slotTaken(t, pushes) |
| 73 | // The signature split across two writes still arms the rule. | 73 | // The signature split across two writes still arms the rule. |
| @@ -116,8 +116,8 @@ func TestPushSilentBeforePackCompletes(t *testing.T) { | |||
| 116 | pw.Close() | 116 | pw.Close() |
| 117 | }() | 117 | }() |
| 118 | var errOut strings.Builder | 118 | var errOut strings.Builder |
| 119 | if code := Exec(cfg, st, nil, pushes, alice, key, control.Term{}, "git-receive-pack alice/app", | 119 | if code := Exec(Backend{Cfg: cfg, St: st, Pushes: pushes}, alice, key, control.Term{}, "git-receive-pack alice/app", |
| 120 | pr, io.Discard, &errOut, nil, nil, nil); code != 0 { | 120 | Streams{Stdin: pr, Stdout: io.Discard, Stderr: &errOut}); code != 0 { |
| 121 | t.Fatalf("exit %d: %s", code, errOut.String()) | 121 | t.Fatalf("exit %d: %s", code, errOut.String()) |
| 122 | } | 122 | } |
| 123 | out, err := exec.Command("git", "-C", control.RepoDir(cfg.Server.Root, "alice", "app"), "rev-parse", "refs/heads/main").Output() | 123 | out, err := exec.Command("git", "-C", control.RepoDir(cfg.Server.Root, "alice", "app"), "rev-parse", "refs/heads/main").Output() |
| @@ -160,8 +160,8 @@ func TestTricklingPushKilledAtReceiveTimeout(t *testing.T) { | |||
| 160 | codec := make(chan int, 1) | 160 | codec := make(chan int, 1) |
| 161 | start := time.Now() | 161 | start := time.Now() |
| 162 | go func() { | 162 | go func() { |
| 163 | codec <- Exec(cfg, st, nil, pushes, alice, key, control.Term{}, "git-receive-pack alice/app", | 163 | codec <- Exec(Backend{Cfg: cfg, St: st, Pushes: pushes}, alice, key, control.Term{}, "git-receive-pack alice/app", |
| 164 | r, io.Discard, io.Discard, nil, nil, nil) | 164 | Streams{Stdin: r, Stdout: io.Discard, Stderr: io.Discard}) |
| 165 | }() | 165 | }() |
| 166 | slotTaken(t, pushes) | 166 | slotTaken(t, pushes) |
| 167 | pushEnded(t, codec, pushes, 5*time.Second) | 167 | pushEnded(t, codec, pushes, 5*time.Second) |
internal/sshd/refusal_test.go +22 −22
| @@ -58,8 +58,8 @@ func TestRefusedPushIsAudited(t *testing.T) { | |||
| 58 | bob.Pending = pending | 58 | bob.Pending = pending |
| 59 | key := store.SSHKey{Scope: "full", Fingerprint: "SHA256:test"} | 59 | key := store.SSHKey{Scope: "full", Fingerprint: "SHA256:test"} |
| 60 | var out, errOut bytes.Buffer | 60 | var out, errOut bytes.Buffer |
| 61 | code := Exec(cfg, st, nil, nil, bob, key, control.Term{}, "git-receive-pack alice/app", | 61 | code := Exec(Backend{Cfg: cfg, St: st}, bob, key, control.Term{}, "git-receive-pack alice/app", |
| 62 | strings.NewReader(""), &out, &errOut, nil, nil, nil) | 62 | Streams{Stdin: strings.NewReader(""), Stdout: &out, Stderr: &errOut}) |
| 63 | if code != protocol.ExitDenied { | 63 | if code != protocol.ExitDenied { |
| 64 | t.Fatalf("pending %v: exit %d: %s", pending, code, errOut.String()) | 64 | t.Fatalf("pending %v: exit %d: %s", pending, code, errOut.String()) |
| 65 | } | 65 | } |
| @@ -85,8 +85,8 @@ func TestCloneRefusedWhenPackSlotsAreFull(t *testing.T) { | |||
| 85 | key := store.SSHKey{Scope: "full", Fingerprint: "SHA256:test"} | 85 | key := store.SSHKey{Scope: "full", Fingerprint: "SHA256:test"} |
| 86 | for _, service := range []string{"git-upload-pack", "git-upload-archive"} { | 86 | for _, service := range []string{"git-upload-pack", "git-upload-archive"} { |
| 87 | var out, errOut bytes.Buffer | 87 | var out, errOut bytes.Buffer |
| 88 | code := Exec(cfg, st, packs, nil, bob, key, control.Term{}, service+" alice/app", | 88 | code := Exec(Backend{Cfg: cfg, St: st, Packs: packs}, bob, key, control.Term{}, service+" alice/app", |
| 89 | strings.NewReader(""), &out, &errOut, nil, nil, nil) | 89 | Streams{Stdin: strings.NewReader(""), Stdout: &out, Stderr: &errOut}) |
| 90 | if code != protocol.ExitFailure || !strings.Contains(errOut.String(), "busy") { | 90 | if code != protocol.ExitFailure || !strings.Contains(errOut.String(), "busy") { |
| 91 | t.Fatalf("%s: exit %d: %q", service, code, errOut.String()) | 91 | t.Fatalf("%s: exit %d: %q", service, code, errOut.String()) |
| 92 | } | 92 | } |
| @@ -108,8 +108,8 @@ func TestPushBypassesPackLimitAndCloneReleasesSlot(t *testing.T) { | |||
| 108 | packs := packlimit.New(1, 0, 0, time.Second) | 108 | packs := packlimit.New(1, 0, 0, time.Second) |
| 109 | 109 | ||
| 110 | var out, errOut bytes.Buffer | 110 | var out, errOut bytes.Buffer |
| 111 | if code := Exec(cfg, st, packs, nil, alice, key, control.Term{}, "git-upload-pack alice/app", | 111 | if code := Exec(Backend{Cfg: cfg, St: st, Packs: packs}, alice, key, control.Term{}, "git-upload-pack alice/app", |
| 112 | strings.NewReader("0000"), &out, &errOut, nil, nil, nil); code != protocol.ExitOK { | 112 | Streams{Stdin: strings.NewReader("0000"), Stdout: &out, Stderr: &errOut}); code != protocol.ExitOK { |
| 113 | t.Fatalf("clone: exit %d: %s", code, errOut.String()) | 113 | t.Fatalf("clone: exit %d: %s", code, errOut.String()) |
| 114 | } | 114 | } |
| 115 | hold, err := packs.Acquire(nil, "ip:elsewhere") | 115 | hold, err := packs.Acquire(nil, "ip:elsewhere") |
| @@ -120,8 +120,8 @@ func TestPushBypassesPackLimitAndCloneReleasesSlot(t *testing.T) { | |||
| 120 | 120 | ||
| 121 | out.Reset() | 121 | out.Reset() |
| 122 | errOut.Reset() | 122 | errOut.Reset() |
| 123 | if code := Exec(cfg, st, packs, nil, alice, key, control.Term{}, "git-receive-pack alice/app", | 123 | if code := Exec(Backend{Cfg: cfg, St: st, Packs: packs}, alice, key, control.Term{}, "git-receive-pack alice/app", |
| 124 | strings.NewReader("0000"), &out, &errOut, nil, nil, nil); code != protocol.ExitOK { | 124 | Streams{Stdin: strings.NewReader("0000"), Stdout: &out, Stderr: &errOut}); code != protocol.ExitOK { |
| 125 | t.Fatalf("push with slots full: exit %d: %s", code, errOut.String()) | 125 | t.Fatalf("push with slots full: exit %d: %s", code, errOut.String()) |
| 126 | } | 126 | } |
| 127 | } | 127 | } |
| @@ -161,8 +161,8 @@ func killedClone(t *testing.T, stdout io.Writer, done, stopping, revoked <-chan | |||
| 161 | packs := packlimit.New(1, 0, 0, time.Second) | 161 | packs := packlimit.New(1, 0, 0, time.Second) |
| 162 | codec := make(chan int, 1) | 162 | codec := make(chan int, 1) |
| 163 | go func() { | 163 | go func() { |
| 164 | codec <- Exec(cfg, st, packs, nil, alice, key, control.Term{}, "git-upload-pack alice/app", | 164 | codec <- Exec(Backend{Cfg: cfg, St: st, Packs: packs}, alice, key, control.Term{}, "git-upload-pack alice/app", |
| 165 | silentStdin(t), stdout, io.Discard, done, stopping, revoked) | 165 | Streams{Stdin: silentStdin(t), Stdout: stdout, Stderr: io.Discard, Done: done, Stopping: stopping, Revoked: revoked}) |
| 166 | }() | 166 | }() |
| 167 | select { | 167 | select { |
| 168 | case code := <-codec: | 168 | case code := <-codec: |
| @@ -210,8 +210,8 @@ func TestCloneRunsOnDuringRestart(t *testing.T) { | |||
| 210 | key := store.SSHKey{Scope: "full", Fingerprint: "SHA256:test"} | 210 | key := store.SSHKey{Scope: "full", Fingerprint: "SHA256:test"} |
| 211 | packs := packlimit.New(1, 0, 0, time.Second) | 211 | packs := packlimit.New(1, 0, 0, time.Second) |
| 212 | var errOut bytes.Buffer | 212 | var errOut bytes.Buffer |
| 213 | if code := Exec(cfg, st, packs, nil, alice, key, control.Term{}, "git-upload-pack alice/app", | 213 | if code := Exec(Backend{Cfg: cfg, St: st, Packs: packs}, alice, key, control.Term{}, "git-upload-pack alice/app", |
| 214 | strings.NewReader("0000"), io.Discard, &errOut, closed(), closed(), nil); code != protocol.ExitOK { | 214 | Streams{Stdin: strings.NewReader("0000"), Stdout: io.Discard, Stderr: &errOut, Done: closed(), Stopping: closed()}); code != protocol.ExitOK { |
| 215 | t.Fatalf("exit %d: %s", code, errOut.String()) | 215 | t.Fatalf("exit %d: %s", code, errOut.String()) |
| 216 | } | 216 | } |
| 217 | } | 217 | } |
| @@ -235,8 +235,8 @@ func TestRefusedCloneStaysOffLimiter(t *testing.T) { | |||
| 235 | defer hold() | 235 | defer hold() |
| 236 | key := store.SSHKey{Scope: "full", Fingerprint: "SHA256:test"} | 236 | key := store.SSHKey{Scope: "full", Fingerprint: "SHA256:test"} |
| 237 | var out, errOut bytes.Buffer | 237 | var out, errOut bytes.Buffer |
| 238 | code := Exec(cfg, st, packs, nil, bob, key, control.Term{}, "git-upload-pack alice/secret", | 238 | code := Exec(Backend{Cfg: cfg, St: st, Packs: packs}, bob, key, control.Term{}, "git-upload-pack alice/secret", |
| 239 | strings.NewReader(""), &out, &errOut, nil, nil, nil) | 239 | Streams{Stdin: strings.NewReader(""), Stdout: &out, Stderr: &errOut}) |
| 240 | if code != protocol.ExitNotFound || strings.Contains(errOut.String(), "busy") { | 240 | if code != protocol.ExitNotFound || strings.Contains(errOut.String(), "busy") { |
| 241 | t.Fatalf("exit %d: %q", code, errOut.String()) | 241 | t.Fatalf("exit %d: %q", code, errOut.String()) |
| 242 | } | 242 | } |
| @@ -282,8 +282,8 @@ func TestPushPerPrincipalCap(t *testing.T) { | |||
| 282 | push := func(k store.SSHKey, stdin io.Reader, errOut io.Writer) <-chan int { | 282 | push := func(k store.SSHKey, stdin io.Reader, errOut io.Writer) <-chan int { |
| 283 | codec := make(chan int, 1) | 283 | codec := make(chan int, 1) |
| 284 | go func() { | 284 | go func() { |
| 285 | codec <- Exec(cfg, st, nil, pushes, alice, k, control.Term{}, "git-receive-pack alice/app", | 285 | codec <- Exec(Backend{Cfg: cfg, St: st, Pushes: pushes}, alice, k, control.Term{}, "git-receive-pack alice/app", |
| 286 | stdin, io.Discard, errOut, nil, nil, nil) | 286 | Streams{Stdin: stdin, Stdout: io.Discard, Stderr: errOut}) |
| 287 | }() | 287 | }() |
| 288 | return codec | 288 | return codec |
| 289 | } | 289 | } |
| @@ -320,8 +320,8 @@ func TestPushPerPrincipalCap(t *testing.T) { | |||
| 320 | queuedFor(t, pushes, principal) | 320 | queuedFor(t, pushes, principal) |
| 321 | 321 | ||
| 322 | var errOut bytes.Buffer | 322 | var errOut bytes.Buffer |
| 323 | if code := Exec(cfg, st, nil, pushes, alice, key, control.Term{}, "git-receive-pack alice/app", | 323 | if code := Exec(Backend{Cfg: cfg, St: st, Pushes: pushes}, alice, key, control.Term{}, "git-receive-pack alice/app", |
| 324 | strings.NewReader(""), io.Discard, &errOut, nil, nil, nil); code != protocol.ExitFailure || | 324 | Streams{Stdin: strings.NewReader(""), Stdout: io.Discard, Stderr: &errOut}); code != protocol.ExitFailure || |
| 325 | !strings.Contains(errOut.String(), "limit of concurrent pushes") { | 325 | !strings.Contains(errOut.String(), "limit of concurrent pushes") { |
| 326 | t.Fatalf("third push: exit %d: %q", code, errOut.String()) | 326 | t.Fatalf("third push: exit %d: %q", code, errOut.String()) |
| 327 | } | 327 | } |
| @@ -354,8 +354,8 @@ func TestPushKilledWhenKeyRevokedReleasesSlot(t *testing.T) { | |||
| 354 | revoked := make(chan struct{}) | 354 | revoked := make(chan struct{}) |
| 355 | codec := make(chan int, 1) | 355 | codec := make(chan int, 1) |
| 356 | go func() { | 356 | go func() { |
| 357 | codec <- Exec(cfg, st, nil, pushes, alice, key, control.Term{}, "git-receive-pack alice/app", | 357 | codec <- Exec(Backend{Cfg: cfg, St: st, Pushes: pushes}, alice, key, control.Term{}, "git-receive-pack alice/app", |
| 358 | silentStdin(t), io.Discard, io.Discard, nil, nil, revoked) | 358 | Streams{Stdin: silentStdin(t), Stdout: io.Discard, Stderr: io.Discard, Revoked: revoked}) |
| 359 | }() | 359 | }() |
| 360 | slotTaken(t, pushes) | 360 | slotTaken(t, pushes) |
| 361 | close(revoked) | 361 | close(revoked) |
| @@ -407,8 +407,8 @@ func TestRefusedPushStaysOffLimiter(t *testing.T) { | |||
| 407 | defer hold() | 407 | defer hold() |
| 408 | key := store.SSHKey{Scope: "full", Fingerprint: "SHA256:test"} | 408 | key := store.SSHKey{Scope: "full", Fingerprint: "SHA256:test"} |
| 409 | var errOut bytes.Buffer | 409 | var errOut bytes.Buffer |
| 410 | code := Exec(cfg, st, nil, pushes, bob, key, control.Term{}, "git-receive-pack alice/app", | 410 | code := Exec(Backend{Cfg: cfg, St: st, Pushes: pushes}, bob, key, control.Term{}, "git-receive-pack alice/app", |
| 411 | strings.NewReader(""), io.Discard, &errOut, nil, nil, nil) | 411 | Streams{Stdin: strings.NewReader(""), Stdout: io.Discard, Stderr: &errOut}) |
| 412 | if code != protocol.ExitDenied || strings.Contains(errOut.String(), "busy") { | 412 | if code != protocol.ExitDenied || strings.Contains(errOut.String(), "busy") { |
| 413 | t.Fatalf("exit %d: %q", code, errOut.String()) | 413 | t.Fatalf("exit %d: %q", code, errOut.String()) |
| 414 | } | 414 | } |
internal/sshd/sshd.go +58 −35
| @@ -427,7 +427,8 @@ func (s *Server) runExec(c *conn, sconn *ssh.ServerConn, ch ssh.Channel, term co | |||
| 427 | return protocol.ExitDenied | 427 | return protocol.ExitDenied |
| 428 | } | 428 | } |
| 429 | _ = s.st.TouchSSHKey(keyID) | 429 | _ = s.st.TouchSSHKey(keyID) |
| 430 | return Exec(s.cfg, s.st, s.packs, s.pushes, user, key, term, cmdline, ch, ch, ch.Stderr(), done, s.stopping, c.revoked) | 430 | return Exec(Backend{Cfg: s.cfg, St: s.st, Packs: s.packs, Pushes: s.pushes}, user, key, term, cmdline, |
| 431 | Streams{Stdin: ch, Stdout: ch, Stderr: ch.Stderr(), Done: done, Stopping: s.stopping, Revoked: c.revoked}) | ||
| 431 | } | 432 | } |
| 432 | 433 | ||
| 433 | // runAnonymous handles a session from an unregistered key: the register | 434 | // runAnonymous handles a session from an unregistered key: the register |
| @@ -460,13 +461,29 @@ func (s *Server) runAnonymous(ch ssh.Channel, keyB64, cmdline string) int { | |||
| 460 | return control.RunRegister(s.cfg, s.st, pub, argv, ch, ch.Stderr()) | 461 | return control.RunRegister(s.cfg, s.st, pub, argv, ch, ch.Stderr()) |
| 461 | } | 462 | } |
| 462 | 463 | ||
| 464 | // Backend is what a command runs against. Packs bounds clones and fetches, | ||
| 465 | // and repo download; Pushes bounds receive-pack. A nil limiter is no limit. | ||
| 466 | type Backend struct { | ||
| 467 | Cfg config.Config | ||
| 468 | St *store.Store | ||
| 469 | Packs, Pushes *packlimit.Limiter | ||
| 470 | } | ||
| 471 | |||
| 472 | // Streams are a command's input and output and the channels that end it. | ||
| 473 | // Closing Revoked kills a git transport. | ||
| 474 | type Streams struct { | ||
| 475 | Stdin io.Reader | ||
| 476 | Stdout, Stderr io.Writer | ||
| 477 | Done, Stopping, Revoked <-chan struct{} | ||
| 478 | } | ||
| 479 | |||
| 463 | // Exec runs one SSH exec command line for an authenticated key. It is the | 480 | // Exec runs one SSH exec command line for an authenticated key. It is the |
| 464 | // single dispatch path shared by the embedded listener and the system-sshd | 481 | // single dispatch path shared by the embedded listener and the system-sshd |
| 465 | // forced command (gitbayd shell). Closing revoked kills a git transport. | 482 | // forced command (gitbayd shell). |
| 466 | // packs bounds clones and fetches, and repo download; pushes bounds | 483 | func Exec(b Backend, user store.User, key store.SSHKey, term control.Term, cmdline string, s Streams) int { |
| 467 | // receive-pack. A nil limiter is no limit. | 484 | cfg, st, packs := b.Cfg, b.St, b.Packs |
| 468 | func Exec(cfg config.Config, st *store.Store, packs, pushes *packlimit.Limiter, user store.User, key store.SSHKey, term control.Term, cmdline string, | 485 | stdin, stdout, stderr := s.Stdin, s.Stdout, s.Stderr |
| 469 | stdin io.Reader, stdout, stderr io.Writer, done, stopping, revoked <-chan struct{}) int { | 486 | done, stopping := s.Done, s.Stopping |
| 470 | // A person signing in with a full-scope key cancels a scheduled | 487 | // A person signing in with a full-scope key cancels a scheduled |
| 471 | // deletion; automation on narrower keys is refused and cannot. | 488 | // deletion; automation on narrower keys is refused and cannot. |
| 472 | if user.Disabled && user.DeleteAfter != "" && key.Scope == "full" && control.CancelScheduledDeletion(st, &user, "ssh") { | 489 | if user.Disabled && user.DeleteAfter != "" && key.Scope == "full" && control.CancelScheduledDeletion(st, &user, "ssh") { |
| @@ -492,7 +509,7 @@ func Exec(cfg config.Config, st *store.Store, packs, pushes *packlimit.Limiter, | |||
| 492 | if user.Pending { | 509 | if user.Pending { |
| 493 | fmt.Fprintln(stderr, "your account is not active yet: verify your email first") | 510 | fmt.Fprintln(stderr, "your account is not active yet: verify your email first") |
| 494 | } else { | 511 | } else { |
| 495 | code = runGit(cfg, st, packs, pushes, user, key, argv, stdin, stdout, stderr, done, stopping, revoked) | 512 | code = runGit(b, user, key, argv, s) |
| 496 | } | 513 | } |
| 497 | // A refused push is a refused write, audited like one. runGit | 514 | // A refused push is a refused write, audited like one. runGit |
| 498 | // refuses only with the path as the one argument, so argv[1:] | 515 | // refuses only with the path as the one argument, so argv[1:] |
| @@ -530,9 +547,40 @@ func Exec(cfg config.Config, st *store.Store, packs, pushes *packlimit.Limiter, | |||
| 530 | return control.Dispatch(ctx, argv) | 547 | return control.Dispatch(ctx, argv) |
| 531 | } | 548 | } |
| 532 | 549 | ||
| 550 | // cutStalledPush closes kill and the client's streams when the key is | ||
| 551 | // revoked, the push goes idle, or receiving fires before pre-receive has | ||
| 552 | // started. started arms the idle rule and retires receiving. It returns | ||
| 553 | // when finished closes. | ||
| 554 | func cutStalledPush(finished, started, revoked, idle <-chan struct{}, receiving <-chan time.Time, arm func(), kill chan struct{}, client ...any) { | ||
| 555 | for { | ||
| 556 | select { | ||
| 557 | case <-finished: | ||
| 558 | return | ||
| 559 | case <-started: | ||
| 560 | arm() | ||
| 561 | started, receiving = nil, nil | ||
| 562 | continue | ||
| 563 | case <-revoked: | ||
| 564 | case <-idle: | ||
| 565 | case <-receiving: | ||
| 566 | } | ||
| 567 | close(kill) | ||
| 568 | // A read blocked on a silent client outlives git; closing the | ||
| 569 | // channel ends it and the stdin copy, so Transport's Wait returns. | ||
| 570 | for _, c := range client { | ||
| 571 | if c, ok := c.(io.Closer); ok { | ||
| 572 | c.Close() | ||
| 573 | } | ||
| 574 | } | ||
| 575 | return | ||
| 576 | } | ||
| 577 | } | ||
| 578 | |||
| 533 | // runGit streams a git transport service after access checks. | 579 | // runGit streams a git transport service after access checks. |
| 534 | func runGit(cfg config.Config, st *store.Store, packs, pushes *packlimit.Limiter, user store.User, key store.SSHKey, argv []string, | 580 | func runGit(b Backend, user store.User, key store.SSHKey, argv []string, s Streams) int { |
| 535 | stdin io.Reader, stdout, stderr io.Writer, done, stopping, revoked <-chan struct{}) int { | 581 | cfg, st, packs, pushes := b.Cfg, b.St, b.Packs, b.Pushes |
| 582 | stdin, stdout, stderr := s.Stdin, s.Stdout, s.Stderr | ||
| 583 | done, stopping, revoked := s.Done, s.Stopping, s.Revoked | ||
| 536 | service, scope := argv[0], key.Scope | 584 | service, scope := argv[0], key.Scope |
| 537 | if len(argv) != 2 { | 585 | if len(argv) != 2 { |
| 538 | fmt.Fprintf(stderr, "usage: %s <path>\n", service) | 586 | fmt.Fprintf(stderr, "usage: %s <path>\n", service) |
| @@ -663,32 +711,7 @@ func runGit(cfg config.Config, st *store.Store, packs, pushes *packlimit.Limiter | |||
| 663 | kill := make(chan struct{}) | 711 | kill := make(chan struct{}) |
| 664 | finished := make(chan struct{}) | 712 | finished := make(chan struct{}) |
| 665 | defer close(finished) | 713 | defer close(finished) |
| 666 | go func() { | 714 | go cutStalledPush(finished, started, revoked, idle, deadline.C, arm, kill, client, clientOut) |
| 667 | receiving := deadline.C | ||
| 668 | for { | ||
| 669 | select { | ||
| 670 | case <-finished: | ||
| 671 | return | ||
| 672 | case <-started: | ||
| 673 | arm() | ||
| 674 | started, receiving = nil, nil | ||
| 675 | continue | ||
| 676 | case <-revoked: | ||
| 677 | case <-idle: | ||
| 678 | case <-receiving: | ||
| 679 | } | ||
| 680 | close(kill) | ||
| 681 | // A read blocked on a silent client outlives git; | ||
| 682 | // closing the channel ends it and the stdin copy, so | ||
| 683 | // Transport's Wait returns. | ||
| 684 | for _, c := range []any{client, clientOut} { | ||
| 685 | if c, ok := c.(io.Closer); ok { | ||
| 686 | c.Close() | ||
| 687 | } | ||
| 688 | } | ||
| 689 | return | ||
| 690 | } | ||
| 691 | }() | ||
| 692 | cancel = kill | 715 | cancel = kill |
| 693 | } | 716 | } |
| 694 | } | 717 | } |
internal/store/activity.go +7 −16
| @@ -49,32 +49,18 @@ func (s *Store) RecordCommitActivity(repoID int64, sha string, userID int64, day | |||
| 49 | // commits landed on default branches plus everything the events table | 49 | // commits landed on default branches plus everything the events table |
| 50 | // attributes to them (issues, MRs, comments, releases, pushes). | 50 | // attributes to them (issues, MRs, comments, releases, pushes). |
| 51 | func (s *Store) ActivityByDay(userID int64, sinceDay string) (map[string]int, error) { | 51 | func (s *Store) ActivityByDay(userID int64, sinceDay string) (map[string]int, error) { |
| 52 | rows, err := s.DB.Query(` | 52 | return s.dayCounts(` |
| 53 | SELECT day, COUNT(*) FROM ( | 53 | SELECT day, COUNT(*) FROM ( |
| 54 | SELECT day FROM commit_activity WHERE user_id = ?1 AND day >= ?2 | 54 | SELECT day FROM commit_activity WHERE user_id = ?1 AND day >= ?2 |
| 55 | UNION ALL | 55 | UNION ALL |
| 56 | SELECT date(created_at) AS day FROM events | 56 | SELECT date(created_at) AS day FROM events |
| 57 | WHERE actor_id = ?1 AND date(created_at) >= ?2 AND kind <> 'push' | 57 | WHERE actor_id = ?1 AND date(created_at) >= ?2 AND kind <> 'push' |
| 58 | ) GROUP BY day`, userID, sinceDay) | 58 | ) GROUP BY day`, userID, sinceDay) |
| 59 | if err != nil { | ||
| 60 | return nil, err | ||
| 61 | } | ||
| 62 | defer rows.Close() | ||
| 63 | out := map[string]int{} | ||
| 64 | for rows.Next() { | ||
| 65 | var day string | ||
| 66 | var n int | ||
| 67 | if err := rows.Scan(&day, &n); err != nil { | ||
| 68 | return nil, err | ||
| 69 | } | ||
| 70 | out[day] = n | ||
| 71 | } | ||
| 72 | return out, rows.Err() | ||
| 73 | } | 59 | } |
| 74 | 60 | ||
| 75 | // OrgActivityByDay aggregates activity across an org's repositories. | 61 | // OrgActivityByDay aggregates activity across an org's repositories. |
| 76 | func (s *Store) OrgActivityByDay(orgID int64, sinceDay string) (map[string]int, error) { | 62 | func (s *Store) OrgActivityByDay(orgID int64, sinceDay string) (map[string]int, error) { |
| 77 | rows, err := s.DB.Query(` | 63 | return s.dayCounts(` |
| 78 | SELECT day, COUNT(*) FROM ( | 64 | SELECT day, COUNT(*) FROM ( |
| 79 | SELECT ca.day FROM commit_activity ca | 65 | SELECT ca.day FROM commit_activity ca |
| 80 | JOIN repos r ON r.id = ca.repo_id | 66 | JOIN repos r ON r.id = ca.repo_id |
| @@ -85,6 +71,11 @@ func (s *Store) OrgActivityByDay(orgID int64, sinceDay string) (map[string]int, | |||
| 85 | WHERE r.owner_kind = 'org' AND r.owner_id = ?1 | 71 | WHERE r.owner_kind = 'org' AND r.owner_id = ?1 |
| 86 | AND date(e.created_at) >= ?2 AND e.kind <> 'push' | 72 | AND date(e.created_at) >= ?2 AND e.kind <> 'push' |
| 87 | ) GROUP BY day`, orgID, sinceDay) | 73 | ) GROUP BY day`, orgID, sinceDay) |
| 74 | } | ||
| 75 | |||
| 76 | // dayCounts reads a query's (day, count) rows into a map. | ||
| 77 | func (s *Store) dayCounts(query string, args ...any) (map[string]int, error) { | ||
| 78 | rows, err := s.DB.Query(query, args...) | ||
| 88 | if err != nil { | 79 | if err != nil { |
| 89 | return nil, err | 80 | return nil, err |
| 90 | } | 81 | } |
internal/store/adminusers.go +1 −14
| @@ -61,20 +61,7 @@ func (s *Store) ListUsers(state string, limit int, after string) ([]AdminUser, e | |||
| 61 | q += " LIMIT ?" | 61 | q += " LIMIT ?" |
| 62 | args = append(args, limit) | 62 | args = append(args, limit) |
| 63 | } | 63 | } |
| 64 | rows, err := s.DB.Query(q, args...) | 64 | return queryAll(s.DB, scanAdminUser, q, args...) |
| 65 | if err != nil { | ||
| 66 | return nil, err | ||
| 67 | } | ||
| 68 | defer rows.Close() | ||
| 69 | var out []AdminUser | ||
| 70 | for rows.Next() { | ||
| 71 | u, err := scanAdminUser(rows) | ||
| 72 | if err != nil { | ||
| 73 | return nil, err | ||
| 74 | } | ||
| 75 | out = append(out, u) | ||
| 76 | } | ||
| 77 | return out, rows.Err() | ||
| 78 | } | 65 | } |
| 79 | 66 | ||
| 80 | // AdminUserByName is the ListUsers row for one account. | 67 | // AdminUserByName is the ListUsers row for one account. |
internal/store/bookmarks.go +1 −14
| @@ -43,20 +43,7 @@ func (s *Store) BookmarkCount(repoID int64) int { | |||
| 43 | // The caller filters by what the viewer may see: a bookmarked repository | 43 | // The caller filters by what the viewer may see: a bookmarked repository |
| 44 | // can since have gone private. | 44 | // can since have gone private. |
| 45 | func (s *Store) ListBookmarks(userID int64) ([]Repo, error) { | 45 | func (s *Store) ListBookmarks(userID int64) ([]Repo, error) { |
| 46 | rows, err := s.DB.Query(repoSelect+` | 46 | return queryAll(s.DB, scanRepo, repoSelect+` |
| 47 | JOIN repo_bookmarks b ON b.repo_id = r.id | 47 | JOIN repo_bookmarks b ON b.repo_id = r.id |
| 48 | WHERE b.user_id = ? ORDER BY b.bookmarked_at DESC`, userID) | 48 | WHERE b.user_id = ? ORDER BY b.bookmarked_at DESC`, userID) |
| 49 | if err != nil { | ||
| 50 | return nil, err | ||
| 51 | } | ||
| 52 | defer rows.Close() | ||
| 53 | var out []Repo | ||
| 54 | for rows.Next() { | ||
| 55 | r, err := scanRepo(rows) | ||
| 56 | if err != nil { | ||
| 57 | return nil, err | ||
| 58 | } | ||
| 59 | out = append(out, r) | ||
| 60 | } | ||
| 61 | return out, rows.Err() | ||
| 62 | } | 49 | } |
internal/store/builds.go +1 −14
| @@ -348,20 +348,7 @@ func (s *Store) ListBuilds(repoID int64, f BuildFilter, limit int) ([]Build, err | |||
| 348 | } | 348 | } |
| 349 | q += " ORDER BY number DESC LIMIT ?" | 349 | q += " ORDER BY number DESC LIMIT ?" |
| 350 | args = append(args, limit) | 350 | args = append(args, limit) |
| 351 | rows, err := s.DB.Query(q, args...) | 351 | return queryAll(s.DB, scanBuild, q, args...) |
| 352 | if err != nil { | ||
| 353 | return nil, err | ||
| 354 | } | ||
| 355 | defer rows.Close() | ||
| 356 | var out []Build | ||
| 357 | for rows.Next() { | ||
| 358 | b, err := scanBuild(rows) | ||
| 359 | if err != nil { | ||
| 360 | return nil, err | ||
| 361 | } | ||
| 362 | out = append(out, b) | ||
| 363 | } | ||
| 364 | return out, rows.Err() | ||
| 365 | } | 352 | } |
| 366 | 353 | ||
| 367 | // BuildLog returns the stored log bytes. | 354 | // BuildLog returns the stored log bytes. |
internal/store/dashboard.go +22 −80
| @@ -115,22 +115,9 @@ func (s *Store) UnpinRepo(userID, repoID int64) error { | |||
| 115 | // PinnedRepos returns the user's pinned repositories in pin order. The | 115 | // PinnedRepos returns the user's pinned repositories in pin order. The |
| 116 | // caller applies visibility checks before rendering. | 116 | // caller applies visibility checks before rendering. |
| 117 | func (s *Store) PinnedRepos(userID int64) ([]Repo, error) { | 117 | func (s *Store) PinnedRepos(userID int64) ([]Repo, error) { |
| 118 | rows, err := s.DB.Query(repoSelect+` | 118 | return queryAll(s.DB, scanRepo, repoSelect+` |
| 119 | JOIN repo_pins p ON p.repo_id = r.id AND p.user_id = ? | 119 | JOIN repo_pins p ON p.repo_id = r.id AND p.user_id = ? |
| 120 | ORDER BY p.pinned_at`, userID) | 120 | ORDER BY p.pinned_at`, userID) |
| 121 | if err != nil { | ||
| 122 | return nil, err | ||
| 123 | } | ||
| 124 | defer rows.Close() | ||
| 125 | var out []Repo | ||
| 126 | for rows.Next() { | ||
| 127 | r, err := scanRepo(rows) | ||
| 128 | if err != nil { | ||
| 129 | return nil, err | ||
| 130 | } | ||
| 131 | out = append(out, r) | ||
| 132 | } | ||
| 133 | return out, rows.Err() | ||
| 134 | } | 121 | } |
| 135 | 122 | ||
| 136 | // reviewQueueQuery is ReviewQueue's involved half: open merge requests the | 123 | // reviewQueueQuery is ReviewQueue's involved half: open merge requests the |
| @@ -304,29 +291,8 @@ type FeedEvent struct { | |||
| 304 | // newest first, for readers carrying no session. Push events are | 291 | // newest first, for readers carrying no session. Push events are |
| 305 | // excluded as in RecentEvents. | 292 | // excluded as in RecentEvents. |
| 306 | func (s *Store) OwnerPublicEvents(ownerKind string, ownerID int64, limit int) ([]FeedEvent, error) { | 293 | func (s *Store) OwnerPublicEvents(ownerKind string, ownerID int64, limit int) ([]FeedEvent, error) { |
| 307 | rows, err := s.DB.Query(` | 294 | return queryAll(s.DB, scanFeedEvent, feedSelect+`r.visibility = 'public' AND r.owner_kind = ? AND r.owner_id = ? |
| 308 | SELECT e.id, COALESCE(u.username, o.name) || '/' || r.name, | ||
| 309 | COALESCE(ac.username, ''), e.kind, e.data_json, e.created_at | ||
| 310 | FROM events e | ||
| 311 | JOIN repos r ON r.id = e.repo_id | ||
| 312 | LEFT JOIN users u ON r.owner_kind = 'user' AND u.id = r.owner_id | ||
| 313 | LEFT JOIN orgs o ON r.owner_kind = 'org' AND o.id = r.owner_id | ||
| 314 | LEFT JOIN users ac ON ac.id = e.actor_id | ||
| 315 | WHERE e.kind <> 'push' AND r.visibility = 'public' AND r.owner_kind = ? AND r.owner_id = ? | ||
| 316 | ORDER BY e.id DESC LIMIT ?`, ownerKind, ownerID, limit) | 295 | ORDER BY e.id DESC LIMIT ?`, ownerKind, ownerID, limit) |
| 317 | if err != nil { | ||
| 318 | return nil, err | ||
| 319 | } | ||
| 320 | defer rows.Close() | ||
| 321 | var out []FeedEvent | ||
| 322 | for rows.Next() { | ||
| 323 | var e FeedEvent | ||
| 324 | if err := rows.Scan(&e.ID, &e.RepoPath, &e.Actor, &e.Kind, &e.Data, &e.CreatedAt); err != nil { | ||
| 325 | return nil, err | ||
| 326 | } | ||
| 327 | out = append(out, e) | ||
| 328 | } | ||
| 329 | return out, rows.Err() | ||
| 330 | } | 296 | } |
| 331 | 297 | ||
| 332 | // UserPublicEvents returns what a user did on public repositories, | 298 | // UserPublicEvents returns what a user did on public repositories, |
| @@ -335,29 +301,8 @@ func (s *Store) OwnerPublicEvents(ownerKind string, ownerID int64, limit int) ([ | |||
| 335 | // agree with the total printed above its graph. Push events are | 301 | // agree with the total printed above its graph. Push events are |
| 336 | // excluded as in RecentEvents. | 302 | // excluded as in RecentEvents. |
| 337 | func (s *Store) UserPublicEvents(userID int64, limit int) ([]FeedEvent, error) { | 303 | func (s *Store) UserPublicEvents(userID int64, limit int) ([]FeedEvent, error) { |
| 338 | rows, err := s.DB.Query(` | 304 | return queryAll(s.DB, scanFeedEvent, feedSelect+`r.visibility = 'public' AND e.actor_id = ? |
| 339 | SELECT e.id, COALESCE(u.username, o.name) || '/' || r.name, | ||
| 340 | COALESCE(ac.username, ''), e.kind, e.data_json, e.created_at | ||
| 341 | FROM events e | ||
| 342 | JOIN repos r ON r.id = e.repo_id | ||
| 343 | LEFT JOIN users u ON r.owner_kind = 'user' AND u.id = r.owner_id | ||
| 344 | LEFT JOIN orgs o ON r.owner_kind = 'org' AND o.id = r.owner_id | ||
| 345 | LEFT JOIN users ac ON ac.id = e.actor_id | ||
| 346 | WHERE e.kind <> 'push' AND r.visibility = 'public' AND e.actor_id = ? | ||
| 347 | ORDER BY e.id DESC LIMIT ?`, userID, limit) | 305 | ORDER BY e.id DESC LIMIT ?`, userID, limit) |
| 348 | if err != nil { | ||
| 349 | return nil, err | ||
| 350 | } | ||
| 351 | defer rows.Close() | ||
| 352 | var out []FeedEvent | ||
| 353 | for rows.Next() { | ||
| 354 | var e FeedEvent | ||
| 355 | if err := rows.Scan(&e.ID, &e.RepoPath, &e.Actor, &e.Kind, &e.Data, &e.CreatedAt); err != nil { | ||
| 356 | return nil, err | ||
| 357 | } | ||
| 358 | out = append(out, e) | ||
| 359 | } | ||
| 360 | return out, rows.Err() | ||
| 361 | } | 306 | } |
| 362 | 307 | ||
| 363 | // RecentEvents returns activity on repositories the user can reach. Push | 308 | // RecentEvents returns activity on repositories the user can reach. Push |
| @@ -365,7 +310,19 @@ func (s *Store) UserPublicEvents(userID int64, limit int) ([]FeedEvent, error) { | |||
| 365 | // before (an event id) starts the page strictly below it, matching the | 310 | // before (an event id) starts the page strictly below it, matching the |
| 366 | // id-descending order; 0 starts at the newest. | 311 | // id-descending order; 0 starts at the newest. |
| 367 | func (s *Store) RecentEvents(userID int64, limit int, before int64) ([]FeedEvent, error) { | 312 | func (s *Store) RecentEvents(userID int64, limit int, before int64) ([]FeedEvent, error) { |
| 368 | q := ` | 313 | q := feedSelect + reachableCond |
| 314 | args := []any{userID, limit} | ||
| 315 | if before > 0 { | ||
| 316 | q += " AND e.id < ?3" | ||
| 317 | args = append(args, before) | ||
| 318 | } | ||
| 319 | q += " ORDER BY e.id DESC LIMIT ?2" | ||
| 320 | return queryAll(s.DB, scanFeedEvent, q, args...) | ||
| 321 | } | ||
| 322 | |||
| 323 | // feedSelect reads FeedEvents, push events left out; callers append the | ||
| 324 | // rest of the WHERE clause. | ||
| 325 | const feedSelect = ` | ||
| 369 | SELECT e.id, COALESCE(u.username, o.name) || '/' || r.name, | 326 | SELECT e.id, COALESCE(u.username, o.name) || '/' || r.name, |
| 370 | COALESCE(ac.username, ''), e.kind, e.data_json, e.created_at | 327 | COALESCE(ac.username, ''), e.kind, e.data_json, e.created_at |
| 371 | FROM events e | 328 | FROM events e |
| @@ -373,25 +330,10 @@ func (s *Store) RecentEvents(userID int64, limit int, before int64) ([]FeedEvent | |||
| 373 | LEFT JOIN users u ON r.owner_kind = 'user' AND u.id = r.owner_id | 330 | LEFT JOIN users u ON r.owner_kind = 'user' AND u.id = r.owner_id |
| 374 | LEFT JOIN orgs o ON r.owner_kind = 'org' AND o.id = r.owner_id | 331 | LEFT JOIN orgs o ON r.owner_kind = 'org' AND o.id = r.owner_id |
| 375 | LEFT JOIN users ac ON ac.id = e.actor_id | 332 | LEFT JOIN users ac ON ac.id = e.actor_id |
| 376 | WHERE e.kind <> 'push' AND ` + reachableCond | 333 | WHERE e.kind <> 'push' AND ` |
| 377 | args := []any{userID, limit} | 334 | |
| 378 | if before > 0 { | 335 | func scanFeedEvent(row interface{ Scan(...any) error }) (FeedEvent, error) { |
| 379 | q += " AND e.id < ?3" | 336 | var e FeedEvent |
| 380 | args = append(args, before) | 337 | err := row.Scan(&e.ID, &e.RepoPath, &e.Actor, &e.Kind, &e.Data, &e.CreatedAt) |
| 381 | } | 338 | return e, err |
| 382 | q += " ORDER BY e.id DESC LIMIT ?2" | ||
| 383 | rows, err := s.DB.Query(q, args...) | ||
| 384 | if err != nil { | ||
| 385 | return nil, err | ||
| 386 | } | ||
| 387 | defer rows.Close() | ||
| 388 | var out []FeedEvent | ||
| 389 | for rows.Next() { | ||
| 390 | var e FeedEvent | ||
| 391 | if err := rows.Scan(&e.ID, &e.RepoPath, &e.Actor, &e.Kind, &e.Data, &e.CreatedAt); err != nil { | ||
| 392 | return nil, err | ||
| 393 | } | ||
| 394 | out = append(out, e) | ||
| 395 | } | ||
| 396 | return out, rows.Err() | ||
| 397 | } | 339 | } |
internal/store/diffcomments.go +1 −14
| @@ -69,26 +69,13 @@ func (s *Store) AddDiffComment(mrID, authorID int64, headSHA, path, side string, | |||
| 69 | // see: everything published, plus their own pending ones. viewer 0 is an | 69 | // see: everything published, plus their own pending ones. viewer 0 is an |
| 70 | // anonymous reader, who sees only what is published. | 70 | // anonymous reader, who sees only what is published. |
| 71 | func (s *Store) ListDiffComments(mrID, viewer int64) ([]DiffComment, error) { | 71 | func (s *Store) ListDiffComments(mrID, viewer int64) ([]DiffComment, error) { |
| 72 | rows, err := s.DB.Query(` | 72 | return queryAll(s.DB, scanDiffComment, ` |
| 73 | SELECT `+diffCommentCols+` | 73 | SELECT `+diffCommentCols+` |
| 74 | FROM mr_diff_comments c | 74 | FROM mr_diff_comments c |
| 75 | JOIN users u ON u.id = c.author_id | 75 | JOIN users u ON u.id = c.author_id |
| 76 | LEFT JOIN users r ON r.id = c.resolved_by | 76 | LEFT JOIN users r ON r.id = c.resolved_by |
| 77 | WHERE c.mr_id = ?1 AND (c.pending = 0 OR c.author_id = ?2) | 77 | WHERE c.mr_id = ?1 AND (c.pending = 0 OR c.author_id = ?2) |
| 78 | ORDER BY c.id`, mrID, viewer) | 78 | ORDER BY c.id`, mrID, viewer) |
| 79 | if err != nil { | ||
| 80 | return nil, err | ||
| 81 | } | ||
| 82 | defer rows.Close() | ||
| 83 | var out []DiffComment | ||
| 84 | for rows.Next() { | ||
| 85 | c, err := scanDiffComment(rows) | ||
| 86 | if err != nil { | ||
| 87 | return nil, err | ||
| 88 | } | ||
| 89 | out = append(out, c) | ||
| 90 | } | ||
| 91 | return out, rows.Err() | ||
| 92 | } | 79 | } |
| 93 | 80 | ||
| 94 | const diffCommentCols = `c.id, u.username, c.head_sha, c.path, c.side, c.line, c.start_line, c.body, | 81 | const diffCommentCols = `c.id, u.username, c.head_sha, c.path, c.side, c.line, c.start_line, c.body, |
internal/store/issues.go +16 −6
| @@ -264,6 +264,12 @@ func (s *Store) QueryIssues(repoID int64, f IssueFilter) ([]Issue, error) { | |||
| 264 | // UpdateIssueText edits title, body, and/or markup format; nil leaves a field | 264 | // UpdateIssueText edits title, body, and/or markup format; nil leaves a field |
| 265 | // unchanged. | 265 | // unchanged. |
| 266 | func (s *Store) UpdateIssueText(issueID int64, title, body, format *string) error { | 266 | func (s *Store) UpdateIssueText(issueID int64, title, body, format *string) error { |
| 267 | return s.updateText("issues", issueID, title, body, format) | ||
| 268 | } | ||
| 269 | |||
| 270 | // updateText sets whichever of title, body and body_format are given on | ||
| 271 | // the row of table with id, and its updated_at. | ||
| 272 | func (s *Store) updateText(table string, id int64, title, body, format *string) error { | ||
| 267 | set, args := []string{}, []any{} | 273 | set, args := []string{}, []any{} |
| 268 | if title != nil { | 274 | if title != nil { |
| 269 | set, args = append(set, "title = ?"), append(args, *title) | 275 | set, args = append(set, "title = ?"), append(args, *title) |
| @@ -278,8 +284,8 @@ func (s *Store) UpdateIssueText(issueID int64, title, body, format *string) erro | |||
| 278 | return nil | 284 | return nil |
| 279 | } | 285 | } |
| 280 | set = append(set, "updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')") | 286 | set = append(set, "updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')") |
| 281 | args = append(args, issueID) | 287 | args = append(args, id) |
| 282 | res, err := s.DB.Exec("UPDATE issues SET "+strings.Join(set, ", ")+" WHERE id = ?", args...) | 288 | res, err := s.DB.Exec("UPDATE "+table+" SET "+strings.Join(set, ", ")+" WHERE id = ?", args...) |
| 283 | if err != nil { | 289 | if err != nil { |
| 284 | return err | 290 | return err |
| 285 | } | 291 | } |
| @@ -388,14 +394,18 @@ func (s *Store) SetIssueLabel(repo Repo, issueID int64, name string, add bool) e | |||
| 388 | 394 | ||
| 389 | // SetIssueAssignee adds or removes an assignee by user id. | 395 | // SetIssueAssignee adds or removes an assignee by user id. |
| 390 | func (s *Store) SetIssueAssignee(issueID, userID int64, add bool) error { | 396 | func (s *Store) SetIssueAssignee(issueID, userID int64, add bool) error { |
| 397 | return s.setItemUser("issue_assignees", "issue_id", issueID, userID, add) | ||
| 398 | } | ||
| 399 | |||
| 400 | // setItemUser adds or removes the (item, user) row of a join table. | ||
| 401 | func (s *Store) setItemUser(table, itemCol string, itemID, userID int64, add bool) error { | ||
| 391 | if add { | 402 | if add { |
| 392 | _, err := s.DB.Exec( | 403 | _, err := s.DB.Exec( |
| 393 | "INSERT INTO issue_assignees (issue_id, user_id) VALUES (?, ?) ON CONFLICT DO NOTHING", | 404 | "INSERT INTO "+table+" ("+itemCol+", user_id) VALUES (?, ?) ON CONFLICT DO NOTHING", |
| 394 | issueID, userID) | 405 | itemID, userID) |
| 395 | return err | 406 | return err |
| 396 | } | 407 | } |
| 397 | res, err := s.DB.Exec( | 408 | res, err := s.DB.Exec("DELETE FROM "+table+" WHERE "+itemCol+" = ? AND user_id = ?", itemID, userID) |
| 398 | "DELETE FROM issue_assignees WHERE issue_id = ? AND user_id = ?", issueID, userID) | ||
| 399 | if err != nil { | 409 | if err != nil { |
| 400 | return err | 410 | return err |
| 401 | } | 411 | } |
internal/store/mergequeue.go +1 −10
| @@ -86,14 +86,5 @@ func (s *Store) QueuedMRsAtHead(repoID int64, sha string) ([]int64, error) { | |||
| 86 | if err != nil { | 86 | if err != nil { |
| 87 | return nil, err | 87 | return nil, err |
| 88 | } | 88 | } |
| 89 | defer rows.Close() | 89 | return scanIDs(rows) |
| 90 | var ids []int64 | ||
| 91 | for rows.Next() { | ||
| 92 | var id int64 | ||
| 93 | if err := rows.Scan(&id); err != nil { | ||
| 94 | return nil, err | ||
| 95 | } | ||
| 96 | ids = append(ids, id) | ||
| 97 | } | ||
| 98 | return ids, rows.Err() | ||
| 99 | } | 90 | } |
internal/store/milestones.go +1 −14
| @@ -172,20 +172,7 @@ func (s *Store) listMilestones(where string, args []any, state string, readable | |||
| 172 | qargs = append(qargs, state) | 172 | qargs = append(qargs, state) |
| 173 | } | 173 | } |
| 174 | q += " ORDER BY m.org_id IS NULL, m.due_date = '', m.due_date, m.title" | 174 | q += " ORDER BY m.org_id IS NULL, m.due_date = '', m.due_date, m.title" |
| 175 | rows, err := s.DB.Query(q, qargs...) | 175 | return queryAll(s.DB, scanMilestone, q, qargs...) |
| 176 | if err != nil { | ||
| 177 | return nil, err | ||
| 178 | } | ||
| 179 | defer rows.Close() | ||
| 180 | var out []Milestone | ||
| 181 | for rows.Next() { | ||
| 182 | m, err := scanMilestone(rows) | ||
| 183 | if err != nil { | ||
| 184 | return nil, err | ||
| 185 | } | ||
| 186 | out = append(out, m) | ||
| 187 | } | ||
| 188 | return out, rows.Err() | ||
| 189 | } | 176 | } |
| 190 | 177 | ||
| 191 | // ListMilestones lists the milestones a repository sees, the org's first, | 178 | // ListMilestones lists the milestones a repository sees, the org's first, |
internal/store/mirrors.go +1 −14
| @@ -74,20 +74,7 @@ func (s *Store) scanMirror(row interface{ Scan(...any) error }) (Mirror, error) | |||
| 74 | } | 74 | } |
| 75 | 75 | ||
| 76 | func (s *Store) mirrorQuery(q string, args ...any) ([]Mirror, error) { | 76 | func (s *Store) mirrorQuery(q string, args ...any) ([]Mirror, error) { |
| 77 | rows, err := s.DB.Query(q, args...) | 77 | return queryAll(s.DB, s.scanMirror, q, args...) |
| 78 | if err != nil { | ||
| 79 | return nil, err | ||
| 80 | } | ||
| 81 | defer rows.Close() | ||
| 82 | var out []Mirror | ||
| 83 | for rows.Next() { | ||
| 84 | m, err := s.scanMirror(rows) | ||
| 85 | if err != nil { | ||
| 86 | return nil, err | ||
| 87 | } | ||
| 88 | out = append(out, m) | ||
| 89 | } | ||
| 90 | return out, rows.Err() | ||
| 91 | } | 78 | } |
| 92 | 79 | ||
| 93 | func (s *Store) ListMirrors(repoID int64) ([]Mirror, error) { | 80 | func (s *Store) ListMirrors(repoID int64) ([]Mirror, error) { |
internal/store/mrs.go +11 −112
| @@ -164,21 +164,7 @@ func (s *Store) SetMRLabel(repo Repo, mrID int64, name string, add bool) error { | |||
| 164 | // SetMRReviewRequest adds or removes a review request by user id — the | 164 | // SetMRReviewRequest adds or removes a review request by user id — the |
| 165 | // mr review request counterpart of SetIssueAssignee. | 165 | // mr review request counterpart of SetIssueAssignee. |
| 166 | func (s *Store) SetMRReviewRequest(mrID, userID int64, add bool) error { | 166 | func (s *Store) SetMRReviewRequest(mrID, userID int64, add bool) error { |
| 167 | if add { | 167 | return s.setItemUser("mr_review_requests", "mr_id", mrID, userID, add) |
| 168 | _, err := s.DB.Exec( | ||
| 169 | "INSERT INTO mr_review_requests (mr_id, user_id) VALUES (?, ?) ON CONFLICT DO NOTHING", | ||
| 170 | mrID, userID) | ||
| 171 | return err | ||
| 172 | } | ||
| 173 | res, err := s.DB.Exec( | ||
| 174 | "DELETE FROM mr_review_requests WHERE mr_id = ? AND user_id = ?", mrID, userID) | ||
| 175 | if err != nil { | ||
| 176 | return err | ||
| 177 | } | ||
| 178 | if n, _ := res.RowsAffected(); n == 0 { | ||
| 179 | return ErrNotFound | ||
| 180 | } | ||
| 181 | return nil | ||
| 182 | } | 168 | } |
| 183 | 169 | ||
| 184 | // MRReviewRequestIDs returns who has been asked for a review, by id — for | 170 | // MRReviewRequestIDs returns who has been asked for a review, by id — for |
| @@ -245,62 +231,23 @@ func (s *Store) QueryMRs(repoID int64, f MRFilter) ([]MR, error) { | |||
| 245 | q += " LIMIT ?" | 231 | q += " LIMIT ?" |
| 246 | args = append(args, f.Limit) | 232 | args = append(args, f.Limit) |
| 247 | } | 233 | } |
| 248 | rows, err := s.DB.Query(q, args...) | 234 | return queryAll(s.DB, scanMR, q, args...) |
| 249 | if err != nil { | ||
| 250 | return nil, err | ||
| 251 | } | ||
| 252 | defer rows.Close() | ||
| 253 | var out []MR | ||
| 254 | for rows.Next() { | ||
| 255 | m, err := scanMR(rows) | ||
| 256 | if err != nil { | ||
| 257 | return nil, err | ||
| 258 | } | ||
| 259 | out = append(out, m) | ||
| 260 | } | ||
| 261 | return out, rows.Err() | ||
| 262 | } | 235 | } |
| 263 | 236 | ||
| 264 | // OpenMRsBySource returns open (and source_gone) MRs fed by the given source | 237 | // OpenMRsBySource returns open (and source_gone) MRs fed by the given source |
| 265 | // repo branch — the cross-repo hook effect consults this. | 238 | // repo branch — the cross-repo hook effect consults this. |
| 266 | func (s *Store) OpenMRsBySource(sourceRepoID int64, sourceRef string) ([]MR, error) { | 239 | func (s *Store) OpenMRsBySource(sourceRepoID int64, sourceRef string) ([]MR, error) { |
| 267 | rows, err := s.DB.Query( | 240 | return queryAll(s.DB, scanMR, |
| 268 | mrSelect+" WHERE m.source_repo_id = ? AND m.source_ref = ? AND m.state IN ('open','source_gone')", | 241 | mrSelect+" WHERE m.source_repo_id = ? AND m.source_ref = ? AND m.state IN ('open','source_gone')", |
| 269 | sourceRepoID, sourceRef) | 242 | sourceRepoID, sourceRef) |
| 270 | if err != nil { | ||
| 271 | return nil, err | ||
| 272 | } | ||
| 273 | defer rows.Close() | ||
| 274 | var out []MR | ||
| 275 | for rows.Next() { | ||
| 276 | m, err := scanMR(rows) | ||
| 277 | if err != nil { | ||
| 278 | return nil, err | ||
| 279 | } | ||
| 280 | out = append(out, m) | ||
| 281 | } | ||
| 282 | return out, rows.Err() | ||
| 283 | } | 243 | } |
| 284 | 244 | ||
| 285 | // UnmergedMRsByTarget returns the open and source_gone MRs in repoID | 245 | // UnmergedMRsByTarget returns the open and source_gone MRs in repoID |
| 286 | // targeting targetRef, oldest first. | 246 | // targeting targetRef, oldest first. |
| 287 | func (s *Store) UnmergedMRsByTarget(repoID int64, targetRef string) ([]MR, error) { | 247 | func (s *Store) UnmergedMRsByTarget(repoID int64, targetRef string) ([]MR, error) { |
| 288 | rows, err := s.DB.Query( | 248 | return queryAll(s.DB, scanMR, |
| 289 | mrSelect+" WHERE m.repo_id = ? AND m.target_ref = ? AND m.state IN ('open','source_gone') ORDER BY m.number", | 249 | mrSelect+" WHERE m.repo_id = ? AND m.target_ref = ? AND m.state IN ('open','source_gone') ORDER BY m.number", |
| 290 | repoID, targetRef) | 250 | repoID, targetRef) |
| 291 | if err != nil { | ||
| 292 | return nil, err | ||
| 293 | } | ||
| 294 | defer rows.Close() | ||
| 295 | var out []MR | ||
| 296 | for rows.Next() { | ||
| 297 | m, err := scanMR(rows) | ||
| 298 | if err != nil { | ||
| 299 | return nil, err | ||
| 300 | } | ||
| 301 | out = append(out, m) | ||
| 302 | } | ||
| 303 | return out, rows.Err() | ||
| 304 | } | 251 | } |
| 305 | 252 | ||
| 306 | // MarkMerged records the merge along with the target tip it landed on, so | 253 | // MarkMerged records the merge along with the target tip it landed on, so |
| @@ -346,20 +293,7 @@ func (s *Store) SetSupersededBy(mrID, n int64) error { | |||
| 346 | // superseded_by names number, oldest first — the reverse of | 293 | // superseded_by names number, oldest first — the reverse of |
| 347 | // MR.SupersededBy. | 294 | // MR.SupersededBy. |
| 348 | func (s *Store) MRsSuperseding(repoID, number int64) ([]MR, error) { | 295 | func (s *Store) MRsSuperseding(repoID, number int64) ([]MR, error) { |
| 349 | rows, err := s.DB.Query(mrSelect+" WHERE m.repo_id = ? AND m.superseded_by = ? ORDER BY m.number ASC", repoID, number) | 296 | return queryAll(s.DB, scanMR, mrSelect+" WHERE m.repo_id = ? AND m.superseded_by = ? ORDER BY m.number ASC", repoID, number) |
| 350 | if err != nil { | ||
| 351 | return nil, err | ||
| 352 | } | ||
| 353 | defer rows.Close() | ||
| 354 | var out []MR | ||
| 355 | for rows.Next() { | ||
| 356 | m, err := scanMR(rows) | ||
| 357 | if err != nil { | ||
| 358 | return nil, err | ||
| 359 | } | ||
| 360 | out = append(out, m) | ||
| 361 | } | ||
| 362 | return out, rows.Err() | ||
| 363 | } | 297 | } |
| 364 | 298 | ||
| 365 | // SetMRState moves an MR between states that carry no resolution stamp. | 299 | // SetMRState moves an MR between states that carry no resolution stamp. |
| @@ -457,24 +391,11 @@ func (s *Store) MRHeads(mrID int64) ([]MRHead, error) { | |||
| 457 | // target on every read, so nothing else has to move; an approval, | 391 | // target on every read, so nothing else has to move; an approval, |
| 458 | // though, was of the diff against the old branch. | 392 | // though, was of the diff against the old branch. |
| 459 | func (s *Store) SetMRTarget(mrID int64, targetRef string) error { | 393 | func (s *Store) SetMRTarget(mrID int64, targetRef string) error { |
| 460 | tx, err := s.DB.Begin() | 394 | return s.execAll( |
| 461 | if err != nil { | 395 | stmt{"UPDATE merge_requests SET target_ref = ?, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?", |
| 462 | return err | 396 | []any{targetRef, mrID}}, |
| 463 | } | 397 | stmt{"UPDATE mr_reviews SET stale = 1 WHERE mr_id = ?", []any{mrID}}, |
| 464 | defer tx.Rollback() | 398 | ) |
| 465 | res, err := tx.Exec( | ||
| 466 | "UPDATE merge_requests SET target_ref = ?, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?", | ||
| 467 | targetRef, mrID) | ||
| 468 | if err != nil { | ||
| 469 | return err | ||
| 470 | } | ||
| 471 | if n, _ := res.RowsAffected(); n == 0 { | ||
| 472 | return ErrNotFound | ||
| 473 | } | ||
| 474 | if _, err := tx.Exec("UPDATE mr_reviews SET stale = 1 WHERE mr_id = ?", mrID); err != nil { | ||
| 475 | return err | ||
| 476 | } | ||
| 477 | return tx.Commit() | ||
| 478 | } | 399 | } |
| 479 | 400 | ||
| 480 | // MarkSourceGoneForRepo flags every open MR sourced from the repo; called | 401 | // MarkSourceGoneForRepo flags every open MR sourced from the repo; called |
| @@ -496,29 +417,7 @@ func (s *Store) AddMRComment(mrID, authorID int64, body, format string) error { | |||
| 496 | // UpdateMRText edits title, body, and/or markup format; nil leaves a field | 417 | // UpdateMRText edits title, body, and/or markup format; nil leaves a field |
| 497 | // unchanged. | 418 | // unchanged. |
| 498 | func (s *Store) UpdateMRText(mrID int64, title, body, format *string) error { | 419 | func (s *Store) UpdateMRText(mrID int64, title, body, format *string) error { |
| 499 | set, args := []string{}, []any{} | 420 | return s.updateText("merge_requests", mrID, title, body, format) |
| 500 | if title != nil { | ||
| 501 | set, args = append(set, "title = ?"), append(args, *title) | ||
| 502 | } | ||
| 503 | if body != nil { | ||
| 504 | set, args = append(set, "body = ?"), append(args, *body) | ||
| 505 | } | ||
| 506 | if format != nil { | ||
| 507 | set, args = append(set, "body_format = ?"), append(args, *format) | ||
| 508 | } | ||
| 509 | if len(set) == 0 { | ||
| 510 | return nil | ||
| 511 | } | ||
| 512 | set = append(set, "updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')") | ||
| 513 | args = append(args, mrID) | ||
| 514 | res, err := s.DB.Exec("UPDATE merge_requests SET "+strings.Join(set, ", ")+" WHERE id = ?", args...) | ||
| 515 | if err != nil { | ||
| 516 | return err | ||
| 517 | } | ||
| 518 | if n, _ := res.RowsAffected(); n == 0 { | ||
| 519 | return ErrNotFound | ||
| 520 | } | ||
| 521 | return nil | ||
| 522 | } | 421 | } |
| 523 | 422 | ||
| 524 | // AddMRSystemComment is the informational counterpart of AddMRComment. | 423 | // AddMRSystemComment is the informational counterpart of AddMRComment. |
internal/store/notify.go +7 −14
| @@ -26,24 +26,11 @@ func (s *Store) EnqueueMailReplyTo(recipient, replyTo, subject, body string) err | |||
| 26 | } | 26 | } |
| 27 | 27 | ||
| 28 | func (s *Store) DueMail(limit int) ([]QueuedMail, error) { | 28 | func (s *Store) DueMail(limit int) ([]QueuedMail, error) { |
| 29 | rows, err := s.DB.Query(` | 29 | return queryAll(s.DB, scanQueuedMail, ` |
| 30 | SELECT id, recipient, reply_to, subject, body, attempts FROM notifications | 30 | SELECT id, recipient, reply_to, subject, body, attempts FROM notifications |
| 31 | WHERE sent_at IS NULL AND failed_at IS NULL | 31 | WHERE sent_at IS NULL AND failed_at IS NULL |
| 32 | AND (next_attempt_at IS NULL OR next_attempt_at <= ?) | 32 | AND (next_attempt_at IS NULL OR next_attempt_at <= ?) |
| 33 | ORDER BY id LIMIT ?`, fmtTime(time.Now()), limit) | 33 | ORDER BY id LIMIT ?`, fmtTime(time.Now()), limit) |
| 34 | if err != nil { | ||
| 35 | return nil, err | ||
| 36 | } | ||
| 37 | defer rows.Close() | ||
| 38 | var out []QueuedMail | ||
| 39 | for rows.Next() { | ||
| 40 | var m QueuedMail | ||
| 41 | if err := rows.Scan(&m.ID, &m.Recipient, &m.ReplyTo, &m.Subject, &m.Body, &m.Attempts); err != nil { | ||
| 42 | return nil, err | ||
| 43 | } | ||
| 44 | out = append(out, m) | ||
| 45 | } | ||
| 46 | return out, rows.Err() | ||
| 47 | } | 34 | } |
| 48 | 35 | ||
| 49 | func (s *Store) MarkMailSent(id int64) error { | 36 | func (s *Store) MarkMailSent(id int64) error { |
| @@ -124,3 +111,9 @@ func (s *Store) idQuery(q string, args ...any) ([]int64, error) { | |||
| 124 | } | 111 | } |
| 125 | return out, rows.Err() | 112 | return out, rows.Err() |
| 126 | } | 113 | } |
| 114 | |||
| 115 | func scanQueuedMail(row interface{ Scan(...any) error }) (QueuedMail, error) { | ||
| 116 | var m QueuedMail | ||
| 117 | err := row.Scan(&m.ID, &m.Recipient, &m.ReplyTo, &m.Subject, &m.Body, &m.Attempts) | ||
| 118 | return m, err | ||
| 119 | } | ||
internal/store/pagedomains.go +1 −14
| @@ -92,20 +92,7 @@ func (s *Store) VerifyPageDomain(domain string, repoID int64) error { | |||
| 92 | } | 92 | } |
| 93 | 93 | ||
| 94 | func (s *Store) ListPageDomains(repoID int64) ([]PageDomain, error) { | 94 | func (s *Store) ListPageDomains(repoID int64) ([]PageDomain, error) { |
| 95 | rows, err := s.DB.Query(pageDomainSelect+" WHERE repo_id = ? ORDER BY domain", repoID) | 95 | return queryAll(s.DB, scanPageDomain, pageDomainSelect+" WHERE repo_id = ? ORDER BY domain", repoID) |
| 96 | if err != nil { | ||
| 97 | return nil, err | ||
| 98 | } | ||
| 99 | defer rows.Close() | ||
| 100 | var out []PageDomain | ||
| 101 | for rows.Next() { | ||
| 102 | d, err := scanPageDomain(rows) | ||
| 103 | if err != nil { | ||
| 104 | return nil, err | ||
| 105 | } | ||
| 106 | out = append(out, d) | ||
| 107 | } | ||
| 108 | return out, rows.Err() | ||
| 109 | } | 96 | } |
| 110 | 97 | ||
| 111 | // PageDomainRepo resolves a request host to the repo serving it. Only | 98 | // PageDomainRepo resolves a request host to the repo serving it. Only |
internal/store/push.go +15 −17
| @@ -167,7 +167,7 @@ func (s *Store) EnqueuePush(userID int64, title, body, path string) error { | |||
| 167 | } | 167 | } |
| 168 | 168 | ||
| 169 | func (s *Store) DuePush(limit int) ([]QueuedPush, error) { | 169 | func (s *Store) DuePush(limit int) ([]QueuedPush, error) { |
| 170 | rows, err := s.DB.Query(` | 170 | return queryAll(s.DB, s.scanQueuedPush, ` |
| 171 | SELECT q.id, q.device_id, d.token, d.user_id, COALESCE(d.token_hash, ''), u.username, q.title, q.body, q.path, q.attempts, | 171 | SELECT q.id, q.device_id, d.token, d.user_id, COALESCE(d.token_hash, ''), u.username, q.title, q.body, q.path, q.attempts, |
| 172 | (SELECT COUNT(*) FROM inbox WHERE user_id = d.user_id AND read_at IS NULL) | 172 | (SELECT COUNT(*) FROM inbox WHERE user_id = d.user_id AND read_at IS NULL) |
| 173 | FROM push_queue q | 173 | FROM push_queue q |
| @@ -176,24 +176,22 @@ func (s *Store) DuePush(limit int) ([]QueuedPush, error) { | |||
| 176 | WHERE q.sent_at IS NULL AND q.failed_at IS NULL | 176 | WHERE q.sent_at IS NULL AND q.failed_at IS NULL |
| 177 | AND (q.next_attempt_at IS NULL OR q.next_attempt_at <= ?) | 177 | AND (q.next_attempt_at IS NULL OR q.next_attempt_at <= ?) |
| 178 | ORDER BY q.id LIMIT ?`, fmtTime(time.Now()), limit) | 178 | ORDER BY q.id LIMIT ?`, fmtTime(time.Now()), limit) |
| 179 | } | ||
| 180 | |||
| 181 | // scanQueuedPush reads a due push and opens its device token. | ||
| 182 | func (s *Store) scanQueuedPush(row interface{ Scan(...any) error }) (QueuedPush, error) { | ||
| 183 | var p QueuedPush | ||
| 184 | var uid int64 | ||
| 185 | var h string | ||
| 186 | if err := row.Scan(&p.ID, &p.DeviceID, &p.Token, &uid, &h, &p.Username, &p.Title, &p.Body, &p.Path, &p.Attempts, &p.Badge); err != nil { | ||
| 187 | return p, err | ||
| 188 | } | ||
| 189 | token, err := s.openValue(pushTokenAAD(uid, h), p.Token) | ||
| 179 | if err != nil { | 190 | if err != nil { |
| 180 | return nil, err | 191 | return p, fmt.Errorf("push device %d: %w", p.DeviceID, err) |
| 181 | } | ||
| 182 | defer rows.Close() | ||
| 183 | var out []QueuedPush | ||
| 184 | for rows.Next() { | ||
| 185 | var p QueuedPush | ||
| 186 | var uid int64 | ||
| 187 | var h string | ||
| 188 | if err := rows.Scan(&p.ID, &p.DeviceID, &p.Token, &uid, &h, &p.Username, &p.Title, &p.Body, &p.Path, &p.Attempts, &p.Badge); err != nil { | ||
| 189 | return nil, err | ||
| 190 | } | ||
| 191 | if p.Token, err = s.openValue(pushTokenAAD(uid, h), p.Token); err != nil { | ||
| 192 | return nil, fmt.Errorf("push device %d: %w", p.DeviceID, err) | ||
| 193 | } | ||
| 194 | out = append(out, p) | ||
| 195 | } | 192 | } |
| 196 | return out, rows.Err() | 193 | p.Token = token |
| 194 | return p, nil | ||
| 197 | } | 195 | } |
| 198 | 196 | ||
| 199 | func (s *Store) MarkPushSent(id int64) error { | 197 | func (s *Store) MarkPushSent(id int64) error { |
internal/store/repos.go +4 −56
| @@ -257,20 +257,7 @@ func (s *Store) ListReposForUser(userID int64, limit int, after string) ([]Repo, | |||
| 257 | q += " LIMIT ?" | 257 | q += " LIMIT ?" |
| 258 | args = append(args, limit) | 258 | args = append(args, limit) |
| 259 | } | 259 | } |
| 260 | rows, err := s.DB.Query(q, args...) | 260 | return queryAll(s.DB, scanRepo, q, args...) |
| 261 | if err != nil { | ||
| 262 | return nil, err | ||
| 263 | } | ||
| 264 | defer rows.Close() | ||
| 265 | var out []Repo | ||
| 266 | for rows.Next() { | ||
| 267 | r, err := scanRepo(rows) | ||
| 268 | if err != nil { | ||
| 269 | return nil, err | ||
| 270 | } | ||
| 271 | out = append(out, r) | ||
| 272 | } | ||
| 273 | return out, rows.Err() | ||
| 274 | } | 261 | } |
| 275 | 262 | ||
| 276 | // AccessRole returns the user's effective role on the repo ("" if none): | 263 | // AccessRole returns the user's effective role on the repo ("" if none): |
| @@ -444,20 +431,7 @@ func (s *Store) RepoByID(id int64) (Repo, error) { | |||
| 444 | 431 | ||
| 445 | // ListPublicRepos returns all public repositories, for the anonymous index. | 432 | // ListPublicRepos returns all public repositories, for the anonymous index. |
| 446 | func (s *Store) ListPublicRepos() ([]Repo, error) { | 433 | func (s *Store) ListPublicRepos() ([]Repo, error) { |
| 447 | rows, err := s.DB.Query(repoSelect + " WHERE r.visibility = 'public' ORDER BY 4, r.name") | 434 | return queryAll(s.DB, scanRepo, repoSelect+" WHERE r.visibility = 'public' ORDER BY 4, r.name") |
| 448 | if err != nil { | ||
| 449 | return nil, err | ||
| 450 | } | ||
| 451 | defer rows.Close() | ||
| 452 | var out []Repo | ||
| 453 | for rows.Next() { | ||
| 454 | r, err := scanRepo(rows) | ||
| 455 | if err != nil { | ||
| 456 | return nil, err | ||
| 457 | } | ||
| 458 | out = append(out, r) | ||
| 459 | } | ||
| 460 | return out, rows.Err() | ||
| 461 | } | 435 | } |
| 462 | 436 | ||
| 463 | // ListPublicReposByActivity returns all public repositories, the most | 437 | // ListPublicReposByActivity returns all public repositories, the most |
| @@ -486,20 +460,7 @@ func (s *Store) ListPublicReposByActivity() ([]Repo, error) { | |||
| 486 | // ListForks returns the repositories forked from one repo. The caller | 460 | // ListForks returns the repositories forked from one repo. The caller |
| 487 | // filters by what the viewer may see. | 461 | // filters by what the viewer may see. |
| 488 | func (s *Store) ListForks(repoID int64) ([]Repo, error) { | 462 | func (s *Store) ListForks(repoID int64) ([]Repo, error) { |
| 489 | rows, err := s.DB.Query(repoSelect+" WHERE r.fork_of = ? ORDER BY 4, r.name", repoID) | 463 | return queryAll(s.DB, scanRepo, repoSelect+" WHERE r.fork_of = ? ORDER BY 4, r.name", repoID) |
| 490 | if err != nil { | ||
| 491 | return nil, err | ||
| 492 | } | ||
| 493 | defer rows.Close() | ||
| 494 | var out []Repo | ||
| 495 | for rows.Next() { | ||
| 496 | r, err := scanRepo(rows) | ||
| 497 | if err != nil { | ||
| 498 | return nil, err | ||
| 499 | } | ||
| 500 | out = append(out, r) | ||
| 501 | } | ||
| 502 | return out, rows.Err() | ||
| 503 | } | 464 | } |
| 504 | 465 | ||
| 505 | func (s *Store) UpdateDefaultBranch(repoID int64, branch string) error { | 466 | func (s *Store) UpdateDefaultBranch(repoID int64, branch string) error { |
| @@ -510,21 +471,8 @@ func (s *Store) UpdateDefaultBranch(repoID int64, branch string) error { | |||
| 510 | // ListReposForOwner returns every repo owned by one user or org; the caller | 471 | // ListReposForOwner returns every repo owned by one user or org; the caller |
| 511 | // filters by viewer visibility. | 472 | // filters by viewer visibility. |
| 512 | func (s *Store) ListReposForOwner(ownerKind string, ownerID int64) ([]Repo, error) { | 473 | func (s *Store) ListReposForOwner(ownerKind string, ownerID int64) ([]Repo, error) { |
| 513 | rows, err := s.DB.Query(repoSelect+" WHERE r.owner_kind = ? AND r.owner_id = ? ORDER BY r.name", | 474 | return queryAll(s.DB, scanRepo, repoSelect+" WHERE r.owner_kind = ? AND r.owner_id = ? ORDER BY r.name", |
| 514 | ownerKind, ownerID) | 475 | ownerKind, ownerID) |
| 515 | if err != nil { | ||
| 516 | return nil, err | ||
| 517 | } | ||
| 518 | defer rows.Close() | ||
| 519 | var out []Repo | ||
| 520 | for rows.Next() { | ||
| 521 | r, err := scanRepo(rows) | ||
| 522 | if err != nil { | ||
| 523 | return nil, err | ||
| 524 | } | ||
| 525 | out = append(out, r) | ||
| 526 | } | ||
| 527 | return out, rows.Err() | ||
| 528 | } | 476 | } |
| 529 | 477 | ||
| 530 | // RenameRepo changes a repository's name under the same owner. The unique | 478 | // RenameRepo changes a repository's name under the same owner. The unique |
internal/store/search.go +1 −14
| @@ -11,20 +11,7 @@ const visibleCond = `(r.visibility = 'public' OR ` + reachableCond + `)` | |||
| 11 | // VisibleRepos returns every repository the user may read, public ones | 11 | // VisibleRepos returns every repository the user may read, public ones |
| 12 | // included, ordered by owner then name. | 12 | // included, ordered by owner then name. |
| 13 | func (s *Store) VisibleRepos(userID int64) ([]Repo, error) { | 13 | func (s *Store) VisibleRepos(userID int64) ([]Repo, error) { |
| 14 | rows, err := s.DB.Query(repoSelect+" WHERE "+visibleCond+" ORDER BY 4, r.name", userID) | 14 | return queryAll(s.DB, scanRepo, repoSelect+" WHERE "+visibleCond+" ORDER BY 4, r.name", userID) |
| 15 | if err != nil { | ||
| 16 | return nil, err | ||
| 17 | } | ||
| 18 | defer rows.Close() | ||
| 19 | var out []Repo | ||
| 20 | for rows.Next() { | ||
| 21 | r, err := scanRepo(rows) | ||
| 22 | if err != nil { | ||
| 23 | return nil, err | ||
| 24 | } | ||
| 25 | out = append(out, r) | ||
| 26 | } | ||
| 27 | return out, rows.Err() | ||
| 28 | } | 15 | } |
| 29 | 16 | ||
| 30 | // SearchIssues returns issues matching q in title or body, newest | 17 | // SearchIssues returns issues matching q in title or body, newest |
internal/store/snippets.go +4 −16
| @@ -206,20 +206,8 @@ func (s *Store) SetSnippetFile(id int64, name string, content []byte) error { | |||
| 206 | } | 206 | } |
| 207 | 207 | ||
| 208 | func (s *Store) RemoveSnippetFile(id int64, name string) error { | 208 | func (s *Store) RemoveSnippetFile(id int64, name string) error { |
| 209 | tx, err := s.DB.Begin() | 209 | return s.execAll( |
| 210 | if err != nil { | 210 | stmt{"DELETE FROM snippet_files WHERE snippet_id = ? AND name = ?", []any{id, name}}, |
| 211 | return err | 211 | stmt{"UPDATE snippets SET updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?", []any{id}}, |
| 212 | } | 212 | ) |
| 213 | defer tx.Rollback() | ||
| 214 | res, err := tx.Exec("DELETE FROM snippet_files WHERE snippet_id = ? AND name = ?", id, name) | ||
| 215 | if err != nil { | ||
| 216 | return err | ||
| 217 | } | ||
| 218 | if n, _ := res.RowsAffected(); n == 0 { | ||
| 219 | return ErrNotFound | ||
| 220 | } | ||
| 221 | if _, err := tx.Exec("UPDATE snippets SET updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?", id); err != nil { | ||
| 222 | return err | ||
| 223 | } | ||
| 224 | return tx.Commit() | ||
| 225 | } | 213 | } |
internal/store/stack.go +1 −14
| @@ -12,22 +12,9 @@ import ( | |||
| 12 | // OpenMRsByTarget lists the open merge requests in repoID targeting | 12 | // OpenMRsByTarget lists the open merge requests in repoID targeting |
| 13 | // targetRef, oldest first. | 13 | // targetRef, oldest first. |
| 14 | func (s *Store) OpenMRsByTarget(repoID int64, targetRef string) ([]MR, error) { | 14 | func (s *Store) OpenMRsByTarget(repoID int64, targetRef string) ([]MR, error) { |
| 15 | rows, err := s.DB.Query( | 15 | return queryAll(s.DB, scanMR, |
| 16 | mrSelect+" WHERE m.repo_id = ? AND m.target_ref = ? AND m.state = 'open' ORDER BY m.number", | 16 | mrSelect+" WHERE m.repo_id = ? AND m.target_ref = ? AND m.state = 'open' ORDER BY m.number", |
| 17 | repoID, targetRef) | 17 | repoID, targetRef) |
| 18 | if err != nil { | ||
| 19 | return nil, err | ||
| 20 | } | ||
| 21 | defer rows.Close() | ||
| 22 | var out []MR | ||
| 23 | for rows.Next() { | ||
| 24 | m, err := scanMR(rows) | ||
| 25 | if err != nil { | ||
| 26 | return nil, err | ||
| 27 | } | ||
| 28 | out = append(out, m) | ||
| 29 | } | ||
| 30 | return out, rows.Err() | ||
| 31 | } | 18 | } |
| 32 | 19 | ||
| 33 | // OpenMRBySource finds the open merge request in repoID whose source is | 20 | // OpenMRBySource finds the open merge request in repoID whose source is |
internal/store/stats.go +1 −14
| @@ -2,20 +2,7 @@ package store | |||
| 2 | 2 | ||
| 3 | // ListAllRepos returns every repository, for host-local admin tooling. | 3 | // ListAllRepos returns every repository, for host-local admin tooling. |
| 4 | func (s *Store) ListAllRepos() ([]Repo, error) { | 4 | func (s *Store) ListAllRepos() ([]Repo, error) { |
| 5 | rows, err := s.DB.Query(repoSelect + " ORDER BY 4, r.name") | 5 | return queryAll(s.DB, scanRepo, repoSelect+" ORDER BY 4, r.name") |
| 6 | if err != nil { | ||
| 7 | return nil, err | ||
| 8 | } | ||
| 9 | defer rows.Close() | ||
| 10 | var out []Repo | ||
| 11 | for rows.Next() { | ||
| 12 | r, err := scanRepo(rows) | ||
| 13 | if err != nil { | ||
| 14 | return nil, err | ||
| 15 | } | ||
| 16 | out = append(out, r) | ||
| 17 | } | ||
| 18 | return out, rows.Err() | ||
| 19 | } | 6 | } |
| 20 | 7 | ||
| 21 | type Counts struct { | 8 | type Counts struct { |
internal/store/statuses.go +7 −14
| @@ -34,23 +34,10 @@ func (s *Store) SetCommitStatus(repoID int64, sha, context, state, description, | |||
| 34 | 34 | ||
| 35 | // ListCommitStatuses returns the latest status per context for a commit. | 35 | // ListCommitStatuses returns the latest status per context for a commit. |
| 36 | func (s *Store) ListCommitStatuses(repoID int64, sha string) ([]CommitStatus, error) { | 36 | func (s *Store) ListCommitStatuses(repoID int64, sha string) ([]CommitStatus, error) { |
| 37 | rows, err := s.DB.Query(` | 37 | return queryAll(s.DB, scanCommitStatus, ` |
| 38 | SELECT cs.context, cs.state, cs.description, cs.target_url, COALESCE(u.username, ''), cs.updated_at | 38 | SELECT cs.context, cs.state, cs.description, cs.target_url, COALESCE(u.username, ''), cs.updated_at |
| 39 | FROM commit_statuses cs LEFT JOIN users u ON u.id = cs.creator_id | 39 | FROM commit_statuses cs LEFT JOIN users u ON u.id = cs.creator_id |
| 40 | WHERE cs.repo_id = ? AND cs.commit_sha = ? ORDER BY cs.context`, repoID, sha) | 40 | WHERE cs.repo_id = ? AND cs.commit_sha = ? ORDER BY cs.context`, repoID, sha) |
| 41 | if err != nil { | ||
| 42 | return nil, err | ||
| 43 | } | ||
| 44 | defer rows.Close() | ||
| 45 | var out []CommitStatus | ||
| 46 | for rows.Next() { | ||
| 47 | var c CommitStatus | ||
| 48 | if err := rows.Scan(&c.Context, &c.State, &c.Description, &c.TargetURL, &c.Creator, &c.UpdatedAt); err != nil { | ||
| 49 | return nil, err | ||
| 50 | } | ||
| 51 | out = append(out, c) | ||
| 52 | } | ||
| 53 | return out, rows.Err() | ||
| 54 | } | 41 | } |
| 55 | 42 | ||
| 56 | // CommitStatusesFor is ListCommitStatuses for every commit on a list | 43 | // CommitStatusesFor is ListCommitStatuses for every commit on a list |
| @@ -188,3 +175,9 @@ func (s *Store) ChecksForCommit(repoID int64, sha string) ([]Check, string, erro | |||
| 188 | } | 175 | } |
| 189 | return checks, CombinedStatus(statuses), nil | 176 | return checks, CombinedStatus(statuses), nil |
| 190 | } | 177 | } |
| 178 | |||
| 179 | func scanCommitStatus(row interface{ Scan(...any) error }) (CommitStatus, error) { | ||
| 180 | var c CommitStatus | ||
| 181 | err := row.Scan(&c.Context, &c.State, &c.Description, &c.TargetURL, &c.Creator, &c.UpdatedAt) | ||
| 182 | return c, err | ||
| 183 | } | ||
internal/store/store.go +53 −3
| @@ -311,7 +311,57 @@ func (s *Store) migrateStep(sqlText string, newVersion int, fkOff bool) (retErr | |||
| 311 | func IsInternal(err error) bool { | 311 | func IsInternal(err error) bool { |
| 312 | var sqlErr *sqlite.Error | 312 | var sqlErr *sqlite.Error |
| 313 | var pathErr *fs.PathError | 313 | var pathErr *fs.PathError |
| 314 | return errors.As(err, &sqlErr) || errors.As(err, &pathErr) || | 314 | if errors.As(err, &sqlErr) || errors.As(err, &pathErr) { |
| 315 | errors.Is(err, sql.ErrTxDone) || errors.Is(err, sql.ErrConnDone) || | 315 | return true |
| 316 | errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) | 316 | } |
| 317 | for _, target := range []error{sql.ErrTxDone, sql.ErrConnDone, context.DeadlineExceeded, context.Canceled} { | ||
| 318 | if errors.Is(err, target) { | ||
| 319 | return true | ||
| 320 | } | ||
| 321 | } | ||
| 322 | return false | ||
| 323 | } | ||
| 324 | |||
| 325 | // stmt is one statement and its arguments. | ||
| 326 | type stmt struct { | ||
| 327 | query string | ||
| 328 | args []any | ||
| 329 | } | ||
| 330 | |||
| 331 | // execAll runs stmts in one transaction. The first must change a row; | ||
| 332 | // when it changes none, nothing is kept and the error is ErrNotFound. | ||
| 333 | func (s *Store) execAll(stmts ...stmt) error { | ||
| 334 | tx, err := s.DB.Begin() | ||
| 335 | if err != nil { | ||
| 336 | return err | ||
| 337 | } | ||
| 338 | defer tx.Rollback() | ||
| 339 | for i, st := range stmts { | ||
| 340 | res, err := tx.Exec(st.query, st.args...) | ||
| 341 | if err != nil { | ||
| 342 | return err | ||
| 343 | } | ||
| 344 | if n, _ := res.RowsAffected(); i == 0 && n == 0 { | ||
| 345 | return ErrNotFound | ||
| 346 | } | ||
| 347 | } | ||
| 348 | return tx.Commit() | ||
| 349 | } | ||
| 350 | |||
| 351 | // queryAll runs query on q and reads every row it returns with scan. | ||
| 352 | func queryAll[T any](q queryer, scan func(interface{ Scan(...any) error }) (T, error), query string, args ...any) ([]T, error) { | ||
| 353 | rows, err := q.Query(query, args...) | ||
| 354 | if err != nil { | ||
| 355 | return nil, err | ||
| 356 | } | ||
| 357 | defer rows.Close() | ||
| 358 | var out []T | ||
| 359 | for rows.Next() { | ||
| 360 | v, err := scan(rows) | ||
| 361 | if err != nil { | ||
| 362 | return nil, err | ||
| 363 | } | ||
| 364 | out = append(out, v) | ||
| 365 | } | ||
| 366 | return out, rows.Err() | ||
| 317 | } | 367 | } |
internal/store/users.go +16 −38
| @@ -140,20 +140,7 @@ func (s *Store) OwnerExists(name string) bool { | |||
| 140 | } | 140 | } |
| 141 | 141 | ||
| 142 | func (s *Store) UserByUsername(name string) (User, error) { | 142 | func (s *Store) UserByUsername(name string) (User, error) { |
| 143 | var u User | 143 | return s.userBy("username", name) |
| 144 | var admin, pending, disabled, ghost int | ||
| 145 | var deleteAfter sql.NullString | ||
| 146 | err := s.DB.QueryRow("SELECT id, username, is_admin, pending, disabled, delete_after, ghost FROM users WHERE username = ?", name). | ||
| 147 | Scan(&u.ID, &u.Username, &admin, &pending, &disabled, &deleteAfter, &ghost) | ||
| 148 | if errors.Is(err, sql.ErrNoRows) { | ||
| 149 | return u, ErrNotFound | ||
| 150 | } | ||
| 151 | u.IsAdmin = admin != 0 | ||
| 152 | u.Pending = pending != 0 | ||
| 153 | u.Disabled = disabled != 0 | ||
| 154 | u.DeleteAfter = deleteAfter.String | ||
| 155 | u.Ghost = ghost != 0 | ||
| 156 | return u, err | ||
| 157 | } | 144 | } |
| 158 | 145 | ||
| 159 | // UserEmailAddresses returns every address on the account, verified or not. | 146 | // UserEmailAddresses returns every address on the account, verified or not. |
| @@ -333,10 +320,15 @@ func (s *Store) SetDiffLayout(userID int64, layout string) error { | |||
| 333 | } | 320 | } |
| 334 | 321 | ||
| 335 | func (s *Store) UserByID(id int64) (User, error) { | 322 | func (s *Store) UserByID(id int64) (User, error) { |
| 323 | return s.userBy("id", id) | ||
| 324 | } | ||
| 325 | |||
| 326 | // userBy reads the account whose column equals v. | ||
| 327 | func (s *Store) userBy(column string, v any) (User, error) { | ||
| 336 | var u User | 328 | var u User |
| 337 | var admin, pending, disabled, ghost int | 329 | var admin, pending, disabled, ghost int |
| 338 | var deleteAfter sql.NullString | 330 | var deleteAfter sql.NullString |
| 339 | err := s.DB.QueryRow("SELECT id, username, is_admin, pending, disabled, delete_after, ghost FROM users WHERE id = ?", id). | 331 | err := s.DB.QueryRow("SELECT id, username, is_admin, pending, disabled, delete_after, ghost FROM users WHERE "+column+" = ?", v). |
| 340 | Scan(&u.ID, &u.Username, &admin, &pending, &disabled, &deleteAfter, &ghost) | 332 | Scan(&u.ID, &u.Username, &admin, &pending, &disabled, &deleteAfter, &ghost) |
| 341 | if errors.Is(err, sql.ErrNoRows) { | 333 | if errors.Is(err, sql.ErrNoRows) { |
| 342 | return u, ErrNotFound | 334 | return u, ErrNotFound |
| @@ -388,13 +380,19 @@ func (s *Store) AddSSHKeyFrom(userID int64, fingerprint, algo string, blob []byt | |||
| 388 | // RemoveSSHKey removes a key owned by userID, bumps the key epoch, and | 380 | // RemoveSSHKey removes a key owned by userID, bumps the key epoch, and |
| 389 | // announces the revocation. | 381 | // announces the revocation. |
| 390 | func (s *Store) RemoveSSHKey(userID int64, fingerprint string) error { | 382 | func (s *Store) RemoveSSHKey(userID int64, fingerprint string) error { |
| 383 | return s.removeKey("DELETE FROM ssh_keys WHERE user_id = ? AND fingerprint = ? RETURNING id", userID, fingerprint) | ||
| 384 | } | ||
| 385 | |||
| 386 | // removeKey deletes the key that query (a DELETE ... RETURNING id) | ||
| 387 | // matches, bumps the key epoch, and announces the revocation. | ||
| 388 | func (s *Store) removeKey(query string, args ...any) error { | ||
| 391 | tx, err := s.DB.Begin() | 389 | tx, err := s.DB.Begin() |
| 392 | if err != nil { | 390 | if err != nil { |
| 393 | return err | 391 | return err |
| 394 | } | 392 | } |
| 395 | defer tx.Rollback() | 393 | defer tx.Rollback() |
| 396 | var id int64 | 394 | var id int64 |
| 397 | err = tx.QueryRow("DELETE FROM ssh_keys WHERE user_id = ? AND fingerprint = ? RETURNING id", userID, fingerprint).Scan(&id) | 395 | err = tx.QueryRow(query, args...).Scan(&id) |
| 398 | if errors.Is(err, sql.ErrNoRows) { | 396 | if errors.Is(err, sql.ErrNoRows) { |
| 399 | return ErrNotFound | 397 | return ErrNotFound |
| 400 | } | 398 | } |
| @@ -647,27 +645,7 @@ func (s *Store) ListDeployKeys(repoID int64) ([]SSHKey, error) { | |||
| 647 | // RemoveDeployKey removes a deploy key from a repository by fingerprint; | 645 | // RemoveDeployKey removes a deploy key from a repository by fingerprint; |
| 648 | // any repo admin may remove it regardless of who added it. | 646 | // any repo admin may remove it regardless of who added it. |
| 649 | func (s *Store) RemoveDeployKey(repoID int64, fingerprint string) error { | 647 | func (s *Store) RemoveDeployKey(repoID int64, fingerprint string) error { |
| 650 | tx, err := s.DB.Begin() | 648 | return s.removeKey( |
| 651 | if err != nil { | ||
| 652 | return err | ||
| 653 | } | ||
| 654 | defer tx.Rollback() | ||
| 655 | var id int64 | ||
| 656 | err = tx.QueryRow( | ||
| 657 | "DELETE FROM ssh_keys WHERE fingerprint = ? AND scope LIKE 'deploy:' || ? || ':%' RETURNING id", | 649 | "DELETE FROM ssh_keys WHERE fingerprint = ? AND scope LIKE 'deploy:' || ? || ':%' RETURNING id", |
| 658 | fingerprint, repoID).Scan(&id) | 650 | fingerprint, repoID) |
| 659 | if errors.Is(err, sql.ErrNoRows) { | ||
| 660 | return ErrNotFound | ||
| 661 | } | ||
| 662 | if err != nil { | ||
| 663 | return err | ||
| 664 | } | ||
| 665 | if err := bumpKeyEpoch(tx); err != nil { | ||
| 666 | return err | ||
| 667 | } | ||
| 668 | if err := tx.Commit(); err != nil { | ||
| 669 | return err | ||
| 670 | } | ||
| 671 | s.announce(Revoked{KeyIDs: []int64{id}}) | ||
| 672 | return nil | ||
| 673 | } | 651 | } |
internal/store/webhooks.go +21 −30
| @@ -106,7 +106,7 @@ func (s *Store) RemoveWebhook(repoID, hookID int64) error { | |||
| 106 | // DueDeliveries returns pending deliveries whose time has come, with the | 106 | // DueDeliveries returns pending deliveries whose time has come, with the |
| 107 | // event and hook context needed to send them. | 107 | // event and hook context needed to send them. |
| 108 | func (s *Store) DueDeliveries(limit int) ([]Delivery, error) { | 108 | func (s *Store) DueDeliveries(limit int) ([]Delivery, error) { |
| 109 | rows, err := s.DB.Query(` | 109 | return queryAll(s.DB, s.scanDelivery, ` |
| 110 | SELECT d.id, d.webhook_id, w.url, w.secret, d.event_id, e.kind, | 110 | SELECT d.id, d.webhook_id, w.url, w.secret, d.event_id, e.kind, |
| 111 | COALESCE(u2.username, o.name, '') || '/' || COALESCE(r.name, ''), | 111 | COALESCE(u2.username, o.name, '') || '/' || COALESCE(r.name, ''), |
| 112 | COALESCE(u.username, ''), e.data_json, e.created_at, d.attempts | 112 | COALESCE(u.username, ''), e.data_json, e.created_at, d.attempts |
| @@ -120,23 +120,21 @@ func (s *Store) DueDeliveries(limit int) ([]Delivery, error) { | |||
| 120 | WHERE d.delivered_at IS NULL AND d.failed_at IS NULL | 120 | WHERE d.delivered_at IS NULL AND d.failed_at IS NULL |
| 121 | AND (d.next_attempt_at IS NULL OR d.next_attempt_at <= ?) | 121 | AND (d.next_attempt_at IS NULL OR d.next_attempt_at <= ?) |
| 122 | ORDER BY d.id LIMIT ?`, fmtTime(time.Now()), limit) | 122 | ORDER BY d.id LIMIT ?`, fmtTime(time.Now()), limit) |
| 123 | if err != nil { | 123 | } |
| 124 | return nil, err | 124 | |
| 125 | // scanDelivery reads a due delivery and opens its hook's secret. | ||
| 126 | func (s *Store) scanDelivery(row interface{ Scan(...any) error }) (Delivery, error) { | ||
| 127 | var d Delivery | ||
| 128 | if err := row.Scan(&d.ID, &d.WebhookID, &d.URL, &d.Secret, &d.EventID, &d.EventKind, | ||
| 129 | &d.RepoPath, &d.Actor, &d.DataJSON, &d.EventAt, &d.Attempts); err != nil { | ||
| 130 | return d, err | ||
| 125 | } | 131 | } |
| 126 | defer rows.Close() | 132 | secret, err := s.openValue(webhookAAD(d.WebhookID), d.Secret) |
| 127 | var out []Delivery | 133 | if err != nil { |
| 128 | for rows.Next() { | 134 | return d, fmt.Errorf("webhook %d: %w", d.WebhookID, err) |
| 129 | var d Delivery | ||
| 130 | if err := rows.Scan(&d.ID, &d.WebhookID, &d.URL, &d.Secret, &d.EventID, &d.EventKind, | ||
| 131 | &d.RepoPath, &d.Actor, &d.DataJSON, &d.EventAt, &d.Attempts); err != nil { | ||
| 132 | return nil, err | ||
| 133 | } | ||
| 134 | if d.Secret, err = s.openValue(webhookAAD(d.WebhookID), d.Secret); err != nil { | ||
| 135 | return nil, fmt.Errorf("webhook %d: %w", d.WebhookID, err) | ||
| 136 | } | ||
| 137 | out = append(out, d) | ||
| 138 | } | 135 | } |
| 139 | return out, rows.Err() | 136 | d.Secret = secret |
| 137 | return d, nil | ||
| 140 | } | 138 | } |
| 141 | 139 | ||
| 142 | func (s *Store) MarkDelivered(id int64, status int) error { | 140 | func (s *Store) MarkDelivered(id int64, status int) error { |
| @@ -161,7 +159,7 @@ func (s *Store) MarkAttemptFailed(id int64, status int, errMsg string, nextAt *t | |||
| 161 | } | 159 | } |
| 162 | 160 | ||
| 163 | func (s *Store) ListDeliveries(repoID int64, limit int) ([]DeliveryStatus, error) { | 161 | func (s *Store) ListDeliveries(repoID int64, limit int) ([]DeliveryStatus, error) { |
| 164 | rows, err := s.DB.Query(` | 162 | return queryAll(s.DB, scanDeliveryStatus, ` |
| 165 | SELECT d.id, w.url, e.kind, | 163 | SELECT d.id, w.url, e.kind, |
| 166 | CASE WHEN d.delivered_at IS NOT NULL THEN 'delivered' | 164 | CASE WHEN d.delivered_at IS NOT NULL THEN 'delivered' |
| 167 | WHEN d.failed_at IS NOT NULL THEN 'failed' | 165 | WHEN d.failed_at IS NOT NULL THEN 'failed' |
| @@ -171,19 +169,6 @@ func (s *Store) ListDeliveries(repoID int64, limit int) ([]DeliveryStatus, error | |||
| 171 | JOIN webhooks w ON w.id = d.webhook_id | 169 | JOIN webhooks w ON w.id = d.webhook_id |
| 172 | JOIN events e ON e.id = d.event_id | 170 | JOIN events e ON e.id = d.event_id |
| 173 | WHERE w.repo_id = ? ORDER BY d.id DESC LIMIT ?`, repoID, limit) | 171 | WHERE w.repo_id = ? ORDER BY d.id DESC LIMIT ?`, repoID, limit) |
| 174 | if err != nil { | ||
| 175 | return nil, err | ||
| 176 | } | ||
| 177 | defer rows.Close() | ||
| 178 | var out []DeliveryStatus | ||
| 179 | for rows.Next() { | ||
| 180 | var d DeliveryStatus | ||
| 181 | if err := rows.Scan(&d.ID, &d.URL, &d.EventKind, &d.Status, &d.Attempts, &d.LastStatus, &d.LastError, &d.CreatedAt); err != nil { | ||
| 182 | return nil, err | ||
| 183 | } | ||
| 184 | out = append(out, d) | ||
| 185 | } | ||
| 186 | return out, rows.Err() | ||
| 187 | } | 172 | } |
| 188 | 173 | ||
| 189 | // Redeliver resets a delivery for an immediate retry. | 174 | // Redeliver resets a delivery for an immediate retry. |
| @@ -199,3 +184,9 @@ func (s *Store) Redeliver(repoID, deliveryID int64) error { | |||
| 199 | } | 184 | } |
| 200 | return nil | 185 | return nil |
| 201 | } | 186 | } |
| 187 | |||
| 188 | func scanDeliveryStatus(row interface{ Scan(...any) error }) (DeliveryStatus, error) { | ||
| 189 | var d DeliveryStatus | ||
| 190 | err := row.Scan(&d.ID, &d.URL, &d.EventKind, &d.Status, &d.Attempts, &d.LastStatus, &d.LastError, &d.CreatedAt) | ||
| 191 | return d, err | ||
| 192 | } | ||
internal/symbols/extract.go +10 −7
| @@ -162,6 +162,11 @@ func extractGo(data []byte) []Symbol { | |||
| 162 | } | 162 | } |
| 163 | out = append(out, Symbol{Name: name, Key: id.Name, Kind: kind, Line: fset.Position(id.Pos()).Line}) | 163 | out = append(out, Symbol{Name: name, Key: id.Name, Kind: kind, Line: fset.Position(id.Pos()).Line}) |
| 164 | } | 164 | } |
| 165 | addNames := func(ids []*ast.Ident, kind string) { | ||
| 166 | for _, id := range ids { | ||
| 167 | add(id, id.Name, kind) | ||
| 168 | } | ||
| 169 | } | ||
| 165 | for _, d := range f.Decls { | 170 | for _, d := range f.Decls { |
| 166 | switch d := d.(type) { | 171 | switch d := d.(type) { |
| 167 | case *ast.FuncDecl: | 172 | case *ast.FuncDecl: |
| @@ -176,18 +181,16 @@ func extractGo(data []byte) []Symbol { | |||
| 176 | } | 181 | } |
| 177 | add(d.Name, recv+"."+d.Name.Name, "method") | 182 | add(d.Name, recv+"."+d.Name.Name, "method") |
| 178 | case *ast.GenDecl: | 183 | case *ast.GenDecl: |
| 184 | kind := "var" | ||
| 185 | if d.Tok == token.CONST { | ||
| 186 | kind = "const" | ||
| 187 | } | ||
| 179 | for _, spec := range d.Specs { | 188 | for _, spec := range d.Specs { |
| 180 | switch s := spec.(type) { | 189 | switch s := spec.(type) { |
| 181 | case *ast.TypeSpec: | 190 | case *ast.TypeSpec: |
| 182 | add(s.Name, s.Name.Name, "type") | 191 | add(s.Name, s.Name.Name, "type") |
| 183 | case *ast.ValueSpec: | 192 | case *ast.ValueSpec: |
| 184 | kind := "var" | 193 | addNames(s.Names, kind) |
| 185 | if d.Tok == token.CONST { | ||
| 186 | kind = "const" | ||
| 187 | } | ||
| 188 | for _, n := range s.Names { | ||
| 189 | add(n, n.Name, kind) | ||
| 190 | } | ||
| 191 | } | 194 | } |
| 192 | } | 195 | } |
| 193 | } | 196 | } |
internal/termtext/markdown.go +5 −5
| @@ -80,12 +80,12 @@ func (r mdRenderer) block(n ast.Node, first, rest string) { | |||
| 80 | for c := item.FirstChild(); c != nil; c = c.NextSibling() { | 80 | for c := item.FirstChild(); c != nil; c = c.NextSibling() { |
| 81 | if c == item.FirstChild() { | 81 | if c == item.FirstChild() { |
| 82 | r.block(c, p+marker, hang) | 82 | r.block(c, p+marker, hang) |
| 83 | } else { | 83 | continue |
| 84 | if !n.IsTight { | ||
| 85 | r.w.blank() | ||
| 86 | } | ||
| 87 | r.block(c, hang, hang) | ||
| 88 | } | 84 | } |
| 85 | if !n.IsTight { | ||
| 86 | r.w.blank() | ||
| 87 | } | ||
| 88 | r.block(c, hang, hang) | ||
| 89 | } | 89 | } |
| 90 | p = rest | 90 | p = rest |
| 91 | } | 91 | } |
internal/texmath/texmath.go +15 −2
| @@ -66,7 +66,7 @@ func Convert(tex string, display bool) (string, error) { | |||
| 66 | return "", errors.New("texmath: invalid UTF-8") | 66 | return "", errors.New("texmath: invalid UTF-8") |
| 67 | } | 67 | } |
| 68 | for _, r := range tex { | 68 | for _, r := range tex { |
| 69 | if r < 0x20 && r != '\t' && r != '\n' && r != '\r' || r == 0x7F || r == 0xFFFE || r == 0xFFFF { | 69 | if isControl(r) { |
| 70 | return "", errors.New("texmath: control character") | 70 | return "", errors.New("texmath: control character") |
| 71 | } | 71 | } |
| 72 | } | 72 | } |
| @@ -206,6 +206,19 @@ func (p *parser) next() token { | |||
| 206 | var starred = map[string]bool{"operatorname": true} | 206 | var starred = map[string]bool{"operatorname": true} |
| 207 | 207 | ||
| 208 | func isASCIILetter(c byte) bool { return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' } | 208 | func isASCIILetter(c byte) bool { return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' } |
| 209 | func isDigit(c byte) bool { return c >= '0' && c <= '9' } | ||
| 210 | |||
| 211 | // isControl is a C0 control other than tab and the line ends, DEL, or | ||
| 212 | // the noncharacters U+FFFE and U+FFFF. | ||
| 213 | func isControl(r rune) bool { | ||
| 214 | switch r { | ||
| 215 | case '\t', '\n', '\r': | ||
| 216 | return false | ||
| 217 | case 0x7F, 0xFFFE, 0xFFFF: | ||
| 218 | return true | ||
| 219 | } | ||
| 220 | return r < 0x20 | ||
| 221 | } | ||
| 209 | 222 | ||
| 210 | func (p *parser) unexpected(t token) error { | 223 | func (p *parser) unexpected(t token) error { |
| 211 | switch t.kind { | 224 | switch t.kind { |
| @@ -402,7 +415,7 @@ func (p *parser) charAtom(t token) (*node, error) { | |||
| 402 | num := t.val | 415 | num := t.val |
| 403 | for p.pos < len(p.src) { | 416 | for p.pos < len(p.src) { |
| 404 | c := p.src[p.pos] | 417 | c := p.src[p.pos] |
| 405 | if c >= '0' && c <= '9' || c == '.' && p.pos+1 < len(p.src) && p.src[p.pos+1] >= '0' && p.src[p.pos+1] <= '9' { | 418 | if isDigit(c) || c == '.' && p.pos+1 < len(p.src) && isDigit(p.src[p.pos+1]) { |
| 406 | num += string(c) | 419 | num += string(c) |
| 407 | p.pos++ | 420 | p.pos++ |
| 408 | continue | 421 | continue |
internal/webhook/webhook.go +5 −2
| @@ -69,8 +69,11 @@ func CheckAddrs(host string, ips []net.IP, allowLocal bool) error { | |||
| 69 | var cgnat = &net.IPNet{IP: net.IPv4(100, 64, 0, 0), Mask: net.CIDRMask(10, 32)} | 69 | var cgnat = &net.IPNet{IP: net.IPv4(100, 64, 0, 0), Mask: net.CIDRMask(10, 32)} |
| 70 | 70 | ||
| 71 | func isForbidden(ip net.IP) bool { | 71 | func isForbidden(ip net.IP) bool { |
| 72 | return ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() || | 72 | switch { |
| 73 | ip.IsMulticast() || ip.IsUnspecified() || cgnat.Contains(ip) | 73 | case ip.IsLoopback(), ip.IsPrivate(), ip.IsLinkLocalUnicast(), ip.IsMulticast(), ip.IsUnspecified(): |
| 74 | return true | ||
| 75 | } | ||
| 76 | return cgnat.Contains(ip) | ||
| 74 | } | 77 | } |
| 75 | 78 | ||
| 76 | type Deliverer struct { | 79 | type Deliverer struct { |