-
Notifications
You must be signed in to change notification settings - Fork 2
/
provenance.go
83 lines (70 loc) · 2.44 KB
/
provenance.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"strings"
"github.com/spf13/cobra"
)
var resultsPath string
type Provenance struct {
Uri string `json:"uri"`
Digest string `json:"digest"`
Ref string `json:"ref"`
}
var generateProvenanceCmd = &cobra.Command{
Use: "generate-provenance",
Short: "Get the git artifact results.",
RunE: func(cmd *cobra.Command, args []string) error {
uriCmd := exec.Command("git", strings.Fields("config --get remote.origin.url")...)
uri, err := uriCmd.Output()
if err != nil {
fmt.Printf("error running 'git config --get remote.origin.url': %v", err) // capture error, but continue with empty field
uri = []byte("")
}
digestCmd := exec.Command("git", strings.Fields("rev-parse HEAD")...)
digest, err := digestCmd.Output()
if err != nil {
fmt.Printf("error running 'git rev-parse HEAD': %v", err) // capture error, but continue with empty field
digest = []byte("")
}
refCmd := exec.Command("git", strings.Fields("symbolic-ref HEAD")...)
ref, err := refCmd.Output()
if err != nil {
fmt.Printf("error running 'git symbolic-ref HEAD': %v", err) // capture error, but continue with empty field
ref = []byte("")
}
provenance := &Provenance{
Uri: strings.TrimSpace(string(uri)),
Digest: strings.TrimSpace("sha1:" + string(digest)),
Ref: strings.TrimSpace(string(ref)),
}
file, err := json.Marshal(provenance)
if err != nil {
return fmt.Errorf("error marshaling json %v: %v", provenance, err)
}
// Write provenance as json file in path
if err := os.WriteFile(resultsPath, file, 0444); err != nil {
return fmt.Errorf("error writing results into %s: %v", resultsPath, err)
}
return nil
},
}
func init() {
rootCmd.AddCommand(generateProvenanceCmd)
generateProvenanceCmd.Flags().StringVar(&resultsPath, "resultsPath", "", "Path to write the results in.")
}