Repository: googleapis/api-linter
Pull request #1151 (2023-05-12 05:11:26)

feat(AIP-123): verify resource patterns alternate
Linter to verify the folowing from AIP-122:

Resource name components should usually alternate between collection identifiers (example: publishers, books, users) and resource IDs (example: 123, les-miserables, vhugo1802).

fixes feat(AIP-122): enforce resource names as alternating collection and identifiers. #1144

toumorokoshi: fyi I moved this to AIP-123 since `pattern` is dictated in the AIP-123, and it looks like other pattern verification is there.

Patch:
diff --git a/docs/rules/0123/resource-name-components-alternate.md b/docs/rules/0123/resource-name-components-alternate.md
new file mode 100644
index 0000000..4bd5dcb
--- /dev/null
+++ b/docs/rules/0123/resource-name-components-alternate.md
@@ -0,0 +1,72 @@
+---
+rule:
+  aip: 123
+  name: [core, '0123', resource-name-components-alternate]
+  summary: Resource name components should alternate between collection and
+  identifiers.
+permalink: /123/resource-name-components-alternate
+redirect_from:
+  - /0123/resource-name-components-alternate
+---
+
+# Resource name components alternate
+
+This rule enforces that messages that have a `google.api.resource` annotation
+have `pattern` annotations that alternate between collection and identifier, as
+described in [AIP-123][].
+
+## Details
+
+This rule scans messages with a `google.api.resource` annotation, and validates
+that each `pattern` alternated between collection and identifiers.
+
+## Examples
+
+**Incorrect** code for this rule:
+
+```proto
+// Incorrect.
+message Book {
+  option (google.api.resource) = {
+    type: "library.googleapis.com/Book"
+    // two collections next to each other.
+    pattern: "publishers/books/{book}"
+  };
+  string name = 1;
+}
+```
+
+**Correct** code for this rule:
+
+```proto
+// Correct.
+message Book {
+  option (google.api.resource) = {
+    type: "library.googleapis.com/Book"
+    pattern: "publishers/{publisher}/books/{book}"
+  };
+  string name = 1;
+}
+```
+
+## Disabling
+
+If you need to violate this rule, use a leading comment above the message.
+
+```proto
+// (-- api-linter: core::0123::resource-name-components-alternate=disabled
+//     aip.dev/not-precedent: We need to do this because reasons. --)
+message Book {
+  option (google.api.resource) = {
+    type: "library.googleapis.com/Book"
+    pattern: "publishers/books/{book}"
+  };
+  string name = 1;
+}
+```
+
+If you need to violate this rule for an entire file, place the comment at the
+top of the file.
+
+[aip-123]: http://aip.dev/123
+[aip.dev/not-precedent]: https://aip.dev/not-precedent
diff --git a/rules/aip0123/aip0123.go b/rules/aip0123/aip0123.go
index 5588a8b..bd1ef6f 100644
--- a/rules/aip0123/aip0123.go
+++ b/rules/aip0123/aip0123.go
@@ -33,6 +33,7 @@ func AddRules(r lint.RuleRegistry) error {
 		123,
 		duplicateResource,
 		resourceAnnotation,
+		resourceNameComponentsAlternate,
 		resourceNameField,
 		resourcePattern,
 		resourcePlural,
diff --git a/rules/aip0123/resource_name_components_alternate.go b/rules/aip0123/resource_name_components_alternate.go
new file mode 100644
index 0000000..274a5f8
--- /dev/null
+++ b/rules/aip0123/resource_name_components_alternate.go
@@ -0,0 +1,56 @@
+// Copyright 2023 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 aip0123
+
+import (
+	"fmt"
+	"regexp"
+	"strings"
+
+	"github.com/googleapis/api-linter/lint"
+	"github.com/googleapis/api-linter/locations"
+	"github.com/googleapis/api-linter/rules/internal/utils"
+	"github.com/jhump/protoreflect/desc"
+)
+
+var identifierRegexp = regexp.MustCompile("^{[a-z][_a-z0-9]*[a-z0-9]}$")
+
+var resourceNameComponentsAlternate = &lint.MessageRule{
+	Name:   lint.NewRuleName(123, "resource-name-components-alternate"),
+	OnlyIf: utils.IsResource,
+	LintMessage: func(m *desc.MessageDescriptor) []lint.Problem {
+		var problems []lint.Problem
+		resource := utils.GetResource(m)
+		for _, p := range resource.GetPattern() {
+			components := strings.Split(p, "/")
+			for i, c := range components {
+				identifierExpected := i%2 == 1
+				if identifierExpected != isIdentifier(c) {
+					problems = append(problems, lint.Problem{
+						Message:    fmt.Sprintf("Resource pattern %q must alternate between collection and identifier. %q is not an identifier", p, c),
+						Descriptor: m,
+						Location:   locations.MessageResource(m),
+					})
+					break
+				}
+			}
+		}
+		return problems
+	},
+}
+
+func isIdentifier(s string) bool {
+	return identifierRegexp.MatchString(s)
+}


Test patch:
diff --git a/rules/aip0123/resource_name_components_alternate_test.go b/rules/aip0123/resource_name_components_alternate_test.go
new file mode 100644
index 0000000..afa6bcc
--- /dev/null
+++ b/rules/aip0123/resource_name_components_alternate_test.go
@@ -0,0 +1,51 @@
+// Copyright 2023 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 aip0123
+
+import (
+	"testing"
+
+	"github.com/googleapis/api-linter/rules/internal/testutils"
+)
+
+func TestResourceNameComponentsAlternate(t *testing.T) {
+	for _, test := range []struct {
+		name     string
+		Pattern  string
+		problems testutils.Problems
+	}{
+		{"Valid", "author/{author}/books/{book}", testutils.Problems{}},
+		{"ValidSingleton", "user/{user}/config", testutils.Problems{}},
+		{"InvalidDoubleCollection", "author/books/{book}", testutils.Problems{{Message: "must alternate"}}},
+		{"InvalidDoubleIdentifier", "books/{author}/{book}", testutils.Problems{{Message: "must alternate"}}},
+	} {
+		t.Run(test.name, func(t *testing.T) {
+			f := testutils.ParseProto3Tmpl(t, `
+			import "google/api/resource.proto";
+			message Book {
+				option (google.api.resource) = {
+					type: "library.googleapis.com/Book"
+					pattern: "{{ .Pattern }}"
+				};
+				string name = 1;
+			}
+		`, test)
+			m := f.GetMessageTypes()[0]
+			if diff := test.problems.SetDescriptor(m).Diff(resourceNameComponentsAlternate.Lint(f)); diff != "" {
+				t.Errorf(diff)
+			}
+		})
+	}
+}