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