gunk-dev/the-valley

report.go

source4cbb5ec9c5dbmain's published tip history
22.0 KiB
1// Package report sums klaus's session event logs into where agent wall-clock
2// time goes: per repository and overall, the runs and their phases, the
3// checks agents ran, the wait between runs on the same change, follow-up runs
4// and their reasons, consults, reviews and cost.
5package report
6
7import (
8 "sort"
9 "strconv"
10 "strings"
11 "time"
12
13 "the-valley/flow/internal/event"
14)
15
16// Options narrow a report.
17type Options struct {
18 Since time.Time // runs, consults and reviews that started before it are left out; zero keeps all
19 Until time.Time // the report's end, for its header; zero is unset
20 Repo string // keep only this repo: a repo key, or its name after valley: or its last path component
21}
22
23// Report is where agent time went.
24type Report struct {
25 Since string `json:"since,omitempty"` // RFC3339; empty for all time
26 Until string `json:"until,omitempty"`
27 Sessions int `json:"sessions"` // event logs read
28 Overall Totals `json:"overall"`
29 Repos []Totals `json:"repos"` // by repo key; "" for runs whose repo no event names
30 Changes []Change `json:"changes"` // every change with a run in the report, most runs first
31}
32
33// Totals sum a repo's runs, or every run. Durations are milliseconds.
34type Totals struct {
35 Repo string `json:"repo,omitempty"`
36 Runs int `json:"runs"`
37 // Unfinished runs have no end in the logs: still running, or killed
38 // before finalize.
39 Unfinished int `json:"unfinished,omitempty"`
40 // Reasons counts runs by dispatch reason; "unknown" for runs from
41 // before klaus recorded one.
42 Reasons map[string]int `json:"reasons"`
43 SetupMS int64 `json:"setup_ms"`
44 AgentMS int64 `json:"agent_ms"`
45 FinalizeMS int64 `json:"finalize_ms"`
46 // Untimed runs predate phase events: their agent time is the span from
47 // agent:started to the event that ended them, and they have no setup or
48 // finalize time.
49 Untimed int `json:"untimed,omitempty"`
50 // Checks sums check:completed by kind. Checks run within the agent
51 // phase, so their time is part of AgentMS. A command line that also ran
52 // _pre-review counts without the pre-review's time, which is its own
53 // check's.
54 Checks map[string]*CheckTotals `json:"checks"`
55 // Changes counts the changes the runs worked on, and FollowUps the
56 // runs that continued one: a run after the change's first in the
57 // report, or one dispatched as a follow-up (a fix, --pr, --change,
58 // --resume-from), whose first run is earlier.
59 Changes int `json:"changes"`
60 FollowUps int `json:"follow_ups"`
61 FollowUpReasons map[string]int `json:"follow_up_reasons"`
62 // WaitMS sums the time a change waited with none of its runs going:
63 // from the last end among its earlier runs to the next run's start, on
64 // review, CI or the operator. UnknownWaits counts the follow-ups whose
65 // wait is unknown, because an earlier run on the change has no end.
66 WaitMS int64 `json:"wait_between_runs_ms"`
67 UnknownWaits int `json:"unknown_waits,omitempty"`
68 // ApprovalWaitMS sums, over Approvals changes, the time from the run
69 // that ended last before a change's first approval to that approval.
70 ApprovalWaitMS int64 `json:"approval_wait_ms"`
71 Approvals int `json:"approvals"`
72 Consults int `json:"consults"`
73 ConsultMS int64 `json:"consult_ms"`
74 Reviews int `json:"reviews"`
75 ReviewMS int64 `json:"review_ms"`
76 CostUSD float64 `json:"cost_usd"`
77 CostRuns int `json:"cost_runs"` // runs whose cost is known
78}
79
80// CheckTotals sum one kind of check.
81type CheckTotals struct {
82 Count int `json:"count"`
83 MS int64 `json:"ms"`
84 Failed int `json:"failed"`
85}
86
87// Change is one change's runs.
88type Change struct {
89 Key string `json:"key"` // <repo>#<pr>, <repo>@<change id>, or the run ID of a lone run
90 Repo string `json:"repo,omitempty"`
91 Runs int `json:"runs"`
92 AgentMS int64 `json:"agent_ms"`
93 WaitMS int64 `json:"wait_between_runs_ms"`
94 ApprovalWaitMS int64 `json:"approval_wait_ms,omitempty"`
95 FollowUps []FollowUp `json:"follow_ups"`
96}
97
98// FollowUp is a run that continued a change.
99type FollowUp struct {
100 RunID string `json:"run_id"`
101 Reason string `json:"reason"`
102 // WaitMS is the time since the change's earlier runs in the report had
103 // all ended; 0 when one was still going. WaitUnknown says an earlier
104 // run has no end, so whether the change waited is unknown.
105 WaitMS int64 `json:"wait_ms"`
106 WaitUnknown bool `json:"wait_unknown,omitempty"`
107}
108
109// unknownReason is a run's reason when its events don't say.
110const unknownReason = "unknown"
111
112// followUpReasons are the reasons that continue an existing change.
113var followUpReasons = map[string]bool{
114 event.DispatchPRFollowUp: true,
115 event.DispatchChangeFollowUp: true,
116 event.DispatchResume: true,
117 event.DispatchBudgetResume: true,
118 event.DispatchCIFix: true,
119 event.DispatchReviewFix: true,
120 event.DispatchReviewCommentFix: true,
121 event.DispatchConflictFix: true,
122 event.DispatchRestackConflict: true,
123}
124
125// runInfo is what one run's events say about it.
126type runInfo struct {
127 id string
128 repo, changeID, pr string
129 repos []string // every repo key its events gave, first seen first
130 prKeys []string // <repo>#<pr> for each canonical name of its repo, once it has a PR
131 reason string
132 start, end time.Time
133 agentStartedAt time.Time
134 terminalAt time.Time
135 setup, agent, final int64
136 timed bool // has phase:completed for agent
137 cost *float64
138 checks []check
139 finished bool
140}
141
142type check struct {
143 kind string
144 start, end time.Time
145 ms int64
146 success *bool
147 // includesPreReview: the check's command line also ran _pre-review,
148 // whose own check covers part of it.
149 includesPreReview bool
150}
151
152// approval is an approval of a PR, from the pipeline or klaus approve.
153type approval struct {
154 key string
155 at time.Time
156}
157
158// job is a consult or review that finished.
159type job struct {
160 review bool
161 repo string
162 start time.Time
163 ms int64
164}
165
166// Build sums sessions' event logs, one slice of events per session.
167func Build(sessions [][]event.Event, opts Options) *Report {
168 runs := map[string]*runInfo{}
169 var order []string
170 var approvals []approval
171 var jobs []job
172
173 for _, evts := range sessions {
174 for _, e := range evts {
175 at, err := time.Parse(time.RFC3339, e.Timestamp)
176 if err != nil {
177 continue
178 }
179 d := data(e.Data)
180 switch e.Type {
181 case event.ConsultCompleted, event.ReviewCompleted:
182 ms := d.int("duration_ms")
183 repo := d.str("repo_key")
184 if e.Type == event.ReviewCompleted && repo == "" {
185 repo = d.str("repo")
186 }
187 jobs = append(jobs, job{review: e.Type == event.ReviewCompleted, repo: repo, start: at.Add(-time.Duration(ms) * time.Millisecond), ms: ms})
188 continue
189 case event.PRApproved, event.PRApprovalChanged:
190 if e.Type == event.PRApprovalChanged && d.str("approved") != "true" {
191 continue
192 }
193 if key := prKey(d, e.RunID); key != "" {
194 approvals = append(approvals, approval{key: key, at: at})
195 }
196 continue
197 }
198 if !isRunID(e.RunID) {
199 continue // a PR's pipeline event, or a consult's or review's start
200 }
201 r := runs[e.RunID]
202 if r == nil {
203 r = &runInfo{id: e.RunID}
204 runs[e.RunID] = r
205 order = append(order, e.RunID)
206 }
207 r.observe(e.Type, at, d)
208 }
209 }
210
211 rep := &Report{Sessions: len(sessions)}
212 if !opts.Since.IsZero() {
213 rep.Since = opts.Since.UTC().Format(time.RFC3339)
214 }
215 if !opts.Until.IsZero() {
216 rep.Until = opts.Until.UTC().Format(time.RFC3339)
217 }
218
219 // Runs from before repo_key name their repo by its short name; one that
220 // newer events qualify one way only takes that key.
221 qualified := map[string]map[string]bool{}
222 for _, r := range runs {
223 r.finish()
224 for _, repo := range r.repos {
225 if isQualified(repo) {
226 name := repoName(repo)
227 if qualified[name] == nil {
228 qualified[name] = map[string]bool{}
229 }
230 qualified[name][repo] = true
231 }
232 }
233 }
234 qualify := func(repo string) string {
235 if keys := qualified[repo]; !isQualified(repo) && len(keys) == 1 {
236 for k := range keys {
237 return k
238 }
239 }
240 return repo
241 }
242
243 // A change's runs share an identity: its change ID or its PR, each
244 // qualified by the repo. Older runs know only the PR, and a renamed
245 // repo has two names, so runs that share any identity are one change.
246 same := unionFind{}
247 ids := map[string][]string{}
248 for _, id := range order {
249 r := runs[id]
250 r.repo = qualify(r.repo)
251 ids[id] = r.identities(qualify)
252 for _, k := range ids[id][1:] {
253 same.union(ids[id][0], k)
254 }
255 }
256
257 // The runs in the report, grouped by change.
258 changes := map[string][]*runInfo{}
259 var changeOrder []string
260 for _, id := range order {
261 r := runs[id]
262 if r.start.IsZero() || r.start.Before(opts.Since) || !matchRepo(opts.Repo, r.repo) {
263 continue
264 }
265 c := same.find(ids[id][0])
266 if _, ok := changes[c]; !ok {
267 changeOrder = append(changeOrder, c)
268 }
269 changes[c] = append(changes[c], r)
270 }
271
272 byRepo := map[string]*Totals{}
273 totals := func(repo string) *Totals {
274 t := byRepo[repo]
275 if t == nil {
276 t = newTotals(repo)
277 byRepo[repo] = t
278 }
279 return t
280 }
281 rep.Overall = *newTotals("")
282
283 for _, c := range changeOrder {
284 rs := changes[c]
285 sort.SliceStable(rs, func(i, j int) bool { return rs[i].start.Before(rs[j].start) })
286 key, repo := changeKey(rs)
287 ch := Change{Key: key, Repo: repo, Runs: len(rs), FollowUps: []FollowUp{}}
288 repoT := totals(ch.Repo)
289 for _, t := range []*Totals{&rep.Overall, repoT} {
290 t.Changes++
291 }
292 // Runs on a change can overlap, so it waits only once every earlier
293 // run has ended: from the last of their ends. After a run with no
294 // end, whether it waited is unknown.
295 var ended time.Time
296 unknown := false
297 for i, r := range rs {
298 var wait int64
299 if i > 0 && !unknown && r.start.After(ended) {
300 wait = r.start.Sub(ended).Milliseconds()
301 }
302 waitUnknown := i > 0 && unknown
303 if r.end.IsZero() {
304 unknown = true
305 } else if r.end.After(ended) {
306 ended = r.end
307 }
308 followUp := i > 0 || followUpReasons[r.reason]
309 ch.AgentMS += r.agent
310 ch.WaitMS += wait
311 if followUp {
312 ch.FollowUps = append(ch.FollowUps, FollowUp{RunID: r.id, Reason: reasonOf(r), WaitMS: wait, WaitUnknown: waitUnknown})
313 }
314 for _, t := range []*Totals{&rep.Overall, repoT} {
315 t.addRun(r)
316 t.WaitMS += wait
317 if waitUnknown {
318 t.UnknownWaits++
319 }
320 if followUp {
321 t.FollowUps++
322 t.FollowUpReasons[reasonOf(r)]++
323 }
324 }
325 }
326 if wait, ok := approvalWait(rs, approvals); ok {
327 ch.ApprovalWaitMS = wait
328 for _, t := range []*Totals{&rep.Overall, repoT} {
329 t.ApprovalWaitMS += wait
330 t.Approvals++
331 }
332 }
333 rep.Changes = append(rep.Changes, ch)
334 }
335
336 for _, j := range jobs {
337 j.repo = qualify(j.repo)
338 if j.start.Before(opts.Since) || !matchRepo(opts.Repo, j.repo) {
339 continue
340 }
341 ts := []*Totals{&rep.Overall}
342 if j.repo != "" {
343 ts = append(ts, totals(j.repo))
344 }
345 for _, t := range ts {
346 if j.review {
347 t.Reviews++
348 t.ReviewMS += j.ms
349 } else {
350 t.Consults++
351 t.ConsultMS += j.ms
352 }
353 }
354 }
355
356 for _, t := range byRepo {
357 rep.Repos = append(rep.Repos, *t)
358 }
359 sort.Slice(rep.Repos, func(i, j int) bool {
360 a, b := rep.Repos[i], rep.Repos[j]
361 if a.AgentMS != b.AgentMS {
362 return a.AgentMS > b.AgentMS
363 }
364 return a.Repo < b.Repo
365 })
366 sort.SliceStable(rep.Changes, func(i, j int) bool { return rep.Changes[i].Runs > rep.Changes[j].Runs })
367 if rep.Repos == nil {
368 rep.Repos = []Totals{}
369 }
370 if rep.Changes == nil {
371 rep.Changes = []Change{}
372 }
373 return rep
374}
375
376func newTotals(repo string) *Totals {
377 return &Totals{Repo: repo, Reasons: map[string]int{}, Checks: map[string]*CheckTotals{}, FollowUpReasons: map[string]int{}}
378}
379
380func (t *Totals) addRun(r *runInfo) {
381 t.Runs++
382 t.Reasons[reasonOf(r)]++
383 if r.end.IsZero() {
384 t.Unfinished++
385 }
386 if !r.timed && r.agent > 0 {
387 t.Untimed++
388 }
389 t.SetupMS += r.setup
390 t.AgentMS += r.agent
391 t.FinalizeMS += r.final
392 for _, c := range r.checks {
393 ct := t.Checks[c.kind]
394 if ct == nil {
395 ct = &CheckTotals{}
396 t.Checks[c.kind] = ct
397 }
398 ct.Count++
399 ct.MS += c.ms
400 if c.success != nil && !*c.success {
401 ct.Failed++
402 }
403 }
404 if r.cost != nil {
405 t.CostUSD += *r.cost
406 t.CostRuns++
407 }
408}
409
410func reasonOf(r *runInfo) string {
411 if r.reason == "" {
412 return unknownReason
413 }
414 return r.reason
415}
416
417// observe takes one of the run's events, at its timestamp.
418func (r *runInfo) observe(typ string, at time.Time, d data) {
419 if r.start.IsZero() || at.Before(r.start) {
420 r.start = at
421 }
422 // The fields every run event carries; later events know more (a PR, a
423 // valley's name for the repo).
424 if v := d.str("repo_key"); v != "" {
425 r.nameRepo(v)
426 }
427 if v := d.str("change_id"); v != "" {
428 r.changeID = v
429 }
430 if v := d.str("pr_number"); v != "" {
431 r.pr = v
432 }
433 if v := d.str("dispatch_reason"); v != "" && r.reason == "" {
434 r.reason = v
435 }
436
437 switch typ {
438 case event.AgentStarted:
439 r.agentStartedAt = at
440 if r.repo == "" {
441 r.nameRepo(d.str("target_repo")) // before repo_key
442 }
443 case event.PhaseCompleted:
444 ms := d.int("duration_ms")
445 switch d.str("phase") {
446 case event.PhaseSetup:
447 r.setup = ms
448 if t, err := time.Parse(time.RFC3339Nano, d.str("started_at")); err == nil {
449 r.start = t
450 }
451 case event.PhaseAgent:
452 r.agent, r.timed = ms, true
453 if c, ok := d.float("cost_usd"); ok {
454 r.cost = &c
455 }
456 case event.PhaseFinalize:
457 r.final = ms
458 r.end = at
459 if t, err := time.Parse(time.RFC3339Nano, d.str("ended_at")); err == nil {
460 r.end = t
461 }
462 }
463 case event.CheckCompleted:
464 c := check{kind: d.str("kind"), ms: d.int("duration_ms"), end: at, includesPreReview: d.str("includes_pre_review") == "true"}
465 if t, err := time.Parse(time.RFC3339Nano, d.str("ended_at")); err == nil {
466 c.end = t
467 }
468 c.start = c.end.Add(-time.Duration(c.ms) * time.Millisecond)
469 if t, err := time.Parse(time.RFC3339Nano, d.str("started_at")); err == nil {
470 c.start = t
471 }
472 if v, ok := d["success"].(bool); ok {
473 c.success = &v
474 }
475 r.checks = append(r.checks, c)
476 case event.AgentCompleted, event.AgentPaused, event.AgentNeedsAttention:
477 r.terminalAt = at
478 if c, ok := d.float("cost_usd"); ok && r.cost == nil {
479 r.cost = &c
480 }
481 case event.AgentPRCreated:
482 r.terminalAt = at
483 if r.repo == "" || !strings.Contains(r.repo, "/") {
484 if repo := repoFromPRURL(d.str("pr_url")); repo != "" {
485 r.nameRepo(repo)
486 }
487 }
488 case event.AgentBranchPushed:
489 r.terminalAt = at
490 if r.repo == "" {
491 r.nameRepo(shortName(d.str("repo")))
492 }
493 case event.AgentChangeReady, event.AgentChangeDraft:
494 // klaus ready marks a draft ready long after the run ended.
495 if d.str("via") == "" {
496 r.terminalAt = at
497 }
498 if v := d.str("repo"); v != "" && !strings.HasPrefix(r.repo, "valley:") {
499 r.nameRepo("valley:" + v)
500 }
501 }
502}
503
504// nameRepo takes a repo key for the run from one of its events.
505func (r *runInfo) nameRepo(repo string) {
506 if repo == "" {
507 return
508 }
509 r.repo = repo
510 for _, k := range r.repos {
511 if k == repo {
512 return
513 }
514 }
515 r.repos = append(r.repos, repo)
516}
517
518// finish settles what the run's events leave open: a run from before phase
519// events ends at its terminal event, and its agent time runs there from
520// agent:started. A check whose command line also ran _pre-review loses the
521// time the pre-review's own check covers.
522func (r *runInfo) finish() {
523 if r.finished {
524 return
525 }
526 r.finished = true
527 if r.end.IsZero() && !r.terminalAt.IsZero() {
528 r.end = r.terminalAt
529 }
530 if !r.timed && !r.agentStartedAt.IsZero() && r.terminalAt.After(r.agentStartedAt) {
531 r.agent = r.terminalAt.Sub(r.agentStartedAt).Milliseconds()
532 }
533 for i := range r.checks {
534 c := &r.checks[i]
535 if !c.includesPreReview {
536 continue
537 }
538 for _, p := range r.checks {
539 if p.kind == event.CheckPreReview {
540 c.ms -= overlapMS(c.start, c.end, p.start, p.end)
541 }
542 }
543 c.ms = max(c.ms, 0)
544 }
545}
546
547// overlapMS is how long two intervals overlap, in milliseconds.
548func overlapMS(aStart, aEnd, bStart, bEnd time.Time) int64 {
549 start, end := aStart, aEnd
550 if bStart.After(start) {
551 start = bStart
552 }
553 if bEnd.Before(end) {
554 end = bEnd
555 }
556 if !end.After(start) {
557 return 0
558 }
559 return end.Sub(start).Milliseconds()
560}
561
562// identities are the keys that name the run's change, the first of them
563// joining the rest: <repo>@<change id> and <repo>#<pr> for each name its
564// events gave its repo (a renamed repo has two), qualified when other runs
565// qualify a short name one way only, in lower case as GitHub's names are; or
566// the run alone. A short name counts only when no event qualified the repo,
567// so the runs of two repos that share a short name stay apart. It also sets
568// prKeys.
569func (r *runInfo) identities(qualify func(string) string) []string {
570 var repos []string
571 add := func(repo string) {
572 repo = strings.ToLower(repo)
573 for _, k := range repos {
574 if k == repo {
575 return
576 }
577 }
578 repos = append(repos, repo)
579 }
580 for i := len(r.repos) - 1; i >= 0; i-- {
581 if repo := qualify(r.repos[i]); isQualified(repo) {
582 add(repo)
583 }
584 }
585 if len(repos) == 0 {
586 add(r.repo)
587 }
588 var ids []string
589 for _, repo := range repos {
590 if r.changeID != "" {
591 ids = append(ids, "change:"+repo+"@"+r.changeID)
592 }
593 if r.pr != "" {
594 ids = append(ids, "pr:"+repo+"#"+r.pr)
595 r.prKeys = append(r.prKeys, repo+"#"+r.pr)
596 }
597 }
598 if len(ids) == 0 {
599 ids = append(ids, "run:"+r.id)
600 }
601 return ids
602}
603
604// unionFind joins keys that name the same thing.
605type unionFind map[string]string
606
607// find returns the key that names k and every key joined to it.
608func (u unionFind) find(k string) string {
609 for {
610 p, ok := u[k]
611 if !ok || p == k {
612 return k
613 }
614 if gp, ok := u[p]; ok {
615 u[k] = gp
616 }
617 k = p
618 }
619}
620
621func (u unionFind) union(a, b string) {
622 if ra, rb := u.find(a), u.find(b); ra != rb {
623 u[rb] = ra
624 }
625}
626
627// changeKey names a change's runs as runFields' key does, and returns the
628// repo it names them in: by the PR of the last run with one, in that run's
629// repo, since a PR's URL names a renamed repo by its new name; else by its
630// change ID in its last run's repo; else by its lone run.
631func changeKey(rs []*runInfo) (key, repo string) {
632 for i := len(rs) - 1; i >= 0; i-- {
633 if rs[i].pr != "" {
634 if repo = rs[i].repo; repo == "" {
635 repo = lastRepo(rs)
636 }
637 return repo + "#" + rs[i].pr, repo
638 }
639 }
640 repo = lastRepo(rs)
641 for _, r := range rs {
642 if r.changeID != "" {
643 return repo + "@" + r.changeID, repo
644 }
645 }
646 return rs[0].id, repo
647}
648
649func lastRepo(rs []*runInfo) string {
650 for i := len(rs) - 1; i >= 0; i-- {
651 if rs[i].repo != "" {
652 return rs[i].repo
653 }
654 }
655 return ""
656}
657
658// approvalWait is the time from the run that ended last before the change's
659// first approval to that approval. An approval is the change's when it names
660// one of its runs' PRs, under any name of the repo.
661func approvalWait(rs []*runInfo, approvals []approval) (int64, bool) {
662 prs := map[string]bool{}
663 for _, r := range rs {
664 for _, k := range r.prKeys {
665 prs[k] = true
666 }
667 }
668 if len(prs) == 0 {
669 return 0, false
670 }
671 var first time.Time
672 for _, a := range approvals {
673 if prs[strings.ToLower(a.key)] && (first.IsZero() || a.at.Before(first)) {
674 first = a.at
675 }
676 }
677 if first.IsZero() {
678 return 0, false
679 }
680 var last time.Time
681 for _, r := range rs {
682 if !r.end.IsZero() && !r.end.After(first) && r.end.After(last) {
683 last = r.end
684 }
685 }
686 if last.IsZero() {
687 return 0, false
688 }
689 return first.Sub(last).Milliseconds(), true
690}
691
692// prKey is the repo-qualified key of a PR event: its key, else built from
693// its PR URL.
694func prKey(d data, runID string) string {
695 if k := d.str("key"); strings.Contains(k, "#") {
696 return k
697 }
698 repo, pr := repoFromPRURL(d.str("pr_url")), d.str("pr_number")
699 if pr == "" && isDigits(runID) {
700 pr = runID
701 }
702 if repo == "" || pr == "" {
703 return ""
704 }
705 return repo + "#" + pr
706}
707
708// repoFromPRURL is the owner/repo of a GitHub PR URL, or "".
709func repoFromPRURL(u string) string {
710 s := strings.TrimPrefix(strings.TrimPrefix(u, "https://"), "http://")
711 s, ok := strings.CutPrefix(s, "github.com/")
712 if !ok {
713 return ""
714 }
715 parts := strings.Split(s, "/")
716 if len(parts) < 4 || parts[0] == "" || parts[1] == "" || parts[2] != "pull" {
717 return ""
718 }
719 return parts[0] + "/" + parts[1]
720}
721
722func shortName(repo string) string {
723 name := strings.TrimSuffix(strings.TrimRight(repo, "/"), ".git")
724 if strings.Contains(name, "://") || strings.Contains(name, "@") || strings.HasPrefix(name, "/") {
725 if i := strings.LastIndexAny(name, "/:"); i >= 0 {
726 name = name[i+1:]
727 }
728 }
729 return name
730}
731
732// matchRepo reports whether repo is the one want names: its key, its name
733// after valley:, or its last path component, in any case. "" wants all.
734func matchRepo(want, repo string) bool {
735 if want == "" {
736 return true
737 }
738 want, repo = strings.ToLower(want), strings.ToLower(repo)
739 return want == repo || want == strings.TrimPrefix(repo, "valley:") || want == repoName(repo)
740}
741
742// isQualified reports whether a repo key says where the repo lives:
743// owner/repo or valley:<name>.
744func isQualified(repo string) bool {
745 return strings.Contains(repo, "/") || strings.HasPrefix(repo, "valley:")
746}
747
748// repoName is a repo key's short name: after valley:, its last path
749// component.
750func repoName(repo string) string {
751 name := strings.TrimPrefix(repo, "valley:")
752 if i := strings.LastIndex(name, "/"); i >= 0 {
753 name = name[i+1:]
754 }
755 return name
756}
757
758// isRunID reports whether id is a run's (YYYYMMDD-HHMM-xxxxxxxx), not a
759// PR number or a consult's or review's.
760func isRunID(id string) bool {
761 if id == "" || isDigits(id) {
762 return false
763 }
764 for _, p := range []string{"consult-", "review-", "panel-"} {
765 if strings.HasPrefix(id, p) {
766 return false
767 }
768 }
769 return true
770}
771
772func isDigits(s string) bool {
773 if s == "" {
774 return false
775 }
776 for _, c := range s {
777 if c < '0' || c > '9' {
778 return false
779 }
780 }
781 return true
782}
783
784// data reads an event's payload as JSON decoded it.
785type data map[string]interface{}
786
787func (d data) str(k string) string {
788 switch v := d[k].(type) {
789 case string:
790 return v
791 case bool:
792 if v {
793 return "true"
794 }
795 return "false"
796 case float64:
797 if v == float64(int64(v)) {
798 return strconv.FormatInt(int64(v), 10)
799 }
800 }
801 return ""
802}
803
804func (d data) int(k string) int64 {
805 if v, ok := d[k].(float64); ok {
806 return int64(v)
807 }
808 return 0
809}
810
811func (d data) float(k string) (float64, bool) {
812 v, ok := d[k].(float64)
813 return v, ok
814}