cmd/gitbay-runner/results.go

545ba0bcdea3b534903bd78c918c0c025a97eda7
gitbay/cmd/gitbay-runner/results.go

65 lines · 1765 bytes

4 symbols in this file
 1package main
 2
 3import (
 4	"bytes"
 5	"encoding/json"
 6	"errors"
 7	"fmt"
 8	"os"
 9	"path/filepath"
10	"sort"
11)
12
13// resultsDir is where a code scan's steps write SARIF, relative to the
14// workspace.
15const resultsDir = ".gitbay-results"
16
17// maxResults matches the server's upload limit (codescan.MaxUpload).
18const maxResults = 8 << 20
19
20// mergeResults reads every .sarif file in dir and joins their runs into
21// one document, the shape runner results takes. Steps that wrote nothing
22// is an error: a scan that produced no results did not run.
23func mergeResults(dir string) ([]byte, error) {
24	names, err := filepath.Glob(filepath.Join(dir, "*.sarif"))
25	if err != nil {
26		return nil, err
27	}
28	if len(names) == 0 {
29		return nil, fmt.Errorf("no .sarif files in %s", resultsDir)
30	}
31	sort.Strings(names)
32	var runs []json.RawMessage
33	total := 0
34	for _, name := range names {
35		raw, err := os.ReadFile(name)
36		if err != nil {
37			return nil, err
38		}
39		if total += len(raw); total > maxResults {
40			return nil, fmt.Errorf("results are over %d bytes", maxResults)
41		}
42		var doc struct {
43			Runs []json.RawMessage `json:"runs"`
44		}
45		if err := json.Unmarshal(raw, &doc); err != nil {
46			return nil, fmt.Errorf("%s: %w", filepath.Base(name), err)
47		}
48		if doc.Runs == nil {
49			return nil, errors.New(filepath.Base(name) + ": no runs")
50		}
51		runs = append(runs, doc.Runs...)
52	}
53	return json.Marshal(map[string]any{"version": "2.1.0", "runs": runs})
54}
55
56// uploadResults sends the merged SARIF, retrying as reportDone does.
57func (r *runner) uploadResults(id int64, dir string) error {
58	doc, err := mergeResults(dir)
59	if err != nil {
60		return err
61	}
62	return reportWithRetry(func() (string, error) {
63		return r.ssh(bytes.NewReader(doc), "runner", "results", fmt.Sprint(id))
64	}, id, retryDelays)
65}