sce.Create -> sce.WithMessage for wrapcheck (#995)

Co-authored-by: Azeem Shaikh <azeems@google.com>
This commit is contained in:
Azeem Shaikh 2021-09-10 08:50:33 -07:00 committed by GitHub
parent 1cb8c06001
commit e730e911e6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
37 changed files with 100 additions and 158 deletions

View File

@ -98,8 +98,7 @@ func logStats(ctx context.Context, startTime time.Time, result *CheckResult) err
if result.Error != nil {
ctx, err := tag.New(ctx, tag.Upsert(stats.ErrorName, sce.GetName(result.Error2)))
if err != nil {
//nolint:wrapcheck
return sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("tag.New: %v", err))
return sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("tag.New: %v", err))
}
opencensusstats.Record(ctx, stats.CheckErrors.M(1))
}

View File

@ -91,8 +91,7 @@ func checkBinaryFileContent(path string, content []byte,
var t types.Type
var err error
if t, err = filetype.Get(content); err != nil {
//nolint
return false, sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("filetype.Get:%v", err))
return false, sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("filetype.Get:%v", err))
}
if _, ok := binaryFileTypes[t.Extension]; ok {

View File

@ -90,7 +90,7 @@ func checkReleaseAndDevBranchProtection(
for _, release := range releases {
if release.TargetCommitish == "" {
// Log with a named error if target_commitish is nil.
e := sce.Create(sce.ErrScorecardInternal, errInternalCommitishNil.Error())
e := sce.WithMessage(sce.ErrScorecardInternal, errInternalCommitishNil.Error())
return checker.CreateRuntimeErrorResult(CheckBranchProtection, e)
}

View File

@ -44,7 +44,7 @@ func init() {
func CITests(c *checker.CheckRequest) checker.CheckResult {
prs, err := c.RepoClient.ListMergedPRs()
if err != nil {
e := sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("RepoClient.ListMergedPRs: %v", err))
e := sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("RepoClient.ListMergedPRs: %v", err))
return checker.CreateRuntimeErrorResult(CheckCITests, e)
}
@ -106,8 +106,7 @@ func CITests(c *checker.CheckRequest) checker.CheckResult {
func prHasSuccessStatus(pr *clients.PullRequest, c *checker.CheckRequest) (bool, error) {
statuses, err := c.RepoClient.ListStatuses(pr.HeadSHA)
if err != nil {
//nolint
return false, sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("Client.Repositories.ListStatuses: %v", err))
return false, sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("Client.Repositories.ListStatuses: %v", err))
}
for _, status := range statuses {
@ -131,12 +130,10 @@ func prHasSuccessStatus(pr *clients.PullRequest, c *checker.CheckRequest) (bool,
func prHasSuccessfulCheck(pr *clients.PullRequest, c *checker.CheckRequest) (bool, error) {
crs, err := c.RepoClient.ListCheckRunsForRef(pr.HeadSHA)
if err != nil {
//nolint
return false, sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("Client.Checks.ListCheckRunsForRef: %v", err))
return false, sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("Client.Checks.ListCheckRunsForRef: %v", err))
}
if crs == nil {
//nolint
return false, sce.Create(sce.ErrScorecardInternal, "cannot list check runs by ref")
return false, sce.WithMessage(sce.ErrScorecardInternal, "cannot list check runs by ref")
}
for _, cr := range crs {

View File

@ -43,25 +43,25 @@ func CIIBestPractices(c *checker.CheckRequest) checker.CheckResult {
url := fmt.Sprintf("https://bestpractices.coreinfrastructure.org/projects.json?url=%s", repoURL)
req, err := http.NewRequestWithContext(c.Ctx, "GET", url, nil)
if err != nil {
e := sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("http.NewRequestWithContext: %v", err))
e := sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("http.NewRequestWithContext: %v", err))
return checker.CreateRuntimeErrorResult(CheckCIIBestPractices, e)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
e := sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("HTTPClient.Do: %v", err))
e := sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("HTTPClient.Do: %v", err))
return checker.CreateRuntimeErrorResult(CheckCIIBestPractices, e)
}
defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
e := sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("ioutil.ReadAll: %v", err))
e := sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("ioutil.ReadAll: %v", err))
return checker.CreateRuntimeErrorResult(CheckCIIBestPractices, e)
}
parsedResponse := []response{}
if err := json.Unmarshal(b, &parsedResponse); err != nil {
e := sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("json.Unmarshal: %v", err))
e := sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("json.Unmarshal: %v", err))
return checker.CreateRuntimeErrorResult(CheckCIIBestPractices, e)
}
@ -79,7 +79,7 @@ func CIIBestPractices(c *checker.CheckRequest) checker.CheckResult {
const inProgressScore = 2
switch {
default:
e := sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("unsupported badge: %v", result.BadgeLevel))
e := sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("unsupported badge: %v", result.BadgeLevel))
return checker.CreateRuntimeErrorResult(CheckCIIBestPractices, e)
case strings.Contains(result.BadgeLevel, "in_progress"):
return checker.CreateResultWithScore(CheckCIIBestPractices, "badge detected: in_progress", inProgressScore)

