| 1 | package forge |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/sha256" |
| 7 | "encoding/hex" |
| 8 | "encoding/json" |
| 9 | "errors" |
| 10 | "fmt" |
| 11 | "html" |
| 12 | "io" |
| 13 | "net/http" |
| 14 | "net/url" |
| 15 | "os" |
| 16 | "path/filepath" |
| 17 | "regexp" |
| 18 | "slices" |
| 19 | "strconv" |
| 20 | "strings" |
| 21 | "syscall" |
| 22 | "time" |
| 23 | |
| 24 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 25 | ) |
| 26 | |
| 27 | // Merge errors. ErrMergeUncertain is settled by the next MergeBranch for |
| 28 | // the same task and commit: it reads the default branch first. |
| 29 | var ( |
| 30 | ErrMergeRefused = errors.New("forge: merge refused by validation") |
| 31 | ErrMergeMoved = errors.New("forge: the task branch is not at the judged commit") |
| 32 | ErrMergeConflict = errors.New("forge: the branch conflicts with the default branch") |
| 33 | ErrMergeCIPending = errors.New("forge: the hub's own CI on the commit has not finished") |
| 34 | ErrMergeCIFailed = errors.New("forge: the hub's own CI on the commit is not green") |
| 35 | ErrMergeForbidden = errors.New("forge: the agent may not merge in this repository") |
| 36 | ErrMergeFailed = errors.New("forge: the hub refused the merge") |
| 37 | ErrMergeUncertain = errors.New("forge: merge outcome unknown") |
| 38 | // ErrMergeUnbornDefault: the default branch has no commits yet and |
| 39 | // the hub refused to make the first merge (unborn_default, or |
| 40 | // is_default once a rebuild pointed its HEAD at the task branch). |
| 41 | ErrMergeUnbornDefault = errors.New("forge: the hub cannot make the first merge into an empty repository") |
| 42 | // ErrMergeNoCredential: the runner has no usable forge credential for |
| 43 | // the repository (none in the credential file, and it is not one the |
| 44 | // agent-wide credential serves), so it refused the merge itself. |
| 45 | ErrMergeNoCredential = errors.New("forge: no usable forge credential for the repository") |
| 46 | ) |
| 47 | |
| 48 | // NotSentError is a merge Equipo refused itself before any merge request |
| 49 | // left for the hub: a definite refusal, never "outcome unknown", since the |
| 50 | // hub cannot have acted on it. Only code that has sent no merge request |
| 51 | // returns one. |
| 52 | type NotSentError struct { |
| 53 | // Repo is the repository refused, "" when it is not a valid hub key. |
| 54 | Repo string |
| 55 | Err error |
| 56 | } |
| 57 | |
| 58 | func (e *NotSentError) Error() string { |
| 59 | repo := e.Repo |
| 60 | if repo == "" { |
| 61 | repo = "this repository" |
| 62 | } |
| 63 | return fmt.Sprintf("%v (%s; refused by the runner, no merge request was sent)", e.Err, repo) |
| 64 | } |
| 65 | |
| 66 | func (e *NotSentError) Unwrap() error { return e.Err } |
| 67 | |
| 68 | // NotSent is err as a refusal made before the merge request, naming repo |
| 69 | // only when it is a valid hub repository. |
| 70 | func NotSent(repo string, err error) error { |
| 71 | if !validRepository(repo) { |
| 72 | repo = "" |
| 73 | } |
| 74 | return &NotSentError{Repo: repo, Err: err} |
| 75 | } |
| 76 | |
| 77 | // HubError is the hub's answer to a merge it did not make: its HTTP |
| 78 | // status, its machine-readable reason (the JSON "reason") and its |
| 79 | // sentence (the JSON "error", or a page's text), both redacted and |
| 80 | // bounded. It wraps the outcome the answer means (ErrMergeConflict, |
| 81 | // ErrMergeFailed, ErrMergeUncertain, ...), which still decides the |
| 82 | // step's reason. |
| 83 | type HubError struct { |
| 84 | Status int |
| 85 | Code, Message string |
| 86 | Err error |
| 87 | } |
| 88 | |
| 89 | func (e *HubError) Error() string { |
| 90 | return fmt.Sprintf("%v (hub %s: %s)", e.Err, strings.TrimSpace(strconv.Itoa(e.Status)+" "+e.Code), e.Message) |
| 91 | } |
| 92 | |
| 93 | func (e *HubError) Unwrap() error { return e.Err } |
| 94 | |
| 95 | func hubError(res MergeResult, err error) error { |
| 96 | return &HubError{Status: res.Status, Code: runnerproto.RedactDetail(res.Reason, 64), Message: runnerproto.RedactDetail(res.Message, runnerproto.DetailLimit), Err: err} |
| 97 | } |
| 98 | |
| 99 | // uncertain is ErrMergeUncertain with what is known of why: the hub's |
| 100 | // answer when it gave one, else the cause's words. Only the words: a |
| 101 | // cause's own identity never decides the outcome (MergeBranch settles a |
| 102 | // NotSentError, the one refusal known to have sent nothing, before this). |
| 103 | func uncertain(res MergeResult, cause error) error { |
| 104 | switch { |
| 105 | case res.Status != 0: |
| 106 | return hubError(res, ErrMergeUncertain) |
| 107 | case cause == nil: |
| 108 | return ErrMergeUncertain |
| 109 | case errors.Is(cause, ErrMergeUncertain): |
| 110 | return cause |
| 111 | } |
| 112 | return fmt.Errorf("%w: %v", ErrMergeUncertain, cause) |
| 113 | } |
| 114 | |
| 115 | // MergeDetail is a failed merge for the step report, a few lines: the |
| 116 | // hub's status, code and message when it answered, else the error's own |
| 117 | // words; redacted and bounded either way. |
| 118 | func MergeDetail(err error) string { |
| 119 | var h *HubError |
| 120 | switch { |
| 121 | case err == nil: |
| 122 | return "" |
| 123 | case !errors.As(err, &h): |
| 124 | return "error: " + runnerproto.RedactDetail(err.Error(), runnerproto.DetailLimit) |
| 125 | } |
| 126 | out := "status: " + strconv.Itoa(h.Status) |
| 127 | if code := runnerproto.RedactDetail(h.Code, 64); code != "" { |
| 128 | out += "\ncode: " + code |
| 129 | } |
| 130 | if msg := runnerproto.RedactDetail(h.Message, runnerproto.DetailLimit); msg != "" { |
| 131 | out += "\nmessage: " + msg |
| 132 | } |
| 133 | return out |
| 134 | } |
| 135 | |
| 136 | // pageTag is markup in an answer that is not JSON (a proxy's error page). |
| 137 | var pageTag = regexp.MustCompile(`(?s)<(?:script|style)\b.*?</(?:script|style)>|<[^>]*>`) |
| 138 | |
| 139 | // MergeRequest is the hub's merge API body (POST /api/v1/repos/{ns}/ |
| 140 | // {repo}/branches/{name}/merge). ExpectSHA is the commit that was judged: |
| 141 | // the hub's instance compares it with the branch under its git lock, so a |
| 142 | // branch that moved is refused, never merged. |
| 143 | type MergeRequest struct { |
| 144 | ExpectSHA string `json:"expect_sha"` |
| 145 | Message string `json:"message"` |
| 146 | KeepBranch bool `json:"keep_branch"` |
| 147 | Strategy string `json:"strategy"` |
| 148 | Agent AgentMeta `json:"agent"` |
| 149 | } |
| 150 | |
| 151 | // AgentMeta names the agent session making the request, as the hub |
| 152 | // requires of agent accounts. |
| 153 | type AgentMeta struct { |
| 154 | Session string `json:"session"` |
| 155 | Harness string `json:"harness"` |
| 156 | Host string `json:"host"` |
| 157 | } |
| 158 | |
| 159 | // MergeResult is the hub's answer: merged with the new commit on Into, |
| 160 | // or a refusal with its machine-readable reason (conflicts, moved, |
| 161 | // ci_not_green with CIState, up_to_date, no_such_branch, ...) and its |
| 162 | // sentence (Message, redacted and bounded). |
| 163 | type MergeResult struct { |
| 164 | Status int |
| 165 | Merged bool |
| 166 | SHA string |
| 167 | Into string |
| 168 | BranchClosed bool |
| 169 | Reason string |
| 170 | CIState string |
| 171 | Message string |
| 172 | } |
| 173 | |
| 174 | type hubMergeBody struct { |
| 175 | Merged bool `json:"merged"` |
| 176 | SHA string `json:"sha"` |
| 177 | Into string `json:"into"` |
| 178 | BranchClosed bool `json:"branch_closed"` |
| 179 | Reason string `json:"reason"` |
| 180 | CIState string `json:"ci_state"` |
| 181 | Error string `json:"error"` |
| 182 | } |
| 183 | |
| 184 | // HubMerge sends one merge request to the hub with the agent's bearer. |
| 185 | // A transport failure or an unreadable answer is an error: the caller |
| 186 | // cannot know whether the merge happened. What it refuses before sending |
| 187 | // is a NotSentError. |
| 188 | func HubMerge(ctx context.Context, client *http.Client, hub string, cred Credential, repo, branch string, req MergeRequest) (MergeResult, error) { |
| 189 | if !validRepository(repo) || !validRef(branch) { |
| 190 | return MergeResult{}, NotSent(repo, ErrMergeRefused) |
| 191 | } |
| 192 | if cred.Bearer == "" || strings.ContainsAny(cred.Bearer, "\r\n") { |
| 193 | return MergeResult{}, NotSent(repo, ErrMergeNoCredential) |
| 194 | } |
| 195 | parts := strings.Split(strings.TrimPrefix(repo, "amadan.net/"), "/") |
| 196 | body, _ := json.Marshal(req) |
| 197 | hr, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(hub, "/")+"/api/v1/repos/"+url.PathEscape(parts[0])+"/"+url.PathEscape(parts[1])+"/branches/"+url.PathEscape(branch)+"/merge", bytes.NewReader(body)) |
| 198 | if err != nil { |
| 199 | return MergeResult{}, NotSent(repo, ErrMergeRefused) |
| 200 | } |
| 201 | hr.Header.Set("Authorization", "Bearer "+cred.Bearer) |
| 202 | hr.Header.Set("Content-Type", "application/json") |
| 203 | hr.Header.Set("Accept", "application/json") |
| 204 | res, err := client.Do(hr) |
| 205 | if err != nil { |
| 206 | return MergeResult{}, fmt.Errorf("%w: %v", ErrMergeUncertain, err) |
| 207 | } |
| 208 | defer res.Body.Close() |
| 209 | var out hubMergeBody |
| 210 | raw, err := io.ReadAll(io.LimitReader(res.Body, 64<<10)) |
| 211 | if err != nil || json.Unmarshal(raw, &out) != nil { |
| 212 | // Not JSON (a proxy's page, say): its text is the sentence. |
| 213 | out = hubMergeBody{Error: html.UnescapeString(pageTag.ReplaceAllString(string(raw), " "))} |
| 214 | if res.StatusCode == http.StatusOK || res.StatusCode >= 500 { |
| 215 | return MergeResult{Status: res.StatusCode, Message: runnerproto.RedactDetail(out.Error, runnerproto.DetailLimit)}, ErrMergeUncertain |
| 216 | } |
| 217 | } |
| 218 | // Merged only on a 200 that says so with a commit: anything else is a |
| 219 | // refusal, never a success. |
| 220 | merged := res.StatusCode == http.StatusOK && out.Merged && object.MatchString(out.SHA) |
| 221 | return MergeResult{Status: res.StatusCode, Merged: merged, SHA: out.SHA, Into: out.Into, BranchClosed: out.BranchClosed, Reason: out.Reason, CIState: out.CIState, |
| 222 | Message: runnerproto.RedactDetail(out.Error, runnerproto.DetailLimit)}, nil |
| 223 | } |
| 224 | |
| 225 | // RemoteState is the repository as the runner reads it: the task |
| 226 | // branch's head ("" when gone), the default branch and its tip, and |
| 227 | // whether the commit is on the default branch, with the commit there that |
| 228 | // brought it in (its merge, or the commit itself). |
| 229 | type RemoteState struct { |
| 230 | Head string |
| 231 | Default string |
| 232 | Tip string |
| 233 | Landed bool |
| 234 | MergeSHA string |
| 235 | // Unborn: the default branch has no commits yet (an empty |
| 236 | // repository): no Tip, no advertised Default, nothing landed. |
| 237 | Unborn bool |
| 238 | } |
| 239 | |
| 240 | // BranchMerge is one judged commit of a task's branch to merge into the |
| 241 | // default branch through the hub. Forge validates the repository, the |
| 242 | // branch (equipo/..., never the default), the commit and the person, |
| 243 | // reads the remote, records its intent, confirms the lease and only then |
| 244 | // asks the hub; a later call for the same task and commit reconciles from |
| 245 | // the default branch instead of asking again blind. |
| 246 | type BranchMerge struct { |
| 247 | // Root keeps the merge records (private, 0700). |
| 248 | Root string |
| 249 | Repo string |
| 250 | Branch string |
| 251 | Commit string |
| 252 | Task string |
| 253 | Message string |
| 254 | Strategy string |
| 255 | Agent AgentMeta |
| 256 | // Person is whose task this is; Owners are the persons this runner |
| 257 | // executes for. |
| 258 | Person string |
| 259 | Owners []string |
| 260 | // Inspect reads the remote (ls-remote and, when needed, a fetch). |
| 261 | Inspect func(context.Context) (RemoteState, error) |
| 262 | // Request sends the merge to the hub. |
| 263 | Request func(context.Context, MergeRequest) (MergeResult, error) |
| 264 | // Confirm checks the execution lease right before the request. |
| 265 | Confirm func(context.Context) error |
| 266 | // Preflight, if set, makes the runner's own checks that need no |
| 267 | // remote (the credential the inspection and the request use) before |
| 268 | // the remote is read. It returns a NotSentError to refuse. |
| 269 | Preflight func(context.Context) error |
| 270 | // beforeRequest runs right before the request (tests move the branch). |
| 271 | beforeRequest func() |
| 272 | } |
| 273 | |
| 274 | // MergeOutcome is a confirmed merge: the commit on Into, how, and whether |
| 275 | // it was found on the default branch rather than in the hub's answer. |
| 276 | type MergeOutcome struct { |
| 277 | SHA, Into, Strategy string |
| 278 | Reconciled bool |
| 279 | // Source is where SHA came from: SourceHub, this request's own answer |
| 280 | // from the hub; SourceReconciled, the default branch read after the |
| 281 | // fact (its tip when the landing commit was not found); SourceCached, |
| 282 | // this runner's earlier record. Only SourceHub is the hub's word. |
| 283 | Source string |
| 284 | } |
| 285 | |
| 286 | // Merge outcome sources. |
| 287 | const ( |
| 288 | SourceHub = "hub" |
| 289 | SourceReconciled = "reconciled" |
| 290 | SourceCached = "cached" |
| 291 | ) |
| 292 | |
| 293 | type mergeRecord struct { |
| 294 | Task string `json:"task"` |
| 295 | Repo string `json:"repo"` |
| 296 | Branch string `json:"branch"` |
| 297 | Commit string `json:"commit"` |
| 298 | Phase string `json:"phase"` |
| 299 | Strategy string `json:"strategy"` |
| 300 | SHA string `json:"sha"` |
| 301 | Into string `json:"into"` |
| 302 | Reason string `json:"reason"` |
| 303 | At string `json:"at"` |
| 304 | } |
| 305 | |
| 306 | // Merge record phases: prepared (nothing sent), requested (a request may |
| 307 | // have reached the hub), merged (the hub confirmed it, or the default |
| 308 | // branch shows it), refused (the hub answered no; a new request may go). |
| 309 | const ( |
| 310 | mergePrepared = "prepared" |
| 311 | mergeRequested = "requested" |
| 312 | mergeMerged = "merged" |
| 313 | mergeRefusedPh = "refused" |
| 314 | ) |
| 315 | |
| 316 | var mergeTaskRef = taskRef |
| 317 | |
| 318 | func (m BranchMerge) validate() error { |
| 319 | if !validRepository(m.Repo) || !validRef(m.Branch) || !mergeTaskRef.MatchString(m.Branch) || len(m.Branch) > 100 || !object.MatchString(m.Commit) || |
| 320 | m.Task == "" || strings.ContainsAny(m.Task, "/\\\x00") || !filepath.IsAbs(m.Root) || m.Inspect == nil || m.Request == nil || m.Confirm == nil || |
| 321 | m.Strategy != "merge" && m.Strategy != "squash" || m.Agent.Session == "" || m.Person == "" || !slices.Contains(m.Owners, m.Person) || len(m.Message) > 4000 { |
| 322 | return ErrMergeRefused |
| 323 | } |
| 324 | return nil |
| 325 | } |
| 326 | |
| 327 | // path is the record for this task and commit: a new attempt to merge the |
| 328 | // same judged commit reads the same record. |
| 329 | func (m BranchMerge) path() string { |
| 330 | sum := sha256.Sum256([]byte(m.Task + "\x00" + m.Repo + "\x00" + m.Branch + "\x00" + m.Commit)) |
| 331 | return filepath.Join(m.Root, "merge-"+hex.EncodeToString(sum[:12])+".json") |
| 332 | } |
| 333 | |
| 334 | func (m BranchMerge) load() (mergeRecord, bool, error) { |
| 335 | var r mergeRecord |
| 336 | raw, err := os.ReadFile(m.path()) |
| 337 | if errors.Is(err, os.ErrNotExist) { |
| 338 | return r, false, nil |
| 339 | } |
| 340 | if err != nil || json.Unmarshal(raw, &r) != nil { |
| 341 | return r, false, ErrMergeUncertain |
| 342 | } |
| 343 | return r, true, nil |
| 344 | } |
| 345 | |
| 346 | func (m BranchMerge) save(r mergeRecord) error { |
| 347 | r.At = time.Now().UTC().Format(time.RFC3339Nano) |
| 348 | raw, _ := json.Marshal(r) |
| 349 | tmp := m.path() + ".tmp" |
| 350 | f, err := os.OpenFile(tmp, os.O_CREATE|os.O_TRUNC|os.O_WRONLY|syscall.O_NOFOLLOW, 0600) |
| 351 | if err != nil { |
| 352 | return err |
| 353 | } |
| 354 | if _, err = f.Write(raw); err == nil { |
| 355 | err = f.Sync() |
| 356 | } |
| 357 | if cerr := f.Close(); err == nil { |
| 358 | err = cerr |
| 359 | } |
| 360 | if err != nil { |
| 361 | return err |
| 362 | } |
| 363 | if err = os.Rename(tmp, m.path()); err != nil { |
| 364 | return err |
| 365 | } |
| 366 | dir, err := os.Open(m.Root) |
| 367 | if err != nil { |
| 368 | return err |
| 369 | } |
| 370 | defer dir.Close() |
| 371 | return dir.Sync() |
| 372 | } |
| 373 | |
| 374 | // landed records a merge the default branch shows and returns it. |
| 375 | func (m BranchMerge) landed(rec mergeRecord, st RemoteState, reconciled bool) (MergeOutcome, error) { |
| 376 | rec.Phase, rec.SHA, rec.Into = mergeMerged, firstOf(st.MergeSHA, st.Tip), st.Default |
| 377 | if err := m.save(rec); err != nil { |
| 378 | return MergeOutcome{}, ErrMergeUncertain |
| 379 | } |
| 380 | return MergeOutcome{SHA: rec.SHA, Into: rec.Into, Strategy: rec.Strategy, Reconciled: reconciled, Source: SourceReconciled}, nil |
| 381 | } |
| 382 | |
| 383 | func firstOf(a, b string) string { |
| 384 | if a != "" { |
| 385 | return a |
| 386 | } |
| 387 | return b |
| 388 | } |
| 389 | |
| 390 | // MergeBranch merges Commit into the default branch once. The remote is |
| 391 | // read first: a commit already on the default branch is done (a lost |
| 392 | // answer, a crash after the request, or a person who merged it), and a |
| 393 | // branch no longer at Commit is never merged. The record is written |
| 394 | // before the request; the lease is confirmed right before it. |
| 395 | func MergeBranch(ctx context.Context, m BranchMerge) (MergeOutcome, error) { |
| 396 | if err := m.validate(); err != nil { |
| 397 | return MergeOutcome{}, err |
| 398 | } |
| 399 | if err := os.MkdirAll(m.Root, 0700); err != nil { |
| 400 | return MergeOutcome{}, ErrMergeUncertain |
| 401 | } |
| 402 | lock, err := os.OpenFile(m.path()+".lock", os.O_CREATE|os.O_RDWR|syscall.O_NOFOLLOW, 0600) |
| 403 | if err != nil { |
| 404 | return MergeOutcome{}, ErrMergeUncertain |
| 405 | } |
| 406 | defer lock.Close() |
| 407 | if syscall.Flock(int(lock.Fd()), syscall.LOCK_EX) != nil { |
| 408 | return MergeOutcome{}, ErrMergeUncertain |
| 409 | } |
| 410 | rec, found, err := m.load() |
| 411 | if err != nil { |
| 412 | return MergeOutcome{}, err |
| 413 | } |
| 414 | if found && (rec.Task != m.Task || rec.Repo != m.Repo || rec.Branch != m.Branch || rec.Commit != m.Commit) { |
| 415 | return MergeOutcome{}, ErrMergeRefused |
| 416 | } |
| 417 | if found && rec.Phase == mergeMerged { |
| 418 | return MergeOutcome{SHA: rec.SHA, Into: rec.Into, Strategy: rec.Strategy, Source: SourceCached}, nil |
| 419 | } |
| 420 | // An earlier request may still land: reconcile from the default branch |
| 421 | // (a read) before the runner's write check, which then gates only a |
| 422 | // new request. |
| 423 | unresolved := found && rec.Phase == mergeRequested |
| 424 | if m.Preflight != nil && !unresolved { |
| 425 | // The runner's own refusals come before the remote is read (that |
| 426 | // read needs the same credential): definite, as no request was |
| 427 | // ever sent. |
| 428 | if err := m.Preflight(ctx); err != nil { |
| 429 | var ns *NotSentError |
| 430 | if !errors.As(err, &ns) { |
| 431 | return MergeOutcome{}, uncertain(MergeResult{}, err) |
| 432 | } |
| 433 | return MergeOutcome{}, err |
| 434 | } |
| 435 | } |
| 436 | if !found { |
| 437 | rec = mergeRecord{Task: m.Task, Repo: m.Repo, Branch: m.Branch, Commit: m.Commit, Phase: mergePrepared, Strategy: m.Strategy} |
| 438 | } |
| 439 | st, err := m.Inspect(ctx) |
| 440 | if err != nil { |
| 441 | return MergeOutcome{}, fmt.Errorf("%w: reading the repository: %v", ErrMergeUncertain, err) |
| 442 | } |
| 443 | if st.Landed { |
| 444 | // Already on the default branch: a request that reached the hub |
| 445 | // before its answer was lost, or a person merged it. Never again. |
| 446 | return m.landed(rec, st, true) |
| 447 | } |
| 448 | if st.Head != m.Commit { |
| 449 | // The branch moved (or is gone) since it was judged: what is there |
| 450 | // now was not checked or reviewed. |
| 451 | return MergeOutcome{}, ErrMergeMoved |
| 452 | } |
| 453 | if !st.Unborn && (st.Default == "" || st.Default == m.Branch || !validRef(st.Default)) { |
| 454 | return MergeOutcome{}, ErrMergeRefused |
| 455 | } |
| 456 | if !found || rec.Phase != mergeRequested { |
| 457 | rec.Phase = mergePrepared |
| 458 | if err := m.save(rec); err != nil { |
| 459 | return MergeOutcome{}, ErrMergeUncertain |
| 460 | } |
| 461 | } |
| 462 | before := rec.Phase |
| 463 | if m.Preflight != nil && unresolved { |
| 464 | // Not landed, and the earlier request is unresolved: a new one only |
| 465 | // with write access confirmed; without it, still unknown. |
| 466 | if err := m.Preflight(ctx); err != nil { |
| 467 | return MergeOutcome{}, uncertain(MergeResult{}, err) |
| 468 | } |
| 469 | } |
| 470 | if err := m.Confirm(ctx); err != nil { |
| 471 | return MergeOutcome{}, fmt.Errorf("%w: confirming the lease: %v", ErrMergeUncertain, err) |
| 472 | } |
| 473 | rec.Phase = mergeRequested |
| 474 | if err := m.save(rec); err != nil { |
| 475 | return MergeOutcome{}, ErrMergeUncertain |
| 476 | } |
| 477 | if m.beforeRequest != nil { |
| 478 | m.beforeRequest() |
| 479 | } |
| 480 | res, rerr := m.Request(ctx, MergeRequest{ExpectSHA: m.Commit, Message: m.Message, Strategy: m.Strategy, Agent: m.Agent}) |
| 481 | var notSent *NotSentError |
| 482 | if errors.As(rerr, ¬Sent) && before != mergeRequested { |
| 483 | // Refused here before anything left for the hub, and no earlier |
| 484 | // request is unresolved: definite, nothing to reconcile. The |
| 485 | // record goes back to prepared, so a later Merge asks as usual. |
| 486 | // After an unresolved request it is no answer at all: the default |
| 487 | // branch decides below, and the record stays requested. |
| 488 | rec.Phase = before |
| 489 | if err := m.save(rec); err != nil { |
| 490 | return MergeOutcome{}, ErrMergeUncertain |
| 491 | } |
| 492 | return MergeOutcome{}, rerr |
| 493 | } |
| 494 | if rerr == nil && res.Merged { |
| 495 | rec.Phase, rec.SHA, rec.Into = mergeMerged, res.SHA, firstOf(res.Into, st.Default) |
| 496 | if err := m.save(rec); err != nil { |
| 497 | return MergeOutcome{}, ErrMergeUncertain |
| 498 | } |
| 499 | return MergeOutcome{SHA: rec.SHA, Into: rec.Into, Strategy: rec.Strategy, Source: SourceHub}, nil |
| 500 | } |
| 501 | if rerr == nil && st.Unborn && (res.Reason == "unborn_default" || res.Reason == "is_default") { |
| 502 | // The hub cannot make the first merge yet: final for this request, |
| 503 | // never sent again blind. |
| 504 | return MergeOutcome{}, m.refused(rec, res, ErrMergeUnbornDefault) |
| 505 | } |
| 506 | if rerr != nil || res.Reason == "up_to_date" || res.Reason == "moved" || res.Reason == "no_such_branch" || res.Status >= 500 { |
| 507 | // No answer, or one that may mean it landed after all: the default |
| 508 | // branch decides. Not landed stays requested; the next call reads |
| 509 | // the remote again before any new request. |
| 510 | again, err := m.Inspect(ctx) |
| 511 | if err == nil && again.Landed { |
| 512 | return m.landed(rec, again, true) |
| 513 | } |
| 514 | if rerr != nil || res.Status >= 500 || err != nil { |
| 515 | return MergeOutcome{}, uncertain(res, rerr) |
| 516 | } |
| 517 | if again.Head != m.Commit { |
| 518 | return MergeOutcome{}, m.refused(rec, res, ErrMergeMoved) |
| 519 | } |
| 520 | if st.Unborn && again.Unborn { |
| 521 | // Still no default branch, the branch where it was: the hub |
| 522 | // could not create it. |
| 523 | return MergeOutcome{}, m.refused(rec, res, ErrMergeUnbornDefault) |
| 524 | } |
| 525 | return MergeOutcome{}, m.refused(rec, res, ErrMergeFailed) |
| 526 | } |
| 527 | switch { |
| 528 | case res.Reason == "conflicts": |
| 529 | return MergeOutcome{}, m.refused(rec, res, ErrMergeConflict) |
| 530 | case res.Reason == "ci_not_green" && (res.CIState == "pending" || res.CIState == "running" || res.CIState == "queued" || res.CIState == "unknown" || res.CIState == ""): |
| 531 | return MergeOutcome{}, m.refused(rec, res, ErrMergeCIPending) |
| 532 | case res.Reason == "ci_not_green": |
| 533 | return MergeOutcome{}, m.refused(rec, res, ErrMergeCIFailed) |
| 534 | case res.Status == http.StatusForbidden || res.Status == http.StatusNotFound || res.Status == http.StatusUnauthorized: |
| 535 | return MergeOutcome{}, m.refused(rec, res, ErrMergeForbidden) |
| 536 | } |
| 537 | return MergeOutcome{}, m.refused(rec, res, ErrMergeFailed) |
| 538 | } |
| 539 | |
| 540 | // refused records the hub's refusal (a new request may go later) and |
| 541 | // returns err. |
| 542 | func (m BranchMerge) refused(rec mergeRecord, res MergeResult, err error) error { |
| 543 | rec.Phase, rec.Reason = mergeRefusedPh, res.Reason |
| 544 | if serr := m.save(rec); serr != nil { |
| 545 | return uncertain(res, nil) |
| 546 | } |
| 547 | if res.Status == 0 { |
| 548 | return err |
| 549 | } |
| 550 | return hubError(res, err) |
| 551 | } |
| 552 | |
| 553 | // SweepMerges removes merge records older than keep. |
| 554 | func SweepMerges(root string, keep time.Duration) { |
| 555 | paths, _ := filepath.Glob(filepath.Join(root, "merge-*.json")) |
| 556 | for _, p := range paths { |
| 557 | if info, err := os.Lstat(p); err == nil && info.Mode().IsRegular() && time.Since(info.ModTime()) > keep { |
| 558 | os.Remove(p) |
| 559 | os.Remove(p + ".lock") |
| 560 | } |
| 561 | } |
| 562 | } |
| 563 | |