Repository: googleapis/api-linter
Pull request #434 (2019-12-06 21:21:13)

[AIP-133] Enforce a consistent method signature.
Uses #431 as a base.


Patch:
diff --git a/docs/rules/0133/method-signature.md b/docs/rules/0133/method-signature.md
new file mode 100644
index 0000000..5c6b5fe
--- /dev/null
+++ b/docs/rules/0133/method-signature.md
@@ -0,0 +1,84 @@
+---
+rule:
+  aip: 133
+  name: [core, '0133', method-signature]
+  summary: |
+    Create RPCs should annotate an appropriate method signature.
+permalink: /133/method-signature
+redirect_from:
+  - /0133/method-signature
+---
+
+# Create methods: Method signature
+
+This rule enforces that all `Create` standard methods have a
+`google.api.method_signature` annotation with an appropirate value, as mandated
+in [AIP-133][].
+
+## Details
+
+This rule looks at any method beginning with `Create`, and complains if the
+`google.api.method_signature` annotation is missing, or if it is set to an
+incorrect value. Additional method signatures, if present, are ignored.
+
+The correct value is `"parent,{resource},{resource}_id"` if the `{resource}_id`
+field exists, and `"parent,{resource}"` otherwise.
+
+## Examples
+
+**Incorrect** code for this rule:
+
+```proto
+// Incorrect.
+rpc CreateBook(CreateBookRequest) returns (Book) {
+  // A google.api.method_signature annotation should be present.
+}
+```
+
+```proto
+// Incorrect.
+rpc CreateBook(CreateBookRequest) returns (Book) {
+  // Should be "parent,book" or "parent,book,book_id", depending on whether
+  // a "book_id" field exists.
+  option (google.api.method_signature) = "publisher,book";
+}
+```
+
+**Correct** code for this rule:
+
+If the `book_id` field does not exist:
+
+```proto
+// Correct.
+rpc CreateBook(CreateBookRequest) returns (Book) {
+  option (google.api.method_signature) = "parent,book";
+}
+```
+
+If the `book_id` field exists:
+
+```proto
+// Correct.
+rpc CreateBook(CreateBookRequest) returns (Book) {
+  option (google.api.method_signature) = "parent,book,book_id";
+}
+```
+
+## Disabling
+
+If you need to violate this rule, use a leading comment above the method.
+Remember to also include an [aip.dev/not-precedent][] comment explaining why.
+
+```proto
+// (-- api-linter: core::0133::method-signature=disabled
+//     aip.dev/not-precedent: We need to do this because reasons. --)
+rpc CreateBook(CreateBookRequest) returns (Book) {
+  option (google.api.method_signature) = "publisher,book";
+}
+```
+
+If you need to violate this rule for an entire file, place the comment at the
+top of the file.
+
+[aip-133]: https://aip.dev/133
+[aip.dev/not-precedent]: https://aip.dev/not-precedent
diff --git a/rules/aip0133/aip0133.go b/rules/aip0133/aip0133.go
index d62459f..dd2f769 100644
--- a/rules/aip0133/aip0133.go
+++ b/rules/aip0133/aip0133.go
@@ -32,6 +32,7 @@ func AddRules(r lint.RuleRegistry) error {
 		httpURIField,
 		httpMethod,
 		inputName,
+		methodSignature,
 		outputName,
 		parentField,
 		requestParentBehavior,
diff --git a/rules/aip0133/method_signature.go b/rules/aip0133/method_signature.go
new file mode 100644
index 0000000..b866747
--- /dev/null
+++ b/rules/aip0133/method_signature.go
@@ -0,0 +1,71 @@
+// 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 aip0133
+
+import (
+	"fmt"
+	"reflect"
+	"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"
+	"github.com/stoewer/go-strcase"
+)
+
+var methodSignature = &lint.MethodRule{
+	Name:   lint.NewRuleName(133, "method-signature"),
+	OnlyIf: isCreateMethod,
+	LintMethod: func(m *desc.MethodDescriptor) []lint.Problem {
+		signatures := utils.GetMethodSignatures(m)
+
+		// Determine what signature we want. The {resource}_id is desired
+		// if and only if the field exists on the request.
+		resourceField := strcase.SnakeCase(getResourceMsgName(m))
+		want := []string{"parent", resourceField}
+		if idField := resourceField + "_id"; m.GetInputType().FindFieldByName(idField) != nil {
+			want = append(want, idField)
+		}
+
+		// Check if the signature is missing.
+		if len(signatures) == 0 {
+			return []lint.Problem{{
+				Message: fmt.Sprintf(
+					"Create methods should include `(google.api.method_signature) = %q`",
+					strings.Join(want, ","),
+				),
+				Descriptor: m,
+			}}
+		}
+
+		// Check if the signature is wrong.
+		if !reflect.DeepEqual(signatures[0], want) {
+			return []lint.Problem{{
+				Message: fmt.Sprintf(
+					"The method signature for Create methods should be %q.",
+					strings.Join(want, ","),
+				),
+				Suggestion: fmt.Sprintf(
+					"option (google.api.method_signature) = %q;",
+					strings.Join(want, ","),
+				),
+				Descriptor: m,
+				Location:   locations.MethodSignature(m, 0),
+			}}
+		}
+		return nil
+	},
+}


Test patch:
diff --git a/rules/aip0133/method_signature_test.go b/rules/aip0133/method_signature_test.go
new file mode 100644
index 0000000..607112d
--- /dev/null
+++ b/rules/aip0133/method_signature_test.go
@@ -0,0 +1,85 @@
+// 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 aip0133
+
+import (
+	"testing"
+
+	"github.com/googleapis/api-linter/rules/internal/testutils"
+)
+
+func TestMethodSignature(t *testing.T) {
+	for _, test := range []struct {
+		name       string
+		MethodName string
+		Signature  string
+		IDField    string
+		problems   testutils.Problems
+	}{
+		{"ValidNoID", "CreateBook", `option (google.api.method_signature) = "parent,book";`, "", testutils.Problems{}},
+		{"ValidID", "CreateBook", `option (google.api.method_signature) = "parent,book,book_id";`, "string book_id = 3;", testutils.Problems{}},
+		{"MissingNoID", "CreateBook", "", "", testutils.Problems{{Message: `(google.api.method_signature) = "parent,book"`}}},
+		{
+			"MissingID",
+			"CreateBook",
+			"",
+			"string book_id = 3;",
+			testutils.Problems{{Message: `(google.api.method_signature) = "parent,book,book_id"`}},
+		},
+		{
+			"Wrong",
+			"CreateBook",
+			`option (google.api.method_signature) = "publisher,book";`,
+			"",
+			testutils.Problems{{Suggestion: `option (google.api.method_signature) = "parent,book";`}},
+		},
+		{
+			"WrongIDMissing",
+			"CreateBook",
+			`option (google.api.method_signature) = "parent,book";`,
+			"string book_id = 3;",
+			testutils.Problems{{Suggestion: `option (google.api.method_signature) = "parent,book,book_id";`}},
+		},
+		{
+			"WrongIDPresent",
+			"CreateBook",
+			`option (google.api.method_signature) = "parent,book,book_id";`,
+			"",
+			testutils.Problems{{Suggestion: `option (google.api.method_signature) = "parent,book";`}},
+		},
+		{"Irrelevant", "WriteBook", "", "", testutils.Problems{}},
+	} {
+		t.Run(test.name, func(t *testing.T) {
+			f := testutils.ParseProto3Tmpl(t, `
+				import "google/api/client.proto";
+				service Library {
+					rpc {{.MethodName}}({{.MethodName}}Request) returns (Book) {
+						{{.Signature}}
+					}
+				}
+				message {{.MethodName}}Request {
+					string parent = 1;
+					Book book = 2;
+					{{.IDField}}
+				}
+				message Book {}
+			`, test)
+			m := f.GetServices()[0].GetMethods()[0]
+			if diff := test.problems.SetDescriptor(m).Diff(methodSignature.Lint(f)); diff != "" {
+				t.Errorf(diff)
+			}
+		})
+	}
+}