View File

@ -93,7 +93,7 @@ func githubCodeReview(c *checker.CheckRequest) (int, string, error) {
totalReviewed := 0
prs, err := c.RepoClient.ListMergedPRs()
if err != nil {
return 0, "", sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("RepoClient.ListMergedPRs: %v", err))
return 0, "", sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("RepoClient.ListMergedPRs: %v", err))
}
for _, pr := range prs {
if pr.MergedAt.IsZero() {
@ -136,7 +136,7 @@ func isPrReviewRequired(c *checker.CheckRequest) (int, string) {
// Check the branch protection rules, we may not be able to get these though.
branch, err := c.RepoClient.GetDefaultBranch()
if err != nil {
sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("RepoClient.GetDefaultBranch: %v", err))
sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("RepoClient.GetDefaultBranch: %v", err))
}
if branch.GetBranchProtectionRule() == nil ||
branch.GetBranchProtectionRule().GetRequiredPullRequestReviews() == nil ||
@ -156,7 +156,7 @@ func prowCodeReview(c *checker.CheckRequest) (int, string, error) {
totalReviewed := 0
prs, err := c.RepoClient.ListMergedPRs()
if err != nil {
sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("RepoClient.ListMergedPRs: %v", err))
sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("RepoClient.ListMergedPRs: %v", err))
}
for _, pr := range prs {
if pr.MergedAt.IsZero() {
@ -178,9 +178,8 @@ func prowCodeReview(c *checker.CheckRequest) (int, string, error) {
func commitMessageHints(c *checker.CheckRequest) (int, string, error) {
commits, err := c.RepoClient.ListCommits()
if err != nil {
// nolint: wrapcheck
return checker.InconclusiveResultScore, "",
sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("Client.Repositories.ListCommits: %v", err))
sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("Client.Repositories.ListCommits: %v", err))
}
total := 0

View File

@ -38,7 +38,7 @@ func init() {
func Contributors(c *checker.CheckRequest) checker.CheckResult {
contribs, err := c.RepoClient.ListContributors()
if err != nil {
e := sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("Client.Repositories.ListContributors: %v", err))
e := sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("Client.Repositories.ListContributors: %v", err))
return checker.CreateRuntimeErrorResult(CheckContributors, e)
}

View File

@ -35,15 +35,13 @@ func isMatchingPath(pattern, fullpath string, caseSensitive bool) (bool, error)
filename := path.Base(fullpath)
match, err := path.Match(pattern, fullpath)
if err != nil {
//nolint
return false, sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("%v: %v", errInternalFilenameMatch, err))
return false, sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("%v: %v", errInternalFilenameMatch, err))
}
// No match on the fullpath, let's try on the filename only.
if !match {
if match, err = path.Match(pattern, filename); err != nil {
//nolint
return false, sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("%v: %v", errInternalFilenameMatch, err))
return false, sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("%v: %v", errInternalFilenameMatch, err))
}
}

View File

@ -52,7 +52,7 @@ func Fuzzing(c *checker.CheckRequest) checker.CheckResult {
errOssFuzzRepo = ossFuzzRepo.InitRepo("google", "oss-fuzz")
})
if errOssFuzzRepo != nil {
e := sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("InitRepo: %v", errOssFuzzRepo))
e := sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("InitRepo: %v", errOssFuzzRepo))
return checker.CreateRuntimeErrorResult(CheckFuzzing, e)
}
@ -62,7 +62,7 @@ func Fuzzing(c *checker.CheckRequest) checker.CheckResult {
}
result, err := ossFuzzRepo.Search(req)
if err != nil {
e := sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("Client.Search.Code: %v", err))
e := sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("Client.Search.Code: %v", err))
return checker.CreateRuntimeErrorResult(CheckFuzzing, e)
}

View File

@ -52,7 +52,7 @@ func IsMaintained(c *checker.CheckRequest) checker.CheckResult {
tz, err := time.LoadLocation("UTC")
if err != nil {
e := sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("time.LoadLocation: %v", err))
e := sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("time.LoadLocation: %v", err))
return checker.CreateRuntimeErrorResult(CheckMaintained, e)
}
threshold := time.Now().In(tz).AddDate(0, 0, -1*lookBackDays)

View File

