1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package usecase
4
5import (
6 "context"
7 "errors"
8 "fmt"
9 "io"
10 "path"
11 "runtime/debug"
12 "slices"
13 "strconv"
14 "strings"
15 "time"
16
17 "github.com/bnema/zerowrap"
18
19 "bnema.dev/ermite-actions/expr"
20 "bnema.dev/ermite-actions/template"
21 "bnema.dev/ermite-actions/workflow"
22 "bnema.dev/ermite/internal/domain"
23 "bnema.dev/ermite/internal/ports"
24)
25
26const (
27 workflowDir = ".github/workflows"
28 // maxRunError bounds Run.error (8 KiB, run.proto).
29 maxRunError = 8 << 10
30 // maxPushCommits is the number of commits of the push event payload.
31 maxPushCommits = 20
32)
33
34// ciTrigger is a push waiting to be planned.
35type ciTrigger struct {
36 repo domain.RepoName
37 updates []domain.RefUpdate
38 actor string
39 pusher domain.CIPusher
40 // trusted: the principal that pushed or merged is the owner
41 // (domain.TrustedActor), so the run gets secrets.
42 trusted bool
43 at time.Time
44 log zerowrap.Logger
45}
46
47// OnPush queues the refs of a push or a merge for planning and returns at once;
48// a worker plans them. A full queue drops the trigger, logged at error: a push
49// is never slowed down or failed by CI.
50func (c *CI) OnPush(ctx context.Context, repo domain.RepoName, updates []domain.RefUpdate, pusher domain.Principal) {
51 c.enqueue(ctx, repo, updates, authorOf(pusher), domain.PusherOf(pusher), domain.TrustedActor(pusher))
52}
53
54// OnMerge queues the move of a target branch by a merge. The actor of the run is
55// the owner, as GitHub shows; the pusher recorded with it, whose rights the
56// actions of other repositories are resolved with, is the principal that merged:
57// a token limited to some repositories does not gain the owner's reach by
58// merging. For the same reason the run is trusted (gets secrets) only when the
59// merger is: the displayed actor is not the one that decides.
60func (c *CI) OnMerge(ctx context.Context, repo domain.RepoName, updates []domain.RefUpdate, merger domain.Principal) {
61 c.enqueue(ctx, repo, updates, authorOf(domain.Owner()), domain.PusherOf(merger), domain.TrustedActor(merger))
62}
63
64func (c *CI) enqueue(ctx context.Context, repo domain.RepoName, updates []domain.RefUpdate, actor string, pusher domain.CIPusher, trusted bool) {
65 var kept []domain.RefUpdate
66 for _, u := range updates {
67 if !u.IsDelete() && (strings.HasPrefix(u.Ref, "refs/heads/") || strings.HasPrefix(u.Ref, "refs/tags/")) {
68 kept = append(kept, u)
69 }
70 }
71 if len(kept) == 0 {
72 return
73 }
74 t := ciTrigger{repo: repo, updates: kept, actor: actor, pusher: pusher, trusted: trusted, at: c.now(), log: zerowrap.FromCtx(ctx)}
75 c.mu.Lock()
76 closed := c.closed
77 c.mu.Unlock()
78 if closed {
79 return
80 }
81 select {
82 case c.queue <- t:
83 default:
84 t.log.Error().Str("repo", repo.String()).Int("refs", len(kept)).Msg("ci trigger queue is full: the workflows of this push are not run")
85 }
86}
87
88func (c *CI) triggerLoop() {
89 defer c.wg.Done()
90 for {
91 select {
92 case <-c.ctx.Done():
93 return
94 case t := <-c.queue:
95 c.planPush(t)
96 }
97 }
98}
99
100// planPush plans one push; a panic or an error is logged and never escapes.
101func (c *CI) planPush(t ciTrigger) {
102 ctx := zerowrap.WithCtx(c.ctx, t.log)
103 defer func() {
104 if r := recover(); r != nil {
105 t.log.Error().Interface("panic", r).Bytes("stack", debug.Stack()).Str("repo", t.repo.String()).Msg("ci trigger panicked")
106 }
107 }()
108 if err := c.handlePush(ctx, t); err != nil && ctx.Err() == nil {
109 t.log.Error().Err(err).Str("repo", t.repo.String()).Msg("ci trigger failed")
110 }
111}
112
113// handlePush starts the workflows that match each ref of the push.
114func (c *CI) handlePush(ctx context.Context, t ciTrigger) error {
115 // CI is on once a runner is registered (plan, "Config"): without one a push
116 // makes no run and no check, so a forge that does not use CI shows nothing.
117 runners, err := c.cfg.Store.ListRunners(ctx)
118 if err != nil {
119 return fmt.Errorf("list the runners: %w", err)
120 }
121 if len(runners) == 0 {
122 return nil
123 }
124 tags := 0
125 for _, u := range t.updates {
126 if strings.HasPrefix(u.Ref, "refs/tags/") {
127 tags++
128 }
129 }
130 var errs []error
131 for _, u := range t.updates {
132 if err := c.handleRef(ctx, t, u, tags); err != nil {
133 errs = append(errs, fmt.Errorf("%s: %w", u.Ref, err))
134 }
135 }
136 return errors.Join(errs...)
137}
138
139// pushFacts is what is known of one pushed ref.
140type pushFacts struct {
141 update domain.RefUpdate
142 commit domain.ObjectID // the commit the ref points to, tags followed
143 head domain.Commit
144 commits []domain.Commit // oldest first, at most maxPushCommits
145 forced bool
146 created bool
147 files []string
148 // filesTruncated: the list of changed files is not available.
149 filesTruncated bool
150 tagCount int
151 isTag bool
152 // defaultBranch is the default branch of the repository, "" when unknown.
153 defaultBranch string
154 // payload is the commit part of the push event, shared by the workflows
155 // of the ref; handleRef builds it once, before the first one that matches.
156 payload *pushPayload
157}
158
159func (c *CI) handleRef(ctx context.Context, t ciTrigger, u domain.RefUpdate, tagCount int) error {
160 isTag := strings.HasPrefix(u.Ref, "refs/tags/")
161 if isTag && tagCount > workflow.MaxTagsPerPush {
162 return nil // GitHub creates no event for the tags of such a push
163 }
164 repo, err := c.cfg.Meta.Get(ctx, t.repo)
165 if err != nil {
166 return nil // deleted meanwhile
167 }
168 facts, err := c.collect(ctx, t.repo, u, isTag, tagCount)
169 if err != nil {
170 return err
171 }
172 files, err := c.workflowFiles(ctx, t.repo, facts.commit)
173 if err != nil || len(files) == 0 {
174 return err
175 }
176 skip := workflow.SkipCI(facts.head.Message)
177 var errs []error
178 for _, f := range files {
179 wf, perrs := workflow.Parse(f.path, f.content)
180 switch {
181 case f.problem != "":
182 errs = append(errs, c.startInvalid(ctx, repo, t, facts, f.path, f.path, f.problem))
183 case len(perrs) > 0:
184 var lines []string
185 for _, e := range perrs {
186 lines = append(lines, e.Error())
187 }
188 errs = append(errs, c.startInvalid(ctx, repo, t, facts, f.path, f.path, strings.Join(lines, "\n")))
189 case skip || !wf.MatchPush(workflow.PushInfo{
190 Ref: u.Ref, Created: facts.created, ChangedFiles: facts.files, FilesTruncated: facts.filesTruncated, TagCount: tagCount,
191 }):
192 default:
193 if facts.payload == nil {
194 facts.payload = c.pushPayload(ctx, repo, facts)
195 }
196 if problem := c.matrixProblem(ctx, repo, t, facts, f.path, wf); problem.text != "" {
197 name := f.path
198 if problem.named {
199 name = workflowName(wf, f.path)
200 }
201 errs = append(errs, c.startInvalid(ctx, repo, t, facts, f.path, name, problem.text))
202 continue
203 }
204 errs = append(errs, c.startRun(ctx, repo, t, facts, f.path, string(f.content), wf))
205 }
206 }
207 return errors.Join(errs...)
208}
209
210// collect reads what the payload and the filters need from Git.
211func (c *CI) collect(ctx context.Context, repo domain.RepoName, u domain.RefUpdate, isTag bool, tagCount int) (pushFacts, error) {
212 newID, err := domain.ParseObjectID(u.New)
213 if err != nil {
214 return pushFacts{}, err
215 }
216 f := pushFacts{update: u, created: u.IsCreate(), isTag: isTag, tagCount: tagCount}
217 if def, _, err := c.cfg.Repos.DefaultBranch(ctx, repo); err == nil {
218 f.defaultBranch = def
219 }
220 res, err := c.cfg.Reader.ResolveRevision(ctx, repo, domain.RevisionOf(newID))
221 if err != nil {
222 return f, fmt.Errorf("resolve %s: %w", u.New, err)
223 }
224 f.commit = res.CommitID
225 if isTag {
226 // Recorded (push-tag, skip-directive-tag, push-tags-limit): the event of
227 // a tag carries the commits that no branch has, newest as head_commit
228 // ("compare" is then that commit's page, or "<first>^...<head>" for
229 // several). Not the range from the previous push, and not the commits
230 // the default branch lacks: in push-tag the branch commit under the
231 // tagged one is not listed, in skip-directive-tag, which has no branch,
232 // both commits are. A tag on a commit that a branch has lists that
233 // commit alone (not recorded). No file list: paths filters are not
234 // evaluated for tags.
235 cs, _, err := c.cfg.Diff.CommitsOffBranches(ctx, repo, f.commit, ports.MaxCommitLimit)
236 if err != nil {
237 return f, fmt.Errorf("read the commits of the tag: %w", err)
238 }
239 if len(cs) == 0 {
240 cs, _, err = c.cfg.Git.ListRange(ctx, repo, domain.ObjectID{}, f.commit, 1)
241 if err != nil {
242 return f, fmt.Errorf("read the commit of the tag: %w", err)
243 }
244 if len(cs) == 0 {
245 return f, fmt.Errorf("read the commit of the tag: %w", domain.ErrNotFound)
246 }
247 }
248 f.head = cs[0]
249 f.commits = slices.Clone(cs[:min(len(cs), maxPushCommits)])
250 slices.Reverse(f.commits)
251 return f, nil
252 }
253
254 var exclude domain.ObjectID
255 if !f.created {
256 if old, err := domain.ParseObjectID(u.Old); err == nil {
257 exclude = old
258 if ok, err := c.cfg.Git.IsAncestor(ctx, repo, old, f.commit); err == nil && !ok {
259 f.forced = true
260 }
261 }
262 }
263 base := exclude
264 if f.created {
265 base = c.defaultBase(ctx, repo, strings.TrimPrefix(u.Ref, "refs/heads/"), f.commit)
266 exclude = base
267 }
268 cs, more, err := c.cfg.Git.ListRange(ctx, repo, exclude, f.commit, ports.MaxCommitLimit)
269 if err != nil {
270 return f, fmt.Errorf("read the commits of the push: %w", err)
271 }
272 if len(cs) == 0 {
273 // A new branch at a commit the default branch has, or a branch rewound
274 // to an ancestor: no new commit, no changed file. GitHub still runs
275 // the push workflows that have no paths filter, for the head commit.
276 head, _, err := c.cfg.Git.ListRange(ctx, repo, domain.ObjectID{}, f.commit, 1)
277 if err != nil {
278 return f, fmt.Errorf("read the head commit of the push: %w", err)
279 }
280 if len(head) == 0 {
281 return f, fmt.Errorf("read the head commit of the push: %w", domain.ErrNotFound)
282 }
283 f.head = head[0]
284 return f, nil
285 }
286 f.head = cs[0]
287 n := min(len(cs), maxPushCommits)
288 f.commits = slices.Clone(cs[:n])
289 slices.Reverse(f.commits)
290 if more || base == f.commit {
291 // More than 1,000 commits: the diff is not looked at (it runs).
292 f.filesTruncated = more
293 }
294 if !more && base != f.commit {
295 paths, _, err := c.cfg.Diff.ChangedPaths(ctx, repo, base, f.commit, workflow.MaxFilesEvaluated)
296 if err != nil {
297 f.filesTruncated = true // diff unavailable: runs
298 } else {
299 f.files = paths
300 }
301 }
302 return f, nil
303}
304
305// defaultBase is the merge base of a new branch with the default branch, the
306// zero id when there is none (every file of the branch counts).
307func (c *CI) defaultBase(ctx context.Context, repo domain.RepoName, branch string, head domain.ObjectID) domain.ObjectID {
308 def, exists, err := c.cfg.Repos.DefaultBranch(ctx, repo)
309 if err != nil || !exists || def == branch {
310 return domain.ObjectID{}
311 }
312 tip, err := c.cfg.Git.BranchHead(ctx, repo, def)
313 if err != nil {
314 return domain.ObjectID{}
315 }
316 base, err := c.cfg.Git.MergeBase(ctx, repo, tip, head)
317 if err != nil {
318 return domain.ObjectID{}
319 }
320 return base
321}
322
323type workflowFile struct {
324 path string
325 content []byte
326 // problem is set when the file cannot even be parsed (too large).
327 problem string
328}
329
330// workflowFiles reads .github/workflows/*.yml|*.yaml at the commit.
331func (c *CI) workflowFiles(ctx context.Context, repo domain.RepoName, commit domain.ObjectID) ([]workflowFile, error) {
332 dir, err := domain.ParseTreePath(workflowDir)
333 if err != nil {
334 return nil, err
335 }
336 tree, err := c.cfg.Reader.GetTree(ctx, repo, domain.RevisionOf(commit), dir, false)
337 if errors.Is(err, domain.ErrNotFound) || errors.Is(err, domain.ErrNotDirectory) {
338 return nil, nil
339 }
340 if err != nil {
341 return nil, fmt.Errorf("list %s: %w", workflowDir, err)
342 }
343 var out []workflowFile
344 for _, e := range tree.Entries {
345 ext := strings.ToLower(path.Ext(e.Name))
346 if (e.Kind != domain.EntryFile && e.Kind != domain.EntryExecutable) || (ext != ".yml" && ext != ".yaml") {
347 continue
348 }
349 if len(out) == maxCIWorkflowFiles {
350 break
351 }
352 wf := workflowFile{path: e.Path}
353 if wf.path == "" {
354 wf.path = workflowDir + "/" + e.Name
355 }
356 if e.Size > maxCIWorkflowBytes {
357 wf.problem = fmt.Sprintf("%s: the workflow file is larger than 1 MiB", wf.path)
358 out = append(out, wf)
359 continue
360 }
361 tp, err := domain.ParseTreePath(wf.path)
362 if err != nil {
363 continue
364 }
365 _, rc, err := c.cfg.Reader.OpenBlob(ctx, repo, domain.RevisionOf(commit), tp)
366 if err != nil {
367 return nil, fmt.Errorf("read %s: %w", wf.path, err)
368 }
369 wf.content, err = io.ReadAll(io.LimitReader(rc, maxCIWorkflowBytes+1))
370 _ = rc.Close()
371 if err != nil {
372 return nil, fmt.Errorf("read %s: %w", wf.path, err)
373 }
374 if len(wf.content) > maxCIWorkflowBytes {
375 wf.content, wf.problem = nil, fmt.Sprintf("%s: the workflow file is larger than 1 MiB", wf.path)
376 }
377 out = append(out, wf)
378 }
379 return out, nil
380}
381
382// --- the run ---
383
384func firstLine(s string) string {
385 line, _, _ := strings.Cut(s, "\n")
386 return truncateRunes(strings.TrimSpace(line), 256)
387}
388
389// startInvalid records the failed run of an invalid workflow file: no job, the
390// errors as Run.error, like GitHub's "Invalid workflow file".
391//
392// name is what the run is called: the path of the file when the file is not a
393// workflow GitHub accepts, or the workflow's own name for a workflow that
394// parses but whose strategy GitHub refuses (recorded: matrix-over-256).
395func (c *CI) startInvalid(ctx context.Context, repo domain.Repo, t ciTrigger, f pushFacts, wfPath, name, problem string) error {
396 now := c.now()
397 draft, err := c.cfg.Store.CreateRun(ctx, repo.Name, wfPath, func(id, number int64) ports.CIRunDraft {
398 run := domain.CIRun{
399 Repo: repo.Name, ID: id, Number: number, Attempt: 1, WorkflowPath: wfPath, WorkflowName: name, Name: name,
400 Title: firstLine(f.head.Message), Event: "push", Ref: f.update.Ref, Sha: f.commit.String(), Actor: t.actor,
401 Status: domain.CICompleted, Conclusion: domain.CIFailure, Error: cutText(problem, maxRunError), Trusted: t.trusted,
402 CreatedAt: now, StartedAt: now, CompletedAt: now,
403 }
404 return ports.CIRunDraft{
405 Run: run, Source: domain.CIRunSource{Repo: repo.Name, WorkflowYAML: "", GithubJSON: "{}", Pusher: t.pusher},
406 Checks: []domain.CICheck{{
407 ID: "run-" + strconv.FormatInt(id, 10), Repo: repo.Name, Sha: run.Sha, Name: wfPath, Status: domain.CICompleted,
408 Conclusion: domain.CIFailure, RunID: id, Attempt: 1, WorkflowName: name, CreatedAt: now, StartedAt: now, CompletedAt: now,
409 }},
410 }
411 })
412 if errors.Is(err, domain.ErrNotFound) {
413 return nil
414 }
415 if err != nil {
416 return err
417 }
418 c.publishRun(ctx, repo, draft.Run)
419 log := logRun(ctx, draft.Run)
420 log.Info().Str("workflow", wfPath).Msg("ci run failed: invalid workflow file")
421 return nil
422}
423
424func (c *CI) publishRun(ctx context.Context, repo domain.Repo, run domain.CIRun) {
425 c.cfg.Bus.Publish(ctx, domain.RunUpdated{Run: run, At: c.now(), Visibility: repo.Visibility, CreatedAt: repo.CreatedAt})
426}
427
428// startRun creates the run of a matching workflow with one waiting record per
429// job of the file, then plans the jobs that can start.
430func (c *CI) startRun(ctx context.Context, repo domain.Repo, t ciTrigger, f pushFacts, wfPath, yaml string, wf *workflow.Workflow) error {
431 now := c.now()
432 name := workflowName(wf, wfPath)
433 // The title of a run without run-name is the commit message for a branch.
434 // For a tag GitHub shows the name of the workflow registered for the path,
435 // not the commit message (recorded: filter-tags, filter-paths-tag,
436 // filter-branches-ignore, and push-tag, push-tags-limit, push-delete-tag,
437 // skip-directive-tag, whose ci.yml is called "push-branch-create" on the
438 // default branch of the recording repository although each run's own
439 // workflow has another name: 14 of 14 tag runs). Registered is read as the
440 // "name:" of the file on the default branch; the first version GitHub saw
441 // is the same file in the recording and cannot be told apart.
442 title := firstLine(f.head.Message)
443 if f.isTag {
444 title = c.registeredName(ctx, repo.Name, wfPath, name)
445 }
446 vars, err := c.varsContext(ctx, repo.Name)
447 if err != nil {
448 return err
449 }
450 draft, err := c.cfg.Store.CreateRun(ctx, repo.Name, wfPath, func(id, number int64) ports.CIRunDraft {
451 run := domain.CIRun{
452 Repo: repo.Name, ID: id, Number: number, Attempt: 1, WorkflowPath: wfPath, WorkflowName: name, Name: name,
453 Title: title, Event: "push", Ref: f.update.Ref, Sha: f.commit.String(), Actor: t.actor,
454 Status: domain.CIQueued, Trusted: t.trusted, CreatedAt: now,
455 }
456 githubJSON := c.githubJSON(ctx, repo, run, f)
457 if runName, ok := c.evalRunName(ctx, wf, githubJSON, vars); ok {
458 run.Name, run.Title = runName, runName
459 }
460 d := ports.CIRunDraft{Run: run, Source: domain.CIRunSource{
461 Repo: repo.Name, WorkflowYAML: yaml, GithubJSON: githubJSON, Pusher: t.pusher,
462 }}
463 for i, j := range wf.Jobs {
464 job := domain.CIJob{
465 ID: domain.NewJobID(id, i, 0), RunID: id, Attempt: 1, RunAttempt: 1, Repo: repo.Name, Key: j.ID, Name: j.ID,
466 Phase: domain.CIPhaseWaiting, Needs: slices.Clone(j.Needs), Index: i, CreatedAt: now,
467 }
468 d.Jobs = append(d.Jobs, job)
469 d.Checks = append(d.Checks, domain.CICheck{
470 ID: job.ID, Repo: repo.Name, Sha: run.Sha, Name: job.Name, Status: domain.CIQueued, RunID: id, JobID: job.ID,
471 Attempt: 1, WorkflowName: name, CreatedAt: now,
472 })
473 }
474 return d
475 })
476 if errors.Is(err, domain.ErrNotFound) {
477 return nil
478 }
479 if err != nil {
480 return err
481 }
482 c.publishRun(ctx, repo, draft.Run)
483 for _, j := range draft.Jobs {
484 c.cfg.Bus.Publish(ctx, domain.JobUpdated{Job: j, At: now, Visibility: repo.Visibility, CreatedAt: repo.CreatedAt})
485 }
486 log := logRun(ctx, draft.Run)
487 log.Info().Str("workflow", wfPath).Str("ref", f.update.Ref).Int("jobs", len(draft.Jobs)).Msg("ci run created")
488 return c.advanceRun(ctx, draft.Run.ID)
489}
490
491// workflowName is the name of a workflow, the path of its file when it has no
492// "name:".
493func workflowName(wf *workflow.Workflow, path string) string {
494 if wf.Name == "" {
495 return path
496 }
497 return wf.Name
498}
499
500// registeredName is the name GitHub shows for a tag run without run-name: the
501// name of the workflow registered for the path, here the "name:" of the file on
502// the default branch (the path when that file has none). It falls back to own,
503// the name of the workflow of the run, when the default branch has no such
504// file, the file does not parse, or anything cannot be read; a failure other
505// than a missing file is logged at debug.
506func (c *CI) registeredName(ctx context.Context, repo domain.RepoName, wfPath, own string) string {
507 name, err := c.registeredNameOf(ctx, repo, wfPath)
508 if err != nil {
509 if !errors.Is(err, domain.ErrNotFound) {
510 log := zerowrap.FromCtx(ctx)
511 log.Debug().Err(err).Str("workflow", wfPath).Msg("ci tag run title: the registered workflow name is not readable, using the run's own")
512 }
513 return own
514 }
515 return name
516}
517
518// registeredNameOf is registeredName without the fallback; a missing default
519// branch or file is domain.ErrNotFound.
520func (c *CI) registeredNameOf(ctx context.Context, repo domain.RepoName, wfPath string) (string, error) {
521 def, exists, err := c.cfg.Repos.DefaultBranch(ctx, repo)
522 if err != nil {
523 return "", err
524 }
525 if !exists {
526 return "", domain.ErrNotFound
527 }
528 tip, err := c.cfg.Git.BranchHead(ctx, repo, def)
529 if err != nil {
530 return "", err
531 }
532 tp, err := domain.ParseTreePath(wfPath)
533 if err != nil {
534 return "", err
535 }
536 _, rc, err := c.cfg.Reader.OpenBlob(ctx, repo, domain.RevisionOf(tip), tp)
537 if err != nil {
538 return "", err
539 }
540 content, err := io.ReadAll(io.LimitReader(rc, maxCIWorkflowBytes+1))
541 _ = rc.Close()
542 if err != nil {
543 return "", err
544 }
545 if len(content) > maxCIWorkflowBytes {
546 return "", fmt.Errorf("workflow file over %d bytes", maxCIWorkflowBytes)
547 }
548 wf, errs := workflow.Parse(wfPath, content)
549 if len(errs) > 0 {
550 return "", fmt.Errorf("workflow does not parse: %v", errs[0])
551 }
552 return workflowName(wf, wfPath), nil
553}
554
555// evalRunName evaluates the run-name of a workflow with the github, inputs and
556// vars contexts (the contexts the schema allows there). ok is false when the
557// workflow has none, when it does not evaluate (logged), or when it evaluates
558// to nothing: the run then has no name of its own, GitHub's display title falls
559// back to the commit message (a branch) or the registered name (a tag), and
560// the name of the run to the name of the workflow.
561func (c *CI) evalRunName(ctx context.Context, wf *workflow.Workflow, githubJSON string, vars *expr.Dictionary) (string, bool) {
562 if wf.RunName == nil {
563 return "", false
564 }
565 gh, err := expr.FromJSON([]byte(githubJSON))
566 if err != nil {
567 return "", false
568 }
569 env := template.Env{Contexts: map[string]expr.Value{
570 "github": gh, "inputs": expr.NewDictionary(), "vars": vars,
571 }}
572 name, err := template.EvaluateString(ctx, wf.RunName, env)
573 if err != nil {
574 log := zerowrap.FromCtx(ctx)
575 log.Warn().Err(err).Msg("ci run-name does not evaluate: the run keeps the workflow name and the default title")
576 return "", false
577 }
578 if name = firstLine(name); name == "" {
579 return "", false
580 }
581 return name, true
582}
583
584// matrixProblem expands the strategy of every job of the file, whatever its
585// "if:" says, with an empty needs context (a matrix built from a needs output does not
586// evaluate here, and that error is ignored),
587// and returns the error text of the first strategy that produces more
588// configurations than GitHub allows: GitHub then fails the run with no job,
589// like an invalid workflow file (recorded: matrix-over-256; the run keeps the
590// name of the workflow). An "exclude" entry with a key that is no vector of the
591// matrix is refused too, and there GitHub names the run after the file path
592// (recorded: matrix-edge-values, a-exclude-unknown-key.yml). Any other error
593// of a strategy is ignored here and stays a job failure, found when the job is
594// planned. Whether GitHub counts the matrix of a job that "if:" skips is not
595// recorded yet (needs an "if: false" scenario over 256). The github context
596// is that of a run with no id yet, on the commits shared by the ref.
597func (c *CI) matrixProblem(ctx context.Context, repo domain.Repo, t ciTrigger, f pushFacts, wfPath string, wf *workflow.Workflow) matrixIssue {
598 if !slices.ContainsFunc(wf.Jobs, func(j *workflow.Job) bool { return j.Strategy != nil }) {
599 return matrixIssue{} // nothing to expand: no context to build
600 }
601 probe := domain.CIRun{Repo: repo.Name, Ref: f.update.Ref, Sha: f.commit.String(), Actor: t.actor, WorkflowPath: wfPath, WorkflowName: wf.Name, CreatedAt: c.now()}
602 gh, err := expr.FromJSON([]byte(c.githubJSON(ctx, repo, probe, f)))
603 if err != nil {
604 return matrixIssue{}
605 }
606 vars, err := c.varsContext(ctx, repo.Name)
607 if err != nil {
608 // Only the sizes of the matrices are looked at here: the job fails on
609 // the same error when it is planned.
610 vars = expr.NewDictionary()
611 }
612 env := template.Env{Contexts: map[string]expr.Value{
613 "github": gh, "needs": expr.NewDictionary(), "inputs": expr.NewDictionary(), "vars": vars,
614 }}
615 for _, j := range wf.Jobs {
616 _, err := j.EvaluateStrategy(ctx, env)
617 switch {
618 case errors.Is(err, workflow.ErrTooManyConfigurations):
619 return matrixIssue{text: wfPath + ": " + err.Error(), named: true}
620 case errors.Is(err, workflow.ErrExcludeUnknownKey):
621 // One line per offending entry, each with the file.
622 return matrixIssue{text: wfPath + ": " + strings.ReplaceAll(err.Error(), "\n", "\n"+wfPath+": ")}
623 }
624 }
625 return matrixIssue{}
626}
627
628// matrixIssue is a strategy GitHub refuses: the error text, and whether the run
629// keeps the name of the workflow (else it is named after the file).
630type matrixIssue struct {
631 text string
632 named bool
633}
634
635// --- the github context (see ci_github.go) ---
636
637// shortID is the 12-character form of an object id that GitHub puts in the
638// compare URL of a push.
639func shortID(id string) string {
640 if len(id) > 12 {
641 return id[:12]
642 }
643 return id
644}
645
646// retentionDays is the retention in days, as github.retention_days shows it
647// (at least 1).
648func (c *CI) retentionDays() int {
649 return max(int(c.cfg.Retention/(24*time.Hour)), 1)
650}