-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
196 lines (170 loc) · 6.23 KB
/
main.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
//
// Copyright 2024 Stacklok, Inc.
//
// 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
//
// http://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 (
"context"
"encoding/json"
"log"
"os"
"strconv"
"strings"
"github.com/stacklok/trusty-action/pkg/githubapi"
"github.com/stacklok/trusty-action/pkg/parser"
"github.com/stacklok/trusty-action/pkg/trustyapi"
"github.com/stacklok/trusty-action/pkg/types"
"github.com/google/go-github/v60/github"
"golang.org/x/oauth2"
)
func parseScore(scoreStr, defaultScore string) float64 {
if scoreStr == "" {
scoreStr = defaultScore
}
score, err := strconv.ParseFloat(scoreStr, 64)
if err != nil {
log.Printf("Invalid score threshold value: %s\n", scoreStr)
return 0
}
return score
}
func parseFail(failStr, defaultFail string) bool {
if failStr == "" {
failStr = defaultFail
}
fail, err := strconv.ParseBool(failStr)
if err != nil {
log.Printf("Invalid fail value: %s\n", failStr)
return false
}
return fail
}
func main() {
ctx := context.Background()
globalThreshold := parseScore(os.Getenv("INPUT_GLOBAL_THRESHOLD"), "5")
repoActivityThreshold := parseScore(os.Getenv("INPUT_REPO_ACTIVITY_THRESHOLD"), "0")
authorActivityThreshold := parseScore(os.Getenv("INPUT_AUTHOR_ACTIVITY_THRESHOLD"), "0")
provenanceThreshold := parseScore(os.Getenv("INPUT_PROVENANCE_THRESHOLD"), "0")
typosquattingThreshold := parseScore(os.Getenv("INPUT_TYPOSQUATTING_THRESHOLD"), "0")
failOnMalicious := parseFail(os.Getenv("INPUT_FAIL_ON_MALICIOUS"), "true")
failOnDeprecated := parseFail(os.Getenv("INPUT_FAIL_ON_DEPRECATED"), "true")
failOnArchived := parseFail(os.Getenv("INPUT_FAIL_ON_ARCHIVED"), "true")
// Split the GITHUB_REPOSITORY environment variable to get owner and repo
repoFullName := os.Getenv("GITHUB_REPOSITORY")
if repoFullName == "" {
log.Println("GITHUB_REPOSITORY environment variable is not set.")
os.Exit(1)
}
repoParts := strings.Split(repoFullName, "/")
if len(repoParts) != 2 {
log.Println("Invalid GITHUB_REPOSITORY format. Expected format is 'owner/repo'.")
os.Exit(1)
}
owner, repo := repoParts[0], repoParts[1]
// Read the event file to get the pull request number
eventPath := os.Getenv("GITHUB_EVENT_PATH")
if eventPath == "" {
log.Println("GITHUB_EVENT_PATH environment variable is not set.")
os.Exit(1)
}
eventData, err := os.ReadFile(eventPath)
if err != nil {
log.Printf("Error reading event payload file: %v\n", err)
os.Exit(1)
}
var eventPayload struct {
PullRequest struct {
Number int `json:"number"`
} `json:"pull_request"`
}
if err := json.Unmarshal(eventData, &eventPayload); err != nil {
log.Printf("Error parsing event payload JSON: %v\n", err)
os.Exit(1)
}
prNumber := eventPayload.PullRequest.Number
if prNumber == 0 {
log.Println("Pull request number not found in event payload.")
os.Exit(1)
}
token := os.Getenv("GITHUB_TOKEN")
if token == "" {
log.Println("GITHUB_TOKEN environment variable is not set.")
os.Exit(1)
}
ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})
tc := oauth2.NewClient(ctx, ts)
ghClient := github.NewClient(tc)
githubClient := githubapi.NewGitHubClient(token)
// To debug overide the owner, repo and prNumber below
// owner := "lukehinds" // Replace with the owner of the repository
// repo := "bad-npm" // Replace with the repository name
// prNumber := 54 // Replace with the actual PR number you want to analyze
// Fetch PR to get base and head refs (using the original GitHub client)
pr, _, err := ghClient.PullRequests.Get(ctx, owner, repo, prNumber)
if err != nil {
log.Printf("Error fetching PR: %v\n", err)
return
}
baseRef, headRef := *pr.Base.Ref, *pr.Head.Ref
// Get the files that were changed in the PR
files, _, err := ghClient.PullRequests.ListFiles(ctx, owner, repo, prNumber, nil)
if err != nil {
log.Printf("Error fetching changed files: %v\n", err)
return
}
for _, file := range files {
baseContent, err := githubClient.GetFileContent(owner, repo, *file.Filename, baseRef)
if err != nil {
log.Printf("Error fetching base content for %s: %v\n", *file.Filename, err)
continue
}
headContent, err := githubClient.GetFileContent(owner, repo, *file.Filename, headRef)
if err != nil {
log.Printf("Error fetching head content for %s: %v\n", *file.Filename, err)
continue
}
// Parse the contents to get slices of Dependency structs and the ecosystem from the base content
baseDeps, ecosystem, err := parser.Parse(*file.Filename, baseContent) // Use ecosystem from base content parsing
if err != nil {
log.Printf("Error parsing base dependencies for %s: %v\n", *file.Filename, err)
continue
}
// Ignore the ecosystem from head content parsing
headDeps, _, err := parser.Parse(*file.Filename, headContent) // Ignore ecosystem from head content parsing
if err != nil {
log.Printf("Error parsing head dependencies for %s: %v\n", *file.Filename, err)
continue
}
// Convert slices to maps
baseDepsMap := make(map[string]string)
for _, dep := range baseDeps {
baseDepsMap[dep.Name] = dep.Version
}
headDepsMap := make(map[string]string)
for _, dep := range headDeps {
headDepsMap[dep.Name] = dep.Version
}
// Find added dependencies
addedDepsMap := types.DiffDependencies(baseDepsMap, headDepsMap)
// Extract dependency names from the addedDepsMap
var addedDepNames []string
for depName := range addedDepsMap {
addedDepNames = append(addedDepNames, depName)
}
// Debug print
log.Printf("Added dependencies: %v\n", addedDepNames)
// In your main application where you call ProcessDependencies
trustyapi.BuildReport(ctx, ghClient, owner, repo, prNumber, addedDepNames, ecosystem, globalThreshold, repoActivityThreshold, authorActivityThreshold, provenanceThreshold, typosquattingThreshold,
failOnMalicious, failOnDeprecated, failOnArchived)
}
}