@ -40,14 +40,14 @@ func isGithubWorkflowFile(filename string) (bool, error) {
func Packaging(c *checker.CheckRequest) checker.CheckResult {
matchedFiles, err := c.RepoClient.ListFiles(isGithubWorkflowFile)
if err != nil {
e := sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("RepoClient.ListFiles: %v", err))
e := sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("RepoClient.ListFiles: %v", err))
return checker.CreateRuntimeErrorResult(CheckPackaging, e)
}
for _, fp := range matchedFiles {
fc, err := c.RepoClient.GetFileContent(fp)
if err != nil {
e := sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("RepoClient.GetFileContent: %v", err))
e := sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("RepoClient.GetFileContent: %v", err))
return checker.CreateRuntimeErrorResult(CheckPackaging, e)
}
@ -57,7 +57,7 @@ func Packaging(c *checker.CheckRequest) checker.CheckResult {
runs, err := c.RepoClient.ListSuccessfulWorkflowRuns(filepath.Base(fp))
if err != nil {
e := sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("Client.Actions.ListWorkflowRunsByFileName: %v", err))
e := sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("Client.Actions.ListWorkflowRunsByFileName: %v", err))
return checker.CreateRuntimeErrorResult(CheckPackaging, e)
}
if len(runs) > 0 {

View File

@ -57,8 +57,7 @@ func validatePermission(key string, value interface{}, path string,
ignoredPermissions map[string]bool) error {
val, ok := value.(string)
if !ok {
//nolint
return sce.Create(sce.ErrScorecardInternal, errInvalidGitHubWorkflow.Error())
return sce.WithMessage(sce.ErrScorecardInternal, errInvalidGitHubWorkflow.Error())
}
if strings.EqualFold(val, "write") {
@ -105,8 +104,7 @@ func validateMapPermissions(values map[interface{}]interface{}, path string,
for k, v := range values {
key, ok := k.(string)
if !ok {
//nolint
return sce.Create(sce.ErrScorecardInternal, errInvalidGitHubWorkflow.Error())
return sce.WithMessage(sce.ErrScorecardInternal, errInvalidGitHubWorkflow.Error())
}
if err := validatePermission(key, v, path, dl, pPermissions, ignoredPermissions); err != nil {
@ -174,8 +172,7 @@ func validatePermissions(permissions interface{}, path string,
// Invalid type.
default:
//nolint
return sce.Create(sce.ErrScorecardInternal, errInvalidGitHubWorkflow.Error())
return sce.WithMessage(sce.ErrScorecardInternal, errInvalidGitHubWorkflow.Error())
}
return nil
}
@ -211,15 +208,13 @@ func validateRunLevelPermissions(config map[interface{}]interface{}, path string
mjobs, ok := jobs.(map[interface{}]interface{})
if !ok {
//nolint:wrapcheck
return sce.Create(sce.ErrScorecardInternal, errInvalidGitHubWorkflow.Error())
return sce.WithMessage(sce.ErrScorecardInternal, errInvalidGitHubWorkflow.Error())
}
for _, value := range mjobs {
job, ok := value.(map[interface{}]interface{})
if !ok {
//nolint:wrapcheck
return sce.Create(sce.ErrScorecardInternal, errInvalidGitHubWorkflow.Error())
return sce.WithMessage(sce.ErrScorecardInternal, errInvalidGitHubWorkflow.Error())
}
// Run-level permissions may be left undefined.
// For most workflows, no write permissions are needed,
@ -379,9 +374,8 @@ func validateGitHubActionTokenPermissions(path string, content []byte,
var workflow map[interface{}]interface{}
err := yaml.Unmarshal(content, &workflow)
if err != nil {
//nolint
return false,
sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("yaml.Unmarshal: %v", err))
sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("yaml.Unmarshal: %v", err))
}
// 1. Top-level permission definitions.

View File

@ -89,8 +89,7 @@ func (s *stringOrSlice) UnmarshalYAML(value *yaml.Node) error {
var single string
err = value.Decode(&single)
if err != nil {
//nolint:wrapcheck
return sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("error decoding stringOrSlice Value: %v", err))
return sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("error decoding stringOrSlice Value: %v", err))
}
*s = []string{single}
return nil
@ -112,8 +111,7 @@ type worklowPinningResult struct {
func (ws *stringWithLine) UnmarshalYAML(value *yaml.Node) error {
err := value.Decode(&ws.Value)
if err != nil {
//nolint:wrapcheck
return sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("error decoding stringWithLine Value: %v", err))
return sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("error decoding stringWithLine Value: %v", err))
}
ws.Line = value.Line
@ -356,8 +354,7 @@ func validateDockerfileIsFreeOfInsecureDownloads(pathfn string, content []byte,
contentReader := strings.NewReader(string(content))
res, err := parser.Parse(contentReader)
if err != nil {
//nolint
return false, sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("%v: %v", errInternalInvalidDockerFile, err))
return false, sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("%v: %v", errInternalInvalidDockerFile, err))
}
var bytes []byte
@ -376,8 +373,7 @@ func validateDockerfileIsFreeOfInsecureDownloads(pathfn string, content []byte,
}
if len(valueList) == 0 {
//nolint
return false, sce.Create(sce.ErrScorecardInternal, errInternalInvalidDockerFile.Error())
return false, sce.WithMessage(sce.ErrScorecardInternal, errInternalInvalidDockerFile.Error())
}
// Build a file content.
@ -441,8 +437,7 @@ func validateDockerfileIsPinned(pathfn string, content []byte,
pinnedAsNames := make(map[string]bool)
res, err := parser.Parse(contentReader)
if err != nil {
//nolint
return false, sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("%v: %v", errInternalInvalidDockerFile, err))
return false, sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("%v: %v", errInternalInvalidDockerFile, err))
}
for _, child := range res.AST.Children {
@ -489,8 +484,7 @@ func validateDockerfileIsPinned(pathfn string, content []byte,
default:
// That should not happen.
//nolint
return false, sce.Create(sce.ErrScorecardInternal, errInternalInvalidDockerFile.Error())
return false, sce.WithMessage(sce.ErrScorecardInternal, errInternalInvalidDockerFile.Error())
}
}
@ -541,8 +535,7 @@ func validateGitHubWorkflowIsFreeOfInsecureDownloads(pathfn string, content []by
var workflow gitHubActionWorkflowConfig
err := yaml.Unmarshal(content, &workflow)
if err != nil {
//nolint
return false, sce.Create(sce.ErrScorecardInternal,
return false, sce.WithMessage(sce.ErrScorecardInternal,
fmt.Sprintf("%v: %v", errInternalInvalidYamlFile, err))
}
@ -642,8 +635,7 @@ func isStepWindows(step *gitHubActionWorkflowStep) (bool, error) {
for _, windowsRegex := range windowsRegexes {
matches, err := regexp.MatchString(windowsRegex, step.If)
if err != nil {
//nolint:wrapcheck
return false, sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("error matching Windows regex: %v", err))
return false, sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("error matching Windows regex: %v", err))
}
if matches {
return true, nil
@ -689,8 +681,7 @@ func validateGitHubActionWorkflow(pathfn string, content []byte,
var workflow gitHubActionWorkflowConfig
err := yaml.Unmarshal(content, &workflow)
if err != nil {
//nolint
return false, sce.Create(sce.ErrScorecardInternal,
return false, sce.WithMessage(sce.ErrScorecardInternal,
fmt.Sprintf("%v: %v", errInternalInvalidYamlFile, err))
}

View File

@ -75,7 +75,7 @@ func SAST(c *checker.CheckRequest) checker.CheckResult {
score := checker.AggregateScoresWithWeight(map[int]int{sastScore: sastWeight, codeQlScore: codeQlWeight})
return checker.CreateResultWithScore(CheckSAST, "SAST tool detected but not run on all commmits", score)
default:
return checker.CreateRuntimeErrorResult(CheckSAST, sce.Create(sce.ErrScorecardInternal, "contact team"))
return checker.CreateRuntimeErrorResult(CheckSAST, sce.WithMessage(sce.ErrScorecardInternal, "contact team"))
}
}
@ -98,7 +98,7 @@ func SAST(c *checker.CheckRequest) checker.CheckResult {
}
// Should never happen.
return checker.CreateRuntimeErrorResult(CheckSAST, sce.Create(sce.ErrScorecardInternal, "contact team"))
return checker.CreateRuntimeErrorResult(CheckSAST, sce.WithMessage(sce.ErrScorecardInternal, "contact team"))
}
// nolint
@ -107,7 +107,7 @@ func sastToolInCheckRuns(c *checker.CheckRequest) (int, error) {
if err != nil {
//nolint
return checker.InconclusiveResultScore,
sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("RepoClient.ListMergedPRs: %v", err))
sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("RepoClient.ListMergedPRs: %v", err))
}
totalMerged := 0
@ -120,7 +120,7 @@ func sastToolInCheckRuns(c *checker.CheckRequest) (int, error) {
crs, err := c.RepoClient.ListCheckRunsForRef(pr.HeadSHA)
if err != nil {
return checker.InconclusiveResultScore,
sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("Client.Checks.ListCheckRunsForRef: %v", err))
sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("Client.Checks.ListCheckRunsForRef: %v", err))
}
if crs == nil {
c.Dlogger.Warn3(&checker.LogMessage{
@ -175,7 +175,7 @@ func codeQLInCheckDefinitions(c *checker.CheckRequest) (int, error) {
resp, err := c.RepoClient.Search(searchRequest)
if err != nil {
return checker.InconclusiveResultScore,
sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("Client.Search.Code: %v", err))
sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("Client.Search.Code: %v", err))
}
for _, result := range resp.Results {

View File

@ -107,8 +107,7 @@ func getWgetOutputFile(cmd []string) (pathfn string, ok bool, err error) {
u, err := url.Parse(cmd[i])
if err != nil {
//nolint
return "", false, sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("url.Parse: %v", err))
return "", false, sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("url.Parse: %v", err))
}
return path.Base(u.Path), true, nil
}
@ -127,8 +126,7 @@ func getGsutilOutputFile(cmd []string) (pathfn string, ok bool, err error) {
// Directory.
u, err := url.Parse(cmd[i])
if err != nil {
//nolint
return "", false, sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("url.Parse: %v", err))
return "", false, sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("url.Parse: %v", err))
}
return filepath.Join(filepath.Dir(pathfn), path.Base(u.Path)), true, nil
}
@ -153,8 +151,7 @@ func getAWSOutputFile(cmd []string) (pathfn string, ok bool, err error) {
if filepath.Clean(filepath.Dir(ofile)) == filepath.Clean(ofile) {
u, err := url.Parse(ifile)
if err != nil {
//nolint
return "", false, sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("url.Parse: %v", err))
return "", false, sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("url.Parse: %v", err))
}
return filepath.Join(filepath.Dir(ofile), path.Base(u.Path)), true, nil
}
@ -672,8 +669,7 @@ func nodeToString(p *syntax.Printer, node syntax.Node) (string, error) {
err := p.Print(&buf, node)
// This is ugly, but the parser does not have a defined error type :/.
if err != nil && !strings.Contains(err.Error(), "unsupported node type") {
//nolint
return "", sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("syntax.Printer.Print: %v", err))
return "", sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("syntax.Printer.Print: %v", err))
}
return buf.String(), nil
}

