Repository: googleapis/api-linter
Pull request #497 (2020-02-18 00:43:39)

[AIP-158] Response's first field should be repeated.
Issue #490 

For all messages that:
- end in Response
- Contain a next_page_token field.

Throw a linter warning if: 
The first field in the message (by both position and field number) is not repeated


Dos-Ph: @lukesneeringer @jgeewax @mingzhi Hi, I wonder if there's anything else that you think I missed on this PR?
lukesneeringer: In the interest of getting this in, I made the needed fixes. :-)

Patch:
diff --git a/docs/rules/0158/response-repeated-first-field.md b/docs/rules/0158/response-repeated-first-field.md
new file mode 100644
index 0000000..2abe852
--- /dev/null
+++ b/docs/rules/0158/response-repeated-first-field.md
@@ -0,0 +1,65 @@
+---
+rule:
+  aip: 158
+  name: [core, '0158', response-repeated-first-field]
+  summary: |
+    First field (by both position and field number) of Paginated RPCs' response
+    should be repeated.
+permalink: /158/response-repeated-first-field
+redirect_from:
+  - /0158/response-repeated-first-field
+---
+
+# Paginated methods: Page token field
+
+This rule enforces that all `List` and `Search` methods have a repeatable field
+as a first field in the response message, as mandated in [AIP-158][].
+
+## Details
+
+This rule looks at any message matching `List*Response` or `Search*Response`
+that has `next_page_token` field and complains if the first field (by both
+position and field number) is not repeated.
+
+## Examples
+
+**Incorrect** code for this rule:
+
+```proto
+// Incorrect.
+message ListBooksResponse {
+  Book books = 1;  // Field should be repeated.
+  string next_page_token = 2;
+}
+```
+
+**Correct** code for this rule:
+
+```proto
+// Correct.
+message ListBooksResponse {
+  repeated Book books = 1;
+  string next_page_token = 2;
+}
+```
+
+## Disabling
+
+If you need to violate this rule, use a leading comment above the message or
+above the field. Remember to also include an [aip.dev/not-precedent][] comment
+explaining why.
+
+```proto
+// (-- api-linter: core::0158::response-repeated-first-field
+//     aip.dev/not-precedent: We need to do this because reasons. --)
+message ListBooksResponse {
+    Book books = 1;
+    string next_page_token = 2;
+}
+```
+
+If you need to violate this rule for an entire file, place the comment at the
+top of the file.
+
+[aip-158]: https://aip.dev/158
+[aip.dev/not-precedent]: https://aip.dev/not-precedent
diff --git a/rules/aip0158/aip0158.go b/rules/aip0158/aip0158.go
index d006cc4..121c369 100644
--- a/rules/aip0158/aip0158.go
+++ b/rules/aip0158/aip0158.go
@@ -29,6 +29,7 @@ func AddRules(r lint.RuleRegistry) error {
 		requestPaginationPageSize,
 		requestPaginationPageToken,
 		responsePaginationNextPageToken,
+		responseRepeatedFirstField,
 		responsePluralFirstField,
 	)
 }
diff --git a/rules/aip0158/response_repeated_first_field.go b/rules/aip0158/response_repeated_first_field.go
new file mode 100644
index 0000000..967cd01
--- /dev/null
+++ b/rules/aip0158/response_repeated_first_field.go
@@ -0,0 +1,47 @@
+// Copyright 2020 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 aip0158
+
+import (
+	"github.com/googleapis/api-linter/lint"
+	"github.com/jhump/protoreflect/desc"
+)
+
+var responseRepeatedFirstField = &lint.MessageRule{
+	Name: lint.NewRuleName(158, "response-repeated-first-field"),
+	OnlyIf: func(m *desc.MessageDescriptor) bool {
+		return isPaginatedResponseMessage(m) && len(m.GetFields()) > 0
+	},
+	LintMessage: func(m *desc.MessageDescriptor) []lint.Problem {
+		// Sanity check: Is the first field (positionally) and the field with
+		// an ID of 1 actually the same field?
+		if m.GetFields()[0] != m.FindFieldByNumber(1) {
+			return []lint.Problem{{
+				Message:    "The first field of paginated RPCs must have a protobuf ID of 1.",
+				Descriptor: m.GetFields()[0],
+			}}
+		}
+
+		// Make sure the field is repeated.
+		if !m.GetFields()[0].IsRepeated() {
+			return []lint.Problem{{
+				Message:    "The first field of a paginated response should be repeated.",
+				Descriptor: m.GetFields()[0],
+			}}
+		}
+
+		return nil
+	},
+}


Test patch:
diff --git a/rules/aip0158/response_repeated_first_field_test.go b/rules/aip0158/response_repeated_first_field_test.go
new file mode 100644
index 0000000..1b23728
--- /dev/null
+++ b/rules/aip0158/response_repeated_first_field_test.go
@@ -0,0 +1,61 @@
+// Copyright 2020 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 aip0158
+
+import (
+	"testing"
+
+	"github.com/googleapis/api-linter/rules/internal/testutils"
+)
+
+func TestResponseRepeatedFirstField(t *testing.T) {
+	tests := []struct {
+		testName    string
+		FirstField  string
+		SecondField string
+		problems    testutils.Problems
+	}{
+		{"Valid", "repeated Book books = 1;", "string next_page_token = 2;", nil},
+		{"SkippedZeroFields", "", "", nil},
+		{"InvalidFirstFieldsNoMatch", "string next_page_token = 2;", "repeated Book books = 1;", testutils.Problems{{Message: "protobuf ID"}}},
+		{"InvalidNotRepeated", "Book book = 1;", "string next_page_token = 2;", testutils.Problems{{Message: "repeated"}}},
+	}
+	for _, test := range tests {
+		t.Run(test.testName, func(t *testing.T) {
+			// Create the proto message.
+			f := testutils.ParseProto3Tmpl(t, `
+				message Book {
+					string name = 1;
+				}
+				message ListBooksResponse {
+					{{.FirstField}}
+					{{.SecondField}}
+				}
+			`, test)
+
+			// Determine the descriptor that a failing test will attach to.
+			if m := f.GetMessageTypes()[1]; len(m.GetFields()) > 0 {
+				test.problems.SetDescriptor(m.GetFields()[0])
+			}
+
+			// Run the lint rule and establish we get the correct problems.
+			problems := responseRepeatedFirstField.Lint(f)
+			if diff := test.problems.Diff(problems); diff != "" {
+				t.Errorf(diff)
+			}
+		})
+	}
+
+}