Repository: googleapis/api-linter
Pull request #441 (2019-12-11 00:30:03)

[Refactor] Split 0135::request-name-field into two rules.


Patch:
diff --git a/docs/rules/0135/request-name-required.md b/docs/rules/0135/request-name-required.md
new file mode 100644
index 0000000..ccbebb8
--- /dev/null
+++ b/docs/rules/0135/request-name-required.md
@@ -0,0 +1,59 @@
+---
+rule:
+  aip: 135
+  name: [core, '0135', request-name-required]
+  summary: Delete RPCs must have a `name` field in the request.
+permalink: /135/request-name-required
+redirect_from:
+  - /0135/request-name-required
+---
+
+# Delete methods: Name field
+
+This rule enforces that all `Delete` standard methods have a `string name`
+field in the request message, as mandated in [AIP-135][].
+
+## Details
+
+This rule looks at any message matching `Delete*Request` and complains if
+the `name` field is missing.
+
+## Examples
+
+**Incorrect** code for this rule:
+
+```proto
+// Incorrect.
+message DeleteBookRequest {
+  // Field name should be `name`.
+  string book = 1;
+}
+```
+
+**Correct** code for this rule:
+
+```proto
+// Correct.
+message DeleteBookRequest {
+  string name = 1;
+}
+```
+
+## Disabling
+
+If you need to violate this rule, use a leading comment above the message.
+Remember to also include an [aip.dev/not-precedent][] comment explaining why.
+
+```proto
+// (-- api-linter: core::0135::request-name-required=disabled
+//     aip.dev/not-precedent: We need to do this because reasons. --)
+message DeleteBookRequest {
+  string book = 1;
+}
+```
+
+If you need to violate this rule for an entire file, place the comment at the
+top of the file.
+
+[aip-135]: https://aip.dev/135
+[aip.dev/not-precedent]: https://aip.dev/not-precedent
diff --git a/rules/aip0135/aip0135.go b/rules/aip0135/aip0135.go
index eb180e8..b515f9d 100644
--- a/rules/aip0135/aip0135.go
+++ b/rules/aip0135/aip0135.go
@@ -34,8 +34,9 @@ func AddRules(r lint.RuleRegistry) error {
 		responseMessageName,
 		requestMessageName,
 		requestNameBehavior,
+		requestNameField,
 		requestNameReference,
-		standardFields,
+		requestNameRequired,
 		unknownFields,
 	)
 }
diff --git a/rules/aip0135/request_name_field.go b/rules/aip0135/request_name_field.go
index 6028755..6524429 100644
--- a/rules/aip0135/request_name_field.go
+++ b/rules/aip0135/request_name_field.go
@@ -15,35 +15,24 @@
 package aip0135
 
 import (
-	"fmt"
-
 	"github.com/googleapis/api-linter/lint"
 	"github.com/googleapis/api-linter/locations"
 	"github.com/jhump/protoreflect/desc"
 	"github.com/jhump/protoreflect/desc/builder"
 )
 