View File

@ -39,7 +39,7 @@ func init() {
func SignedReleases(c *checker.CheckRequest) checker.CheckResult {
releases, err := c.RepoClient.ListReleases()
if err != nil {
e := sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("Client.Repositories.ListReleases: %v", err))
e := sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("Client.Repositories.ListReleases: %v", err))
return checker.CreateRuntimeErrorResult(CheckSignedReleases, e)
}

View File

@ -58,7 +58,7 @@ func (resp *osvResponse) getVulnerabilities() []string {
func HasUnfixedVulnerabilities(c *checker.CheckRequest) checker.CheckResult {
commits, err := c.RepoClient.ListCommits()
if err != nil {
e := sce.Create(sce.ErrScorecardInternal, "Client.Repositories.ListCommits")
e := sce.WithMessage(sce.ErrScorecardInternal, "Client.Repositories.ListCommits")
return checker.CreateRuntimeErrorResult(CheckVulnerabilities, e)
}
@ -70,13 +70,13 @@ func HasUnfixedVulnerabilities(c *checker.CheckRequest) checker.CheckResult {
Commit: commits[0].SHA,
})
if err != nil {
e := sce.Create(sce.ErrScorecardInternal, "json.Marshal")
e := sce.WithMessage(sce.ErrScorecardInternal, "json.Marshal")
return checker.CreateRuntimeErrorResult(CheckVulnerabilities, e)
}
req, err := http.NewRequestWithContext(c.Ctx, http.MethodPost, osvQueryEndpoint, bytes.NewReader(query))
if err != nil {
e := sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("http.NewRequestWithContext: %v", err))
e := sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("http.NewRequestWithContext: %v", err))
return checker.CreateRuntimeErrorResult(CheckVulnerabilities, e)
}
@ -84,7 +84,7 @@ func HasUnfixedVulnerabilities(c *checker.CheckRequest) checker.CheckResult {
httpClient := &http.Client{}
resp, err := httpClient.Do(req)
if err != nil {
e := sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("httpClient.Do: %v", err))
e := sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("httpClient.Do: %v", err))
return checker.CreateRuntimeErrorResult(CheckVulnerabilities, e)
}
defer resp.Body.Close()
@ -92,7 +92,7 @@ func HasUnfixedVulnerabilities(c *checker.CheckRequest) checker.CheckResult {
var osvResp osvResponse
decoder := json.NewDecoder(resp.Body)
if err := decoder.Decode(&osvResp); err != nil {
e := sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("decoder.Decode: %v", err))
e := sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("decoder.Decode: %v", err))
return checker.CreateRuntimeErrorResult(CheckVulnerabilities, e)
}

