Repository: googleapis/api-linter
Pull request #534 (2020-04-23 04:47:52)

[feat] return non-zero exit status when lint problems found
This change introduces a new flag `--set-exit-status` which will return
a non-zero exit status when lint problems are found. This is a non
breaking change that allows api-linter to be used in CI environments.

This addresses issue #522

googlebot: 
Thanks for your pull request. It looks like this may be your first contribution to a Google open source project (if not, look below for help). Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

:memo: **Please visit <https://cla.developers.google.com/> to sign.**

Once you've signed (or fixed any issues), please reply here with `@googlebot I signed it!` and we'll verify it.

----

#### What to do if you already signed the CLA

##### Individual signers

*   It's possible we don't have your GitHub username or you're using a different email address on your commit. Check [your existing CLA data](https://cla.developers.google.com/clas) and verify that your [email is set on your git commits](https://help.github.com/articles/setting-your-email-in-git/).

##### Corporate signers

*   Your company has a Point of Contact who decides which employees are authorized to participate. Ask your POC to be added to the group of authorized contributors. If you don't know who your Point of Contact is, direct the Google project maintainer to [go/cla#troubleshoot](http://go/cla#troubleshoot) ([Public version](https://opensource.google/docs/cla/#troubleshoot)).
*   The email used to register you as an authorized contributor must be the email used for the Git commit. Check [your existing CLA data](https://cla.developers.google.com/clas) and verify that your [email is set on your git commits](https://help.github.com/articles/setting-your-email-in-git/).
*   The email used to register you as an authorized contributor must also be [attached to your GitHub account](https://github.com/settings/emails).
		

ℹ️ **Googlers: [Go here](https://goto.google.com/prinfo/https%3A%2F%2Fgithub.com%2Fgoogleapis%2Fapi-linter%2Fpull%2F534) for more info**.

<!-- need_sender_cla -->
googlebot: CLAs look good, thanks!

ℹ️ **Googlers: [Go here](https://goto.google.com/prinfo/https%3A%2F%2Fgithub.com%2Fgoogleapis%2Fapi-linter%2Fpull%2F534) for more info**.

<!-- ok -->

Patch:
diff --git a/cmd/api-linter/cli.go b/cmd/api-linter/cli.go
index 0984fed..c602269 100644
--- a/cmd/api-linter/cli.go
+++ b/cmd/api-linter/cli.go
@@ -33,21 +33,25 @@ import (
 )
 
 type cli struct {
-	ConfigPath       string
-	FormatType       string
-	OutputPath       string
-	ProtoImportPaths []string
-	ProtoFiles       []string
-	ProtoDescPath    []string
-	EnabledRules     []string
-	DisabledRules    []string
+	ConfigPath              string
+	FormatType              string
+	OutputPath              string
+	ExitStatusOnLintFailure bool
+	ProtoImportPaths        []string
+	ProtoFiles              []string
+	ProtoDescPath           []string
+	EnabledRules            []string
+	DisabledRules           []string
 }
 
+var ExitForLintFailure = errors.New("found problems during linting")
+
 func newCli(args []string) *cli {
 	// Define flag variables.
 	var cfgFlag string
 	var fmtFlag string
 	var outFlag string
+	var setExitStatusOnLintFailure bool
 	var protoImportFlag []string
 	var protoDescFlag []string
 	var ruleEnableFlag []string
@@ -58,6 +62,7 @@ func newCli(args []string) *cli {
 	fs.StringVar(&cfgFlag, "config", "", "The linter config file.")
 	fs.StringVar(&fmtFlag, "output-format", "", "The format of the linting results.\nSupported formats include \"yaml\", \"json\" and \"summary\" table.\nYAML is the default.")
 	fs.StringVarP(&outFlag, "output-path", "o", "", "The output file path.\nIf not given, the linting results will be printed out to STDOUT.")
+	fs.BoolVar(&setExitStatusOnLintFailure, "set-exit-status", false, "Return exit status 1 when lint errors are found.")
 	fs.StringArrayVarP(&protoImportFlag, "proto-path", "I", nil, "The folder for searching proto imports.\nMay be specified multiple times; directories will be searched in order.\nThe current working directory is always used.")
 	fs.StringArrayVar(&protoDescFlag, "descriptor-set-in", nil, "The file containing a FileDescriptorSet for searching proto imports.\nMay be specified multiple times.")
 	fs.StringArrayVar(&ruleEnableFlag, "enable-rule", nil, "Enable a rule with the given name.\nMay be specified multiple times.")
@@ -70,14 +75,15 @@ func newCli(args []string) *cli {
 	}
 
 	return &cli{
-		ConfigPath:       cfgFlag,
-		FormatType:       fmtFlag,
-		OutputPath:       outFlag,
-		ProtoImportPaths: append(protoImportFlag, "."),
-		ProtoDescPath:    protoDescFlag,
-		EnabledRules:     ruleEnableFlag,
-		DisabledRules:    ruleDisableFlag,
-		ProtoFiles:       fs.Args(),
+		ConfigPath:              cfgFlag,
+		FormatType:              fmtFlag,
+		OutputPath:              outFlag,
+		ExitStatusOnLintFailure: setExitStatusOnLintFailure,
+		ProtoImportPaths:        append(protoImportFlag, "."),
+		ProtoDescPath:           protoDescFlag,
+		EnabledRules:            ruleEnableFlag,
+		DisabledRules:           ruleDisableFlag,
+		ProtoFiles:              fs.Args(),
 	}
 }
 
@@ -181,6 +187,13 @@ func (c *cli) lint(rules lint.RuleRegistry, configs lint.Configs) error {
 	if _, err = w.Write(b); err != nil {
 		return err
 	}
+
+	// Return error on lint failure which subsequently
+	// exits with a non-zero status code
+	if c.ExitStatusOnLintFailure && len(results) > 0 {
+		return ExitForLintFailure
+	}
+
 	return nil
 }
 


Test patch:
diff --git a/cmd/api-linter/cli_test.go b/cmd/api-linter/cli_test.go
index 1efea5c..7b2acc1 100644
--- a/cmd/api-linter/cli_test.go
+++ b/cmd/api-linter/cli_test.go
@@ -34,6 +34,17 @@ func TestNewCli(t *testing.T) {
 				ProtoFiles:       []string{"a.proto", "b.proto"},
 			},
 		},
+		{
+			name: "ExitStatusOnLintFailure",
+			inputArgs: []string{
+				"--set-exit-status",
+			},
+			wantCli: &cli{
+				ExitStatusOnLintFailure: true,
+				ProtoImportPaths:        []string{"."},
+				ProtoFiles:              []string{},
+			},
+		},
 	}
 	for _, test := range tests {
 		t.Run(test.name, func(t *testing.T) {
diff --git a/cmd/api-linter/integration_test.go b/cmd/api-linter/integration_test.go
index ae98a94..785b67a 100644
--- a/cmd/api-linter/integration_test.go
+++ b/cmd/api-linter/integration_test.go
@@ -15,6 +15,7 @@
 package main
 
 import (
+	"errors"
 	"fmt"
 	"io/ioutil"
 	"os"
@@ -142,7 +143,50 @@ internal/testdata/build_errors.proto:13:1: syntax error: unexpected '}', expecti
 	}
 }
 
+func TestExitStatusForLintFailure(t *testing.T) {
+	for _, test := range testCases {
+		// checks lint failure = true when lint problems found
+		t.Run(test.testName+"ReturnsFailure", func(t *testing.T) {
+			proto := test.proto
+			lintFailureStatus, result := runLinterWithFailureStatus(t, proto, "", []string{"--set-exit-status"})
+			expected := result != ""
+			if lintFailureStatus != expected {
+				t.Fatalf("Expected: %v Actual: %v", expected, lintFailureStatus)
+			}
+		})
+
+		// checks lint failure = false when no problems found
+		t.Run(test.testName+"ReturnsNoFailure", func(t *testing.T) {
+			disableInline := fmt.Sprintf("(-- api-linter: %s=disabled --)", test.rule)
+			proto := strings.Replace(test.proto, "disable-me-here", disableInline, -1)
+			lintFailureStatus, result := runLinterWithFailureStatus(t, proto, "", []string{"--set-exit-status"})
+			expected := result != ""
+			if lintFailureStatus != expected {
+				t.Fatalf("Expected: %v Actual: %v", expected, lintFailureStatus)
+			}
+		})
+	}
+
+	// checks lint failure = false when lint problems found but --set-exit-status not set
+	for _, test := range testCases {
+		t.Run(test.testName, func(t *testing.T) {
+			proto := test.proto
+			lintFailureStatus, result := runLinterWithFailureStatus(t, proto, "", []string{})
+			expected := result == ""
+			if lintFailureStatus != expected {
+				t.Fatalf("Expected: %v Actual: %v", expected, lintFailureStatus)
+			}
+		})
+
+	}
+}
+
 func runLinter(t *testing.T, protoContent, configContent string) string {
+	_, result := runLinterWithFailureStatus(t, protoContent, configContent, []string{})
+	return result
+}
+
+func runLinterWithFailureStatus(t *testing.T, protoContent, configContent string, appendArgs []string) (bool, string) {
 	tempDir, err := ioutil.TempDir("", "test")
 	if err != nil {
 		t.Fatal(err)
@@ -175,16 +219,18 @@ func runLinter(t *testing.T, protoContent, configContent string) string {
 		t.Fatal(err)
 	}
 	args = append(args, protoFileName)
+	args = append(args, appendArgs...)
 
-	if err := runCLI(args); err != nil {
-		t.Fatal(err)
+	lintErr := runCLI(args)
+	if lintErr != nil && !errors.Is(lintErr, ExitForLintFailure) {
+		t.Fatal(lintErr)
 	}
 
 	out, err := ioutil.ReadFile(outPath)
 	if err != nil {
 		t.Fatal(err)
 	}
-	return string(out)
+	return errors.Is(lintErr, ExitForLintFailure), string(out)
 }
 
 func writeFile(path, content string) error {