Repository: googleapis/api-linter
Pull request #377 (2019-11-21 22:08:14)

[AIP-191] Enforce common file layout mistakes.


Patch:
diff --git a/docs/rules/0191/file-layout.md b/docs/rules/0191/file-layout.md
new file mode 100644
index 0000000..d0c911e
--- /dev/null
+++ b/docs/rules/0191/file-layout.md
@@ -0,0 +1,99 @@
+---
+rule:
+  aip: 191
+  name: [core, '0191', file-layout]
+  summary: Proto files should follow a consistent layout.
+permalink: /191/file-layout
+redirect_from:
+  - /0191/file-layout
+---
+
+# File layout
+
+This rule attempts to enforce a consistent file layout for proto files, as
+mandated in [AIP-191][].
+
+## Details
+
+This rule checks for common file layout mistakes, but does not currently check
+the exhaustive file layout in AIP-191. This rule currently complains if:
+
+- Services appear below messages.
+- Messages appear below top-level enums.
+
+## Examples
+
+**Incorrect** code for this rule:
+
+```proto
+// Incorrect.
+// Services should appear before messages.
+message Book {
+  string name = 1;
+}
+
+service Library {
+  rpc GetBook(GetBookRequest) returns (Book) {
+    option (google.api.http) = {
+      get: "/v1/{name=publishers/*/books/*}"
+    }
+  }
+}
+
+message GetBookRequest {
+  string name = 1;
+}
+```
+
+**Correct** code for this rule:
+
+```proto
+// Correct.
+service Library {
+  rpc GetBook(GetBookRequest) returns (Book) {
+    option (google.api.http) = {
+      get: "/v1/{name=publishers/*/books/*}"
+    }
+  }
+}
+
+message Book {
+  string name = 1;
+}
+
+message GetBookRequest {
+  string name = 1;
+}
+```
+
+## Disabling
+
+If you need to violate this rule, use a comment at the top of the file.
+Remember to also include an [aip.dev/not-precedent][] comment explaining why.
+
+```proto
+// (-- api-linter: core::0191::file-layout=disabled
+//     aip.dev/not-precedent: We need to do this because reasons. --)
+syntax = "proto3";
+
+import "google/api/anotations.proto";
+
+message Book {
+  string name = 1;
+}
+
+service Library {
+  rpc GetBook(GetBookRequest) returns (Book) {
+    option (google.api.http) = {
+      get: "/v1/{name=publishers/*/books/*}"
+    }
+  }
+}
+
+message GetBookRequest {
+  string name = 1;
+}
+```
+
+[aip-191]: https://aip.dev/191
+[aip.dev/not-precedent]: https://aip.dev/not-precedent
diff --git a/docs/rules/0191/filenames.md b/docs/rules/0191/filenames.md
index 564660b..48f9cfb 100644
--- a/docs/rules/0191/filenames.md
+++ b/docs/rules/0191/filenames.md
@@ -8,7 +8,7 @@ redirect_from:
   - /0191/filenames
 ---
 
-# Proto3 syntax
+# Filenames
 
 This rule attempts to enforce reasonable filenames for proto files, as mandated
 in [AIP-191][].
@@ -29,7 +29,7 @@ This rule currently complains if the filename:
 - `v1.proto`
 - `v1beta1.proto`
 
-**Correct** code for this rule:
+**Correct** filenames for this rule:
 
 - `library.proto`
 - `library_service.proto`