View File

@ -92,7 +92,7 @@ func (handler *branchesHandler) setup() error {
}
handler.data = new(branchesData)
if err := handler.graphClient.Query(handler.ctx, handler.data, vars); err != nil {
handler.errSetup = sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("githubv4.Query: %v", err))
handler.errSetup = sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("githubv4.Query: %v", err))
}
handler.defaultBranchRef = getBranchRefFrom(handler.data.Repository.DefaultBranchRef)
handler.branches = getBranchRefsFrom(handler.data.Repository.Refs.Nodes, handler.defaultBranchRef)

View File

@ -41,8 +41,7 @@ func (handler *checkrunsHandler) listCheckRunsForRef(ref string) ([]clients.Chec
checkRuns, _, err := handler.client.Checks.ListCheckRunsForRef(handler.ctx, handler.owner, handler.repo, ref,
&github.ListCheckRunsOptions{})
if err != nil {
// nolint: wrapcheck
return nil, sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("ListCheckRunsForRef: %v", err))
return nil, sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("ListCheckRunsForRef: %v", err))
}
return checkRunsFrom(checkRuns), nil
}

View File

@ -53,8 +53,7 @@ func (client *Client) InitRepo(owner, repoName string) error {
// Sanity check.
repo, _, err := client.repoClient.Repositories.Get(client.ctx, owner, repoName)
if err != nil {
// nolint: wrapcheck
return sce.Create(sce.ErrRepoUnreachable, err.Error())
return sce.WithMessage(sce.ErrRepoUnreachable, err.Error())
}
client.repo = repo
client.owner = repo.Owner.GetLogin()

View File

@ -110,7 +110,7 @@ func (handler *graphqlHandler) setup() error {
"commitsToAnalyze": githubv4.Int(commitsToAnalyze),
}
if err := handler.client.Query(handler.ctx, handler.data, vars); err != nil {
handler.errSetup = sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("githubv4.Query: %v", err))
handler.errSetup = sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("githubv4.Query: %v", err))
}
handler.archived = bool(handler.data.Repository.IsArchived)
handler.prs = pullRequestsFrom(handler.data)