-// The Delete standard method should only have expected fields.
-var standardFields = &lint.MessageRule{
-	Name:   lint.NewRuleName(135, "request-name-field"),
-	OnlyIf: isDeleteRequestMessage,
-	LintMessage: func(m *desc.MessageDescriptor) []lint.Problem {
-		// Rule check: Establish that a name field is present.
-		name := m.FindFieldByName("name")
-		if name == nil {
-			return []lint.Problem{{
-				Message:    fmt.Sprintf("Method %q has no `name` field", m.GetName()),
-				Descriptor: m,
-			}}
-		}
-
-		// Rule check: Ensure that the name field is the correct type.
-		if name.GetType() != builder.FieldTypeString().GetType() {
+var requestNameField = &lint.FieldRule{
+	Name: lint.NewRuleName(135, "request-name-field"),
+	OnlyIf: func(f *desc.FieldDescriptor) bool {
+		return isDeleteRequestMessage(f.GetOwner()) && f.GetName() == "name"
+	},
+	LintField: func(f *desc.FieldDescriptor) []lint.Problem {
+		if f.GetType() != builder.FieldTypeString().GetType() {
 			return []lint.Problem{{
 				Message:    "`name` field on Get RPCs should be a string",
 				Suggestion: "string",
-				Descriptor: name,
-				Location:   locations.FieldType(name),
+				Descriptor: f,
+				Location:   locations.FieldType(f),
 			}}
 		}
 
diff --git a/rules/aip0135/request_name_required.go b/rules/aip0135/request_name_required.go
new file mode 100644
index 0000000..551cc2b
--- /dev/null
+++ b/rules/aip0135/request_name_required.go
@@ -0,0 +1,36 @@
+// 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 aip0135
+
+import (
+	"fmt"
+
+	"github.com/googleapis/api-linter/lint"
+	"github.com/jhump/protoreflect/desc"
+)
+
+var requestNameRequired = &lint.MessageRule{
+	Name:   lint.NewRuleName(135, "request-name-required"),
+	OnlyIf: isDeleteRequestMessage,
+	LintMessage: func(m *desc.MessageDescriptor) []lint.Problem {
+		if m.FindFieldByName("name") == nil {
+			return []lint.Problem{{
+				Message:    fmt.Sprintf("Method %q has no `name` field", m.GetName()),
+				Descriptor: m,
+			}}
+		}
+		return nil
+	},
+}


Test patch:
diff --git a/rules/aip0135/request_name_field_test.go b/rules/aip0135/request_name_field_test.go
index 06d1de0..92df08d 100644
--- a/rules/aip0135/request_name_field_test.go
+++ b/rules/aip0135/request_name_field_test.go
@@ -18,59 +18,34 @@ import (
 	"testing"
 
 	"github.com/googleapis/api-linter/rules/internal/testutils"
-	"github.com/jhump/protoreflect/desc/builder"
 )
 
-func TestStandardFields(t *testing.T) {
-	// Set up the testing permutations.
+func TestRequestNameField(t *testing.T) {
 	tests := []struct {
-		testName      string
-		messageName   string
-		nameFieldName string
-		problems      testutils.Problems
+		name        string
+		MessageName string
+		FieldType   string
+		FieldName   string
+		problems    testutils.Problems
 	}{
-		{"Valid", "DeleteBookRequest", "name", testutils.Problems{}},
-		{"InvalidName", "DeleteBookRequest", "id", testutils.Problems{{Message: "name"}}},
-		{"Irrelevant", "RemoveBookRequest", "id", testutils.Problems{}},
+		{"Valid", "DeleteBookRequest", "string", "name", nil},
+		{"Invalid", "DeleteBookRequest", "bytes", "name", testutils.Problems{{Suggestion: "string"}}},
+		{"IrrelevantMessage", "RemoveBookRequest", "bytes", "name", nil},
+		{"IrrelevantField", "DeleteBookRequest", "bytes", "title", nil},
 	}
 
-	// Run each test individually.
 	for _, test := range tests {
-		t.Run(test.testName, func(t *testing.T) {
-			// Create an appropriate message descriptor.
-			message, err := builder.NewMessage(test.messageName).AddField(
-				builder.NewField(test.nameFieldName, builder.FieldTypeString()),
-			).Build()
-			if err != nil {
-				t.Fatalf("Could not build %s message.", test.messageName)
-			}
-
-			// Run the lint rule, and establish that it returns the correct problems.
-			problems := standardFields.Lint(message.GetFile())
-			if diff := test.problems.SetDescriptor(message).Diff(problems); diff != "" {
+		t.Run(test.name, func(t *testing.T) {
+			f := testutils.ParseProto3Tmpl(t, `
+				message {{.MessageName}} {
+					{{.FieldType}} {{.FieldName}} = 1;
+				}
+			`, test)
+			field := f.GetMessageTypes()[0].GetFields()[0]
+			problems := requestNameField.Lint(f)
+			if diff := test.problems.SetDescriptor(field).Diff(problems); diff != "" {
 				t.Errorf("Problems did not match: %v", diff)
 			}
 		})
 	}
 }
-
-func TestStandardFieldsInvalidType(t *testing.T) {
-	// Create an appropriate message descriptor.
-	message, err := builder.NewMessage("DeleteBookRequest").AddField(
-		builder.NewField("name", builder.FieldTypeBytes()),
-	).Build()
-	if err != nil {
-		t.Fatalf("Could not build descriptor.")
-	}
-
-	// Run the lint rule, and establish that it returns the correct
-	// number of problems.
-	wantProblems := testutils.Problems{{
-		Descriptor: message.GetFields()[0],
-		Suggestion: "string",
-	}}
-	gotProblems := standardFields.Lint(message.GetFile())
-	if diff := wantProblems.Diff(gotProblems); diff != "" {
-		t.Errorf(diff)
-	}
-}
diff --git a/rules/aip0135/request_name_required_test.go b/rules/aip0135/request_name_required_test.go
new file mode 100644
index 0000000..2d539e7
--- /dev/null
+++ b/rules/aip0135/request_name_required_test.go
@@ -0,0 +1,53 @@
+// 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 aip0135
+
+import (
+	"testing"
+
+	"github.com/googleapis/api-linter/rules/internal/testutils"
+)
+
+func TestRequestNameRequired(t *testing.T) {
+	// Set up the testing permutations.
+	tests := []struct {
+		name        string
+		MessageName string
+		FieldName   string
+		problems    testutils.Problems
+	}{
+		{"Valid", "DeleteBookRequest", "name", nil},
+		{"InvalidName", "DeleteBookRequest", "id", testutils.Problems{{Message: "name"}}},
+		{"Irrelevant", "RemoveBookRequest", "id", nil},
+	}
+
+	// Run each test individually.
+	for _, test := range tests {
+		t.Run(test.name, func(t *testing.T) {
+			f := testutils.ParseProto3Tmpl(t, `
+				message {{.MessageName}} {
+					string {{.FieldName}} = 1;
+				}
+			`, test)
+
+			// Run the lint rule, and establish that it returns the correct problems.
+			problems := requestNameRequired.Lint(f)
+			message := f.GetMessageTypes()[0]
+			if diff := test.problems.SetDescriptor(message).Diff(problems); diff != "" {
+				t.Errorf("Problems did not match: %v", diff)
+			}
+		})
+	}
+}