Repository: googleapis/api-linter
Pull request #351 (2019-11-15 21:38:38)

[AIP-216] Add a rule for nesting states.


Patch:
diff --git a/docs/rules/0216/nesting.md b/docs/rules/0216/nesting.md
new file mode 100644
index 0000000..0314f51
--- /dev/null
+++ b/docs/rules/0216/nesting.md
@@ -0,0 +1,71 @@
+---
+rule:
+  aip: 216
+  name: [core, '0216', nesting]
+  summary: Lifecycle state enums should be nested within the resource.
+permalink: /216/nesting
+redirect_from:
+  - /0216/nesting
+---
+
+# States
+
+This rule enforces that all lifecycle state enums are nested within their
+resource, as recommended in [AIP-216][].
+
+## Details
+
+This rule iterates over enumerations and looks for enums with a name of
+`FooState` where a corresponding `Foo` message exists in the same file. If it
+finds such a case, it recommends that the enum be nested within the message.
+
+## Examples
+
+**Incorrect** code for this rule:
+
+```proto
+// Incorrect.
+message Book {
+  BookState book_state = 1;
+}
+
+// Should be nested under `Book`.
+enum BookState {
+  BOOK_STATE_UNSPECIFIED = 0;
+}
+```
+
+**Correct** code for this rule:
+
+```proto
+// Correct.
+message Book {
+  enum State {
+    STATE_UNSPECIFIED = 0;
+  }
+  State state = 1;
+}
+```
+
+## Disabling
+
+If you need to violate this rule, use a leading comment above the enum.
+Remember to also include an [aip.dev/not-precedent][] comment explaining why.
+
+```proto
+message Book {
+  BookState book_state = 1;
+}
+
+// (-- api-linter: core::0216::synonyms=disabled
+//     aip.dev/not-precedent: We need to do this because reasons. --)
+enum BookState {
+  BOOK_STATE_UNSPECIFIED = 0;
+}
+```
+
+If you need to violate this rule for an entire file, place the comment at the
+top of the file.
+
+[aip-216]: https://aip.dev/216
+[aip.dev/not-precedent]: https://aip.dev/not-precedent
diff --git a/rules/aip0216/aip0216.go b/rules/aip0216/aip0216.go
index 80194f0..3ad24f1 100644
--- a/rules/aip0216/aip0216.go
+++ b/rules/aip0216/aip0216.go
@@ -22,6 +22,7 @@ import "github.com/googleapis/api-linter/lint"
 func AddRules(r lint.RuleRegistry) error {
 	return r.Register(
 		216,
+		nesting,
 		synonyms,
 	)
 }
diff --git a/rules/aip0216/nesting.go b/rules/aip0216/nesting.go
new file mode 100644
index 0000000..a3e3ee8
--- /dev/null
+++ b/rules/aip0216/nesting.go
@@ -0,0 +1,49 @@
+// Copyright 2019 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 aip0216
+
+import (
+	"fmt"
+	"strings"
+
+	"github.com/googleapis/api-linter/lint"
+	"github.com/jhump/protoreflect/desc"
+)
+
+var nesting = &lint.EnumRule{
+	Name: lint.NewRuleName(216, "nesting"),
+	OnlyIf: func(e *desc.EnumDescriptor) bool {
+		return strings.HasSuffix(e.GetName(), "State") && e.GetName() != "State"
+	},
+	LintEnum: func(e *desc.EnumDescriptor) []lint.Problem {
+		messageName := strings.TrimSuffix(e.GetName(), "State")
+		fqMessageName := messageName
+		file := e.GetFile()
+		if pkg := file.GetPackage(); pkg != "" {
+			fqMessageName = pkg + "." + messageName
+		}
+		if file.FindMessage(fqMessageName) != nil {
+			return []lint.Problem{{
+				Message: fmt.Sprintf(
+					"Nest %q within %q, and name it `State`.",
+					e.GetName(),
+					messageName,
+				),
+				Descriptor: e,
+			}}
+		}
+		return nil
+	},
+}


Test patch:
diff --git a/rules/aip0216/nesting_test.go b/rules/aip0216/nesting_test.go
new file mode 100644
index 0000000..ac0f3f2
--- /dev/null
+++ b/rules/aip0216/nesting_test.go
@@ -0,0 +1,64 @@
+// Copyright 2019 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 aip0216
+
+import (
+	"testing"
+
+	"github.com/googleapis/api-linter/rules/internal/testutils"
+)
+
+func TestNesting(t *testing.T) {
+	t.Run("Nested", func(t *testing.T) {
+		f := testutils.ParseProto3String(t, `
+			message Foo {
+				enum State {
+					STATE_UNSPECIFIED = 0;
+				}
+			}
+		`)
+		if diff := (testutils.Problems{}).Diff(nesting.Lint(f)); diff != "" {
+			t.Errorf(diff)
+		}
+	})
+	t.Run("NotNested", func(t *testing.T) {
+		tests := []struct {
+			name        string
+			MessageName string
+			EnumName    string
+			PackageStmt string
+			problems    testutils.Problems
+		}{
+			{"ShouldNest", "Foo", "FooState", "package test;", testutils.Problems{{Message: "Nest"}}},
+			{"ShouldNestNoPkg", "Foo", "FooState", "", testutils.Problems{{Message: "Nest"}}},
+			{"ValidNoFoo", "Bar", "FooState", "package test;", testutils.Problems{}},
+		}
+		for _, test := range tests {
+			t.Run(test.name, func(t *testing.T) {
+				f := testutils.ParseProto3Tmpl(t, `
+					{{.PackageStmt}}
+					message {{.MessageName}} {}
+					enum {{.EnumName}} {
+						UNSPECIFIED = 0;
+					}
+				`, test)
+				e := f.GetEnumTypes()[0]
+				if diff := test.problems.SetDescriptor(e).Diff(nesting.Lint(f)); diff != "" {
+					t.Errorf(diff)
+				}
+			})
+		}
+	})
+}