View File

@ -48,7 +48,7 @@ func (handler *releasesHandler) setup() error {
releases, _, err := handler.client.Repositories.ListReleases(
handler.ctx, handler.owner, handler.repo, &github.ListOptions{})
if err != nil {
handler.errSetup = sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("githubv4.Query: %v", err))
handler.errSetup = sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("githubv4.Query: %v", err))
}
handler.releases = releasesFrom(releases)
})

View File

@ -46,21 +46,18 @@ type censusTransport struct {
func (ct *censusTransport) RoundTrip(r *http.Request) (*http.Response, error) {
ctx, err := tag.New(r.Context(), tag.Upsert(stats.RequestTag, "requested"))
if err != nil {
//nolint:wrapcheck
return nil, sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("tag.New: %v", err))
return nil, sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("tag.New: %v", err))
}
r = r.WithContext(ctx)
resp, err := ct.innerTransport.RoundTrip(r)
if err != nil {
//nolint:wrapcheck
return nil, sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("innerTransport.RoundTrip: %v", err))
return nil, sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("innerTransport.RoundTrip: %v", err))
}
if resp.Header.Get(fromCacheHeader) != "" {
ctx, err = tag.New(ctx, tag.Upsert(stats.RequestTag, fromCacheHeader))
if err != nil {
//nolint:wrapcheck
return nil, sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("tag.New: %v", err))
return nil, sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("tag.New: %v", err))
}
}
opencensusstats.Record(ctx, stats.HTTPRequests.M(1))

View File

@ -43,8 +43,7 @@ type rateLimitTransport struct {
func (gh *rateLimitTransport) RoundTrip(r *http.Request) (*http.Response, error) {
resp, err := gh.innerTransport.RoundTrip(r)
if err != nil {
//nolint:wrapcheck
return nil, sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("innerTransport.RoundTrip: %v", err))
return nil, sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("innerTransport.RoundTrip: %v", err))
}
rateLimit := resp.Header.Get("X-RateLimit-Remaining")
remaining, err := strconv.Atoi(rateLimit)

View File

@ -41,8 +41,7 @@ func (handler *statusesHandler) listStatuses(ref string) ([]clients.Status, erro
statuses, _, err := handler.client.Repositories.ListStatuses(handler.ctx, handler.owner, handler.repo, ref,
&github.ListOptions{})
if err != nil {
// nolint: wrapcheck
return nil, sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("ListStatuses: %v", err))
return nil, sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("ListStatuses: %v", err))
}
return statusesFrom(statuses), nil
}

View File

@ -72,8 +72,7 @@ type tarballHandler struct {
func (handler *tarballHandler) init(ctx context.Context, repo *github.Repository) error {
// Cleanup any previous state.
if err := handler.cleanup(); err != nil {
// nolint: wrapcheck
return sce.Create(sce.ErrScorecardInternal, err.Error())
return sce.WithMessage(sce.ErrScorecardInternal, err.Error())
}
// Setup temp dir/files and download repo tarball.
@ -81,8 +80,7 @@ func (handler *tarballHandler) init(ctx context.Context, repo *github.Repository
log.Printf("unable to get tarball %v. Skipping...", err)
return nil
} else if err != nil {
// nolint: wrapcheck
return sce.Create(sce.ErrScorecardInternal, err.Error())
return sce.WithMessage(sce.ErrScorecardInternal, err.Error())
}
// Extract file names and content from tarball.
@ -90,8 +88,7 @@ func (handler *tarballHandler) init(ctx context.Context, repo *github.Repository
log.Printf("unable to extract tarball %v. Skipping...", err)
return nil
} else if err != nil {
// nolint: wrapcheck
return sce.Create(sce.ErrScorecardInternal, err.Error())
return sce.WithMessage(sce.ErrScorecardInternal, err.Error())
}
return nil

View File

@ -43,8 +43,7 @@ func (handler *workflowsHandler) listSuccessfulWorkflowRuns(filename string) ([]
Status: "success",
})
if err != nil {
// nolint: wrapcheck
return nil, sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("ListWorkflowRunsByFileName: %v", err))
return nil, sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("ListWorkflowRunsByFileName: %v", err))
}
return workflowsRunsFrom(workflowRuns), nil
}

View File

