Repository: googleapis/api-linter
Pull request #457 (2019-12-20 20:33:24)

[AIP-136] Add custom method rule for the name variable.


Patch:
diff --git a/docs/rules/0136/http-name-variable.md b/docs/rules/0136/http-name-variable.md
new file mode 100644
index 0000000..71da9d6
--- /dev/null
+++ b/docs/rules/0136/http-name-variable.md
@@ -0,0 +1,80 @@
+---
+rule:
+  aip: 136
+  name: [core, '0136', http-name-variable]
+  summary:
+    Custom methods should only use `name` if the RPC noun matches the resource.
+permalink: /136/http-name-variable
+redirect_from:
+  - /0136/http-name-variable
+---
+
+# Custom methods: HTTP name variable
+
+This rule enforces that custom methods only use the `name` variable if the RPC
+noun matches the resource, as mandated in [AIP-136][].
+
+## Details
+
+This rule looks at custom methods and, if the URI contains a `name` variable,
+it ensures that the RPC name ends with the same text as the final component in
+the URI (after adjusting for case).
+
+## Examples
+
+**Incorrect** code for this rule:
+
+```proto
+// Incorrect.
+// The variable should be "book", or the RPC name should change.
+rpc WritePage(WritePageRequest) return (WritePageResponse) {
+  option (google.api.http) = {
+    post: "/v1/{name=publishers/*/books/*}:writePage"
+    body: "*"
+  };
+}
+```
+
+**Correct** code for this rule:
+
+```proto
+// Correct.
+rpc WritePage(WritePageRequest) return (WritePageResponse) {
+  option (google.api.http) = {
+    post: "/v1/{book=publishers/*/books/*}:writePage"
+    body: "*"
+  };
+}
+```
+
+```proto
+// Correct.
+rpc WriteBook(WriteBookRequest) return (WriteBookResponse) {
+  option (google.api.http) = {
+    post: "/v1/{name=publishers/*/books/*}:write"
+    body: "*"
+  };
+}
+```
+
+## 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::0136::http-name-variable=disabled
+//     aip.dev/not-precedent: We need to do this because reasons. --)
+rpc WritePage(WritePageRequest) return (WritePageResponse) {
+  option (google.api.http) = {
+    post: "/v1/{name=publishers/*/books/*}:writePage"
+    body: "*"
+  };
+}
+```
+
+If you need to violate this rule for an entire file, place the comment at the
+top of the file.
+
+[aip-136]: https://aip.dev/136
+[aip.dev/not-precedent]: https://aip.dev/not-precedent
diff --git a/rules/aip0136/aip0136.go b/rules/aip0136/aip0136.go
index 352ac4e..19e0a26 100644
--- a/rules/aip0136/aip0136.go
+++ b/rules/aip0136/aip0136.go
@@ -29,6 +29,7 @@ func AddRules(r lint.RuleRegistry) error {
 		136,
 		httpBody,
 		httpMethod,
+		httpNameVariable,
 		noPrepositions,
 		uriSuffix,
 		verbNoun,
diff --git a/rules/aip0136/http_name_variable.go b/rules/aip0136/http_name_variable.go
new file mode 100644
index 0000000..51a5f95
--- /dev/null
+++ b/rules/aip0136/http_name_variable.go
@@ -0,0 +1,55 @@
+// 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 aip0136
+
+import (
+	"strings"
+
+	pluralize "github.com/gertd/go-pluralize"
+	"github.com/googleapis/api-linter/lint"
+	"github.com/googleapis/api-linter/rules/internal/utils"
+	"github.com/jhump/protoreflect/desc"
+	"github.com/stoewer/go-strcase"
+)
+
+var httpNameVariable = &lint.MethodRule{
+	Name:   lint.NewRuleName(136, "http-name-variable"),
+	OnlyIf: isCustomMethod,
+	LintMethod: func(m *desc.MethodDescriptor) []lint.Problem {
+		p := pluralize.NewClient()
+		for _, http := range utils.GetHTTPRules(m) {
+			vars := http.GetVariables()
+
+			// If there is a "name" variable, the noun should be present
+			// in the RPC name.
+			if name, ok := vars["name"]; ok {
+				// Determine the resource.
+				name = strings.TrimSuffix(name, "/*")
+				segs := strings.Split(name, "/")
+				resource := p.Singular(segs[len(segs)-1])
+
+				// Does the RPC name end in the singular name of the resource?
+				// If not, complain.
+				if !strings.HasSuffix(strcase.SnakeCase(m.GetName()), resource) {
+					return []lint.Problem{{
+						Message:    "The name variable should only be used if the RPC noun matches the URI.",
+						Descriptor: m,
+					}}
+				}
+			}
+		}
+		return nil
+	},
+}
diff --git a/rules/aip0136/http_uri_suffix.go b/rules/aip0136/http_uri_suffix.go
index 6dc7d71..ed3cfbf 100644
--- a/rules/aip0136/http_uri_suffix.go
+++ b/rules/aip0136/http_uri_suffix.go
@@ -27,8 +27,10 @@ import (
 )
 
 var uriSuffix = &lint.MethodRule{
-	Name:   lint.NewRuleName(136, "http-uri-suffix"),
-	OnlyIf: isCustomMethod,
+	Name: lint.NewRuleName(136, "http-uri-suffix"),
+	OnlyIf: func(m *desc.MethodDescriptor) bool {
+		return isCustomMethod(m) && httpNameVariable.LintMethod(m) == nil
+	},
 	LintMethod: func(m *desc.MethodDescriptor) []lint.Problem {
 		for _, httpRule := range utils.GetHTTPRules(m) {
 			// URIs should end in a `:` character followed by the name of the method.


Test patch:
diff --git a/rules/aip0136/http_name_variable_test.go b/rules/aip0136/http_name_variable_test.go
new file mode 100644
index 0000000..9fe9ee2
--- /dev/null
+++ b/rules/aip0136/http_name_variable_test.go
@@ -0,0 +1,55 @@
+// 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 aip0136
+
+import (
+	"testing"
+
+	"github.com/googleapis/api-linter/rules/internal/testutils"
+)
+
+func TestHTTPVariables(t *testing.T) {
+	for _, test := range []struct {
+		name       string
+		MethodName string
+		URI        string
+		problems   testutils.Problems
+	}{
+		{"Valid", "WriteBook", "/v1/{name=publishers/*/books/*}:write", testutils.Problems{}},
+		{"Invalid", "WritePage", "/v1/{name=publishers/*/books/*}:writePage", testutils.Problems{{Message: "name variable"}}},
+		{"ValidBookVar", "WritePage", "/v1/{book=publishers/*/books/*}:writePage", testutils.Problems{}},
+	} {
+		t.Run(test.name, func(t *testing.T) {
+			f := testutils.ParseProto3Tmpl(t, `
+				import "google/api/annotations.proto";
+				service Library {
+					rpc {{.MethodName}}({{.MethodName}}Request)
+							returns ({{.MethodName}}Response) {
+						option (google.api.http) = {
+							post: "{{.URI}}"
+							body: "*"
+						};
+					}
+				}
+				message {{.MethodName}}Request {}
+				message {{.MethodName}}Response {}
+			`, test)
+			m := f.GetServices()[0].GetMethods()[0]
+			if diff := test.problems.SetDescriptor(m).Diff(httpNameVariable.Lint(f)); diff != "" {
+				t.Errorf(diff)
+			}
+		})
+	}
+}
diff --git a/rules/aip0136/http_uri_suffix_test.go b/rules/aip0136/http_uri_suffix_test.go
index 469d3e8..669d932 100644
--- a/rules/aip0136/http_uri_suffix_test.go
+++ b/rules/aip0136/http_uri_suffix_test.go
@@ -35,6 +35,7 @@ func TestURISuffix(t *testing.T) {
 		{"InvalidVerbNoun", "TranslateText", "/v3:translate", testutils.Problems{{Message: ":translateText"}}},
 		{"ValidOneWord", "Translate", "/v3:translate", testutils.Problems{}},
 		{"ValidStdMethod", "GetBook", "/v1/{name=publishers/*/books/*}", testutils.Problems{}},
+		{"IgnoredFailsVariables", "AddPages", "/v1/{name=publishers/*/books/*}:addPages", testutils.Problems{}},
 	}
 	for _, test := range tests {
 		t.Run(test.testName, func(t *testing.T) {