diff --git a/rules/aip0191/aip0191.go b/rules/aip0191/aip0191.go
index f5d4e36..02ce033 100644
--- a/rules/aip0191/aip0191.go
+++ b/rules/aip0191/aip0191.go
@@ -28,6 +28,7 @@ func AddRules(r lint.RuleRegistry) error {
 		191,
 		csharpNamespace,
 		filename,
+		fileLayout,
 		fileOptionConsistency,
 		javaMultipleFiles,
 		javaOuterClassname,
diff --git a/rules/aip0191/file_layout.go b/rules/aip0191/file_layout.go
new file mode 100644
index 0000000..89d726a
--- /dev/null
+++ b/rules/aip0191/file_layout.go
@@ -0,0 +1,70 @@
+// 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 aip0191
+
+import (
+	"github.com/googleapis/api-linter/lint"
+	"github.com/jhump/protoreflect/desc"
+)
+
+var fileLayout = &lint.FileRule{
+	Name: lint.NewRuleName(191, "file-layout"),
+	LintFile: func(f *desc.FileDescriptor) (problems []lint.Problem) {
+		// Verify that services precede messages.
+		if len(f.GetMessageTypes()) > 0 {
+			firstMessage := f.GetMessageTypes()[0]
+			for _, service := range f.GetServices() {
+				if isAfter(firstMessage, service) {
+					problems = append(problems, lint.Problem{
+						Message:    "Services should precede all messages.",
+						Descriptor: service,
+					})
+				}
+			}
+		}
+
+		// Verify that messages precede top-level enums.
+		if len(f.GetEnumTypes()) > 0 {
+			firstEnum := f.GetEnumTypes()[0]
+			for _, message := range f.GetMessageTypes() {
+				if isBefore(message, firstEnum) {
+					problems = append(problems, lint.Problem{
+						Message:    "Messages should precede all top-level enums.",
+						Descriptor: firstEnum,
+					})
+					break // Sending this over and over would be obnoxious.
+				}
+			}
+		}
+
+		return
+	},
+}
+
+// isBefore returns true if `d` is known to precede `anchor` in the file.
+//
+// NOTE: A false value here may indicate that there is no source info at all;
+//       use `isAfter` if the goal is to know that `d` comes after `anchor`.
+func isBefore(anchor desc.Descriptor, d desc.Descriptor) bool {
+	return d.GetSourceInfo().GetSpan()[0] < anchor.GetSourceInfo().GetSpan()[0]
+}
+
+// isBefore returns true if `d` is known to follow `anchor` in the file.
+//
+// NOTE: A false value here may indicate that there is no source info at all;
+//       use `isBefore` if the goal is to know that `d` comes before `anchor`.
+func isAfter(anchor desc.Descriptor, d desc.Descriptor) bool {
+	return d.GetSourceInfo().GetSpan()[0] > anchor.GetSourceInfo().GetSpan()[0]
+}


Test patch:
diff --git a/rules/aip0191/file_layout_test.go b/rules/aip0191/file_layout_test.go
new file mode 100644
index 0000000..a54516d
--- /dev/null
+++ b/rules/aip0191/file_layout_test.go
@@ -0,0 +1,75 @@
+// 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 aip0191
+
+import (
+	"testing"
+
+	"github.com/googleapis/api-linter/rules/internal/testutils"
+	"github.com/jhump/protoreflect/desc/builder"
+)
+
+func TestFileLayout(t *testing.T) {
+	t.Run("Valid", func(t *testing.T) {
+		f := testutils.ParseProto3String(t, `
+			service Library {}
+			message Book {}
+			enum Format {
+				FORMAT_UNSPECIFIED = 0;
+			}
+		`)
+		if problems := fileLayout.Lint(f); len(problems) > 0 {
+			t.Errorf("%v", problems)
+		}
+	})
+
+	t.Run("InvalidServiceAfterMessage", func(t *testing.T) {
+		f := testutils.ParseProto3String(t, `
+			message Book {}
+			service Library {}
+		`)
+		want := testutils.Problems{{Descriptor: f.GetServices()[0]}}
+		if diff := want.Diff(fileLayout.Lint(f)); diff != "" {
+			t.Errorf(diff)
+		}
+	})
+
+	t.Run("InvalidEnumBeforeMessage", func(t *testing.T) {
+		f := testutils.ParseProto3String(t, `
+			enum Format {
+				FORMAT_UNSPECIFIED = 0;
+			}
+			message Book {}
+		`)
+		want := testutils.Problems{{Descriptor: f.GetEnumTypes()[0]}}
+		if diff := want.Diff(fileLayout.Lint(f)); diff != "" {
+			t.Errorf(diff)
+		}
+	})
+
+	t.Run("NoSourceInfo", func(t *testing.T) {
+		f, err := builder.NewFile("test.proto").AddMessage(
+			builder.NewMessage("Book"),
+		).AddService(
+			builder.NewService("Library"),
+		).Build()
+		if err != nil {
+			t.Fatalf("Failed to build proto.")
+		}
+		if problems := fileLayout.Lint(f); len(problems) > 0 {
+			t.Errorf("%v", problems)
+		}
+	})
+}