@ -174,7 +174,7 @@ or ./scorecard --{npm,pypi,rubgems}=<package_name> [--checks=check1,...] [--show
}
err = repoResult.AsJSON2(showDetails, *logLevel, checkDocs, os.Stdout)
default:
err = sce.Create(sce.ErrScorecardInternal,
err = sce.WithMessage(sce.ErrScorecardInternal,
fmt.Sprintf("invalid format flag: %v. Expected [default, csv, json]", format))
}
if err != nil {
@ -223,20 +223,17 @@ func fetchGitRepositoryFromNPM(packageName string) (string, error) {
}
resp, err := client.Get(fmt.Sprintf(npmSearchURL, packageName))
if err != nil {
//nolint:wrapcheck
return "", sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("failed to get npm package json: %v", err))
return "", sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("failed to get npm package json: %v", err))
}
defer resp.Body.Close()
v := &npmSearchResults{}
err = json.NewDecoder(resp.Body).Decode(v)
if err != nil {
//nolint:wrapcheck
return "", sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("failed to parse npm package json: %v", err))
return "", sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("failed to parse npm package json: %v", err))
}
if len(v.Objects) == 0 {
//nolint:wrapcheck
return "", sce.Create(sce.ErrScorecardInternal,
return "", sce.WithMessage(sce.ErrScorecardInternal,
fmt.Sprintf("could not find source repo for npm package: %s", packageName))
}
return v.Objects[0].Package.Links.Repository, nil
@ -252,20 +249,17 @@ func fetchGitRepositoryFromPYPI(packageName string) (string, error) {
}
resp, err := client.Get(fmt.Sprintf(pypiSearchURL, packageName))
if err != nil {
//nolint:wrapcheck
return "", sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("failed to get pypi package json: %v", err))
return "", sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("failed to get pypi package json: %v", err))
}
defer resp.Body.Close()
v := &pypiSearchResults{}
err = json.NewDecoder(resp.Body).Decode(v)
if err != nil {
//nolint:wrapcheck
return "", sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("failed to parse pypi package json: %v", err))
return "", sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("failed to parse pypi package json: %v", err))
}
if v.Info.ProjectUrls.Source == "" {
//nolint:wrapcheck
return "", sce.Create(sce.ErrScorecardInternal,
return "", sce.WithMessage(sce.ErrScorecardInternal,
fmt.Sprintf("could not find source repo for pypi package: %s", packageName))
}
return v.Info.ProjectUrls.Source, nil
@ -281,20 +275,17 @@ func fetchGitRepositoryFromRubyGems(packageName string) (string, error) {
}
resp, err := client.Get(fmt.Sprintf(rubyGemsSearchURL, packageName))
if err != nil {
//nolint:wrapcheck
return "", sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("failed to get ruby gem json: %v", err))
return "", sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("failed to get ruby gem json: %v", err))
}
defer resp.Body.Close()
v := &rubyGemsSearchResults{}
err = json.NewDecoder(resp.Body).Decode(v)
if err != nil {
//nolint:wrapcheck
return "", sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("failed to parse ruby gem json: %v", err))
return "", sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("failed to parse ruby gem json: %v", err))
}
if v.SourceCodeURI == "" {
//nolint:wrapcheck
return "", sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("could not find source repo for ruby gem: %v", err))
return "", sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("could not find source repo for ruby gem: %v", err))
}
return v.SourceCodeURI, nil
}

View File

@ -115,6 +115,7 @@ func getIntConfigValue(envVar string, byteValue []byte, fieldName, configName st
if err != nil {
return 0, fmt.Errorf("error getting config value %s: %w", configName, err)
}
// nolint: exhaustive
switch value.Kind() {
case reflect.String:

View File

@ -90,8 +90,7 @@ func AsJSON(r *pkg.ScorecardResult, showDetails bool, logLevel zapcore.Level, wr
out.Checks = append(out.Checks, tmpResult)
}
if err := encoder.Encode(out); err != nil {
//nolint:wrapcheck
return sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("encoder.Encode: %v", err))
return sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("encoder.Encode: %v", err))
}
return nil
}
@ -127,8 +126,7 @@ func AsJSON2(r *pkg.ScorecardResult, showDetails bool, logLevel zapcore.Level, w
out.Checks = append(out.Checks, tmpResult)
}
if err := encoder.Encode(out); err != nil {
//nolint:wrapcheck
return sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("encoder.Encode: %v", err))
return sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("encoder.Encode: %v", err))
}
return nil

View File

@ -17,5 +17,5 @@ package errors
// CreateInternal creates internal error, not using
// any of the errors listed in public.go.
func CreateInternal(e error, msg string) error {
return Create(e, msg)
return WithMessage(e, msg)
}

View File

@ -25,9 +25,9 @@ var (
ErrRepoUnreachable = errors.New("repo unreachable")
)
// Create a public error using any of the errors
// listed above. For examples, see errors/errors.md.
func Create(e error, msg string) error {
// WithMessage wraps any of the errors listed above.
// For examples, see errors/errors.md.
func WithMessage(e error, msg string) error {
// Note: Errorf automatically wraps the error when used with `%w`.
if len(msg) > 0 {
return fmt.Errorf("%w: %v", e, msg)

View File

@ -103,8 +103,7 @@ func (r *ScorecardResult) AsJSON(showDetails bool, logLevel zapcore.Level, write
out.Checks = append(out.Checks, tmpResult)
}
if err := encoder.Encode(out); err != nil {
//nolint:wrapcheck
return sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("encoder.Encode: %v", err))
return sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("encoder.Encode: %v", err))
}
return nil
}
@ -131,7 +130,7 @@ func (r *ScorecardResult) AsJSON2(showDetails bool,
for _, checkResult := range r.Checks {
doc, e := checkDocs.GetCheck(checkResult.Name)
if e != nil {
return sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("GetCheck: %s: %v", checkResult.Name, e))
return sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("GetCheck: %s: %v", checkResult.Name, e))
}
tmpResult := jsonCheckResultV2{
@ -156,8 +155,7 @@ func (r *ScorecardResult) AsJSON2(showDetails bool,
out.Checks = append(out.Checks, tmpResult)
}
if err := encoder.Encode(out); err != nil {
//nolint:wrapcheck
return sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("encoder.Encode: %v", err))
return sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("encoder.Encode: %v", err))
}
return nil

View File

@ -405,7 +405,7 @@ func (r *ScorecardResult) AsSARIF(showDetails bool, logLevel zapcore.Level,
for i, check := range r.Checks {
doc, e := checkDocs.GetCheck(check.Name)
if e != nil {
return sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("GetCheck: %v: %s", e, check.Name))
return sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("GetCheck: %v: %s", e, check.Name))
}
// Unclear what to use for PartialFingerprints.
@ -452,8 +452,7 @@ func (r *ScorecardResult) AsSARIF(showDetails bool, logLevel zapcore.Level,
encoder := json.NewEncoder(writer)
encoder.SetIndent("", " ")
if err := encoder.Encode(sarif); err != nil {
// nolint: wrapcheck
return sce.Create(sce.ErrScorecardInternal, err.Error())
return sce.WithMessage(sce.ErrScorecardInternal, err.Error())
}
return nil

View File

@ -71,14 +71,13 @@ func RunScorecards(ctx context.Context,
repoClient clients.RepoClient) (ScorecardResult, error) {
ctx, err := tag.New(ctx, tag.Upsert(stats.Repo, repo.URL()))
if err != nil {
//nolint:wrapcheck
return ScorecardResult{}, sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("tag.New: %v", err))
return ScorecardResult{}, sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("tag.New: %v", err))
}
defer logStats(ctx, time.Now())
if err := repoClient.InitRepo(repo.Owner, repo.Repo); err != nil {
// No need to call sce.Create() since InitRepo will do that for us.
//nolint:wrapcheck
// No need to call sce.WithMessage() since InitRepo will do that for us.
// nolint: wrapcheck
return ScorecardResult{}, err
}
defer repoClient.Close()

View File

@ -69,13 +69,11 @@ func (r *ScorecardResult) AsCSV(showDetails bool, logLevel zapcore.Level, writer
}
fmt.Fprintf(writer, "%s\n", strings.Join(columns, ","))
if err := w.Write(record); err != nil {
//nolint:wrapcheck
return sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("csv.Write: %v", err))
return sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("csv.Write: %v", err))
}
w.Flush()
if err := w.Error(); err != nil {
//nolint:wrapcheck
return sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("csv.Flush: %v", err))
return sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("csv.Flush: %v", err))
}
return nil
}

View File

@ -79,15 +79,13 @@ func (r *RepoURL) Set(s string) error {
u, e := url.Parse(t)
if e != nil {
//nolint:wrapcheck
return sce.Create(sce.ErrScorecardInternal, fmt.Sprintf("url.Parse: %v", e))
return sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("url.Parse: %v", e))
}
const splitLen = 2
split := strings.SplitN(strings.Trim(u.Path, "/"), "/", splitLen)
if len(split) != splitLen {
//nolint:wrapcheck
return sce.Create(ErrorInvalidURL, fmt.Sprintf("%v. Exepted full repository url", s))
return sce.WithMessage(ErrorInvalidURL, fmt.Sprintf("%v. Exepted full repository url", s))
}
r.Host, r.Owner, r.Repo = u.Host, split[0], split[1]
@ -99,13 +97,11 @@ func (r *RepoURL) ValidGitHubURL() error {
switch r.Host {
case "github.com":
default:
//nolint:wrapcheck
return sce.Create(ErrorUnsupportedHost, r.Host)
return sce.WithMessage(ErrorUnsupportedHost, r.Host)
}
if strings.TrimSpace(r.Owner) == "" || strings.TrimSpace(r.Repo) == "" {
//nolint:wrapcheck
return sce.Create(ErrorInvalidGithubURL,
return sce.WithMessage(ErrorInvalidGithubURL,
fmt.Sprintf("%v. Expected the full reposiroty url", r.URL()))
}
return nil