From c8deaa8d1d4690c3f86b2fecf907422c9b788403 Mon Sep 17 00:00:00 2001 From: Edgar Sipki Date: Sat, 28 Nov 2026 17:32:07 +0300 Subject: [PATCH] docs: align v1 linter (44) and breaking-changes (69) rule catalogs --- content/docs/cli/breaking-changes/index.mdx | 144 ++++-- .../docs/cli/breaking-changes/index.ru.mdx | 146 ++++-- .../docs/cli/breaking-changes/meta.ru.json | 7 + .../cli/breaking-changes/rules/enum-moved.mdx | 60 +++ .../breaking-changes/rules/enum-moved.ru.mdx | 60 +++ .../breaking-changes/rules/enum-no-delete.mdx | 283 +----------- .../rules/enum-no-delete.ru.mdx | 266 +---------- .../rules/enum-same-json-format.mdx | 58 +++ .../rules/enum-same-json-format.ru.mdx | 58 +++ .../breaking-changes/rules/enum-same-type.mdx | 60 +++ .../rules/enum-same-type.ru.mdx | 60 +++ ...m-value-no-delete-unless-name-reserved.mdx | 64 +++ ...alue-no-delete-unless-name-reserved.ru.mdx | 64 +++ ...value-no-delete-unless-number-reserved.mdx | 63 +++ ...ue-no-delete-unless-number-reserved.ru.mdx | 63 +++ .../rules/enum-value-no-delete.mdx | 294 +----------- .../rules/enum-value-no-delete.ru.mdx | 263 +---------- .../rules/enum-value-same-name.mdx | 131 +----- .../rules/enum-value-same-name.ru.mdx | 132 +----- .../rules/extension-message-no-delete.mdx | 60 +++ .../rules/extension-message-no-delete.ru.mdx | 60 +++ .../rules/extension-moved.mdx | 66 +++ .../rules/extension-moved.ru.mdx | 66 +++ .../rules/extension-no-delete.mdx | 61 +++ .../rules/extension-no-delete.ru.mdx | 61 +++ .../rules/extension-same-extendee.mdx | 67 +++ .../rules/extension-same-extendee.ru.mdx | 67 +++ .../rules/extension-same-number.mdx | 63 +++ .../rules/extension-same-number.ru.mdx | 63 +++ .../field-no-delete-unless-name-reserved.mdx | 61 +++ ...ield-no-delete-unless-name-reserved.ru.mdx | 61 +++ ...field-no-delete-unless-number-reserved.mdx | 60 +++ ...ld-no-delete-unless-number-reserved.ru.mdx | 60 +++ .../rules/field-no-delete.mdx | 64 +-- .../rules/field-no-delete.ru.mdx | 68 +-- .../rules/field-same-cardinality.mdx | 270 ++---------- .../rules/field-same-cardinality.ru.mdx | 264 ++--------- .../rules/field-same-cpp-string-type.mdx | 58 +++ .../rules/field-same-cpp-string-type.ru.mdx | 58 +++ .../rules/field-same-default.mdx | 58 +++ .../rules/field-same-default.ru.mdx | 58 +++ .../rules/field-same-java-utf8-validation.mdx | 58 +++ .../field-same-java-utf8-validation.ru.mdx | 58 +++ .../rules/field-same-json-name.mdx | 57 +++ .../rules/field-same-json-name.ru.mdx | 57 +++ .../rules/field-same-jstype.mdx | 57 +++ .../rules/field-same-jstype.ru.mdx | 57 +++ .../rules/field-same-name.mdx | 58 +++ .../rules/field-same-name.ru.mdx | 58 +++ .../rules/field-same-oneof.mdx | 67 +++ .../rules/field-same-oneof.ru.mdx | 67 +++ .../rules/field-same-type.mdx | 117 +---- .../rules/field-same-type.ru.mdx | 124 +----- .../rules/field-same-utf8-validation.mdx | 57 +++ .../rules/field-same-utf8-validation.ru.mdx | 57 +++ .../field-wire-compatible-cardinality.mdx | 58 +++ .../field-wire-compatible-cardinality.ru.mdx | 58 +++ .../rules/field-wire-compatible-type.mdx | 57 +++ .../rules/field-wire-compatible-type.ru.mdx | 57 +++ ...field-wire-json-compatible-cardinality.mdx | 68 +++ ...ld-wire-json-compatible-cardinality.ru.mdx | 68 +++ .../rules/field-wire-json-compatible-type.mdx | 58 +++ .../field-wire-json-compatible-type.ru.mdx | 58 +++ .../breaking-changes/rules/file-no-delete.mdx | 54 +++ .../rules/file-no-delete.ru.mdx | 54 +++ .../rules/file-same-cc-enable-arenas.mdx | 63 +++ .../rules/file-same-cc-enable-arenas.ru.mdx | 63 +++ .../rules/file-same-cc-generic-services.mdx | 63 +++ .../file-same-cc-generic-services.ru.mdx | 63 +++ .../rules/file-same-csharp-namespace.mdx | 63 +++ .../rules/file-same-csharp-namespace.ru.mdx | 63 +++ .../rules/file-same-go-package.mdx | 63 +++ .../rules/file-same-go-package.ru.mdx | 63 +++ .../rules/file-same-java-generic-services.mdx | 63 +++ .../file-same-java-generic-services.ru.mdx | 63 +++ .../rules/file-same-java-multiple-files.mdx | 63 +++ .../file-same-java-multiple-files.ru.mdx | 63 +++ .../rules/file-same-java-outer-classname.mdx | 63 +++ .../file-same-java-outer-classname.ru.mdx | 63 +++ .../rules/file-same-java-package.mdx | 63 +++ .../rules/file-same-java-package.ru.mdx | 63 +++ .../file-same-java-string-check-utf8.mdx | 63 +++ .../file-same-java-string-check-utf8.ru.mdx | 63 +++ .../rules/file-same-objc-class-prefix.mdx | 63 +++ .../rules/file-same-objc-class-prefix.ru.mdx | 63 +++ .../rules/file-same-optimize-for.mdx | 63 +++ .../rules/file-same-optimize-for.ru.mdx | 63 +++ .../rules/file-same-package.mdx | 57 +++ .../rules/file-same-package.ru.mdx | 57 +++ .../rules/file-same-php-class-prefix.mdx | 63 +++ .../rules/file-same-php-class-prefix.ru.mdx | 63 +++ .../file-same-php-metadata-namespace.mdx | 63 +++ .../file-same-php-metadata-namespace.ru.mdx | 63 +++ .../rules/file-same-php-namespace.mdx | 63 +++ .../rules/file-same-php-namespace.ru.mdx | 63 +++ .../rules/file-same-py-generic-services.mdx | 63 +++ .../file-same-py-generic-services.ru.mdx | 63 +++ .../rules/file-same-ruby-package.mdx | 63 +++ .../rules/file-same-ruby-package.ru.mdx | 63 +++ .../rules/file-same-swift-prefix.mdx | 63 +++ .../rules/file-same-swift-prefix.ru.mdx | 63 +++ .../rules/file-same-syntax.mdx | 57 +++ .../rules/file-same-syntax.ru.mdx | 57 +++ .../rules/import-no-delete.mdx | 413 ----------------- .../rules/import-no-delete.ru.mdx | 357 --------------- .../breaking-changes/rules/message-moved.mdx | 60 +++ .../rules/message-moved.ru.mdx | 60 +++ .../rules/message-no-delete.mdx | 198 +-------- .../rules/message-no-delete.ru.mdx | 190 +------- ...no-remove-standard-descriptor-accessor.mdx | 58 +++ ...remove-standard-descriptor-accessor.ru.mdx | 58 +++ .../rules/message-same-json-format.mdx | 58 +++ .../rules/message-same-json-format.ru.mdx | 58 +++ .../message-same-message-set-wire-format.mdx | 58 +++ ...essage-same-message-set-wire-format.ru.mdx | 58 +++ .../rules/message-same-required-fields.mdx | 62 +++ .../rules/message-same-required-fields.ru.mdx | 62 +++ .../docs/cli/breaking-changes/rules/meta.json | 60 ++- .../cli/breaking-changes/rules/meta.ru.json | 74 ++++ .../rules/oneof-field-no-delete.mdx | 415 ----------------- .../rules/oneof-field-no-delete.ru.mdx | 373 ---------------- .../rules/oneof-field-same-type.mdx | 417 ------------------ .../rules/oneof-field-same-type.ru.mdx | 347 --------------- .../breaking-changes/rules/oneof-moved.mdx | 69 +++ .../breaking-changes/rules/oneof-moved.ru.mdx | 69 +++ .../rules/oneof-no-delete.mdx | 376 +--------------- .../rules/oneof-no-delete.ru.mdx | 356 +-------------- .../rules/package-no-delete.mdx | 54 +++ .../rules/package-no-delete.ru.mdx | 54 +++ .../rules/reserved-enum-no-delete.mdx | 66 +++ .../rules/reserved-enum-no-delete.ru.mdx | 66 +++ .../rules/reserved-message-no-delete.mdx | 63 +++ .../rules/reserved-message-no-delete.ru.mdx | 63 +++ .../breaking-changes/rules/rpc-no-delete.mdx | 42 +- .../rules/rpc-no-delete.ru.mdx | 46 +- .../rules/rpc-same-client-streaming.mdx | 58 +++ .../rules/rpc-same-client-streaming.ru.mdx | 58 +++ .../rules/rpc-same-idempotency-level.mdx | 63 +++ .../rules/rpc-same-idempotency-level.ru.mdx | 63 +++ .../rules/rpc-same-request-type.mdx | 212 +-------- .../rules/rpc-same-request-type.ru.mdx | 211 +-------- .../rules/rpc-same-response-type.mdx | 277 +----------- .../rules/rpc-same-response-type.ru.mdx | 272 +----------- .../rules/rpc-same-server-streaming.mdx | 58 +++ .../rules/rpc-same-server-streaming.ru.mdx | 58 +++ .../breaking-changes/rules/service-moved.mdx | 60 +++ .../rules/service-moved.ru.mdx | 60 +++ .../rules/service-no-delete.mdx | 43 +- .../rules/service-no-delete.ru.mdx | 47 +- content/docs/cli/linter/index.mdx | 66 ++- content/docs/cli/linter/index.ru.mdx | 66 ++- content/docs/cli/linter/meta.ru.json | 7 + .../cli/linter/rules/comment-enum-value.mdx | 7 +- .../linter/rules/comment-enum-value.ru.mdx | 13 +- .../docs/cli/linter/rules/comment-enum.mdx | 7 +- .../docs/cli/linter/rules/comment-enum.ru.mdx | 11 +- .../docs/cli/linter/rules/comment-field.mdx | 7 +- .../cli/linter/rules/comment-field.ru.mdx | 11 +- .../docs/cli/linter/rules/comment-message.mdx | 7 +- .../cli/linter/rules/comment-message.ru.mdx | 11 +- .../docs/cli/linter/rules/comment-oneof.mdx | 7 +- .../cli/linter/rules/comment-oneof.ru.mdx | 11 +- content/docs/cli/linter/rules/comment-rpc.mdx | 7 +- .../docs/cli/linter/rules/comment-rpc.ru.mdx | 29 +- .../docs/cli/linter/rules/comment-service.mdx | 7 +- .../cli/linter/rules/comment-service.ru.mdx | 11 +- .../linter/rules/directory-same-package.mdx | 52 ++- .../rules/directory-same-package.ru.mdx | 56 ++- .../linter/rules/enum-first-value-zero.mdx | 9 +- .../linter/rules/enum-first-value-zero.ru.mdx | 15 +- .../cli/linter/rules/enum-no-allow-alias.mdx | 9 +- .../linter/rules/enum-no-allow-alias.ru.mdx | 13 +- .../cli/linter/rules/enum-pascal-case.mdx | 8 +- .../cli/linter/rules/enum-pascal-case.ru.mdx | 12 +- .../cli/linter/rules/enum-value-prefix.mdx | 9 +- .../cli/linter/rules/enum-value-prefix.ru.mdx | 15 +- .../rules/enum-value-upper-snake-case.mdx | 8 +- .../rules/enum-value-upper-snake-case.ru.mdx | 12 +- .../linter/rules/enum-zero-value-suffix.mdx | 38 +- .../rules/enum-zero-value-suffix.ru.mdx | 42 +- .../linter/rules/field-lower-snake-case.mdx | 8 +- .../rules/field-lower-snake-case.ru.mdx | 13 +- .../cli/linter/rules/field-not-required.mdx | 53 +++ .../linter/rules/field-not-required.ru.mdx | 53 +++ .../linter/rules/file-lower-snake-case.mdx | 9 +- .../linter/rules/file-lower-snake-case.ru.mdx | 15 +- .../cli/linter/rules/import-no-public.mdx | 8 +- .../cli/linter/rules/import-no-public.ru.mdx | 12 +- .../docs/cli/linter/rules/import-no-weak.mdx | 8 +- .../cli/linter/rules/import-no-weak.ru.mdx | 12 +- content/docs/cli/linter/rules/import-used.mdx | 8 +- .../docs/cli/linter/rules/import-used.ru.mdx | 12 +- .../cli/linter/rules/message-pascal-case.mdx | 8 +- .../linter/rules/message-pascal-case.ru.mdx | 12 +- content/docs/cli/linter/rules/meta.json | 5 +- content/docs/cli/linter/rules/meta.ru.json | 49 ++ .../linter/rules/oneof-lower-snake-case.mdx | 8 +- .../rules/oneof-lower-snake-case.ru.mdx | 12 +- .../docs/cli/linter/rules/package-defined.mdx | 8 +- .../cli/linter/rules/package-defined.ru.mdx | 12 +- .../linter/rules/package-directory-match.mdx | 45 +- .../rules/package-directory-match.ru.mdx | 50 ++- .../linter/rules/package-lower-snake-case.mdx | 9 +- .../rules/package-lower-snake-case.ru.mdx | 13 +- .../linter/rules/package-no-import-cycle.mdx | 87 ++++ .../rules/package-no-import-cycle.ru.mdx | 87 ++++ .../rules/package-same-csharp-namespace.mdx | 8 +- .../package-same-csharp-namespace.ru.mdx | 12 +- .../linter/rules/package-same-directory.mdx | 52 ++- .../rules/package-same-directory.ru.mdx | 56 ++- .../linter/rules/package-same-go-package.mdx | 8 +- .../rules/package-same-go-package.ru.mdx | 12 +- .../package-same-java-multiple-files.mdx | 27 +- .../package-same-java-multiple-files.ru.mdx | 32 +- .../rules/package-same-java-package.mdx | 9 +- .../rules/package-same-java-package.ru.mdx | 15 +- .../rules/package-same-php-namespace.mdx | 9 +- .../rules/package-same-php-namespace.ru.mdx | 13 +- .../rules/package-same-ruby-package.mdx | 9 +- .../rules/package-same-ruby-package.ru.mdx | 23 +- .../rules/package-same-swift-prefix.mdx | 9 +- .../rules/package-same-swift-prefix.ru.mdx | 15 +- .../linter/rules/package-version-suffix.mdx | 58 ++- .../rules/package-version-suffix.ru.mdx | 60 ++- .../linter/rules/rpc-no-client-streaming.mdx | 7 +- .../rules/rpc-no-client-streaming.ru.mdx | 11 +- .../linter/rules/rpc-no-server-streaming.mdx | 7 +- .../rules/rpc-no-server-streaming.ru.mdx | 11 +- .../docs/cli/linter/rules/rpc-pascal-case.mdx | 9 +- .../cli/linter/rules/rpc-pascal-case.ru.mdx | 13 +- .../rules/rpc-request-response-unique.mdx | 33 +- .../rules/rpc-request-response-unique.ru.mdx | 37 +- .../rules/rpc-request-standard-name.mdx | 23 +- .../rules/rpc-request-standard-name.ru.mdx | 27 +- .../rules/rpc-response-standard-name.mdx | 22 +- .../rules/rpc-response-standard-name.ru.mdx | 26 +- .../cli/linter/rules/service-pascal-case.mdx | 8 +- .../linter/rules/service-pascal-case.ru.mdx | 13 +- .../docs/cli/linter/rules/service-suffix.mdx | 38 +- .../cli/linter/rules/service-suffix.ru.mdx | 42 +- .../cli/linter/rules/syntax-specified.mdx | 48 ++ .../cli/linter/rules/syntax-specified.ru.mdx | 48 ++ next.config.mjs | 31 ++ 243 files changed, 9286 insertions(+), 7053 deletions(-) create mode 100644 content/docs/cli/breaking-changes/meta.ru.json create mode 100644 content/docs/cli/breaking-changes/rules/enum-moved.mdx create mode 100644 content/docs/cli/breaking-changes/rules/enum-moved.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/enum-same-json-format.mdx create mode 100644 content/docs/cli/breaking-changes/rules/enum-same-json-format.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/enum-same-type.mdx create mode 100644 content/docs/cli/breaking-changes/rules/enum-same-type.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/enum-value-no-delete-unless-name-reserved.mdx create mode 100644 content/docs/cli/breaking-changes/rules/enum-value-no-delete-unless-name-reserved.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/enum-value-no-delete-unless-number-reserved.mdx create mode 100644 content/docs/cli/breaking-changes/rules/enum-value-no-delete-unless-number-reserved.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/extension-message-no-delete.mdx create mode 100644 content/docs/cli/breaking-changes/rules/extension-message-no-delete.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/extension-moved.mdx create mode 100644 content/docs/cli/breaking-changes/rules/extension-moved.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/extension-no-delete.mdx create mode 100644 content/docs/cli/breaking-changes/rules/extension-no-delete.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/extension-same-extendee.mdx create mode 100644 content/docs/cli/breaking-changes/rules/extension-same-extendee.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/extension-same-number.mdx create mode 100644 content/docs/cli/breaking-changes/rules/extension-same-number.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/field-no-delete-unless-name-reserved.mdx create mode 100644 content/docs/cli/breaking-changes/rules/field-no-delete-unless-name-reserved.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/field-no-delete-unless-number-reserved.mdx create mode 100644 content/docs/cli/breaking-changes/rules/field-no-delete-unless-number-reserved.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/field-same-cpp-string-type.mdx create mode 100644 content/docs/cli/breaking-changes/rules/field-same-cpp-string-type.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/field-same-default.mdx create mode 100644 content/docs/cli/breaking-changes/rules/field-same-default.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/field-same-java-utf8-validation.mdx create mode 100644 content/docs/cli/breaking-changes/rules/field-same-java-utf8-validation.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/field-same-json-name.mdx create mode 100644 content/docs/cli/breaking-changes/rules/field-same-json-name.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/field-same-jstype.mdx create mode 100644 content/docs/cli/breaking-changes/rules/field-same-jstype.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/field-same-name.mdx create mode 100644 content/docs/cli/breaking-changes/rules/field-same-name.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/field-same-oneof.mdx create mode 100644 content/docs/cli/breaking-changes/rules/field-same-oneof.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/field-same-utf8-validation.mdx create mode 100644 content/docs/cli/breaking-changes/rules/field-same-utf8-validation.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/field-wire-compatible-cardinality.mdx create mode 100644 content/docs/cli/breaking-changes/rules/field-wire-compatible-cardinality.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/field-wire-compatible-type.mdx create mode 100644 content/docs/cli/breaking-changes/rules/field-wire-compatible-type.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/field-wire-json-compatible-cardinality.mdx create mode 100644 content/docs/cli/breaking-changes/rules/field-wire-json-compatible-cardinality.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/field-wire-json-compatible-type.mdx create mode 100644 content/docs/cli/breaking-changes/rules/field-wire-json-compatible-type.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-no-delete.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-no-delete.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-cc-enable-arenas.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-cc-enable-arenas.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-cc-generic-services.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-cc-generic-services.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-csharp-namespace.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-csharp-namespace.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-go-package.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-go-package.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-java-generic-services.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-java-generic-services.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-java-multiple-files.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-java-multiple-files.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-java-outer-classname.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-java-outer-classname.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-java-package.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-java-package.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-java-string-check-utf8.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-java-string-check-utf8.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-objc-class-prefix.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-objc-class-prefix.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-optimize-for.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-optimize-for.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-package.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-package.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-php-class-prefix.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-php-class-prefix.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-php-metadata-namespace.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-php-metadata-namespace.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-php-namespace.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-php-namespace.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-py-generic-services.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-py-generic-services.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-ruby-package.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-ruby-package.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-swift-prefix.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-swift-prefix.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-syntax.mdx create mode 100644 content/docs/cli/breaking-changes/rules/file-same-syntax.ru.mdx delete mode 100644 content/docs/cli/breaking-changes/rules/import-no-delete.mdx delete mode 100644 content/docs/cli/breaking-changes/rules/import-no-delete.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/message-moved.mdx create mode 100644 content/docs/cli/breaking-changes/rules/message-moved.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/message-no-remove-standard-descriptor-accessor.mdx create mode 100644 content/docs/cli/breaking-changes/rules/message-no-remove-standard-descriptor-accessor.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/message-same-json-format.mdx create mode 100644 content/docs/cli/breaking-changes/rules/message-same-json-format.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/message-same-message-set-wire-format.mdx create mode 100644 content/docs/cli/breaking-changes/rules/message-same-message-set-wire-format.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/message-same-required-fields.mdx create mode 100644 content/docs/cli/breaking-changes/rules/message-same-required-fields.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/meta.ru.json delete mode 100644 content/docs/cli/breaking-changes/rules/oneof-field-no-delete.mdx delete mode 100644 content/docs/cli/breaking-changes/rules/oneof-field-no-delete.ru.mdx delete mode 100644 content/docs/cli/breaking-changes/rules/oneof-field-same-type.mdx delete mode 100644 content/docs/cli/breaking-changes/rules/oneof-field-same-type.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/oneof-moved.mdx create mode 100644 content/docs/cli/breaking-changes/rules/oneof-moved.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/package-no-delete.mdx create mode 100644 content/docs/cli/breaking-changes/rules/package-no-delete.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/reserved-enum-no-delete.mdx create mode 100644 content/docs/cli/breaking-changes/rules/reserved-enum-no-delete.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/reserved-message-no-delete.mdx create mode 100644 content/docs/cli/breaking-changes/rules/reserved-message-no-delete.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/rpc-same-client-streaming.mdx create mode 100644 content/docs/cli/breaking-changes/rules/rpc-same-client-streaming.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/rpc-same-idempotency-level.mdx create mode 100644 content/docs/cli/breaking-changes/rules/rpc-same-idempotency-level.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/rpc-same-server-streaming.mdx create mode 100644 content/docs/cli/breaking-changes/rules/rpc-same-server-streaming.ru.mdx create mode 100644 content/docs/cli/breaking-changes/rules/service-moved.mdx create mode 100644 content/docs/cli/breaking-changes/rules/service-moved.ru.mdx create mode 100644 content/docs/cli/linter/meta.ru.json create mode 100644 content/docs/cli/linter/rules/field-not-required.mdx create mode 100644 content/docs/cli/linter/rules/field-not-required.ru.mdx create mode 100644 content/docs/cli/linter/rules/meta.ru.json create mode 100644 content/docs/cli/linter/rules/package-no-import-cycle.mdx create mode 100644 content/docs/cli/linter/rules/package-no-import-cycle.ru.mdx create mode 100644 content/docs/cli/linter/rules/syntax-specified.mdx create mode 100644 content/docs/cli/linter/rules/syntax-specified.ru.mdx diff --git a/content/docs/cli/breaking-changes/index.mdx b/content/docs/cli/breaking-changes/index.mdx index 07aabdf..232d21e 100644 --- a/content/docs/cli/breaking-changes/index.mdx +++ b/content/docs/cli/breaking-changes/index.mdx @@ -3,69 +3,151 @@ title: "Breaking Changes Detection" description: "Compare protobuf schemas with a Git baseline and revision-local dependencies in EasyP v1." --- -easyp breaking compares selected current .proto files with a Git baseline and reports incompatible changes. +`easyp breaking` compares selected current `.proto` files with a Git baseline and reports incompatible changes. -~~~yaml +```yaml version: v1 breaking: baseline: git:main categories: [FILE] ignore_unstable: true ignore: [experimental] -~~~ +``` -~~~bash +```bash easyp breaking --path proto --against main easyp --format json breaking --path proto -~~~ +easyp breaking --config ./policies/easyp.yaml --path proto --against main +easyp breaking --frozen --path proto --against main +``` + +- `--path` (`-p`) selects a file or directory relative to the scan root (defaults to `.`). +- `--root` (`-r`) overrides the scan root from the policy directory. +- `--against` overrides the baseline Git revision (takes precedence over `breaking.baseline`). +- `--config` selects an explicit policy file instead of discovering `easyp.yaml`. +- `--frozen` requires existing `protobuf.mod` and verified `protobuf.lock` files without resolving dependencies, writing files, or allowing local `replace` directives. ## Select a baseline and files -Precedence is explicit --against, then breaking.baseline, then master. Even explicit --against master overrides configuration. An empty or whitespace-only flag is an error; a missing explicit Git baseline never falls back to the configured one. +Precedence is explicit `--against`, then `breaking.baseline`, then `master`. Even explicit `--against master` overrides configuration. An empty or whitespace-only flag is an error; a missing explicit Git baseline never falls back to the configured one. -The baseline can name a local branch, a lightweight or annotated tag, a full commit SHA, or another locally resolvable Git revision such as HEAD. Required refs and objects must already be present in the checkout. A bare branch name takes precedence over an identically named tag; use refs/tags/v1.2.0 to select the tag explicitly. In YAML use git:refs/tags/v1.2.0; for the CLI pass --against refs/tags/v1.2.0 without a git: or git-ref= prefix. +The baseline can name a local branch, a lightweight or annotated tag, a full commit SHA, or another locally resolvable Git revision such as `HEAD`. Required refs and objects must already be present in the checkout. A bare branch name takes precedence over an identically named tag; use `refs/tags/v1.2.0` to select the tag explicitly. In YAML use `git:refs/tags/v1.2.0`; for the CLI pass `--against refs/tags/v1.2.0` without a `git:` or `git-ref=` prefix. ---path selects a file or directory relative to the scan root; --root changes that root from the policy directory. Checked file identities remain repository-relative. breaking.ignore excludes directories; vendored sources are excluded from targets. +`--path` selects a file or directory relative to the scan root; `--root` changes that root from the policy directory. Checked file identities remain repository-relative. `breaking.ignore` excludes directories; vendored sources are excluded from targets. Directory and file symlinks select their canonical repository paths, including a deleted suffix beneath an existing directory. Selecting an alias does not skip changes visible through the original path. Targets outside the repository are rejected. -breaking.ignore paths are relative to the file supplying the effective breaking section, not the Git root or --root. For example, ignore: [generated] in api/easyp.yaml excludes api/generated, including when that section is inherited. Entries must be nonempty local relative paths; absolute paths and paths escaping the policy directory or repository are rejected. +`breaking.ignore` paths are relative to the file supplying the effective `breaking` section, not the Git root or `--root`. For example, `ignore: [generated]` in `api/easyp.yaml` excludes `api/generated`, including when that section is inherited. Entries must be nonempty local relative paths; absolute paths and paths escaping the policy directory or repository are rejected. -Policies come from current configuration. Each nearest defined breaking section applies as a whole; nested policies may select different baselines. Repeated identical findings are emitted once. +Policies come from current configuration. Each nearest defined `breaking` section applies as a whole; nested policies may select different baselines. Repeated identical findings are emitted once. ## Revision-local contexts -Each selected module is compared separately. Current and baseline revisions use their own module roots, protobuf.mod, protobuf.lock, and dependencies. Baseline sources, manifests, and locks are read from an isolated Git snapshot. The caller's checkout, manifest, and lock are unchanged; the verified dependency cache may be populated. Temporary snapshots are removed after use. +Each selected module is compared separately. Current and baseline revisions use their own module roots, `protobuf.mod`, `protobuf.lock`, and dependencies. Baseline sources, manifests, and locks are read from an isolated Git snapshot. The caller's checkout, manifest, and lock are unchanged; the verified dependency cache may be populated. Temporary snapshots are removed after use. Buf source filters and replacement metadata also belong to their respective revisions. Current files or filters never substitute for missing historical metadata. During consumer checks, reached replacement sources supply imports; they become policy targets only when explicitly selected. Unused replacements cannot exclude consumer targets. -Baseline-only files and deleted modules remain checkable, including through --path. Dependency findings use the policy of the selected files. A policy can also run without a module manifest. +Baseline-only files and deleted modules remain checkable, including through `--path`. Dependency findings use the policy of the selected files. A policy can also run without a module manifest (unless `--frozen` is passed). Local replacements inside the repository use the contents of the corresponding revision; absolute paths inside the repository are mapped into the baseline snapshot. External local replacements are rejected because they have no recoverable historical identity. Use a locked dependency for a reproducible baseline. ## Categories and unstable packages -breaking.categories selects descriptor-based profiles: FILE, PACKAGE, WIRE_JSON, or WIRE. Omitted or empty categories select FILE. Multiple profiles apply their union without duplicate diagnostics. +`breaking.categories` selects descriptor-based profiles: `FILE` (61 rules), `PACKAGE` (55 rules), `WIRE_JSON` (27 rules), or `WIRE` (20 rules). Omitted or empty categories select `FILE`. Multiple profiles apply their union without duplicate diagnostics. -| Change | FILE | PACKAGE | WIRE_JSON | WIRE | -|---|---|---|---|---| +| Change | `FILE` | `PACKAGE` | `WIRE_JSON` | `WIRE` | +| --- | --- | --- | --- | --- | | Move a declaration within its package, preserving options | Reject | Allow | Allow | Allow | | Rename a field, even with its old JSON name retained | Reject | Reject | Reject | Allow | -| Change int32 to int64 | Reject | Reject | Reject | Allow | -| Change int32 to uint32 | Reject | Reject | Allow | Allow | -| Change string to bytes | Reject | Reject | Reject | Allow | -| Change bytes to string or int32 to sint32 | Reject | Reject | Reject | Reject | +| Change `int32` to `int64` | Reject | Reject | Reject | Allow | +| Change `int32` to `uint32` | Reject | Reject | Allow | Allow | +| Change `string` to `bytes` | Reject | Reject | Reject | Allow | +| Change `bytes` to `string` or `int32` to `sint32` | Reject | Reject | Reject | Reject | | Delete a non-required field | Reject | Reject | Reserve number and name | Reserve number | | Add/remove a required field or change a real oneof | Reject | Reject | Reject | Reject | -| Add explicit optional presence | Reject | Reject | Allow | Allow | -| Convert repeated entry messages to a compatible map | Reject | Reject | Reject | Allow | - -A map is encoded as repeated entry messages; repeated scalar values are not compatible merely because their type equals the map value type. Existing reserved names and number ranges cannot be released in any profile. Enum aliases are checked by name/number pairs for source/JSON and by retained numbers for WIRE. RPC/service removal, request/response identity, streaming, idempotency, and actual default-value changes remain checked. Source profiles additionally check supported file/field code-generation options, enum openness, declaration and extension ranges. WIRE_JSON also checks JSON format capability. - -Current and baseline sources are compiled separately using their own imports and pinned revisions. Diagnostics retain source coordinates and repository-relative paths; consumer managed options are not applied. Profiles work with section-scoped extends, ignores, local overlays and frozen verification. No source, manifest, lock or plugin output is written by breaking. - -The precise implemented rule catalog is internal/config/breaking_profiles.go. This feature does not claim full rule-for-rule Buf equivalence. It checks standard descriptor properties and supported effective Edition features, not arbitrary application-defined option semantics or external generated-code behavior. Unsupported syntax/editions are rejected by the pinned compiler instead of being declared compatible. - -breaking.ignore_unstable defaults to false. When true, it excludes packages on both sides whose final component matches vNtest..., vNalpha, vNbeta, vNpMalpha, or vNpMbeta. N and M are positive numbers without leading zeros; alpha/beta may have a similarly positive sequence number, and test may have any suffix. For example, acme.v1beta1 is skipped, while acme.v1beta1.service and acme.v0alpha1 are not. Stable packages and their references to unstable types remain checked; source reading and import resolution precede filtering. - -breaking.extends loads a local or locked-module policy. Its baseline and ignore paths apply in the consuming repository; local fields override inherited values. The old breaking_check.against_git_ref key is not accepted by the v1 CLI. See the [policy reference](/docs/reference/easyp-yaml) for all fields. +| Add explicit `optional` presence | Reject | Reject | Allow | Allow | +| Convert repeated entry messages to a compatible `map` | Reject | Reject | Reject | Allow | + +A `map` is encoded as repeated entry messages; repeated scalar values are not compatible merely because their type equals the map value type. Existing reserved names and number ranges cannot be released in any profile. Enum aliases are checked by name/number pairs for source/JSON and by retained numbers for `WIRE`. RPC/service removal, request/response identity, streaming, idempotency, and actual default-value changes remain checked. Source profiles additionally check supported file/field code-generation options, enum openness, declaration and extension ranges. `WIRE_JSON` also checks JSON format capability. + +Current and baseline sources are compiled separately using their own imports and pinned revisions. Diagnostics retain source coordinates and repository-relative paths; consumer managed options are not applied. Profiles work with section-scoped extends, ignores, local overlays, and `--frozen` verification. No source, manifest, lock, or plugin output is written by `easyp breaking`. + +The precise implemented rule catalog is `internal/config/breaking_profiles.go`. This feature does not claim full rule-for-rule Buf equivalence. It checks standard descriptor properties and supported effective Edition features, not arbitrary application-defined option semantics or external generated-code behavior. Unsupported syntax/editions are rejected by the pinned compiler instead of being declared compatible. + +`breaking.ignore_unstable` defaults to `false`. When `true`, it excludes packages on both sides whose final component matches `vNtest...`, `vNalpha`, `vNbeta`, `vNpMalpha`, or `vNpMbeta`. `N` and `M` are positive numbers without leading zeros; `alpha`/`beta` may have a similarly positive sequence number, and `test` may have any suffix. For example, `acme.v1beta1` is skipped, while `acme.v1beta1.service` and `acme.v0alpha1` are not. Stable packages and their references to unstable types remain checked; source reading and import resolution precede filtering. + +`breaking.extends` loads a local or locked-module policy. Its baseline and ignore paths apply in the consuming repository; local fields override inherited values. The old `breaking_check.against_git_ref` key is not accepted by the v1 CLI. See the [policy reference](/docs/reference/easyp-yaml) for all fields. + +## Full rule matrix (69 rules) + +| Rule | `FILE` (61) | `PACKAGE` (55) | `WIRE_JSON` (27) | `WIRE` (20) | +| --- | :---: | :---: | :---: | :---: | +| [`ENUM_MOVED`](/docs/cli/breaking-changes/rules/enum-moved) | Yes | — | — | — | +| [`ENUM_NO_DELETE`](/docs/cli/breaking-changes/rules/enum-no-delete) | Yes | Yes | — | — | +| [`ENUM_SAME_JSON_FORMAT`](/docs/cli/breaking-changes/rules/enum-same-json-format) | Yes | Yes | Yes | — | +| [`ENUM_SAME_TYPE`](/docs/cli/breaking-changes/rules/enum-same-type) | Yes | Yes | — | — | +| [`ENUM_VALUE_NO_DELETE`](/docs/cli/breaking-changes/rules/enum-value-no-delete) | Yes | Yes | — | — | +| [`ENUM_VALUE_NO_DELETE_UNLESS_NAME_RESERVED`](/docs/cli/breaking-changes/rules/enum-value-no-delete-unless-name-reserved) | — | — | Yes | — | +| [`ENUM_VALUE_NO_DELETE_UNLESS_NUMBER_RESERVED`](/docs/cli/breaking-changes/rules/enum-value-no-delete-unless-number-reserved) | — | — | Yes | Yes | +| [`ENUM_VALUE_SAME_NAME`](/docs/cli/breaking-changes/rules/enum-value-same-name) | Yes | Yes | Yes | — | +| [`EXTENSION_MESSAGE_NO_DELETE`](/docs/cli/breaking-changes/rules/extension-message-no-delete) | Yes | Yes | — | — | +| [`EXTENSION_MOVED`](/docs/cli/breaking-changes/rules/extension-moved) | Yes | — | — | — | +| [`EXTENSION_NO_DELETE`](/docs/cli/breaking-changes/rules/extension-no-delete) | Yes | Yes | — | — | +| [`EXTENSION_SAME_EXTENDEE`](/docs/cli/breaking-changes/rules/extension-same-extendee) | Yes | Yes | Yes | Yes | +| [`EXTENSION_SAME_NUMBER`](/docs/cli/breaking-changes/rules/extension-same-number) | Yes | Yes | Yes | Yes | +| [`FIELD_NO_DELETE`](/docs/cli/breaking-changes/rules/field-no-delete) | Yes | Yes | — | — | +| [`FIELD_NO_DELETE_UNLESS_NAME_RESERVED`](/docs/cli/breaking-changes/rules/field-no-delete-unless-name-reserved) | — | — | Yes | — | +| [`FIELD_NO_DELETE_UNLESS_NUMBER_RESERVED`](/docs/cli/breaking-changes/rules/field-no-delete-unless-number-reserved) | — | — | Yes | Yes | +| [`FIELD_SAME_CARDINALITY`](/docs/cli/breaking-changes/rules/field-same-cardinality) | Yes | Yes | — | — | +| [`FIELD_SAME_CPP_STRING_TYPE`](/docs/cli/breaking-changes/rules/field-same-cpp-string-type) | Yes | Yes | — | — | +| [`FIELD_SAME_DEFAULT`](/docs/cli/breaking-changes/rules/field-same-default) | Yes | Yes | Yes | Yes | +| [`FIELD_SAME_JAVA_UTF8_VALIDATION`](/docs/cli/breaking-changes/rules/field-same-java-utf8-validation) | Yes | Yes | — | — | +| [`FIELD_SAME_JSON_NAME`](/docs/cli/breaking-changes/rules/field-same-json-name) | Yes | Yes | Yes | — | +| [`FIELD_SAME_JSTYPE`](/docs/cli/breaking-changes/rules/field-same-jstype) | Yes | Yes | — | — | +| [`FIELD_SAME_NAME`](/docs/cli/breaking-changes/rules/field-same-name) | Yes | Yes | Yes | — | +| [`FIELD_SAME_ONEOF`](/docs/cli/breaking-changes/rules/field-same-oneof) | Yes | Yes | Yes | Yes | +| [`FIELD_SAME_TYPE`](/docs/cli/breaking-changes/rules/field-same-type) | Yes | Yes | — | — | +| [`FIELD_SAME_UTF8_VALIDATION`](/docs/cli/breaking-changes/rules/field-same-utf8-validation) | Yes | Yes | — | — | +| [`FIELD_WIRE_COMPATIBLE_CARDINALITY`](/docs/cli/breaking-changes/rules/field-wire-compatible-cardinality) | — | — | — | Yes | +| [`FIELD_WIRE_COMPATIBLE_TYPE`](/docs/cli/breaking-changes/rules/field-wire-compatible-type) | — | — | — | Yes | +| [`FIELD_WIRE_JSON_COMPATIBLE_CARDINALITY`](/docs/cli/breaking-changes/rules/field-wire-json-compatible-cardinality) | — | — | Yes | — | +| [`FIELD_WIRE_JSON_COMPATIBLE_TYPE`](/docs/cli/breaking-changes/rules/field-wire-json-compatible-type) | — | — | Yes | — | +| [`FILE_NO_DELETE`](/docs/cli/breaking-changes/rules/file-no-delete) | Yes | — | — | — | +| [`FILE_SAME_CC_ENABLE_ARENAS`](/docs/cli/breaking-changes/rules/file-same-cc-enable-arenas) | Yes | Yes | — | — | +| [`FILE_SAME_CC_GENERIC_SERVICES`](/docs/cli/breaking-changes/rules/file-same-cc-generic-services) | Yes | Yes | — | — | +| [`FILE_SAME_CSHARP_NAMESPACE`](/docs/cli/breaking-changes/rules/file-same-csharp-namespace) | Yes | Yes | — | — | +| [`FILE_SAME_GO_PACKAGE`](/docs/cli/breaking-changes/rules/file-same-go-package) | Yes | Yes | — | — | +| [`FILE_SAME_JAVA_GENERIC_SERVICES`](/docs/cli/breaking-changes/rules/file-same-java-generic-services) | Yes | Yes | — | — | +| [`FILE_SAME_JAVA_MULTIPLE_FILES`](/docs/cli/breaking-changes/rules/file-same-java-multiple-files) | Yes | Yes | — | — | +| [`FILE_SAME_JAVA_OUTER_CLASSNAME`](/docs/cli/breaking-changes/rules/file-same-java-outer-classname) | Yes | Yes | — | — | +| [`FILE_SAME_JAVA_PACKAGE`](/docs/cli/breaking-changes/rules/file-same-java-package) | Yes | Yes | — | — | +| [`FILE_SAME_JAVA_STRING_CHECK_UTF8`](/docs/cli/breaking-changes/rules/file-same-java-string-check-utf8) | Yes | Yes | — | — | +| [`FILE_SAME_OBJC_CLASS_PREFIX`](/docs/cli/breaking-changes/rules/file-same-objc-class-prefix) | Yes | Yes | — | — | +| [`FILE_SAME_OPTIMIZE_FOR`](/docs/cli/breaking-changes/rules/file-same-optimize-for) | Yes | Yes | — | — | +| [`FILE_SAME_PACKAGE`](/docs/cli/breaking-changes/rules/file-same-package) | Yes | Yes | Yes | Yes | +| [`FILE_SAME_PHP_CLASS_PREFIX`](/docs/cli/breaking-changes/rules/file-same-php-class-prefix) | Yes | Yes | — | — | +| [`FILE_SAME_PHP_METADATA_NAMESPACE`](/docs/cli/breaking-changes/rules/file-same-php-metadata-namespace) | Yes | Yes | — | — | +| [`FILE_SAME_PHP_NAMESPACE`](/docs/cli/breaking-changes/rules/file-same-php-namespace) | Yes | Yes | — | — | +| [`FILE_SAME_PY_GENERIC_SERVICES`](/docs/cli/breaking-changes/rules/file-same-py-generic-services) | Yes | Yes | — | — | +| [`FILE_SAME_RUBY_PACKAGE`](/docs/cli/breaking-changes/rules/file-same-ruby-package) | Yes | Yes | — | — | +| [`FILE_SAME_SWIFT_PREFIX`](/docs/cli/breaking-changes/rules/file-same-swift-prefix) | Yes | Yes | — | — | +| [`FILE_SAME_SYNTAX`](/docs/cli/breaking-changes/rules/file-same-syntax) | Yes | Yes | — | — | +| [`MESSAGE_MOVED`](/docs/cli/breaking-changes/rules/message-moved) | Yes | — | — | — | +| [`MESSAGE_NO_DELETE`](/docs/cli/breaking-changes/rules/message-no-delete) | Yes | Yes | — | — | +| [`MESSAGE_NO_REMOVE_STANDARD_DESCRIPTOR_ACCESSOR`](/docs/cli/breaking-changes/rules/message-no-remove-standard-descriptor-accessor) | Yes | Yes | — | — | +| [`MESSAGE_SAME_JSON_FORMAT`](/docs/cli/breaking-changes/rules/message-same-json-format) | Yes | Yes | Yes | — | +| [`MESSAGE_SAME_MESSAGE_SET_WIRE_FORMAT`](/docs/cli/breaking-changes/rules/message-same-message-set-wire-format) | Yes | Yes | Yes | Yes | +| [`MESSAGE_SAME_REQUIRED_FIELDS`](/docs/cli/breaking-changes/rules/message-same-required-fields) | Yes | Yes | Yes | Yes | +| [`ONEOF_MOVED`](/docs/cli/breaking-changes/rules/oneof-moved) | Yes | — | — | — | +| [`ONEOF_NO_DELETE`](/docs/cli/breaking-changes/rules/oneof-no-delete) | Yes | Yes | — | — | +| [`PACKAGE_NO_DELETE`](/docs/cli/breaking-changes/rules/package-no-delete) | Yes | Yes | — | — | +| [`RESERVED_ENUM_NO_DELETE`](/docs/cli/breaking-changes/rules/reserved-enum-no-delete) | Yes | Yes | Yes | Yes | +| [`RESERVED_MESSAGE_NO_DELETE`](/docs/cli/breaking-changes/rules/reserved-message-no-delete) | Yes | Yes | Yes | Yes | +| [`RPC_NO_DELETE`](/docs/cli/breaking-changes/rules/rpc-no-delete) | Yes | Yes | Yes | Yes | +| [`RPC_SAME_CLIENT_STREAMING`](/docs/cli/breaking-changes/rules/rpc-same-client-streaming) | Yes | Yes | Yes | Yes | +| [`RPC_SAME_IDEMPOTENCY_LEVEL`](/docs/cli/breaking-changes/rules/rpc-same-idempotency-level) | Yes | Yes | Yes | Yes | +| [`RPC_SAME_REQUEST_TYPE`](/docs/cli/breaking-changes/rules/rpc-same-request-type) | Yes | Yes | Yes | Yes | +| [`RPC_SAME_RESPONSE_TYPE`](/docs/cli/breaking-changes/rules/rpc-same-response-type) | Yes | Yes | Yes | Yes | +| [`RPC_SAME_SERVER_STREAMING`](/docs/cli/breaking-changes/rules/rpc-same-server-streaming) | Yes | Yes | Yes | Yes | +| [`SERVICE_MOVED`](/docs/cli/breaking-changes/rules/service-moved) | Yes | — | — | — | +| [`SERVICE_NO_DELETE`](/docs/cli/breaking-changes/rules/service-no-delete) | Yes | Yes | Yes | Yes | diff --git a/content/docs/cli/breaking-changes/index.ru.mdx b/content/docs/cli/breaking-changes/index.ru.mdx index 0765706..37ea0b0 100644 --- a/content/docs/cli/breaking-changes/index.ru.mdx +++ b/content/docs/cli/breaking-changes/index.ru.mdx @@ -3,69 +3,151 @@ title: "Проверка несовместимых изменений" description: "Сравнение protobuf-схем с Git-базой и зависимостями каждой ревизии в EasyP v1." --- -easyp breaking сравнивает выбранные текущие .proto с Git-базой и выводит несовместимые изменения. +`easyp breaking` сравнивает выбранные текущие `.proto`-файлы с Git-базой и выводит несовместимые изменения. -~~~yaml +```yaml version: v1 breaking: baseline: git:main categories: [FILE] ignore_unstable: true ignore: [experimental] -~~~ +``` -~~~bash +```bash easyp breaking --path proto --against main easyp --format json breaking --path proto -~~~ +easyp breaking --config ./policies/easyp.yaml --path proto --against main +easyp breaking --frozen --path proto --against main +``` + +- `--path` (`-p`) выбирает файл или каталог относительно корня проверки (по умолчанию `.`). +- `--root` (`-r`) переопределяет корень проверки вместо каталога политики. +- `--against` переопределяет базовую Git-ревизию (приоритетнее `breaking.baseline`). +- `--config` указывает явный файл политики вместо автоматического поиска `easyp.yaml`. +- `--frozen` требует наличия `protobuf.mod` и проверенного `protobuf.lock` без разрешения зависимостей, изменения файлов и локальных директив `replace`. ## Выбор базы и файлов -Приоритет: явный --against, затем breaking.baseline, затем master. Даже явный --against master перекрывает конфигурацию. Пустое или пробельное значение флага — ошибка; отсутствующая явная Git-база не заменяется конфигурационной. +Приоритет: явный `--against`, затем `breaking.baseline`, затем `master`. Даже явный `--against master` перекрывает конфигурацию. Пустое или пробельное значение флага — ошибка; отсутствующая явная Git-база не заменяется конфигурационной. -База может указывать на локальную ветку, лёгкий или аннотированный тег, полный SHA коммита или другую разрешимую локально Git-ревизию, например HEAD. Нужные ссылки и объекты должны уже присутствовать в checkout. Короткое имя ветки приоритетнее одноимённого тега; для явного выбора тега используйте refs/tags/v1.2.0. В YAML задавайте git:refs/tags/v1.2.0, а в CLI — --against refs/tags/v1.2.0 без префикса git: или git-ref=. +База может указывать на локальную ветку, лёгкий или аннотированный тег, полный SHA коммита или другую разрешимую локально Git-ревизию, например `HEAD`. Нужные ссылки и объекты должны уже присутствовать в checkout. Короткое имя ветки приоритетнее одноимённого тега; для явного выбора тега используйте `refs/tags/v1.2.0`. В YAML задавайте `git:refs/tags/v1.2.0`, а в CLI — `--against refs/tags/v1.2.0` без префикса `git:` или `git-ref=`. ---path выбирает файл или каталог относительно корня проверки; --root меняет этот корень с каталога политики. Идентичность проверяемых файлов остаётся относительно Git-репозитория. breaking.ignore исключает каталоги; вендорные исходники не становятся целями проверки. +`--path` выбирает файл или каталог относительно корня проверки; `--root` меняет этот корень с каталога политики. Идентичность проверяемых файлов остаётся относительно Git-репозитория. `breaking.ignore` исключает каталоги; вендорные исходники не становятся целями проверки. Symlink на каталог или файл выбирает канонический путь внутри репозитория, в том числе удалённый суффикс под существующим каталогом. Выбор ссылки не пропускает изменения, видимые по исходному пути. Цели за пределами репозитория отклоняются. -Пути breaking.ignore отсчитываются от файла, задающего эффективную секцию breaking, а не от корня Git или --root. Например, ignore: [generated] в api/easyp.yaml исключает api/generated, в том числе при наследовании этой секции. Допустимы непустые локальные относительные пути; абсолютные пути и выход за каталог политики или репозиторий отклоняются. +Пути `breaking.ignore` отсчитываются от файла, задающего эффективную секцию `breaking`, а не от корня Git или `--root`. Например, `ignore: [generated]` в `api/easyp.yaml` исключает `api/generated`, в том числе при наследовании этой секции. Допустимы непустые локальные относительные пути; абсолютные пути и выход за каталог политики или репозиторий отклоняются. -Политики берутся из текущей конфигурации. Ближайшая определённая секция breaking применяется целиком; вложенные политики могут выбирать разные базы. Повторяющиеся одинаковые замечания выводятся один раз. +Политики берутся из текущей конфигурации. Ближайшая определённая секция `breaking` применяется целиком; вложенные политики могут выбирать разные базы. Повторяющиеся одинаковые замечания выводятся один раз. ## Контекст каждой ревизии -Каждый выбранный модуль сравнивается отдельно. Текущая ревизия и база используют собственные корни модулей, protobuf.mod, protobuf.lock и зависимости. Исходники, манифесты и lock базы читаются из изолированного Git-снимка. Рабочее дерево, манифест и lock пользователя не меняются; проверенный кеш зависимостей может пополняться. Временные снимки удаляются после проверки. +Каждый выбранный модуль сравнивается отдельно. Текущая ревизия и база используют собственные корни модулей, `protobuf.mod`, `protobuf.lock` и зависимости. Исходники, манифесты и lock базы читаются из изолированного Git-снимка. Рабочее дерево, манифест и lock пользователя не меняются; проверенный кеш зависимостей может пополняться. Временные снимки удаляются после проверки. Фильтры Buf и метаданные замен также берутся из соответствующей ревизии. Текущие файлы и фильтры не подставляются вместо отсутствующих исторических метаданных. При проверке потребителя достижимые исходники замен предоставляют импорты; собственная политика проверяется при явном выборе замены. Неиспользуемые замены не исключают цели потребителя. -Файлы, существующие только в базе, и удалённые модули остаются доступными для проверки, в том числе через --path. Политика выбранных файлов определяет и политику замечаний о зависимостях. Проверка возможна и без манифеста модуля. +Файлы, существующие только в базе, и удалённые модули остаются доступными для проверки, в том числе через `--path`. Политика выбранных файлов определяет и политику замечаний о зависимостях. Проверка возможна и без манифеста модуля (если не передан `--frozen`). Локальная замена внутри репозитория использует содержимое соответствующей ревизии; абсолютный путь внутри репозитория отображается в снимок базы. Внешняя локальная замена отклоняется: у неё нет восстановимой исторической идентичности. Для воспроизводимой базы используйте зафиксированную зависимость. ## Категории и нестабильные пакеты -breaking.categories выбирает профили сравнения скомпилированных дескрипторов: FILE, PACKAGE, WIRE_JSON или WIRE. Отсутствующий или пустой список выбирает FILE. Несколько профилей применяются совместно без повторения одинаковых диагностик. +`breaking.categories` выбирает профили сравнения скомпилированных дескрипторов: `FILE` (61 правило), `PACKAGE` (55 правил), `WIRE_JSON` (27 правил) или `WIRE` (20 правил). Отсутствующий или пустой список выбирает `FILE`. Несколько профилей применяются совместно без повторения одинаковых диагностик. -| Изменение | FILE | PACKAGE | WIRE_JSON | WIRE | -|---|---|---|---|---| +| Изменение | `FILE` | `PACKAGE` | `WIRE_JSON` | `WIRE` | +| --- | --- | --- | --- | --- | | Перенос объявления внутри пакета с сохранением options | Ошибка | Допустимо | Допустимо | Допустимо | | Переименование поля, даже при сохранённом JSON-имени | Ошибка | Ошибка | Ошибка | Допустимо | -| int32 → int64 | Ошибка | Ошибка | Ошибка | Допустимо | -| int32 → uint32 | Ошибка | Ошибка | Допустимо | Допустимо | -| string → bytes | Ошибка | Ошибка | Ошибка | Допустимо | -| bytes → string или int32 → sint32 | Ошибка | Ошибка | Ошибка | Ошибка | +| `int32` → `int64` | Ошибка | Ошибка | Ошибка | Допустимо | +| `int32` → `uint32` | Ошибка | Ошибка | Допустимо | Допустимо | +| `string` → `bytes` | Ошибка | Ошибка | Ошибка | Допустимо | +| `bytes` → `string` или `int32` → `sint32` | Ошибка | Ошибка | Ошибка | Ошибка | | Удаление необязательного поля | Ошибка | Ошибка | Зарезервировать номер и имя | Зарезервировать номер | -| Добавление/удаление required или изменение настоящего oneof | Ошибка | Ошибка | Ошибка | Ошибка | -| Добавление явной optional-presence | Ошибка | Ошибка | Допустимо | Допустимо | -| Повторяемые entry-сообщения → совместимый map | Ошибка | Ошибка | Ошибка | Допустимо | - -Map кодируется повторяемыми entry-сообщениями: повторяемый scalar не становится совместимым с map только из-за совпадения типа значения. Существующие резервные имена и диапазоны номеров нельзя освобождать ни в одном профиле. Alias-значения enum проверяются по парам имя/номер для source/JSON и сохранённым номерам для WIRE. Проверяются удаления RPC/сервисов, типы запросов/ответов, streaming, idempotency и фактические значения по умолчанию. Source-профили дополнительно проверяют поддержанные file/field options генераторов, открытость enum, объявления и диапазоны extension. WIRE_JSON также проверяет возможность JSON-представления. - -Текущие исходники и baseline компилируются отдельно, со своими импортами и закреплёнными ревизиями. Диагностика сохраняет координаты исходника и путь относительно репозитория; consumer managed-options не применяются. Профили работают с extends, исключениями, локальными заменами и frozen-проверкой. Команда breaking не записывает исходники, manifest, lock или результат плагинов. - -Точный реализованный каталог правил находится в internal/config/breaking_profiles.go. Полная эквивалентность всем правилам Buf не заявляется. Проверяются стандартные свойства дескрипторов и поддержанные эффективные Edition features, а не произвольный смысл пользовательских options или поведение внешнего сгенерированного кода. Неподдерживаемый синтаксис/Edition отклоняется закреплённым компилятором, а не признаётся совместимым. - -breaking.ignore_unstable по умолчанию равен false. При true на обеих сторонах сравнения исключаются пакеты, последний компонент имени которых соответствует vNtest..., vNalpha, vNbeta, vNpMalpha или vNpMbeta. N и M — положительные числа без ведущего нуля; после alpha/beta допустим такой же положительный номер, после test — любой суффикс. Например, acme.v1beta1 пропускается, а acme.v1beta1.service и acme.v0alpha1 — нет. Стабильные пакеты и их ссылки на нестабильные типы всё ещё проверяются; чтение исходников и разрешение импортов происходят до фильтрации. - -breaking.extends загружает локальную политику или базу из закреплённого модуля. Baseline и ignore применяются в репозитории потребителя; локальные поля приоритетнее базы. Старый ключ breaking_check.against_git_ref CLI v1 не принимает. Все поля описаны в [справочнике политики](/ru/docs/reference/easyp-yaml). +| Добавление/удаление `required` или изменение настоящего `oneof` | Ошибка | Ошибка | Ошибка | Ошибка | +| Добавление явной `optional`-presence | Ошибка | Ошибка | Допустимо | Допустимо | +| Повторяемые entry-сообщения → совместимый `map` | Ошибка | Ошибка | Ошибка | Допустимо | + +`map` кодируется повторяемыми entry-сообщениями: повторяемый scalar не становится совместимым с `map` только из-за совпадения типа значения. Существующие резервные имена и диапазоны номеров нельзя освобождать ни в одном профиле. Alias-значения enum проверяются по парам имя/номер для source/JSON и сохранённым номерам для `WIRE`. Проверяются удаления RPC/сервисов, типы запросов/ответов, streaming, idempotency и фактические значения по умолчанию. Source-профили дополнительно проверяют поддержанные file/field options генераторов, открытость enum, объявления и диапазоны extension. `WIRE_JSON` также проверяет возможность JSON-представления. + +Текущие исходники и baseline компилируются отдельно, со своими импортами и закреплёнными ревизиями. Диагностика сохраняет координаты исходника и путь относительно репозитория; consumer managed-options не применяются. Профили работают с `extends`, исключениями, локальными заменами и проверкой `--frozen`. Команда `easyp breaking` не записывает исходники, manifest, lock или результат плагинов. + +Точный реализованный каталог правил находится в `internal/config/breaking_profiles.go`. Полная эквивалентность всем правилам Buf не заявляется. Проверяются стандартные свойства дескрипторов и поддержанные эффективные Edition features, а не произвольный смысл пользовательских options или поведение внешнего сгенерированного кода. Неподдерживаемый синтаксис/Edition отклоняется закреплённым компилятором, а не признаётся совместимым. + +`breaking.ignore_unstable` по умолчанию равен `false`. При `true` на обеих сторонах сравнения исключаются пакеты, последний компонент имени которых соответствует `vNtest...`, `vNalpha`, `vNbeta`, `vNpMalpha` или `vNpMbeta`. `N` и `M` — положительные числа без ведущего нуля; после `alpha`/`beta` допустим такой же положительный номер, после `test` — любой суффикс. Например, `acme.v1beta1` пропускается, а `acme.v1beta1.service` и `acme.v0alpha1` — нет. Стабильные пакеты и их ссылки на нестабильные типы всё ещё проверяются; чтение исходников и разрешение импортов происходят до фильтрации. + +`breaking.extends` загружает локальную политику или базу из закреплённого модуля. Baseline и ignore применяются в репозитории потребителя; локальные поля приоритетнее базы. Старый ключ `breaking_check.against_git_ref` CLI v1 не принимает. Все поля описаны в [справочнике политики](/ru/docs/reference/easyp-yaml). + +## Полная матрица правил (69 правил) + +| Правило | `FILE` (61) | `PACKAGE` (55) | `WIRE_JSON` (27) | `WIRE` (20) | +| --- | :---: | :---: | :---: | :---: | +| [`ENUM_MOVED`](/ru/docs/cli/breaking-changes/rules/enum-moved) | Да | — | — | — | +| [`ENUM_NO_DELETE`](/ru/docs/cli/breaking-changes/rules/enum-no-delete) | Да | Да | — | — | +| [`ENUM_SAME_JSON_FORMAT`](/ru/docs/cli/breaking-changes/rules/enum-same-json-format) | Да | Да | Да | — | +| [`ENUM_SAME_TYPE`](/ru/docs/cli/breaking-changes/rules/enum-same-type) | Да | Да | — | — | +| [`ENUM_VALUE_NO_DELETE`](/ru/docs/cli/breaking-changes/rules/enum-value-no-delete) | Да | Да | — | — | +| [`ENUM_VALUE_NO_DELETE_UNLESS_NAME_RESERVED`](/ru/docs/cli/breaking-changes/rules/enum-value-no-delete-unless-name-reserved) | — | — | Да | — | +| [`ENUM_VALUE_NO_DELETE_UNLESS_NUMBER_RESERVED`](/ru/docs/cli/breaking-changes/rules/enum-value-no-delete-unless-number-reserved) | — | — | Да | Да | +| [`ENUM_VALUE_SAME_NAME`](/ru/docs/cli/breaking-changes/rules/enum-value-same-name) | Да | Да | Да | — | +| [`EXTENSION_MESSAGE_NO_DELETE`](/ru/docs/cli/breaking-changes/rules/extension-message-no-delete) | Да | Да | — | — | +| [`EXTENSION_MOVED`](/ru/docs/cli/breaking-changes/rules/extension-moved) | Да | — | — | — | +| [`EXTENSION_NO_DELETE`](/ru/docs/cli/breaking-changes/rules/extension-no-delete) | Да | Да | — | — | +| [`EXTENSION_SAME_EXTENDEE`](/ru/docs/cli/breaking-changes/rules/extension-same-extendee) | Да | Да | Да | Да | +| [`EXTENSION_SAME_NUMBER`](/ru/docs/cli/breaking-changes/rules/extension-same-number) | Да | Да | Да | Да | +| [`FIELD_NO_DELETE`](/ru/docs/cli/breaking-changes/rules/field-no-delete) | Да | Да | — | — | +| [`FIELD_NO_DELETE_UNLESS_NAME_RESERVED`](/ru/docs/cli/breaking-changes/rules/field-no-delete-unless-name-reserved) | — | — | Да | — | +| [`FIELD_NO_DELETE_UNLESS_NUMBER_RESERVED`](/ru/docs/cli/breaking-changes/rules/field-no-delete-unless-number-reserved) | — | — | Да | Да | +| [`FIELD_SAME_CARDINALITY`](/ru/docs/cli/breaking-changes/rules/field-same-cardinality) | Да | Да | — | — | +| [`FIELD_SAME_CPP_STRING_TYPE`](/ru/docs/cli/breaking-changes/rules/field-same-cpp-string-type) | Да | Да | — | — | +| [`FIELD_SAME_DEFAULT`](/ru/docs/cli/breaking-changes/rules/field-same-default) | Да | Да | Да | Да | +| [`FIELD_SAME_JAVA_UTF8_VALIDATION`](/ru/docs/cli/breaking-changes/rules/field-same-java-utf8-validation) | Да | Да | — | — | +| [`FIELD_SAME_JSON_NAME`](/ru/docs/cli/breaking-changes/rules/field-same-json-name) | Да | Да | Да | — | +| [`FIELD_SAME_JSTYPE`](/ru/docs/cli/breaking-changes/rules/field-same-jstype) | Да | Да | — | — | +| [`FIELD_SAME_NAME`](/ru/docs/cli/breaking-changes/rules/field-same-name) | Да | Да | Да | — | +| [`FIELD_SAME_ONEOF`](/ru/docs/cli/breaking-changes/rules/field-same-oneof) | Да | Да | Да | Да | +| [`FIELD_SAME_TYPE`](/ru/docs/cli/breaking-changes/rules/field-same-type) | Да | Да | — | — | +| [`FIELD_SAME_UTF8_VALIDATION`](/ru/docs/cli/breaking-changes/rules/field-same-utf8-validation) | Да | Да | — | — | +| [`FIELD_WIRE_COMPATIBLE_CARDINALITY`](/ru/docs/cli/breaking-changes/rules/field-wire-compatible-cardinality) | — | — | — | Да | +| [`FIELD_WIRE_COMPATIBLE_TYPE`](/ru/docs/cli/breaking-changes/rules/field-wire-compatible-type) | — | — | — | Да | +| [`FIELD_WIRE_JSON_COMPATIBLE_CARDINALITY`](/ru/docs/cli/breaking-changes/rules/field-wire-json-compatible-cardinality) | — | — | Да | — | +| [`FIELD_WIRE_JSON_COMPATIBLE_TYPE`](/ru/docs/cli/breaking-changes/rules/field-wire-json-compatible-type) | — | — | Да | — | +| [`FILE_NO_DELETE`](/ru/docs/cli/breaking-changes/rules/file-no-delete) | Да | — | — | — | +| [`FILE_SAME_CC_ENABLE_ARENAS`](/ru/docs/cli/breaking-changes/rules/file-same-cc-enable-arenas) | Да | Да | — | — | +| [`FILE_SAME_CC_GENERIC_SERVICES`](/ru/docs/cli/breaking-changes/rules/file-same-cc-generic-services) | Да | Да | — | — | +| [`FILE_SAME_CSHARP_NAMESPACE`](/ru/docs/cli/breaking-changes/rules/file-same-csharp-namespace) | Да | Да | — | — | +| [`FILE_SAME_GO_PACKAGE`](/ru/docs/cli/breaking-changes/rules/file-same-go-package) | Да | Да | — | — | +| [`FILE_SAME_JAVA_GENERIC_SERVICES`](/ru/docs/cli/breaking-changes/rules/file-same-java-generic-services) | Да | Да | — | — | +| [`FILE_SAME_JAVA_MULTIPLE_FILES`](/ru/docs/cli/breaking-changes/rules/file-same-java-multiple-files) | Да | Да | — | — | +| [`FILE_SAME_JAVA_OUTER_CLASSNAME`](/ru/docs/cli/breaking-changes/rules/file-same-java-outer-classname) | Да | Да | — | — | +| [`FILE_SAME_JAVA_PACKAGE`](/ru/docs/cli/breaking-changes/rules/file-same-java-package) | Да | Да | — | — | +| [`FILE_SAME_JAVA_STRING_CHECK_UTF8`](/ru/docs/cli/breaking-changes/rules/file-same-java-string-check-utf8) | Да | Да | — | — | +| [`FILE_SAME_OBJC_CLASS_PREFIX`](/ru/docs/cli/breaking-changes/rules/file-same-objc-class-prefix) | Да | Да | — | — | +| [`FILE_SAME_OPTIMIZE_FOR`](/ru/docs/cli/breaking-changes/rules/file-same-optimize-for) | Да | Да | — | — | +| [`FILE_SAME_PACKAGE`](/ru/docs/cli/breaking-changes/rules/file-same-package) | Да | Да | Да | Да | +| [`FILE_SAME_PHP_CLASS_PREFIX`](/ru/docs/cli/breaking-changes/rules/file-same-php-class-prefix) | Да | Да | — | — | +| [`FILE_SAME_PHP_METADATA_NAMESPACE`](/ru/docs/cli/breaking-changes/rules/file-same-php-metadata-namespace) | Да | Да | — | — | +| [`FILE_SAME_PHP_NAMESPACE`](/ru/docs/cli/breaking-changes/rules/file-same-php-namespace) | Да | Да | — | — | +| [`FILE_SAME_PY_GENERIC_SERVICES`](/ru/docs/cli/breaking-changes/rules/file-same-py-generic-services) | Да | Да | — | — | +| [`FILE_SAME_RUBY_PACKAGE`](/ru/docs/cli/breaking-changes/rules/file-same-ruby-package) | Да | Да | — | — | +| [`FILE_SAME_SWIFT_PREFIX`](/ru/docs/cli/breaking-changes/rules/file-same-swift-prefix) | Да | Да | — | — | +| [`FILE_SAME_SYNTAX`](/ru/docs/cli/breaking-changes/rules/file-same-syntax) | Да | Да | — | — | +| [`MESSAGE_MOVED`](/ru/docs/cli/breaking-changes/rules/message-moved) | Да | — | — | — | +| [`MESSAGE_NO_DELETE`](/ru/docs/cli/breaking-changes/rules/message-no-delete) | Да | Да | — | — | +| [`MESSAGE_NO_REMOVE_STANDARD_DESCRIPTOR_ACCESSOR`](/ru/docs/cli/breaking-changes/rules/message-no-remove-standard-descriptor-accessor) | Да | Да | — | — | +| [`MESSAGE_SAME_JSON_FORMAT`](/ru/docs/cli/breaking-changes/rules/message-same-json-format) | Да | Да | Да | — | +| [`MESSAGE_SAME_MESSAGE_SET_WIRE_FORMAT`](/ru/docs/cli/breaking-changes/rules/message-same-message-set-wire-format) | Да | Да | Да | Да | +| [`MESSAGE_SAME_REQUIRED_FIELDS`](/ru/docs/cli/breaking-changes/rules/message-same-required-fields) | Да | Да | Да | Да | +| [`ONEOF_MOVED`](/ru/docs/cli/breaking-changes/rules/oneof-moved) | Да | — | — | — | +| [`ONEOF_NO_DELETE`](/ru/docs/cli/breaking-changes/rules/oneof-no-delete) | Да | Да | — | — | +| [`PACKAGE_NO_DELETE`](/ru/docs/cli/breaking-changes/rules/package-no-delete) | Да | Да | — | — | +| [`RESERVED_ENUM_NO_DELETE`](/ru/docs/cli/breaking-changes/rules/reserved-enum-no-delete) | Да | Да | Да | Да | +| [`RESERVED_MESSAGE_NO_DELETE`](/ru/docs/cli/breaking-changes/rules/reserved-message-no-delete) | Да | Да | Да | Да | +| [`RPC_NO_DELETE`](/ru/docs/cli/breaking-changes/rules/rpc-no-delete) | Да | Да | Да | Да | +| [`RPC_SAME_CLIENT_STREAMING`](/ru/docs/cli/breaking-changes/rules/rpc-same-client-streaming) | Да | Да | Да | Да | +| [`RPC_SAME_IDEMPOTENCY_LEVEL`](/ru/docs/cli/breaking-changes/rules/rpc-same-idempotency-level) | Да | Да | Да | Да | +| [`RPC_SAME_REQUEST_TYPE`](/ru/docs/cli/breaking-changes/rules/rpc-same-request-type) | Да | Да | Да | Да | +| [`RPC_SAME_RESPONSE_TYPE`](/ru/docs/cli/breaking-changes/rules/rpc-same-response-type) | Да | Да | Да | Да | +| [`RPC_SAME_SERVER_STREAMING`](/ru/docs/cli/breaking-changes/rules/rpc-same-server-streaming) | Да | Да | Да | Да | +| [`SERVICE_MOVED`](/ru/docs/cli/breaking-changes/rules/service-moved) | Да | — | — | — | +| [`SERVICE_NO_DELETE`](/ru/docs/cli/breaking-changes/rules/service-no-delete) | Да | Да | Да | Да | diff --git a/content/docs/cli/breaking-changes/meta.ru.json b/content/docs/cli/breaking-changes/meta.ru.json new file mode 100644 index 0000000..a3c9fa1 --- /dev/null +++ b/content/docs/cli/breaking-changes/meta.ru.json @@ -0,0 +1,7 @@ +{ + "title": "Несовместимые изменения", + "pages": [ + "index", + "rules" + ] +} diff --git a/content/docs/cli/breaking-changes/rules/enum-moved.mdx b/content/docs/cli/breaking-changes/rules/enum-moved.mdx new file mode 100644 index 0000000..d14c4fd --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/enum-moved.mdx @@ -0,0 +1,60 @@ +--- +title: "Enum Moved" +description: "Checks that enums are not moved to a different .proto file in the FILE profile." +--- + +- **Rule ID:** `ENUM_MOVED` +- **Profiles:** `FILE` + +In the `FILE` profile, moving an `enum` from one `.proto` file to another (even within the same protobuf package) is flagged because generated file-level headers and imports (for example, C++ `#include` or Python module imports) depend on the declaring file path. Use the `PACKAGE` profile if you allow moving declarations between files in the same package. + +## Examples + +### Bad + +**Before:** + +```proto +// File: myapi/v1/order.proto +syntax = "proto3"; + +package myapi.v1; + +enum OrderStatus { + ORDER_STATUS_UNSPECIFIED = 0; +} +``` + +**After:** + +```proto +// File: myapi/v1/status.proto +syntax = "proto3"; + +package myapi.v1; + +enum OrderStatus { + ORDER_STATUS_UNSPECIFIED = 0; +} +``` + +**Error:** + +```text +myapi/v1/order.proto:6:1: Enum "myapi.v1.OrderStatus" was moved from "myapi/v1/order.proto" to "myapi/v1/status.proto". (ENUM_MOVED) +``` + +### Good + +Keep the enum in its original `.proto` file when using the `FILE` profile: + +```proto +// File: myapi/v1/order.proto +syntax = "proto3"; + +package myapi.v1; + +enum OrderStatus { + ORDER_STATUS_UNSPECIFIED = 0; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/enum-moved.ru.mdx b/content/docs/cli/breaking-changes/rules/enum-moved.ru.mdx new file mode 100644 index 0000000..1f2c27e --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/enum-moved.ru.mdx @@ -0,0 +1,60 @@ +--- +title: "Enum Moved" +description: "Проверяет, что объявления enum не переносятся в другой .proto-файл в профиле FILE." +--- + +- **ID правила:** `ENUM_MOVED` +- **Профили:** `FILE` + +В профиле `FILE` перенос `enum` из одного `.proto`-файла в другой (даже внутри того же пакета) считается несовместимым, поскольку сгенерированные файловые импорты и заголовки (например, `#include` в C++ или модули Python) зависят от пути файла. Если переносы внутри пакета допустимы, используйте профиль `PACKAGE`. + +## Примеры + +### Неправильно + +**До:** + +```proto +// File: myapi/v1/order.proto +syntax = "proto3"; + +package myapi.v1; + +enum OrderStatus { + ORDER_STATUS_UNSPECIFIED = 0; +} +``` + +**После:** + +```proto +// File: myapi/v1/status.proto +syntax = "proto3"; + +package myapi.v1; + +enum OrderStatus { + ORDER_STATUS_UNSPECIFIED = 0; +} +``` + +**Ошибка:** + +```text +myapi/v1/order.proto:6:1: Enum "myapi.v1.OrderStatus" was moved from "myapi/v1/order.proto" to "myapi/v1/status.proto". (ENUM_MOVED) +``` + +### Правильно + +Оставьте `enum` в исходном `.proto`-файле при использовании профиля `FILE`: + +```proto +// File: myapi/v1/order.proto +syntax = "proto3"; + +package myapi.v1; + +enum OrderStatus { + ORDER_STATUS_UNSPECIFIED = 0; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/enum-no-delete.mdx b/content/docs/cli/breaking-changes/rules/enum-no-delete.mdx index f69bbaf..3f46351 100644 --- a/content/docs/cli/breaking-changes/rules/enum-no-delete.mdx +++ b/content/docs/cli/breaking-changes/rules/enum-no-delete.mdx @@ -1,18 +1,19 @@ --- title: "Enum No Delete" +description: "Checks that no top-level or nested enum declarations are deleted." --- -Categories: +- **Rule ID:** `ENUM_NO_DELETE` +- **Profiles:** `FILE`, `PACKAGE` -- **WIRE+** - -This rule checks that no enums are deleted from proto files. Deleting an enum breaks both wire format compatibility and generated code, as existing data may contain values from the deleted enum and client code depends on the generated enum types. +This rule checks that no top-level or nested `enum` declarations are deleted from a protobuf package. Deleting an enum removes generated enum types and constants, breaking compilation for consumers that reference it. ## Examples ### Bad **Before:** + ```proto syntax = "proto3"; @@ -21,9 +22,6 @@ package myapi.v1; enum OrderStatus { ORDER_STATUS_UNSPECIFIED = 0; ORDER_STATUS_PENDING = 1; - ORDER_STATUS_CONFIRMED = 2; - ORDER_STATUS_SHIPPED = 3; - ORDER_STATUS_DELIVERED = 4; } enum UserRole { @@ -31,15 +29,10 @@ enum UserRole { USER_ROLE_ADMIN = 1; USER_ROLE_USER = 2; } - -message Order { - string id = 1; - OrderStatus status = 2; - UserRole created_by_role = 3; -} ``` **After:** + ```proto syntax = "proto3"; @@ -48,82 +41,21 @@ package myapi.v1; enum OrderStatus { ORDER_STATUS_UNSPECIFIED = 0; ORDER_STATUS_PENDING = 1; - ORDER_STATUS_CONFIRMED = 2; - ORDER_STATUS_SHIPPED = 3; - ORDER_STATUS_DELIVERED = 4; } -// UserRole enum was deleted - BREAKING CHANGE! - -message Order { - string id = 1; - OrderStatus status = 2; - UserRole created_by_role = 3; // ERROR: UserRole no longer exists! -} +// UserRole enum was deleted ``` **Error:** -``` -user.proto:8:1: Previously present enum "UserRole" was deleted from file. (BREAKING_CHECK) -``` - -### More Examples - -**Nested enum deletion:** - -```proto -// Before -message User { - string name = 1; - Status status = 2; - - enum Status { - STATUS_UNSPECIFIED = 0; - STATUS_ACTIVE = 1; - STATUS_INACTIVE = 2; - } -} -// After - BREAKING CHANGE! -message User { - string name = 1; - Status status = 2; // ERROR: Status enum deleted - - // Status nested enum was deleted -} +```text +order.proto:10:1: Enum "myapi.v1.UserRole" was deleted. (ENUM_NO_DELETE) ``` ### Good -**Instead of deleting, deprecate the enum:** -```proto -syntax = "proto3"; - -package myapi.v1; - -enum OrderStatus { - ORDER_STATUS_UNSPECIFIED = 0; - ORDER_STATUS_PENDING = 1; - ORDER_STATUS_CONFIRMED = 2; - ORDER_STATUS_SHIPPED = 3; - ORDER_STATUS_DELIVERED = 4; -} +Keep the enum and mark it deprecated instead of deleting it in the same major version: -enum UserRole { - option deprecated = true; - USER_ROLE_UNSPECIFIED = 0; - USER_ROLE_ADMIN = 1; - USER_ROLE_USER = 2; -} - -message Order { - string id = 1; - OrderStatus status = 2; - UserRole created_by_role = 3 [deprecated = true]; -} -``` - -**Or replace with new enum:** ```proto syntax = "proto3"; @@ -132,209 +64,24 @@ package myapi.v1; enum OrderStatus { ORDER_STATUS_UNSPECIFIED = 0; ORDER_STATUS_PENDING = 1; - ORDER_STATUS_CONFIRMED = 2; - ORDER_STATUS_SHIPPED = 3; - ORDER_STATUS_DELIVERED = 4; } enum UserRole { - option deprecated = true; // Old enum + option deprecated = true; USER_ROLE_UNSPECIFIED = 0; USER_ROLE_ADMIN = 1; USER_ROLE_USER = 2; } -enum UserPermission { // New enum with better design +enum UserPermission { USER_PERMISSION_UNSPECIFIED = 0; USER_PERMISSION_READ = 1; USER_PERMISSION_WRITE = 2; - USER_PERMISSION_ADMIN = 3; -} - -message Order { - string id = 1; - OrderStatus status = 2; - UserRole created_by_role = 3 [deprecated = true]; // Old field - UserPermission created_by_permission = 4; // New field -} -``` - -## Impact - -- **Wire Format:** Existing data with the deleted enum cannot be deserialized -- **Generated Code:** Enum types/constants are removed, breaking client compilation -- **Field References:** Fields using the deleted enum type become invalid -- **Switch Statements:** Client code with enum switch cases breaks - -## Real-World Example - -**Client code breaks:** -```go -// Before - this code works -order := &myapi.Order{ - Id: "order123", - Status: myapi.OrderStatus_ORDER_STATUS_PENDING, - CreatedByRole: myapi.UserRole_USER_ROLE_ADMIN, // ERROR after deletion -} - -// Check role -switch order.CreatedByRole { -case myapi.UserRole_USER_ROLE_ADMIN: // ERROR: undefined type - // Admin logic -case myapi.UserRole_USER_ROLE_USER: // ERROR: undefined type - // User logic -} - -// Generated code compilation fails: -// undefined: myapi.UserRole -// undefined: myapi.UserRole_USER_ROLE_ADMIN -``` - -**Existing data becomes unreadable:** -```json -// Serialized data before deletion -{ - "id": "order123", - "status": "ORDER_STATUS_PENDING", - "created_by_role": "USER_ROLE_ADMIN" -} - -// After UserRole deletion - deserialization fails -// Parser doesn't know how to handle "created_by_role" field -``` - -**Server implementation breaks:** -```go -// Before - server handles enum -func validateOrder(order *Order) error { - switch order.CreatedByRole { - case UserRole_USER_ROLE_ADMIN: // ERROR: type not found - return nil // Admins can create any order - case UserRole_USER_ROLE_USER: // ERROR: type not found - // Additional validation for regular users - return validateUserOrder(order) - default: - return errors.New("invalid user role") - } } ``` ## Migration Strategy -1. **Deprecate the enum first:** - ```proto - enum OldEnum { - option deprecated = true; - // ... values - } - ``` - -2. **Stop using in new fields** and deprecate existing fields: - ```proto - OldEnum old_field = 5 [deprecated = true]; - ``` - -3. **Create replacement** if needed: - ```proto - enum NewEnum { - // Better designed enum values - } - NewEnum new_field = 6; - ``` - -4. **Update server code** to handle both during transition: - ```go - func handleRole(oldRole OldEnum, newRole NewEnum) { - // Handle both enum types during migration - if newRole != NEW_ENUM_UNSPECIFIED { - // Use new enum - return handleNewRole(newRole) - } - // Fall back to old enum - return handleOldRole(oldRole) - } - ``` - -5. **Remove after migration period** in a new major version - -## Common Scenarios - -### Enum Redesign -```proto -// Instead of deleting old enum -enum Priority { - option deprecated = true; // Deprecate old design - PRIORITY_UNSPECIFIED = 0; - PRIORITY_LOW = 1; - PRIORITY_HIGH = 2; -} - -enum TaskPriority { // Create new enum with better naming - TASK_PRIORITY_UNSPECIFIED = 0; - TASK_PRIORITY_LOW = 1; - TASK_PRIORITY_MEDIUM = 2; - TASK_PRIORITY_HIGH = 3; - TASK_PRIORITY_URGENT = 4; -} -``` - -### Consolidating Enums -```proto -// Instead of deleting multiple enums -enum Status { - option deprecated = true; // Keep old enum - STATUS_UNSPECIFIED = 0; - STATUS_ACTIVE = 1; -} - -enum State { - option deprecated = true; // Keep old enum - STATE_UNSPECIFIED = 0; - STATE_ENABLED = 1; -} - -enum EntityStatus { // New consolidated enum - ENTITY_STATUS_UNSPECIFIED = 0; - ENTITY_STATUS_ACTIVE = 1; - ENTITY_STATUS_INACTIVE = 2; - ENTITY_STATUS_ENABLED = 3; - ENTITY_STATUS_DISABLED = 4; -} -``` - -### Moving Enum to Different Package -```proto -// Instead of deleting from current package -enum UserRole { - option deprecated = true; // Mark as deprecated - USER_ROLE_UNSPECIFIED = 0; - USER_ROLE_ADMIN = 1; -} - -// Import from new location -import "common/roles.proto"; - -message Order { - UserRole old_role = 3 [deprecated = true]; - common.UserRole new_role = 4; // Reference from new package -} -``` - -### Version Migration -```proto -// Clean approach - new package version -package myapi.v2; - -// Redesigned enums without deprecated ones -enum UserPermission { - USER_PERMISSION_UNSPECIFIED = 0; - USER_PERMISSION_READ = 1; - USER_PERMISSION_WRITE = 2; - USER_PERMISSION_ADMIN = 3; -} - -message Order { - string id = 1; - UserPermission created_by_permission = 2; // Clean design in v2 -} -``` +1. Mark the old enum with `option deprecated = true;` and deprecate any fields referencing it. +2. Introduce a replacement enum (if needed) alongside the deprecated one. +3. Remove the deprecated enum only in a new major package version (for example, `myapi.v2`). diff --git a/content/docs/cli/breaking-changes/rules/enum-no-delete.ru.mdx b/content/docs/cli/breaking-changes/rules/enum-no-delete.ru.mdx index 1394be0..3be905e 100644 --- a/content/docs/cli/breaking-changes/rules/enum-no-delete.ru.mdx +++ b/content/docs/cli/breaking-changes/rules/enum-no-delete.ru.mdx @@ -1,18 +1,19 @@ --- title: "Enum No Delete" +description: "Проверяет, что ни одно объявление enum (верхнего уровня или вложенное) не было удалено." --- -Категории: +- **ID правила:** `ENUM_NO_DELETE` +- **Профили:** `FILE`, `PACKAGE` -- **WIRE+** - -Это правило проверяет, что ни один enum не был удалён из proto‑файлов. Удаление enum ломает совместимость по wire‑формату и сгенерированный код: сохранённые данные могут содержать удалённые значения, а клиентский код опирается на сгенерированные типы и константы enum. +Это правило проверяет, что из protobuf-пакета не удалено ни одно объявление `enum` (верхнего уровня или вложенное). Удаление enum убирает сгенерированные типы и константы, ломая компиляцию клиентов, которые на него ссылаются. ## Примеры -### Плохой (Breaking) +### Неправильно **До:** + ```proto syntax = "proto3"; @@ -21,9 +22,6 @@ package myapi.v1; enum OrderStatus { ORDER_STATUS_UNSPECIFIED = 0; ORDER_STATUS_PENDING = 1; - ORDER_STATUS_CONFIRMED = 2; - ORDER_STATUS_SHIPPED = 3; - ORDER_STATUS_DELIVERED = 4; } enum UserRole { @@ -31,15 +29,10 @@ enum UserRole { USER_ROLE_ADMIN = 1; USER_ROLE_USER = 2; } - -message Order { - string id = 1; - OrderStatus status = 2; - UserRole created_by_role = 3; -} ``` **После:** + ```proto syntax = "proto3"; @@ -48,81 +41,21 @@ package myapi.v1; enum OrderStatus { ORDER_STATUS_UNSPECIFIED = 0; ORDER_STATUS_PENDING = 1; - ORDER_STATUS_CONFIRMED = 2; - ORDER_STATUS_SHIPPED = 3; - ORDER_STATUS_DELIVERED = 4; } -// UserRole enum удалён — BREAKING CHANGE! - -message Order { - string id = 1; - OrderStatus status = 2; - UserRole created_by_role = 3; // ERROR: UserRole больше не существует -} +// Enum UserRole удалён ``` **Ошибка:** -``` -user.proto:8:1: Previously present enum "UserRole" was deleted from file. (BREAKING_CHECK) -``` -### Дополнительные примеры - -**Удаление вложенного enum:** -```proto -// Before -message User { - string name = 1; - Status status = 2; - - enum Status { - STATUS_UNSPECIFIED = 0; - STATUS_ACTIVE = 1; - STATUS_INACTIVE = 2; - } -} - -// After - BREAKING CHANGE! -message User { - string name = 1; - Status status = 2; // ERROR: Status удалён - - // Вложенный enum Status удалён -} +```text +order.proto:10:1: Enum "myapi.v1.UserRole" was deleted. (ENUM_NO_DELETE) ``` -### Хороший (Безопасный) - -**Вместо удаления — пометить enum deprecated:** -```proto -syntax = "proto3"; - -package myapi.v1; - -enum OrderStatus { - ORDER_STATUS_UNSPECIFIED = 0; - ORDER_STATUS_PENDING = 1; - ORDER_STATUS_CONFIRMED = 2; - ORDER_STATUS_SHIPPED = 3; - ORDER_STATUS_DELIVERED = 4; -} - -enum UserRole { - option deprecated = true; - USER_ROLE_UNSPECIFIED = 0; - USER_ROLE_ADMIN = 1; - USER_ROLE_USER = 2; -} +### Правильно -message Order { - string id = 1; - OrderStatus status = 2; - UserRole created_by_role = 3 [deprecated = true]; -} -``` +Вместо удаления сохраните enum и пометьте его как устаревший в текущей мажорной версии: -**Или заменить новым enum:** ```proto syntax = "proto3"; @@ -131,189 +64,24 @@ package myapi.v1; enum OrderStatus { ORDER_STATUS_UNSPECIFIED = 0; ORDER_STATUS_PENDING = 1; - ORDER_STATUS_CONFIRMED = 2; - ORDER_STATUS_SHIPPED = 3; - ORDER_STATUS_DELIVERED = 4; } enum UserRole { - option deprecated = true; // Старый enum + option deprecated = true; USER_ROLE_UNSPECIFIED = 0; USER_ROLE_ADMIN = 1; USER_ROLE_USER = 2; } -enum UserPermission { // Новый enum +enum UserPermission { USER_PERMISSION_UNSPECIFIED = 0; USER_PERMISSION_READ = 1; USER_PERMISSION_WRITE = 2; - USER_PERMISSION_ADMIN = 3; -} - -message Order { - string id = 1; - OrderStatus status = 2; - UserRole created_by_role = 3 [deprecated = true]; - UserPermission created_by_permission = 4; -} -``` - -## Влияние - -- **Wire Format:** Данные с удалённым enum не десериализуются корректно -- **Generated Code:** Тип и константы удаляются — компиляция клиентов ломается -- **Field References:** Поля с типом удалённого enum становятся невалидны -- **Switch Statements:** `switch` по enum ломается (неизвестные кейсы) - -## Реальный пример - -**Код клиента ломается:** -```go -// Before -order := &myapi.Order{ - Id: "order123", - Status: myapi.OrderStatus_ORDER_STATUS_PENDING, - CreatedByRole: myapi.UserRole_USER_ROLE_ADMIN, // ERROR после удаления -} - -switch order.CreatedByRole { -case myapi.UserRole_USER_ROLE_ADMIN: // ERROR - // Admin logic -case myapi.UserRole_USER_ROLE_USER: // ERROR - // User logic -} - -// undefined: myapi.UserRole -// undefined: myapi.UserRole_USER_ROLE_ADMIN -``` - -**Старые данные становятся нечитаемыми:** -```json -{ - "id": "order123", - "status": "ORDER_STATUS_PENDING", - "created_by_role": "USER_ROLE_ADMIN" -} -// После удаления UserRole — парсер не знает поле created_by_role -``` - -**Серверная логика ломается:** -```go -func validateOrder(order *Order) error { - switch order.CreatedByRole { - case UserRole_USER_ROLE_ADMIN: // ERROR - return nil - case UserRole_USER_ROLE_USER: // ERROR - return validateUserOrder(order) - default: - return errors.New("invalid user role") - } } ``` ## Стратегия миграции -1. **Депрецируйте enum:** - ```proto - enum OldEnum { - option deprecated = true; - // ... - } - ``` -2. **Пометьте поля со старым enum deprecated:** - ```proto - OldEnum old_field = 5 [deprecated = true]; - ``` -3. **Создайте новый enum:** - ```proto - enum NewEnum { - // Улучшенный набор значений - } - NewEnum new_field = 6; - ``` -4. **Сервер обрабатывает оба:** - ```go - func handleRole(oldRole OldEnum, newRole NewEnum) { - if newRole != NEW_ENUM_UNSPECIFIED { - return handleNewRole(newRole) - } - return handleOldRole(oldRole) - } - ``` -5. **Удалите старый enum в следующей major‑версии.** - -## Типовые сценарии - -### Редизайн enum -```proto -enum Priority { - option deprecated = true; - PRIORITY_UNSPECIFIED = 0; - PRIORITY_LOW = 1; - PRIORITY_HIGH = 2; -} - -enum TaskPriority { - TASK_PRIORITY_UNSPECIFIED = 0; - TASK_PRIORITY_LOW = 1; - TASK_PRIORITY_MEDIUM = 2; - TASK_PRIORITY_HIGH = 3; - TASK_PRIORITY_URGENT = 4; -} -``` - -### Консолидация enum -```proto -enum Status { - option deprecated = true; - STATUS_UNSPECIFIED = 0; - STATUS_ACTIVE = 1; -} - -enum State { - option deprecated = true; - STATE_UNSPECIFIED = 0; - STATE_ENABLED = 1; -} - -enum EntityStatus { - ENTITY_STATUS_UNSPECIFIED = 0; - ENTITY_STATUS_ACTIVE = 1; - ENTITY_STATUS_INACTIVE = 2; - ENTITY_STATUS_ENABLED = 3; - ENTITY_STATUS_DISABLED = 4; -} -``` - -### Перемещение enum в новый пакет -```proto -enum UserRole { - option deprecated = true; - USER_ROLE_UNSPECIFIED = 0; - USER_ROLE_ADMIN = 1; -} - -import "common/roles.proto"; - -message Order { - UserRole old_role = 3 [deprecated = true]; - common.UserRole new_role = 4; -} -``` - -### Версионирование / новая версия пакета -```proto -package myapi.v2; - -enum UserPermission { - USER_PERMISSION_UNSPECIFIED = 0; - USER_PERMISSION_READ = 1; - USER_PERMISSION_WRITE = 2; - USER_PERMISSION_ADMIN = 3; -} - -message Order { - string id = 1; - UserPermission created_by_permission = 2; -} -``` +1. Пометьте старый enum опцией `option deprecated = true;` и пометьте устаревшими поля, которые его используют. +2. При необходимости добавьте новый enum рядом со старым. +3. Удалите устаревший enum только в новой мажорной версии пакета (например, `myapi.v2`). diff --git a/content/docs/cli/breaking-changes/rules/enum-same-json-format.mdx b/content/docs/cli/breaking-changes/rules/enum-same-json-format.mdx new file mode 100644 index 0000000..5a816bd --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/enum-same-json-format.mdx @@ -0,0 +1,58 @@ +--- +title: "Enum Same Json Format" +description: "Checks that enums do not downgrade JSON format support from ALLOW to LEGACY_BEST_EFFORT." +--- + +- **Rule ID:** `ENUM_SAME_JSON_FORMAT` +- **Profiles:** `FILE`, `PACKAGE`, `WIRE_JSON` + +This rule checks that an enum whose effective `features.json_format` is `ALLOW` (the default in `proto3` and Editions 2023) does not downgrade to `LEGACY_BEST_EFFORT`. Downgrading weakens guaranteed protobuf JSON compliance in `FILE`, `PACKAGE`, and `WIRE_JSON`. + +## Examples + +### Bad + +**Before:** + +```proto +edition = "2023"; + +package myapi.v1; + +enum Status { + STATUS_UNSPECIFIED = 0; +} +``` + +**After:** + +```proto +edition = "2023"; + +package myapi.v1; + +enum Status { + option features.json_format = LEGACY_BEST_EFFORT; + STATUS_UNSPECIFIED = 0; +} +``` + +**Error:** + +```text +status.proto:5:1: Enum "myapi.v1.Status" changed JSON format support. (ENUM_SAME_JSON_FORMAT) +``` + +### Good + +Keep `features.json_format = ALLOW` (the Editions 2023 default) on enums that already support standard JSON: + +```proto +edition = "2023"; + +package myapi.v1; + +enum Status { + STATUS_UNSPECIFIED = 0; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/enum-same-json-format.ru.mdx b/content/docs/cli/breaking-changes/rules/enum-same-json-format.ru.mdx new file mode 100644 index 0000000..e5237e0 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/enum-same-json-format.ru.mdx @@ -0,0 +1,58 @@ +--- +title: "Enum Same Json Format" +description: "Проверяет, что enum не понижает поддержку формата JSON с ALLOW до LEGACY_BEST_EFFORT." +--- + +- **ID правила:** `ENUM_SAME_JSON_FORMAT` +- **Профили:** `FILE`, `PACKAGE`, `WIRE_JSON` + +Это правило проверяет, что enum с эффективной опцией `features.json_format = ALLOW` (по умолчанию в `proto3` и Editions 2023) не понижает её до `LEGACY_BEST_EFFORT`. Такое понижение нарушает гарантии JSON-формата в профилях `FILE`, `PACKAGE` и `WIRE_JSON`. + +## Примеры + +### Неправильно + +**До:** + +```proto +edition = "2023"; + +package myapi.v1; + +enum Status { + STATUS_UNSPECIFIED = 0; +} +``` + +**После:** + +```proto +edition = "2023"; + +package myapi.v1; + +enum Status { + option features.json_format = LEGACY_BEST_EFFORT; + STATUS_UNSPECIFIED = 0; +} +``` + +**Ошибка:** + +```text +status.proto:5:1: Enum "myapi.v1.Status" changed JSON format support. (ENUM_SAME_JSON_FORMAT) +``` + +### Правильно + +Сохраняйте `features.json_format = ALLOW` (значение по умолчанию в Editions 2023) для enum, уже поддерживающих стандартный JSON: + +```proto +edition = "2023"; + +package myapi.v1; + +enum Status { + STATUS_UNSPECIFIED = 0; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/enum-same-type.mdx b/content/docs/cli/breaking-changes/rules/enum-same-type.mdx new file mode 100644 index 0000000..34bd12b --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/enum-same-type.mdx @@ -0,0 +1,60 @@ +--- +title: "Enum Same Type" +description: "Checks that enums do not switch between open and closed semantics." +--- + +- **Rule ID:** `ENUM_SAME_TYPE` +- **Profiles:** `FILE`, `PACKAGE` + +This rule checks that an enum does not switch between **open** (default in `proto3` and Editions 2023, preserving unrecognized integer values in the field) and **closed** (default in `proto2`, moving unrecognized values to unknown fields and restricting generated types). Changing openness changes runtime handling and generated source semantics in `FILE` and `PACKAGE`. + +## Examples + +### Bad + +**Before:** + +```proto +edition = "2023"; + +package myapi.v1; + +enum Status { + option features.enum_type = OPEN; + STATUS_UNSPECIFIED = 0; +} +``` + +**After:** + +```proto +edition = "2023"; + +package myapi.v1; + +enum Status { + option features.enum_type = CLOSED; + STATUS_UNSPECIFIED = 0; +} +``` + +**Error:** + +```text +status.proto:5:1: Enum "myapi.v1.Status" changed between open and closed semantics. (ENUM_SAME_TYPE) +``` + +### Good + +Preserve the enum `OPEN`/`CLOSED` semantics across releases in the same major version: + +```proto +edition = "2023"; + +package myapi.v1; + +enum Status { + option features.enum_type = OPEN; + STATUS_UNSPECIFIED = 0; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/enum-same-type.ru.mdx b/content/docs/cli/breaking-changes/rules/enum-same-type.ru.mdx new file mode 100644 index 0000000..c474b77 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/enum-same-type.ru.mdx @@ -0,0 +1,60 @@ +--- +title: "Enum Same Type" +description: "Проверяет, что enum не переключается между открытой (open) и закрытой (closed) семантикой." +--- + +- **ID правила:** `ENUM_SAME_TYPE` +- **Профили:** `FILE`, `PACKAGE` + +Это правило проверяет, что enum не переключается между **открытой** (по умолчанию в `proto3` и Editions 2023 — неизвестные числа сохраняются в самом поле) и **закрытой** семантикой (по умолчанию в `proto2` — неизвестные числа уходят в unknown fields). Смена типа enum меняет рантайм-поведение и сгенерированный код в профилях `FILE` и `PACKAGE`. + +## Примеры + +### Неправильно + +**До:** + +```proto +edition = "2023"; + +package myapi.v1; + +enum Status { + option features.enum_type = OPEN; + STATUS_UNSPECIFIED = 0; +} +``` + +**После:** + +```proto +edition = "2023"; + +package myapi.v1; + +enum Status { + option features.enum_type = CLOSED; + STATUS_UNSPECIFIED = 0; +} +``` + +**Ошибка:** + +```text +status.proto:5:1: Enum "myapi.v1.Status" changed between open and closed semantics. (ENUM_SAME_TYPE) +``` + +### Правильно + +Сохраняйте семантику `OPEN`/`CLOSED` неизменной в рамках текущей мажорной версии: + +```proto +edition = "2023"; + +package myapi.v1; + +enum Status { + option features.enum_type = OPEN; + STATUS_UNSPECIFIED = 0; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/enum-value-no-delete-unless-name-reserved.mdx b/content/docs/cli/breaking-changes/rules/enum-value-no-delete-unless-name-reserved.mdx new file mode 100644 index 0000000..3eef6d2 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/enum-value-no-delete-unless-name-reserved.mdx @@ -0,0 +1,64 @@ +--- +title: "Enum Value No Delete Unless Name Reserved" +description: "Checks that any enum value deleted in WIRE_JSON has its name reserved." +--- + +- **Rule ID:** `ENUM_VALUE_NO_DELETE_UNLESS_NAME_RESERVED` +- **Profiles:** `WIRE_JSON` + +In the `WIRE_JSON` profile, deleting an enum value is permitted only if its number is reserved (checked by `ENUM_VALUE_NO_DELETE_UNLESS_NUMBER_RESERVED`) **and** its name is reserved with `reserved "NAME";`. Reserving the name prevents reusing it later for a different numeric value in JSON payloads. + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +enum Color { + COLOR_UNSPECIFIED = 0; + COLOR_RED = 1; + COLOR_BLUE = 2; +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +enum Color { + reserved 2; + COLOR_UNSPECIFIED = 0; + COLOR_RED = 1; +} +``` + +**Error:** + +```text +color.proto:5:1: Deleted enum name "COLOR_BLUE" in "myapi.v1.Color" must be reserved for JSON compatibility. (ENUM_VALUE_NO_DELETE_UNLESS_NAME_RESERVED) +``` + +### Good + +Reserve both the deleted enum number and its name: + +```proto +syntax = "proto3"; + +package myapi.v1; + +enum Color { + reserved 2; + reserved "COLOR_BLUE"; + COLOR_UNSPECIFIED = 0; + COLOR_RED = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/enum-value-no-delete-unless-name-reserved.ru.mdx b/content/docs/cli/breaking-changes/rules/enum-value-no-delete-unless-name-reserved.ru.mdx new file mode 100644 index 0000000..5e38854 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/enum-value-no-delete-unless-name-reserved.ru.mdx @@ -0,0 +1,64 @@ +--- +title: "Enum Value No Delete Unless Name Reserved" +description: "Проверяет, что при удалении значения enum в профиле WIRE_JSON его имя зарезервировано." +--- + +- **ID правила:** `ENUM_VALUE_NO_DELETE_UNLESS_NAME_RESERVED` +- **Профили:** `WIRE_JSON` + +В профиле `WIRE_JSON` удаление значения enum допускается только при одновременном резервировании его номера (правило `ENUM_VALUE_NO_DELETE_UNLESS_NUMBER_RESERVED`) **и** его имени через `reserved "NAME";`. Это предотвращает повторное использование того же имени для другого числа в JSON. + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +enum Color { + COLOR_UNSPECIFIED = 0; + COLOR_RED = 1; + COLOR_BLUE = 2; +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +enum Color { + reserved 2; + COLOR_UNSPECIFIED = 0; + COLOR_RED = 1; +} +``` + +**Ошибка:** + +```text +color.proto:5:1: Deleted enum name "COLOR_BLUE" in "myapi.v1.Color" must be reserved for JSON compatibility. (ENUM_VALUE_NO_DELETE_UNLESS_NAME_RESERVED) +``` + +### Правильно + +Зарезервируйте и номер, и имя удалённого значения enum: + +```proto +syntax = "proto3"; + +package myapi.v1; + +enum Color { + reserved 2; + reserved "COLOR_BLUE"; + COLOR_UNSPECIFIED = 0; + COLOR_RED = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/enum-value-no-delete-unless-number-reserved.mdx b/content/docs/cli/breaking-changes/rules/enum-value-no-delete-unless-number-reserved.mdx new file mode 100644 index 0000000..9100bf2 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/enum-value-no-delete-unless-number-reserved.mdx @@ -0,0 +1,63 @@ +--- +title: "Enum Value No Delete Unless Number Reserved" +description: "Checks that any enum value deleted in WIRE or WIRE_JSON has its number reserved." +--- + +- **Rule ID:** `ENUM_VALUE_NO_DELETE_UNLESS_NUMBER_RESERVED` +- **Profiles:** `WIRE_JSON`, `WIRE` + +In `WIRE` and `WIRE_JSON` profiles, deleting an enum value (when no remaining alias keeps that number) requires permanently reserving its number with `reserved ;` so future values cannot reuse the same wire number with a different meaning. + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +enum Color { + COLOR_UNSPECIFIED = 0; + COLOR_RED = 1; + COLOR_BLUE = 2; +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +enum Color { + COLOR_UNSPECIFIED = 0; + COLOR_RED = 1; +} +``` + +**Error:** + +```text +color.proto:5:1: Deleted enum number 2 in "myapi.v1.Color" must be reserved. (ENUM_VALUE_NO_DELETE_UNLESS_NUMBER_RESERVED) +``` + +### Good + +Reserve the deleted enum value number (and its name if using `WIRE_JSON`): + +```proto +syntax = "proto3"; + +package myapi.v1; + +enum Color { + reserved 2; + reserved "COLOR_BLUE"; + COLOR_UNSPECIFIED = 0; + COLOR_RED = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/enum-value-no-delete-unless-number-reserved.ru.mdx b/content/docs/cli/breaking-changes/rules/enum-value-no-delete-unless-number-reserved.ru.mdx new file mode 100644 index 0000000..f984b93 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/enum-value-no-delete-unless-number-reserved.ru.mdx @@ -0,0 +1,63 @@ +--- +title: "Enum Value No Delete Unless Number Reserved" +description: "Проверяет, что при удалении значения enum в профилях WIRE или WIRE_JSON его номер зарезервирован." +--- + +- **ID правила:** `ENUM_VALUE_NO_DELETE_UNLESS_NUMBER_RESERVED` +- **Профили:** `WIRE_JSON`, `WIRE` + +В профилях `WIRE` и `WIRE_JSON` удаление значения enum (если не осталось алиаса с тем же номером) требует постоянного резервирования его номера через `reserved ;`, чтобы этот номер не был повторно использован с другим смыслом. + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +enum Color { + COLOR_UNSPECIFIED = 0; + COLOR_RED = 1; + COLOR_BLUE = 2; +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +enum Color { + COLOR_UNSPECIFIED = 0; + COLOR_RED = 1; +} +``` + +**Ошибка:** + +```text +color.proto:5:1: Deleted enum number 2 in "myapi.v1.Color" must be reserved. (ENUM_VALUE_NO_DELETE_UNLESS_NUMBER_RESERVED) +``` + +### Правильно + +Зарезервируйте номер удалённого значения enum (и его имя при использовании `WIRE_JSON`): + +```proto +syntax = "proto3"; + +package myapi.v1; + +enum Color { + reserved 2; + reserved "COLOR_BLUE"; + COLOR_UNSPECIFIED = 0; + COLOR_RED = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/enum-value-no-delete.mdx b/content/docs/cli/breaking-changes/rules/enum-value-no-delete.mdx index d8165fe..544cd8c 100644 --- a/content/docs/cli/breaking-changes/rules/enum-value-no-delete.mdx +++ b/content/docs/cli/breaking-changes/rules/enum-value-no-delete.mdx @@ -1,18 +1,23 @@ --- title: "Enum Value No Delete" +description: "Checks that no enum values are deleted in source-compatibility profiles." --- -Categories: +- **Rule ID:** `ENUM_VALUE_NO_DELETE` +- **Profiles:** `FILE`, `PACKAGE` -- **WIRE+** +This rule checks that no enum values are deleted from an enum. Deleting an enum value removes the corresponding generated constant and breaks client code that references it (such as `switch` statements or comparisons). -This rule checks that no enum values are deleted from enums. Deleting an enum value breaks both wire format compatibility and generated code, as existing data may contain the deleted enum value and client code may reference the generated constants. + +Adding `reserved` for a deleted enum number or name does **not** satisfy `ENUM_VALUE_NO_DELETE` in `FILE` or `PACKAGE` profiles, because generated source constants are still removed. Reserving deleted enum numbers (and names for JSON) only satisfies [`ENUM_VALUE_NO_DELETE_UNLESS_NUMBER_RESERVED`](/docs/cli/breaking-changes/rules/enum-value-no-delete-unless-number-reserved) (`WIRE`, `WIRE_JSON`) and [`ENUM_VALUE_NO_DELETE_UNLESS_NAME_RESERVED`](/docs/cli/breaking-changes/rules/enum-value-no-delete-unless-name-reserved) (`WIRE_JSON`). + ## Examples ### Bad **Before:** + ```proto syntax = "proto3"; @@ -22,313 +27,52 @@ enum OrderStatus { ORDER_STATUS_UNSPECIFIED = 0; ORDER_STATUS_PENDING = 1; ORDER_STATUS_CONFIRMED = 2; - ORDER_STATUS_SHIPPED = 3; - ORDER_STATUS_DELIVERED = 4; ORDER_STATUS_CANCELLED = 5; } - -enum Priority { - PRIORITY_UNSPECIFIED = 0; - PRIORITY_LOW = 1; - PRIORITY_MEDIUM = 2; - PRIORITY_HIGH = 3; - PRIORITY_URGENT = 4; -} ``` **After:** + ```proto syntax = "proto3"; package myapi.v1; enum OrderStatus { + reserved 5; + reserved "ORDER_STATUS_CANCELLED"; + ORDER_STATUS_UNSPECIFIED = 0; ORDER_STATUS_PENDING = 1; ORDER_STATUS_CONFIRMED = 2; - ORDER_STATUS_SHIPPED = 3; - ORDER_STATUS_DELIVERED = 4; - // ORDER_STATUS_CANCELLED = 5; // Deleted enum value - BREAKING! -} - -enum Priority { - PRIORITY_UNSPECIFIED = 0; - PRIORITY_LOW = 1; - PRIORITY_MEDIUM = 2; - PRIORITY_HIGH = 3; - // PRIORITY_URGENT = 4; // Deleted enum value - BREAKING! } ``` **Error:** -``` -order.proto:9:3: Previously present enum value "5" on enum "OrderStatus" was deleted. (BREAKING_CHECK) -priority.proto:8:3: Previously present enum value "4" on enum "Priority" was deleted. (BREAKING_CHECK) -``` -### More Examples - -**Multiple value deletions:** - -```proto -// Before -enum UserRole { - USER_ROLE_UNSPECIFIED = 0; - USER_ROLE_GUEST = 1; - USER_ROLE_USER = 2; - USER_ROLE_MODERATOR = 3; - USER_ROLE_ADMIN = 4; - USER_ROLE_SUPERADMIN = 5; -} - -// After - BREAKING CHANGES! -enum UserRole { - USER_ROLE_UNSPECIFIED = 0; - USER_ROLE_USER = 2; - USER_ROLE_ADMIN = 4; - // USER_ROLE_GUEST = 1; // BREAKING: deleted - // USER_ROLE_MODERATOR = 3; // BREAKING: deleted - // USER_ROLE_SUPERADMIN = 5; // BREAKING: deleted -} +```text +order.proto:5:1: Enum value "ORDER_STATUS_CANCELLED" = 5 in "myapi.v1.OrderStatus" was deleted. (ENUM_VALUE_NO_DELETE) ``` ### Good -**Instead of deleting, deprecate the enum values:** -```proto -syntax = "proto3"; +Keep the enum value and mark it deprecated instead of deleting it in `FILE`/`PACKAGE` profiles: -package myapi.v1; - -enum OrderStatus { - ORDER_STATUS_UNSPECIFIED = 0; - ORDER_STATUS_PENDING = 1; - ORDER_STATUS_CONFIRMED = 2; - ORDER_STATUS_SHIPPED = 3; - ORDER_STATUS_DELIVERED = 4; - ORDER_STATUS_CANCELLED = 5 [deprecated = true]; -} - -enum Priority { - PRIORITY_UNSPECIFIED = 0; - PRIORITY_LOW = 1; - PRIORITY_MEDIUM = 2; - PRIORITY_HIGH = 3; - PRIORITY_URGENT = 4 [deprecated = true]; -} -``` - -**Or reserve the enum values after removal:** ```proto syntax = "proto3"; package myapi.v1; enum OrderStatus { - reserved 5; - reserved "ORDER_STATUS_CANCELLED"; - ORDER_STATUS_UNSPECIFIED = 0; ORDER_STATUS_PENDING = 1; ORDER_STATUS_CONFIRMED = 2; - ORDER_STATUS_SHIPPED = 3; - ORDER_STATUS_DELIVERED = 4; -} - -enum Priority { - reserved 4; - reserved "PRIORITY_URGENT"; - - PRIORITY_UNSPECIFIED = 0; - PRIORITY_LOW = 1; - PRIORITY_MEDIUM = 2; - PRIORITY_HIGH = 3; -} -``` - -## Impact - -- **Wire Format:** Existing data with deleted enum values cannot be properly deserialized -- **Generated Code:** Enum constants are removed, breaking client compilation -- **Client Applications:** Code referencing deleted enum values fails to compile -- **Switch Statements:** Case statements for deleted values cause compilation errors -- **Default Handling:** Unknown enum values may be handled differently - -## Real-World Example - -**Client code breaks:** -```go -// Before - this code works -order := &myapi.Order{ - Status: myapi.OrderStatus_ORDER_STATUS_CANCELLED, // ERROR after deletion -} - -// Switch statement breaks -switch order.Status { -case myapi.OrderStatus_ORDER_STATUS_PENDING: - // Handle pending -case myapi.OrderStatus_ORDER_STATUS_CANCELLED: // ERROR: undefined constant - // Handle cancellation -default: - // Handle unknown -} - -// Generated code compilation fails: -// undefined: myapi.OrderStatus_ORDER_STATUS_CANCELLED -``` - -**Existing data becomes problematic:** -```json -// Serialized data before deletion -{ - "id": "order123", - "status": "ORDER_STATUS_CANCELLED" -} - -// After enum value deletion -// Data deserializes but status becomes UNSPECIFIED (0) -// or causes parsing errors depending on implementation -``` - -**Server validation breaks:** -```go -// Before - server handles all enum values -func validateOrderStatus(status OrderStatus) error { - switch status { - case OrderStatus_ORDER_STATUS_PENDING, - OrderStatus_ORDER_STATUS_CONFIRMED, - OrderStatus_ORDER_STATUS_SHIPPED, - OrderStatus_ORDER_STATUS_DELIVERED, - OrderStatus_ORDER_STATUS_CANCELLED: // ERROR: undefined - return nil - default: - return errors.New("invalid order status") - } -} - -// Server logic that depends on cancelled status -func canModifyOrder(order *Order) bool { - return order.Status != OrderStatus_ORDER_STATUS_CANCELLED // ERROR: undefined + ORDER_STATUS_CANCELLED = 5 [deprecated = true]; } ``` ## Migration Strategy -1. **Deprecate enum values first:** - ```proto - ORDER_STATUS_CANCELLED = 5 [deprecated = true]; - ``` - -2. **Stop using deprecated values** in new code: - ```go - // Don't set deprecated values in new code - order.Status = OrderStatus_ORDER_STATUS_DELIVERED // Use alternative - ``` - -3. **Update client code** to handle deprecated values gracefully: - ```go - switch order.Status { - case OrderStatus_ORDER_STATUS_CANCELLED: - // Handle legacy cancelled orders - log.Warn("Processing deprecated cancelled status") - // Convert to new status or handle specially - } - ``` - -4. **Reserve the values** after sufficient migration period: - ```proto - reserved 5, "ORDER_STATUS_CANCELLED"; - ``` - -5. **Never reuse enum numbers** - they must remain reserved permanently - -## Common Scenarios - -### Business Logic Changes -```proto -// Instead of deleting discontinued status -enum ProductStatus { - PRODUCT_STATUS_UNSPECIFIED = 0; - PRODUCT_STATUS_ACTIVE = 1; - PRODUCT_STATUS_INACTIVE = 2; - // PRODUCT_STATUS_DISCONTINUED = 3; // Don't delete! - - // Better approach: - PRODUCT_STATUS_DISCONTINUED = 3 [deprecated = true]; -} -``` - -### Workflow Simplification -```proto -// Instead of removing intermediate states -enum TaskStatus { - TASK_STATUS_UNSPECIFIED = 0; - TASK_STATUS_TODO = 1; - TASK_STATUS_IN_PROGRESS = 2; - // TASK_STATUS_IN_REVIEW = 3; // Don't delete intermediate states! - // TASK_STATUS_APPROVED = 4; // Don't delete! - TASK_STATUS_DONE = 5; - - // Better approach: - TASK_STATUS_IN_REVIEW = 3 [deprecated = true]; - TASK_STATUS_APPROVED = 4 [deprecated = true]; -} -``` - -### Enum Consolidation -```proto -// When merging similar enum values -enum NotificationLevel { - NOTIFICATION_LEVEL_UNSPECIFIED = 0; - NOTIFICATION_LEVEL_INFO = 1; - NOTIFICATION_LEVEL_WARNING = 2; - NOTIFICATION_LEVEL_ERROR = 3; - // Don't delete these even if consolidating: - NOTIFICATION_LEVEL_DEBUG = 4 [deprecated = true]; // Keep deprecated - NOTIFICATION_LEVEL_TRACE = 5 [deprecated = true]; // Keep deprecated -} -``` - -## Wire Format Considerations - -### Enum Value Reuse Prevention -```proto -enum Status { - // Never reuse numbers, even after deletion - reserved 2; // Was STATUS_DELETED, now reserved forever - reserved "STATUS_DELETED"; - - STATUS_UNSPECIFIED = 0; - STATUS_ACTIVE = 1; - // STATUS_DELETED = 2; // This number can never be reused - STATUS_INACTIVE = 3; -} -``` - -### JSON Compatibility -```proto -// JSON uses enum names, so both number and name should be reserved -enum Color { - reserved 2; // Reserve the number - reserved "RED"; // Reserve the name for JSON compatibility - - COLOR_UNSPECIFIED = 0; - COLOR_BLUE = 1; - // COLOR_RED = 2; // Was deleted, now reserved - COLOR_GREEN = 3; -} -``` - -### Proto2 vs Proto3 Behavior -```proto -// Proto2: Unknown enum values are preserved in unknown fields -// Proto3: Unknown enum values are preserved as-is -// Both cases: Don't delete values that might exist in stored data - -// Safe approach for both syntax versions: -enum MyEnum { - MY_ENUM_UNSPECIFIED = 0; - MY_ENUM_VALUE_OLD = 1 [deprecated = true]; // Don't delete - MY_ENUM_VALUE_NEW = 2; -} -``` +1. Deprecate the enum value with `[deprecated = true]` and stop producing it in new code. +2. Keep handling the deprecated value while existing stored data or older clients still use it. +3. If your policy uses `WIRE` or `WIRE_JSON`, reserve the deleted number (and name for `WIRE_JSON`) when removing the value; if your policy uses `FILE` or `PACKAGE`, remove it only in a new major package version (for example, `myapi.v2`). diff --git a/content/docs/cli/breaking-changes/rules/enum-value-no-delete.ru.mdx b/content/docs/cli/breaking-changes/rules/enum-value-no-delete.ru.mdx index c92253a..9375bc1 100644 --- a/content/docs/cli/breaking-changes/rules/enum-value-no-delete.ru.mdx +++ b/content/docs/cli/breaking-changes/rules/enum-value-no-delete.ru.mdx @@ -1,18 +1,23 @@ --- title: "Enum Value No Delete" +description: "Проверяет, что ни одно значение enum не было удалено в профилях совместимости исходного кода." --- -Категории: +- **ID правила:** `ENUM_VALUE_NO_DELETE` +- **Профили:** `FILE`, `PACKAGE` -- **WIRE+** +Это правило проверяет, что из `enum` не удалено ни одно значение. Удаление значения enum убирает соответствующую сгенерированную константу и ломает клиентский код (например, ветки `switch` и сравнения). -Правило проверяет, что ни одно значение enum (enum value) не было удалено. Удаление значения ломает совместимость по wire‑формату и сгенерированный код: в уже сохранённых данных могут присутствовать удалённые значения, а клиентский код может ссылаться на соответствующие константы. + +Директива `reserved` для удалённого номера или имени **не** удовлетворяет `ENUM_VALUE_NO_DELETE` в профилях `FILE` и `PACKAGE`, поскольку сгенерированная константа всё равно исчезает. Резервирование номера (и имени для JSON) достаточно только для [`ENUM_VALUE_NO_DELETE_UNLESS_NUMBER_RESERVED`](/ru/docs/cli/breaking-changes/rules/enum-value-no-delete-unless-number-reserved) (`WIRE`, `WIRE_JSON`) и [`ENUM_VALUE_NO_DELETE_UNLESS_NAME_RESERVED`](/ru/docs/cli/breaking-changes/rules/enum-value-no-delete-unless-name-reserved) (`WIRE_JSON`). + ## Примеры -### Плохой (Breaking) +### Неправильно **До:** + ```proto syntax = "proto3"; @@ -22,278 +27,52 @@ enum OrderStatus { ORDER_STATUS_UNSPECIFIED = 0; ORDER_STATUS_PENDING = 1; ORDER_STATUS_CONFIRMED = 2; - ORDER_STATUS_SHIPPED = 3; - ORDER_STATUS_DELIVERED = 4; ORDER_STATUS_CANCELLED = 5; } - -enum Priority { - PRIORITY_UNSPECIFIED = 0; - PRIORITY_LOW = 1; - PRIORITY_MEDIUM = 2; - PRIORITY_HIGH = 3; - PRIORITY_URGENT = 4; -} ``` **После:** + ```proto syntax = "proto3"; package myapi.v1; enum OrderStatus { + reserved 5; + reserved "ORDER_STATUS_CANCELLED"; + ORDER_STATUS_UNSPECIFIED = 0; ORDER_STATUS_PENDING = 1; ORDER_STATUS_CONFIRMED = 2; - ORDER_STATUS_SHIPPED = 3; - ORDER_STATUS_DELIVERED = 4; - // ORDER_STATUS_CANCELLED = 5; // Удалено значение enum — BREAKING! -} - -enum Priority { - PRIORITY_UNSPECIFIED = 0; - PRIORITY_LOW = 1; - PRIORITY_MEDIUM = 2; - PRIORITY_HIGH = 3; - // PRIORITY_URGENT = 4; // Удалено значение enum — BREAKING! } ``` **Ошибка:** -``` -order.proto:9:3: Previously present enum value "5" on enum "OrderStatus" was deleted. (BREAKING_CHECK) -priority.proto:8:3: Previously present enum value "4" on enum "Priority" was deleted. (BREAKING_CHECK) -``` -### Дополнительные примеры - -**Множественное удаление значений:** -```proto -// Before -enum UserRole { - USER_ROLE_UNSPECIFIED = 0; - USER_ROLE_GUEST = 1; - USER_ROLE_USER = 2; - USER_ROLE_MODERATOR = 3; - USER_ROLE_ADMIN = 4; - USER_ROLE_SUPERADMIN = 5; -} - -// After - BREAKING CHANGES! -enum UserRole { - USER_ROLE_UNSPECIFIED = 0; - USER_ROLE_USER = 2; - USER_ROLE_ADMIN = 4; - // USER_ROLE_GUEST = 1; // BREAKING: deleted - // USER_ROLE_MODERATOR = 3; // BREAKING: deleted - // USER_ROLE_SUPERADMIN = 5; // BREAKING: deleted -} +```text +order.proto:5:1: Enum value "ORDER_STATUS_CANCELLED" = 5 in "myapi.v1.OrderStatus" was deleted. (ENUM_VALUE_NO_DELETE) ``` -### Хороший (Безопасный) +### Правильно -**Вместо удаления — пометить значения deprecated:** -```proto -syntax = "proto3"; +В профилях `FILE` и `PACKAGE` оставьте значение и пометьте его как `deprecated`: -package myapi.v1; - -enum OrderStatus { - ORDER_STATUS_UNSPECIFIED = 0; - ORDER_STATUS_PENDING = 1; - ORDER_STATUS_CONFIRMED = 2; - ORDER_STATUS_SHIPPED = 3; - ORDER_STATUS_DELIVERED = 4; - ORDER_STATUS_CANCELLED = 5 [deprecated = true]; -} - -enum Priority { - PRIORITY_UNSPECIFIED = 0; - PRIORITY_LOW = 1; - PRIORITY_MEDIUM = 2; - PRIORITY_HIGH = 3; - PRIORITY_URGENT = 4 [deprecated = true]; -} -``` - -**Или зарезервировать номер и имя после удаления:** ```proto syntax = "proto3"; package myapi.v1; enum OrderStatus { - reserved 5; - reserved "ORDER_STATUS_CANCELLED"; - ORDER_STATUS_UNSPECIFIED = 0; ORDER_STATUS_PENDING = 1; ORDER_STATUS_CONFIRMED = 2; - ORDER_STATUS_SHIPPED = 3; - ORDER_STATUS_DELIVERED = 4; -} - -enum Priority { - reserved 4; - reserved "PRIORITY_URGENT"; - - PRIORITY_UNSPECIFIED = 0; - PRIORITY_LOW = 1; - PRIORITY_MEDIUM = 2; - PRIORITY_HIGH = 3; -} -``` - -## Влияние - -- **Wire Format:** Данные с удалёнными значениями не десериализуются корректно -- **Generated Code:** Константы исчезают — клиентский код не компилируется -- **Client Applications:** Ссылки на удалённые значения вызывают ошибки компиляции -- **Switch Statements:** `switch` по enum ломается (неизвестные case) -- **Default Handling:** Поведение при неизвестных значениях меняется - -## Реальный пример - -**Код клиента ломается:** -```go -order := &myapi.Order{ - Status: myapi.OrderStatus_ORDER_STATUS_CANCELLED, // ERROR после удаления -} - -switch order.Status { -case myapi.OrderStatus_ORDER_STATUS_PENDING: - // Pending -case myapi.OrderStatus_ORDER_STATUS_CANCELLED: // ERROR: undefined - // Cancellation -default: - // Unknown -} -// undefined: myapi.OrderStatus_ORDER_STATUS_CANCELLED -``` - -**Проблемы с уже сохранёнными данными:** -```json -{ - "id": "order123", - "status": "ORDER_STATUS_CANCELLED" -} -// После удаления: парсер даёт UNSPECIFIED (0) или ошибку -``` - -**Валидация на сервере:** -```go -func validateOrderStatus(status OrderStatus) error { - switch status { - case OrderStatus_ORDER_STATUS_PENDING, - OrderStatus_ORDER_STATUS_CONFIRMED, - OrderStatus_ORDER_STATUS_SHIPPED, - OrderStatus_ORDER_STATUS_DELIVERED, - OrderStatus_ORDER_STATUS_CANCELLED: // ERROR после удаления - return nil - default: - return errors.New("invalid order status") - } -} - -func canModifyOrder(order *Order) bool { - return order.Status != OrderStatus_ORDER_STATUS_CANCELLED // ERROR + ORDER_STATUS_CANCELLED = 5 [deprecated = true]; } ``` ## Стратегия миграции -1. **Сначала пометить deprecated:** - ```proto - ORDER_STATUS_CANCELLED = 5 [deprecated = true]; - ``` -2. **Перестать использовать deprecated значение в новом коде:** - ```go - order.Status = OrderStatus_ORDER_STATUS_DELIVERED - ``` -3. **Обработка legacy в клиенте:** - ```go - switch order.Status { - case OrderStatus_ORDER_STATUS_CANCELLED: - log.Warn("Legacy cancelled status") - // Дополнительная логика - } - ``` -4. **Резервирование после миграции:** - ```proto - reserved 5, "ORDER_STATUS_CANCELLED"; - ``` -5. **Никогда не переиспользовать номера** — зарезервированы навсегда. - -## Типовые сценарии - -### Изменения бизнес‑логики -```proto -enum ProductStatus { - PRODUCT_STATUS_UNSPECIFIED = 0; - PRODUCT_STATUS_ACTIVE = 1; - PRODUCT_STATUS_INACTIVE = 2; - PRODUCT_STATUS_DISCONTINUED = 3 [deprecated = true]; -} -``` - -### Упрощение workflow -```proto -enum TaskStatus { - TASK_STATUS_UNSPECIFIED = 0; - TASK_STATUS_TODO = 1; - TASK_STATUS_IN_PROGRESS = 2; - TASK_STATUS_IN_REVIEW = 3 [deprecated = true]; - TASK_STATUS_APPROVED = 4 [deprecated = true]; - TASK_STATUS_DONE = 5; -} -``` - -### Объединение enum -```proto -enum NotificationLevel { - NOTIFICATION_LEVEL_UNSPECIFIED = 0; - NOTIFICATION_LEVEL_INFO = 1; - NOTIFICATION_LEVEL_WARNING = 2; - NOTIFICATION_LEVEL_ERROR = 3; - NOTIFICATION_LEVEL_DEBUG = 4 [deprecated = true]; - NOTIFICATION_LEVEL_TRACE = 5 [deprecated = true]; -} -``` - -## Особенности wire‑формата - -### Предотвращение переиспользования номера -```proto -enum Status { - reserved 2; - reserved "STATUS_DELETED"; - - STATUS_UNSPECIFIED = 0; - STATUS_ACTIVE = 1; - STATUS_INACTIVE = 3; - // STATUS_DELETED = 2; // Не переиспользуем -} -``` - -### JSON совместимость -```proto -enum Color { - reserved 2; - reserved "RED"; - - COLOR_UNSPECIFIED = 0; - COLOR_BLUE = 1; - COLOR_GREEN = 3; - // COLOR_RED = 2; // Был удалён -} -``` - -### Proto2 vs Proto3 -```proto -enum MyEnum { - MY_ENUM_UNSPECIFIED = 0; - MY_ENUM_VALUE_OLD = 1 [deprecated = true]; - MY_ENUM_VALUE_NEW = 2; -} -``` +1. Пометьте значение опцией `[deprecated = true]` и перестаньте записывать его в новом коде. +2. Продолжайте обрабатывать старое значение, пока оно встречается в сохранённых данных или старых клиентах. +3. При использовании профилей `WIRE`/`WIRE_JSON` зарезервируйте номер (и имя для `WIRE_JSON`) при удалении значения; для `FILE`/`PACKAGE` удаляйте значение только в новой мажорной версии пакета (например, `myapi.v2`). diff --git a/content/docs/cli/breaking-changes/rules/enum-value-same-name.mdx b/content/docs/cli/breaking-changes/rules/enum-value-same-name.mdx index 449c8c3..b7af65b 100644 --- a/content/docs/cli/breaking-changes/rules/enum-value-same-name.mdx +++ b/content/docs/cli/breaking-changes/rules/enum-value-same-name.mdx @@ -1,18 +1,19 @@ --- title: "Enum Value Same Name" +description: "Checks that existing enum values keep the same name for each number." --- -Categories: +- **Rule ID:** `ENUM_VALUE_SAME_NAME` +- **Profiles:** `FILE`, `PACKAGE`, `WIRE_JSON` -- **WIRE+** - -This rule checks that enum values maintain the same name for each number. Changing an enum value's name (while keeping the same number) breaks both JSON compatibility and generated code, as clients expect specific constant names. +This rule checks that existing enum `(name, number)` pairs are not renamed. Changing an enum value's name breaks generated constants and protobuf JSON serialization (which uses enum value names). In the `WIRE` profile, enum values are encoded by number only, so renaming is not flagged there. ## Examples ### Bad **Before:** + ```proto syntax = "proto3"; @@ -22,12 +23,11 @@ enum OrderStatus { ORDER_STATUS_UNSPECIFIED = 0; ORDER_STATUS_PENDING = 1; ORDER_STATUS_CONFIRMED = 2; - ORDER_STATUS_SHIPPED = 3; - ORDER_STATUS_DELIVERED = 4; } ``` **After:** + ```proto syntax = "proto3"; @@ -36,43 +36,20 @@ package myapi.v1; enum OrderStatus { ORDER_STATUS_UNSPECIFIED = 0; ORDER_STATUS_PENDING = 1; - ORDER_STATUS_APPROVED = 2; // Changed from ORDER_STATUS_CONFIRMED - ORDER_STATUS_SHIPPED = 3; - ORDER_STATUS_COMPLETED = 4; // Changed from ORDER_STATUS_DELIVERED + ORDER_STATUS_APPROVED = 2; // Renamed from ORDER_STATUS_CONFIRMED } ``` **Error:** -``` -order.proto:7:3: Enum value "2" on enum "OrderStatus" changed name from "ORDER_STATUS_CONFIRMED" to "ORDER_STATUS_APPROVED". (BREAKING_CHECK) -order.proto:9:3: Enum value "4" on enum "OrderStatus" changed name from "ORDER_STATUS_DELIVERED" to "ORDER_STATUS_COMPLETED". (BREAKING_CHECK) -``` - -### More Examples -**Multiple renames breaking clients:** - -```proto -// Before -enum UserRole { - USER_ROLE_UNSPECIFIED = 0; - USER_ROLE_ADMIN = 1; - USER_ROLE_MODERATOR = 2; - USER_ROLE_USER = 3; -} - -// After - ALL BREAKING CHANGES! -enum UserRole { - USER_ROLE_UNSPECIFIED = 0; - USER_ROLE_ADMINISTRATOR = 1; // BREAKING: ADMIN -> ADMINISTRATOR - USER_ROLE_MOD = 2; // BREAKING: MODERATOR -> MOD - USER_ROLE_MEMBER = 3; // BREAKING: USER -> MEMBER -} +```text +order.proto:5:1: Enum value "ORDER_STATUS_CONFIRMED" at number 2 in "myapi.v1.OrderStatus" changed name to "ORDER_STATUS_APPROVED". (ENUM_VALUE_SAME_NAME) ``` ### Good -**Instead of renaming, add new values and deprecate old ones:** +Add a new enum value and deprecate the old one: + ```proto syntax = "proto3"; @@ -82,94 +59,22 @@ enum OrderStatus { ORDER_STATUS_UNSPECIFIED = 0; ORDER_STATUS_PENDING = 1; ORDER_STATUS_CONFIRMED = 2 [deprecated = true]; - ORDER_STATUS_SHIPPED = 3; - ORDER_STATUS_DELIVERED = 4 [deprecated = true]; - ORDER_STATUS_APPROVED = 5; // New value instead of renaming - ORDER_STATUS_COMPLETED = 6; // New value instead of renaming + ORDER_STATUS_APPROVED = 3; } ``` -**Or create a new enum version:** +Or keep the original `(name, number)` pair alongside an alias when `option allow_alias = true;` is permitted in your project (note that the lint rule [`ENUM_NO_ALLOW_ALIAS`](/docs/cli/linter/rules/enum-no-allow-alias) discourages aliases): + ```proto syntax = "proto3"; -package myapi.v2; // New package version +package myapi.v1; enum OrderStatus { + option allow_alias = true; ORDER_STATUS_UNSPECIFIED = 0; ORDER_STATUS_PENDING = 1; - ORDER_STATUS_APPROVED = 2; // Clean names in v2 - ORDER_STATUS_SHIPPED = 3; - ORDER_STATUS_COMPLETED = 4; -} -``` - -## Impact - -- **Generated Code:** Constant names change, breaking client compilation -- **JSON Compatibility:** JSON serialization uses enum names, breaking parsers -- **Client Applications:** Code referencing old constant names fails to compile -- **Documentation:** API docs become outdated with wrong enum names - -## Real-World Example - -**Client code breaks:** -```go -// Before - this code works -status := myapi.OrderStatus_ORDER_STATUS_CONFIRMED -if order.Status == myapi.OrderStatus_ORDER_STATUS_DELIVERED { - // handle delivery -} - -// After rename - compilation fails -status := myapi.OrderStatus_ORDER_STATUS_CONFIRMED // ERROR: undefined constant -if order.Status == myapi.OrderStatus_ORDER_STATUS_DELIVERED { // ERROR: undefined constant - // handle delivery -} -``` - -**JSON compatibility breaks:** -```json -// Before - JSON uses old names -{ - "status": "ORDER_STATUS_CONFIRMED" -} - -// After - parser expects new names -{ - "status": "ORDER_STATUS_APPROVED" // Old JSON fails to parse -} -``` - -## Migration Strategy - -1. **Add new enum values** instead of renaming: - ```proto - ORDER_STATUS_CONFIRMED = 2 [deprecated = true]; - ORDER_STATUS_APPROVED = 5; // New value - ``` - -2. **Update server code** to handle both old and new values during transition - -3. **Migrate clients** to use new enum values - -4. **Remove deprecated values** in next major version: - ```proto - reserved 2, "ORDER_STATUS_CONFIRMED"; - ORDER_STATUS_APPROVED = 5; - ``` - -## Allow Alias Exception - -With `allow_alias = true`, you can temporarily have multiple names for the same value: - -```proto -enum Status { - option allow_alias = true; - STATUS_UNSPECIFIED = 0; - STATUS_OLD_NAME = 1 [deprecated = true]; - STATUS_NEW_NAME = 1; // Same number, different name - allowed with alias + ORDER_STATUS_CONFIRMED = 2 [deprecated = true]; + ORDER_STATUS_APPROVED = 2; } ``` - -Note: EasyP currently detects this as breaking even with `allow_alias`. This may be refined in future versions. diff --git a/content/docs/cli/breaking-changes/rules/enum-value-same-name.ru.mdx b/content/docs/cli/breaking-changes/rules/enum-value-same-name.ru.mdx index 9ab259b..64be002 100644 --- a/content/docs/cli/breaking-changes/rules/enum-value-same-name.ru.mdx +++ b/content/docs/cli/breaking-changes/rules/enum-value-same-name.ru.mdx @@ -1,18 +1,19 @@ --- title: "Enum Value Same Name" +description: "Проверяет, что существующие значения enum сохраняют прежнее имя для своего номера." --- -Категории: +- **ID правила:** `ENUM_VALUE_SAME_NAME` +- **Профили:** `FILE`, `PACKAGE`, `WIRE_JSON` -- **WIRE+** - -Это правило проверяет, что имя enum значения для каждого номера (number) не изменилось. Переименование enum значения при сохранении его номера ломает совместимость JSON и сгенерированный код: клиенты ожидают конкретные имена констант. +Это правило проверяет, что существующие пары `(имя, номер)` в enum не переименовываются. Переименование значения enum ломает сгенерированные константы и JSON-сериализацию Protobuf (которая использует строковые имена значений). В профиле `WIRE` значения enum передаются только числами, поэтому там это правило не применяется. ## Примеры -### Плохой (Breaking) +### Неправильно **До:** + ```proto syntax = "proto3"; @@ -22,12 +23,11 @@ enum OrderStatus { ORDER_STATUS_UNSPECIFIED = 0; ORDER_STATUS_PENDING = 1; ORDER_STATUS_CONFIRMED = 2; - ORDER_STATUS_SHIPPED = 3; - ORDER_STATUS_DELIVERED = 4; } ``` **После:** + ```proto syntax = "proto3"; @@ -36,42 +36,20 @@ package myapi.v1; enum OrderStatus { ORDER_STATUS_UNSPECIFIED = 0; ORDER_STATUS_PENDING = 1; - ORDER_STATUS_APPROVED = 2; // Было ORDER_STATUS_CONFIRMED - ORDER_STATUS_SHIPPED = 3; - ORDER_STATUS_COMPLETED = 4; // Было ORDER_STATUS_DELIVERED + ORDER_STATUS_APPROVED = 2; // Переименовано из ORDER_STATUS_CONFIRMED } ``` **Ошибка:** -``` -order.proto:7:3: Enum value "2" on enum "OrderStatus" changed name from "ORDER_STATUS_CONFIRMED" to "ORDER_STATUS_APPROVED". (BREAKING_CHECK) -order.proto:9:3: Enum value "4" on enum "OrderStatus" changed name from "ORDER_STATUS_DELIVERED" to "ORDER_STATUS_COMPLETED". (BREAKING_CHECK) -``` -### Дополнительные примеры - -**Множественные переименования:** -```proto -// Before -enum UserRole { - USER_ROLE_UNSPECIFIED = 0; - USER_ROLE_ADMIN = 1; - USER_ROLE_MODERATOR = 2; - USER_ROLE_USER = 3; -} - -// After - ВСЁ BREAKING -enum UserRole { - USER_ROLE_UNSPECIFIED = 0; - USER_ROLE_ADMINISTRATOR = 1; // BREAKING: ADMIN -> ADMINISTRATOR - USER_ROLE_MOD = 2; // BREAKING: MODERATOR -> MOD - USER_ROLE_MEMBER = 3; // BREAKING: USER -> MEMBER -} +```text +order.proto:5:1: Enum value "ORDER_STATUS_CONFIRMED" at number 2 in "myapi.v1.OrderStatus" changed name to "ORDER_STATUS_APPROVED". (ENUM_VALUE_SAME_NAME) ``` -### Хороший (Безопасный) +### Правильно + +Добавьте новое значение enum и пометьте старое как `deprecated`: -**Вместо переименования — добавить новые значения и пометить старые deprecated:** ```proto syntax = "proto3"; @@ -81,92 +59,22 @@ enum OrderStatus { ORDER_STATUS_UNSPECIFIED = 0; ORDER_STATUS_PENDING = 1; ORDER_STATUS_CONFIRMED = 2 [deprecated = true]; - ORDER_STATUS_SHIPPED = 3; - ORDER_STATUS_DELIVERED = 4 [deprecated = true]; - ORDER_STATUS_APPROVED = 5; // Новое значение вместо переименования - ORDER_STATUS_COMPLETED = 6; + ORDER_STATUS_APPROVED = 3; } ``` -**Или создать новую версию enum:** +Либо сохраните исходную пару `(имя, номер)` и добавьте псевдоним через `option allow_alias = true;`, если алиасы разрешены политикой линтинга (см. [`ENUM_NO_ALLOW_ALIAS`](/ru/docs/cli/linter/rules/enum-no-allow-alias)): + ```proto syntax = "proto3"; -package myapi.v2; +package myapi.v1; enum OrderStatus { + option allow_alias = true; ORDER_STATUS_UNSPECIFIED = 0; ORDER_STATUS_PENDING = 1; - ORDER_STATUS_APPROVED = 2; // «Чистые» имена в v2 - ORDER_STATUS_SHIPPED = 3; - ORDER_STATUS_COMPLETED = 4; -} -``` - -## Влияние - -- **Generated Code:** Меняются имена констант — компиляция клиентов ломается -- **JSON Compatibility:** JSON использует имена enum — старые документы не парсятся -- **Client Applications:** Код со старым именем константы не компилируется -- **Documentation:** Документация устаревает с неправильными именами - -## Реальный пример - -**Ломается код клиента:** -```go -// Before -status := myapi.OrderStatus_ORDER_STATUS_CONFIRMED -if order.Status == myapi.OrderStatus_ORDER_STATUS_DELIVERED { - // handle delivery -} - -// After (переименовано) — ошибки компиляции -status := myapi.OrderStatus_ORDER_STATUS_CONFIRMED // ERROR: undefined -if order.Status == myapi.OrderStatus_ORDER_STATUS_DELIVERED { // ERROR: undefined - // handle delivery -} -``` - -**JSON совместимость ломается:** -```json -// Раньше -{ - "status": "ORDER_STATUS_CONFIRMED" -} - -// После -{ - "status": "ORDER_STATUS_APPROVED" // Старые JSON больше не парсятся -} -``` - -## Стратегия миграции - -1. **Добавьте новое значение вместо переименования:** - ```proto - ORDER_STATUS_CONFIRMED = 2 [deprecated = true]; - ORDER_STATUS_APPROVED = 5; - ``` - -2. **Сервер обрабатывает оба значения на переходном этапе** -3. **Мигрируйте клиентов** на новые значения -4. **Удалите (reserve) старое имя и номер** в следующей major‑версии: - ```proto - reserved 2, "ORDER_STATUS_CONFIRMED"; - ORDER_STATUS_APPROVED = 5; - ``` - -## Allow Alias (исключение) - -С `allow_alias = true` можно временно иметь два имени для одного номера: - -```proto -enum Status { - option allow_alias = true; - STATUS_UNSPECIFIED = 0; - STATUS_OLD_NAME = 1 [deprecated = true]; - STATUS_NEW_NAME = 1; // Один номер, два имени + ORDER_STATUS_CONFIRMED = 2 [deprecated = true]; + ORDER_STATUS_APPROVED = 2; } ``` - -Примечание: Сейчас EasyP всё равно считает это breaking (может измениться в будущем). diff --git a/content/docs/cli/breaking-changes/rules/extension-message-no-delete.mdx b/content/docs/cli/breaking-changes/rules/extension-message-no-delete.mdx new file mode 100644 index 0000000..5b0b048 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/extension-message-no-delete.mdx @@ -0,0 +1,60 @@ +--- +title: "Extension Message No Delete" +description: "Checks that messages do not remove or narrow existing extension number ranges." +--- + +- **Rule ID:** `EXTENSION_MESSAGE_NO_DELETE` +- **Profiles:** `FILE`, `PACKAGE` + +This rule checks that every extension range previously declared on a message (`extensions 100 to 199;`) remains fully covered by the new extension ranges. Removing or shrinking an extension range breaks downstream schemas that define extensions within those numbers. + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto2"; + +package myapi.v1; + +message Event { + optional string id = 1; + extensions 100 to 199; +} +``` + +**After:** + +```proto +syntax = "proto2"; + +package myapi.v1; + +message Event { + optional string id = 1; + extensions 100 to 149; +} +``` + +**Error:** + +```text +event.proto:5:1: Message "myapi.v1.Event" removed or narrowed an extension range. (EXTENSION_MESSAGE_NO_DELETE) +``` + +### Good + +Preserve all existing extension ranges (expanding a range or adding new ranges is compatible): + +```proto +syntax = "proto2"; + +package myapi.v1; + +message Event { + optional string id = 1; + extensions 100 to 299; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/extension-message-no-delete.ru.mdx b/content/docs/cli/breaking-changes/rules/extension-message-no-delete.ru.mdx new file mode 100644 index 0000000..1f6ab0f --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/extension-message-no-delete.ru.mdx @@ -0,0 +1,60 @@ +--- +title: "Extension Message No Delete" +description: "Проверяет, что сообщения не удаляют и не сужают существующие диапазоны номеров расширений (extensions)." +--- + +- **ID правила:** `EXTENSION_MESSAGE_NO_DELETE` +- **Профили:** `FILE`, `PACKAGE` + +Это правило проверяет, что все ранее объявленные на сообщении диапазоны расширений (`extensions 100 to 199;`) по-прежнему полностью покрываются новыми диапазонами. Удаление или сужение диапазона ломает зависимые схемы, определяющие расширения в этих номерах. + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto2"; + +package myapi.v1; + +message Event { + optional string id = 1; + extensions 100 to 199; +} +``` + +**После:** + +```proto +syntax = "proto2"; + +package myapi.v1; + +message Event { + optional string id = 1; + extensions 100 to 149; +} +``` + +**Ошибка:** + +```text +event.proto:5:1: Message "myapi.v1.Event" removed or narrowed an extension range. (EXTENSION_MESSAGE_NO_DELETE) +``` + +### Правильно + +Сохраняйте все существующие диапазоны расширений (расширять диапазон или добавлять новые диапазоны безопасно): + +```proto +syntax = "proto2"; + +package myapi.v1; + +message Event { + optional string id = 1; + extensions 100 to 299; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/extension-moved.mdx b/content/docs/cli/breaking-changes/rules/extension-moved.mdx new file mode 100644 index 0000000..e395f1e --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/extension-moved.mdx @@ -0,0 +1,66 @@ +--- +title: "Extension Moved" +description: "Checks that extensions are not moved to a different .proto file in the FILE profile." +--- + +- **Rule ID:** `EXTENSION_MOVED` +- **Profiles:** `FILE` + +In the `FILE` profile, moving an `extend` field declaration to a different `.proto` file breaks generated file-level extension descriptors and language imports. Use the `PACKAGE` profile if moving declarations within the same package is allowed. + +## Examples + +### Bad + +**Before:** + +```proto +// File: myapi/v1/options.proto +syntax = "proto3"; + +package myapi.v1; + +import "google/protobuf/descriptor.proto"; + +extend google.protobuf.FieldOptions { + bool sensitive = 50001; +} +``` + +**After:** + +```proto +// File: myapi/v1/field_options.proto +syntax = "proto3"; + +package myapi.v1; + +import "google/protobuf/descriptor.proto"; + +extend google.protobuf.FieldOptions { + bool sensitive = 50001; +} +``` + +**Error:** + +```text +myapi/v1/options.proto:9:3: Extension "myapi.v1.sensitive" was moved between files. (EXTENSION_MOVED) +``` + +### Good + +Keep the extension in its original `.proto` file when checking with `FILE`: + +```proto +// File: myapi/v1/options.proto +syntax = "proto3"; + +package myapi.v1; + +import "google/protobuf/descriptor.proto"; + +extend google.protobuf.FieldOptions { + bool sensitive = 50001; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/extension-moved.ru.mdx b/content/docs/cli/breaking-changes/rules/extension-moved.ru.mdx new file mode 100644 index 0000000..4de135e --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/extension-moved.ru.mdx @@ -0,0 +1,66 @@ +--- +title: "Extension Moved" +description: "Проверяет, что расширения (extend) не переносятся в другой .proto-файл в профиле FILE." +--- + +- **ID правила:** `EXTENSION_MOVED` +- **Профили:** `FILE` + +В профиле `FILE` перенос объявления расширения (`extend`) в другой `.proto`-файл ломает сгенерированные файловые дескрипторы расширений и импорты. Если перенос внутри одного пакета допустим, используйте профиль `PACKAGE`. + +## Примеры + +### Неправильно + +**До:** + +```proto +// File: myapi/v1/options.proto +syntax = "proto3"; + +package myapi.v1; + +import "google/protobuf/descriptor.proto"; + +extend google.protobuf.FieldOptions { + bool sensitive = 50001; +} +``` + +**После:** + +```proto +// File: myapi/v1/field_options.proto +syntax = "proto3"; + +package myapi.v1; + +import "google/protobuf/descriptor.proto"; + +extend google.protobuf.FieldOptions { + bool sensitive = 50001; +} +``` + +**Ошибка:** + +```text +myapi/v1/options.proto:9:3: Extension "myapi.v1.sensitive" was moved between files. (EXTENSION_MOVED) +``` + +### Правильно + +Сохраняйте расширение в исходном `.proto`-файле при проверке профилем `FILE`: + +```proto +// File: myapi/v1/options.proto +syntax = "proto3"; + +package myapi.v1; + +import "google/protobuf/descriptor.proto"; + +extend google.protobuf.FieldOptions { + bool sensitive = 50001; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/extension-no-delete.mdx b/content/docs/cli/breaking-changes/rules/extension-no-delete.mdx new file mode 100644 index 0000000..bd6a16e --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/extension-no-delete.mdx @@ -0,0 +1,61 @@ +--- +title: "Extension No Delete" +description: "Checks that no extension declarations are deleted." +--- + +- **Rule ID:** `EXTENSION_NO_DELETE` +- **Profiles:** `FILE`, `PACKAGE` + +This rule checks that no top-level or nested `extend` field declaration is deleted. Deleting an extension removes generated extension identifiers and breaks consumers that read or set that option/extension. + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +import "google/protobuf/descriptor.proto"; + +extend google.protobuf.FieldOptions { + bool sensitive = 50001; +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +import "google/protobuf/descriptor.proto"; + +// sensitive extension deleted +``` + +**Error:** + +```text +options.proto:8:3: Extension "myapi.v1.sensitive" was deleted. (EXTENSION_NO_DELETE) +``` + +### Good + +Mark the extension deprecated instead of deleting it: + +```proto +syntax = "proto3"; + +package myapi.v1; + +import "google/protobuf/descriptor.proto"; + +extend google.protobuf.FieldOptions { + bool sensitive = 50001 [deprecated = true]; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/extension-no-delete.ru.mdx b/content/docs/cli/breaking-changes/rules/extension-no-delete.ru.mdx new file mode 100644 index 0000000..5afad7b --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/extension-no-delete.ru.mdx @@ -0,0 +1,61 @@ +--- +title: "Extension No Delete" +description: "Проверяет, что ни одно объявление расширения не было удалено." +--- + +- **ID правила:** `EXTENSION_NO_DELETE` +- **Профили:** `FILE`, `PACKAGE` + +Это правило проверяет, что не удалено ни одно объявление расширения (`extend`, верхнего уровня или вложенное). Удаление расширения убирает сгенерированные идентификаторы расширений и ломает код и схемы, которые его используют. + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +import "google/protobuf/descriptor.proto"; + +extend google.protobuf.FieldOptions { + bool sensitive = 50001; +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +import "google/protobuf/descriptor.proto"; + +// sensitive extension deleted +``` + +**Ошибка:** + +```text +options.proto:8:3: Extension "myapi.v1.sensitive" was deleted. (EXTENSION_NO_DELETE) +``` + +### Правильно + +Пометьте расширение как `deprecated` вместо удаления: + +```proto +syntax = "proto3"; + +package myapi.v1; + +import "google/protobuf/descriptor.proto"; + +extend google.protobuf.FieldOptions { + bool sensitive = 50001 [deprecated = true]; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/extension-same-extendee.mdx b/content/docs/cli/breaking-changes/rules/extension-same-extendee.mdx new file mode 100644 index 0000000..7fb0b28 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/extension-same-extendee.mdx @@ -0,0 +1,67 @@ +--- +title: "Extension Same Extendee" +description: "Checks that extensions keep extending the same target message." +--- + +- **Rule ID:** `EXTENSION_SAME_EXTENDEE` +- **Profiles:** `FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE` + +This rule checks that an extension field keeps extending the same target message (extendee). Moving an extension to extend a different message breaks both wire serialization and generated extension types across all four profiles (`FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE`). + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +import "google/protobuf/descriptor.proto"; + +extend google.protobuf.FieldOptions { + bool sensitive = 50001; +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +import "google/protobuf/descriptor.proto"; + +extend google.protobuf.MessageOptions { + bool sensitive = 50001; +} +``` + +**Error:** + +```text +options.proto:8:3: Extension "myapi.v1.sensitive" changed the extended message. (EXTENSION_SAME_EXTENDEE) +``` + +### Good + +Keep the original extension on its original target message and define a differently named extension for the new target: + +```proto +syntax = "proto3"; + +package myapi.v1; + +import "google/protobuf/descriptor.proto"; + +extend google.protobuf.FieldOptions { + bool sensitive = 50001; +} + +extend google.protobuf.MessageOptions { + bool message_sensitive = 50001; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/extension-same-extendee.ru.mdx b/content/docs/cli/breaking-changes/rules/extension-same-extendee.ru.mdx new file mode 100644 index 0000000..c771847 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/extension-same-extendee.ru.mdx @@ -0,0 +1,67 @@ +--- +title: "Extension Same Extendee" +description: "Проверяет, что расширения продолжают расширять то же целевое сообщение." +--- + +- **ID правила:** `EXTENSION_SAME_EXTENDEE` +- **Профили:** `FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE` + +Это правило проверяет, что расширение продолжает относиться к тому же целевому сообщению (extendee). Перенос расширения на другое сообщение ломает и бинарную сериализацию, и сгенерированный код во всех четырёх профилях (`FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE`). + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +import "google/protobuf/descriptor.proto"; + +extend google.protobuf.FieldOptions { + bool sensitive = 50001; +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +import "google/protobuf/descriptor.proto"; + +extend google.protobuf.MessageOptions { + bool sensitive = 50001; +} +``` + +**Ошибка:** + +```text +options.proto:8:3: Extension "myapi.v1.sensitive" changed the extended message. (EXTENSION_SAME_EXTENDEE) +``` + +### Правильно + +Сохраните исходное расширение на его целевом сообщении и объявите новое расширение с другим именем для нового целевого сообщения: + +```proto +syntax = "proto3"; + +package myapi.v1; + +import "google/protobuf/descriptor.proto"; + +extend google.protobuf.FieldOptions { + bool sensitive = 50001; +} + +extend google.protobuf.MessageOptions { + bool message_sensitive = 50001; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/extension-same-number.mdx b/content/docs/cli/breaking-changes/rules/extension-same-number.mdx new file mode 100644 index 0000000..2b868fd --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/extension-same-number.mdx @@ -0,0 +1,63 @@ +--- +title: "Extension Same Number" +description: "Checks that extensions keep the same field tag number." +--- + +- **Rule ID:** `EXTENSION_SAME_NUMBER` +- **Profiles:** `FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE` + +This rule checks that an extension keeps the exact same tag number. Changing an extension tag number breaks binary wire decoding and generated extension descriptors across all four profiles (`FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE`). + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +import "google/protobuf/descriptor.proto"; + +extend google.protobuf.FieldOptions { + bool sensitive = 50001; +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +import "google/protobuf/descriptor.proto"; + +extend google.protobuf.FieldOptions { + bool sensitive = 50002; +} +``` + +**Error:** + +```text +options.proto:8:3: Extension "myapi.v1.sensitive" changed number from 50001 to 50002. (EXTENSION_SAME_NUMBER) +``` + +### Good + +Keep the extension tag number unchanged: + +```proto +syntax = "proto3"; + +package myapi.v1; + +import "google/protobuf/descriptor.proto"; + +extend google.protobuf.FieldOptions { + bool sensitive = 50001; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/extension-same-number.ru.mdx b/content/docs/cli/breaking-changes/rules/extension-same-number.ru.mdx new file mode 100644 index 0000000..3c336d1 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/extension-same-number.ru.mdx @@ -0,0 +1,63 @@ +--- +title: "Extension Same Number" +description: "Проверяет, что расширения сохраняют прежний номер поля." +--- + +- **ID правила:** `EXTENSION_SAME_NUMBER` +- **Профили:** `FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE` + +Это правило проверяет, что расширение сохраняет прежний номер тега. Изменение номера расширения ломает бинарное декодирование и сгенерированные дескрипторы расширений во всех четырёх профилях (`FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE`). + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +import "google/protobuf/descriptor.proto"; + +extend google.protobuf.FieldOptions { + bool sensitive = 50001; +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +import "google/protobuf/descriptor.proto"; + +extend google.protobuf.FieldOptions { + bool sensitive = 50002; +} +``` + +**Ошибка:** + +```text +options.proto:8:3: Extension "myapi.v1.sensitive" changed number from 50001 to 50002. (EXTENSION_SAME_NUMBER) +``` + +### Правильно + +Не изменяйте номер тега существующего расширения: + +```proto +syntax = "proto3"; + +package myapi.v1; + +import "google/protobuf/descriptor.proto"; + +extend google.protobuf.FieldOptions { + bool sensitive = 50001; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/field-no-delete-unless-name-reserved.mdx b/content/docs/cli/breaking-changes/rules/field-no-delete-unless-name-reserved.mdx new file mode 100644 index 0000000..9464933 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/field-no-delete-unless-name-reserved.mdx @@ -0,0 +1,61 @@ +--- +title: "Field No Delete Unless Name Reserved" +description: "Checks that any field deleted in WIRE_JSON has its field name reserved." +--- + +- **Rule ID:** `FIELD_NO_DELETE_UNLESS_NAME_RESERVED` +- **Profiles:** `WIRE_JSON` + +In the `WIRE_JSON` profile, deleting a non-required field is allowed only if its field number is reserved (checked by `FIELD_NO_DELETE_UNLESS_NUMBER_RESERVED`) **and** its field name is reserved with `reserved "name";`. Reserving the name prevents future fields from reusing it and conflicting with historical protobuf JSON payloads. + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + string name = 1; + string phone = 2; +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + reserved 2; + string name = 1; +} +``` + +**Error:** + +```text +user.proto:7:3: Deleted field "phone" on "myapi.v1.User" must have its name reserved for JSON compatibility. (FIELD_NO_DELETE_UNLESS_NAME_RESERVED) +``` + +### Good + +Reserve both the deleted field number and the deleted field name: + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + reserved 2; + reserved "phone"; + string name = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/field-no-delete-unless-name-reserved.ru.mdx b/content/docs/cli/breaking-changes/rules/field-no-delete-unless-name-reserved.ru.mdx new file mode 100644 index 0000000..e0d102e --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/field-no-delete-unless-name-reserved.ru.mdx @@ -0,0 +1,61 @@ +--- +title: "Field No Delete Unless Name Reserved" +description: "Проверяет, что при удалении поля в профиле WIRE_JSON его имя зарезервировано." +--- + +- **ID правила:** `FIELD_NO_DELETE_UNLESS_NAME_RESERVED` +- **Профили:** `WIRE_JSON` + +В профиле `WIRE_JSON` удаление необязательного поля допускается только при одновременном резервировании его номера (правило `FIELD_NO_DELETE_UNLESS_NUMBER_RESERVED`) **и** его имени через `reserved "name";`. Резервирование имени не даёт будущим полям переиспользовать его и ломать совместимость со старыми JSON-сообщениями. + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + string name = 1; + string phone = 2; +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + reserved 2; + string name = 1; +} +``` + +**Ошибка:** + +```text +user.proto:7:3: Deleted field "phone" on "myapi.v1.User" must have its name reserved for JSON compatibility. (FIELD_NO_DELETE_UNLESS_NAME_RESERVED) +``` + +### Правильно + +Зарезервируйте и номер, и имя удалённого поля: + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + reserved 2; + reserved "phone"; + string name = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/field-no-delete-unless-number-reserved.mdx b/content/docs/cli/breaking-changes/rules/field-no-delete-unless-number-reserved.mdx new file mode 100644 index 0000000..c406946 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/field-no-delete-unless-number-reserved.mdx @@ -0,0 +1,60 @@ +--- +title: "Field No Delete Unless Number Reserved" +description: "Checks that any field deleted in WIRE or WIRE_JSON has its field number reserved." +--- + +- **Rule ID:** `FIELD_NO_DELETE_UNLESS_NUMBER_RESERVED` +- **Profiles:** `WIRE_JSON`, `WIRE` + +In `WIRE` and `WIRE_JSON` profiles, deleting a non-required field is permitted only if its field number is permanently reserved using `reserved ;`. Without reserving the number, a future field could reuse the same wire tag with an incompatible type and corrupt stored or in-flight data. + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + string name = 1; + string phone = 2; +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + string name = 1; +} +``` + +**Error:** + +```text +user.proto:7:3: Deleted field "phone" number 2 on "myapi.v1.User" must be reserved. (FIELD_NO_DELETE_UNLESS_NUMBER_RESERVED) +``` + +### Good + +Reserve the deleted field number (and its name too if you also check `WIRE_JSON`): + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + reserved 2; + reserved "phone"; + string name = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/field-no-delete-unless-number-reserved.ru.mdx b/content/docs/cli/breaking-changes/rules/field-no-delete-unless-number-reserved.ru.mdx new file mode 100644 index 0000000..0b251cf --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/field-no-delete-unless-number-reserved.ru.mdx @@ -0,0 +1,60 @@ +--- +title: "Field No Delete Unless Number Reserved" +description: "Проверяет, что при удалении поля в профилях WIRE или WIRE_JSON его номер зарезервирован." +--- + +- **ID правила:** `FIELD_NO_DELETE_UNLESS_NUMBER_RESERVED` +- **Профили:** `WIRE_JSON`, `WIRE` + +В профилях `WIRE` и `WIRE_JSON` удаление необязательного поля допускается только при постоянном резервировании его номера с помощью `reserved ;`. Без этого будущие изменения могут повторно занять тот же тег другим типом и повредить сериализованные данные. + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + string name = 1; + string phone = 2; +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + string name = 1; +} +``` + +**Ошибка:** + +```text +user.proto:7:3: Deleted field "phone" number 2 on "myapi.v1.User" must be reserved. (FIELD_NO_DELETE_UNLESS_NUMBER_RESERVED) +``` + +### Правильно + +Зарезервируйте номер удалённого поля (и его имя, если используется `WIRE_JSON`): + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + reserved 2; + reserved "phone"; + string name = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/field-no-delete.mdx b/content/docs/cli/breaking-changes/rules/field-no-delete.mdx index 83515e0..acb8997 100644 --- a/content/docs/cli/breaking-changes/rules/field-no-delete.mdx +++ b/content/docs/cli/breaking-changes/rules/field-no-delete.mdx @@ -1,18 +1,23 @@ --- title: "Field No Delete" +description: "Checks that no message or extension fields are deleted in source-compatibility profiles." --- -Categories: +- **Rule ID:** `FIELD_NO_DELETE` +- **Profiles:** `FILE`, `PACKAGE` -- **WIRE+** +This rule checks that no fields are deleted from a message. Deleting a field removes generated struct fields and accessor methods, breaking compilation for consumers. -This rule checks that no message fields are deleted. Deleting a field breaks both wire format compatibility and generated code, as existing data may contain the deleted field and client code may reference it. + +Adding `reserved` for a deleted field number or name does **not** satisfy `FIELD_NO_DELETE` in `FILE` or `PACKAGE` profiles, because generated source accessors are still removed. Reserving deleted field numbers (and names for JSON) only satisfies [`FIELD_NO_DELETE_UNLESS_NUMBER_RESERVED`](/docs/cli/breaking-changes/rules/field-no-delete-unless-number-reserved) (`WIRE`, `WIRE_JSON`) and [`FIELD_NO_DELETE_UNLESS_NAME_RESERVED`](/docs/cli/breaking-changes/rules/field-no-delete-unless-name-reserved) (`WIRE_JSON`). + ## Examples ### Bad **Before:** + ```proto syntax = "proto3"; @@ -27,76 +32,47 @@ message User { ``` **After:** + ```proto syntax = "proto3"; package myapi.v1; message User { + reserved 4; + reserved "phone"; + string name = 1; string email = 2; int32 age = 3; - // phone field was deleted - BREAKING CHANGE! } ``` **Error:** -``` -user.proto:6:3: Previously present field "4" with name "phone" on message "User" was deleted. (BREAKING_CHECK) + +```text +user.proto:9:3: Field "phone" (4) on "myapi.v1.User" was deleted. (FIELD_NO_DELETE) ``` ### Good -**Instead of deleting, deprecate the field:** -```proto -syntax = "proto3"; - -package myapi.v1; +Keep the field and mark it deprecated instead of deleting it in `FILE`/`PACKAGE` profiles: -message User { - string name = 1; - string email = 2; - int32 age = 3; - string phone = 4 [deprecated = true]; -} -``` - -**Or reserve the field number after removal:** ```proto syntax = "proto3"; package myapi.v1; message User { - reserved 4; - reserved "phone"; - string name = 1; string email = 2; int32 age = 3; + string phone = 4 [deprecated = true]; } ``` -## Impact - -- **Wire Format:** Old messages with the deleted field cannot be properly deserialized -- **Generated Code:** Field accessors are removed, breaking client compilation -- **Data Loss:** Existing serialized data loses information -- **JSON Compatibility:** JSON parsers expect the field to exist - ## Migration Strategy -1. **Deprecate first:** - ```proto - string old_field = 5 [deprecated = true]; - ``` - -2. **Stop writing to the field** in your application code - -3. **Reserve the field** in next version to prevent accidental reuse: - ```proto - reserved 5; - reserved "old_field"; - ``` - -4. **Never reuse field numbers** - they must remain reserved permanently +1. Mark the field with `[deprecated = true]` and stop writing to it in application code. +2. If your policy uses `WIRE` or `WIRE_JSON`, delete the field only while permanently reserving its number (and name for `WIRE_JSON`). +3. If your policy uses `FILE` or `PACKAGE`, keep the deprecated field until the next major package version (for example, `myapi.v2`). diff --git a/content/docs/cli/breaking-changes/rules/field-no-delete.ru.mdx b/content/docs/cli/breaking-changes/rules/field-no-delete.ru.mdx index 454fa86..fd1bdf8 100644 --- a/content/docs/cli/breaking-changes/rules/field-no-delete.ru.mdx +++ b/content/docs/cli/breaking-changes/rules/field-no-delete.ru.mdx @@ -1,18 +1,23 @@ --- title: "Field No Delete" +description: "Проверяет, что ни одно поле сообщения не было удалено в профилях совместимости исходного кода." --- -Категории: +- **ID правила:** `FIELD_NO_DELETE` +- **Профили:** `FILE`, `PACKAGE` -- **WIRE+** +Это правило проверяет, что из сообщения не удалено ни одно поле. Удаление поля убирает сгенерированные поля структур и геттеры/сеттеры, что ломает компиляцию клиентского кода. -Это правило проверяет, что ни одно поле сообщения (message field) не было удалено. Удаление поля ломает совместимость по wire‑формату и сгенерированный код: в существующих данных может присутствовать удалённое поле, а клиентский код может ссылаться на него. + +Директива `reserved` для удалённого номера или имени поля **не** удовлетворяет `FIELD_NO_DELETE` в профилях `FILE` и `PACKAGE`, так как сгенерированные методы доступа всё равно исчезают. Резервирование номера (и имени для JSON) достаточно только для [`FIELD_NO_DELETE_UNLESS_NUMBER_RESERVED`](/ru/docs/cli/breaking-changes/rules/field-no-delete-unless-number-reserved) (`WIRE`, `WIRE_JSON`) и [`FIELD_NO_DELETE_UNLESS_NAME_RESERVED`](/ru/docs/cli/breaking-changes/rules/field-no-delete-unless-name-reserved) (`WIRE_JSON`). + ## Примеры -### Плохой (Breaking) +### Неправильно **До:** + ```proto syntax = "proto3"; @@ -27,76 +32,47 @@ message User { ``` **После:** + ```proto syntax = "proto3"; package myapi.v1; message User { + reserved 4; + reserved "phone"; + string name = 1; string email = 2; int32 age = 3; - // phone поле удалено — BREAKING CHANGE! } ``` **Ошибка:** -``` -user.proto:6:3: Previously present field "4" with name "phone" on message "User" was deleted. (BREAKING_CHECK) -``` -### Хороший (Безопасный) +```text +user.proto:9:3: Field "phone" (4) on "myapi.v1.User" was deleted. (FIELD_NO_DELETE) +``` -**Вместо удаления — пометить поле deprecated:** -```proto -syntax = "proto3"; +### Правильно -package myapi.v1; +В профилях `FILE` и `PACKAGE` оставьте поле и пометьте его как `deprecated`: -message User { - string name = 1; - string email = 2; - int32 age = 3; - string phone = 4 [deprecated = true]; -} -``` - -**Или зарезервировать номер и имя поля после удаления:** ```proto syntax = "proto3"; package myapi.v1; message User { - reserved 4; - reserved "phone"; - string name = 1; string email = 2; int32 age = 3; + string phone = 4 [deprecated = true]; } ``` -## Влияние - -- **Wire Format:** Старые сообщения с удалённым полем некорректно десериализуются -- **Generated Code:** Удаляются аксессоры (get/set), компиляция клиента ломается -- **Data Loss:** Потеря сохранённых данных, связанных с полем -- **JSON Compatibility:** JSON парсеры ожидают наличие поля и могут выдавать ошибки - ## Стратегия миграции -1. **Сначала пометить deprecated:** - ```proto - string old_field = 5 [deprecated = true]; - ``` - -2. **Прекратить запись в поле** в прикладном коде - -3. **Зарезервировать поле** в следующей версии, чтобы избежать повторного использования: - ```proto - reserved 5; - reserved "old_field"; - ``` - -4. **Никогда не переиспользовать номер поля** — должен оставаться в reserved навсегда +1. Пометьте поле опцией `[deprecated = true]` и прекратите запись в него в прикладном коде. +2. Если ваша политика использует `WIRE` или `WIRE_JSON`, при удалении поля обязательно зарезервируйте его номер (и имя для `WIRE_JSON`). +3. Если политика использует `FILE` или `PACKAGE`, сохраняйте устаревшее поле до следующей мажорной версии пакета (например, `myapi.v2`). diff --git a/content/docs/cli/breaking-changes/rules/field-same-cardinality.mdx b/content/docs/cli/breaking-changes/rules/field-same-cardinality.mdx index b6cdbfe..578186a 100644 --- a/content/docs/cli/breaking-changes/rules/field-same-cardinality.mdx +++ b/content/docs/cli/breaking-changes/rules/field-same-cardinality.mdx @@ -1,18 +1,25 @@ --- title: "Field Same Cardinality" +description: "Checks that fields keep the exact same cardinality and presence semantics in source-compatibility profiles." --- -Categories: +- **Rule ID:** `FIELD_SAME_CARDINALITY` +- **Profiles:** `FILE`, `PACKAGE` -- **WIRE+** +This rule checks that every field preserves its exact cardinality and presence model (`optional_implicit`, `optional_explicit`, `required`, `repeated`, or `map`). -This rule checks that message fields maintain the same cardinality (optionality). Changing a field's cardinality breaks both wire format compatibility and generated code, as the presence semantics and client code expectations differ between optional and required fields. +In proto3, regular singular fields (such as `string email = 2;`) are **not** `required` — they use **implicit presence** (`optional_implicit`), while `optional string email = 2;` uses **explicit presence** (`optional_explicit`). Changing between implicit and explicit presence changes generated code types and accessors (for example, `string` vs `*string` in Go), so `FIELD_SAME_CARDINALITY` rejects it in `FILE` and `PACKAGE` profiles. + + +Toggling between implicit and explicit `optional` presence (`string` ↔ `optional string`) is wire- and JSON-compatible, so it is allowed in `WIRE` and `WIRE_JSON` profiles (see [`FIELD_WIRE_COMPATIBLE_CARDINALITY`](/docs/cli/breaking-changes/rules/field-wire-compatible-cardinality) and [`FIELD_WIRE_JSON_COMPATIBLE_CARDINALITY`](/docs/cli/breaking-changes/rules/field-wire-json-compatible-cardinality)). + ## Examples ### Bad **Before:** + ```proto syntax = "proto3"; @@ -21,17 +28,12 @@ package myapi.v1; message User { string name = 1; string email = 2; - int32 age = 3; -} - -message CreateUserRequest { - string name = 1; - optional string email = 2; - string phone = 3; + repeated string tags = 3; } ``` **After:** + ```proto syntax = "proto3"; @@ -39,254 +41,40 @@ package myapi.v1; message User { string name = 1; - optional string email = 2; // Changed from required to optional - int32 age = 3; -} - -message CreateUserRequest { - string name = 1; - string email = 2; // Changed from optional to required - string phone = 3; + optional string email = 2; // optional_implicit -> optional_explicit + string tags = 3; // repeated -> optional_implicit } ``` **Error:** -``` -user.proto:6:3: Field "2" with name "email" on message "User" became optional. (BREAKING_CHECK) -request.proto:7:3: Field "2" with name "email" on message "CreateUserRequest" became not optional. (BREAKING_CHECK) -``` -### More Examples - -**Proto2 to Proto3 migration issues:** - -```proto -// Before (proto2) -syntax = "proto2"; - -message Order { - required string id = 1; - optional string notes = 2; - repeated string tags = 3; -} - -// After (proto3) - BREAKING CHANGES! -syntax = "proto3"; - -message Order { - string id = 1; // BREAKING: required -> implicit optional - string notes = 2; // BREAKING: explicit optional -> implicit optional - repeated string tags = 3; // OK: repeated unchanged -} +```text +user.proto:7:3: Field "email" (2) on "myapi.v1.User" changed cardinality from optional_implicit to optional_explicit. (FIELD_SAME_CARDINALITY) +user.proto:8:3: Field "tags" (3) on "myapi.v1.User" changed cardinality from repeated to optional_implicit. (FIELD_SAME_CARDINALITY) ``` ### Good -**Instead of changing cardinality, add new field:** -```proto -syntax = "proto3"; - -package myapi.v1; - -message User { - string name = 1; - string email = 2 [deprecated = true]; // Keep original cardinality - int32 age = 3; - optional string email_optional = 4; // New field with desired cardinality -} - -message CreateUserRequest { - string name = 1; - optional string email = 2 [deprecated = true]; // Keep original cardinality - string phone = 3; - string email_required = 4; // New field with desired cardinality -} -``` +Keep the existing field's cardinality unchanged and add a new field with the desired cardinality: -**Or create a new message version:** ```proto syntax = "proto3"; -package myapi.v2; // New package version +package myapi.v1; message User { string name = 1; - optional string email = 2; // Clean cardinality in v2 - int32 age = 3; -} - -message CreateUserRequest { - string name = 1; - string email = 2; // Required in v2 - string phone = 3; -} -``` - -## Impact - -- **Wire Format:** Field presence semantics change, breaking deserialization expectations -- **Generated Code:** Field accessor methods change (hasField(), clearField()) -- **Validation:** Required field validation changes at runtime -- **Default Values:** Optional vs required fields handle defaults differently - -## Real-World Example - -**Client code breaks with cardinality changes:** -```go -// Before - required field (proto3 implicit) -user := &myapi.User{ - Name: "John", - Email: "john@example.com", // Must be set - Age: 30, -} - -// Check if email is set (implicit presence) -if user.Email != "" { - // Email is provided -} - -// After - optional field (explicit presence) -user := &myapi.User{ - Name: "John", - Age: 30, - // Email can be nil/unset -} - -// Check if email is set (explicit presence) -if user.Email != nil && *user.Email != "" { // Different API! - // Email is provided -} - -// Setting email also changes -user.Email = &emailValue // Pointer assignment vs direct -``` - -**Server validation breaks:** -```go -// Before - implicit required field -func validateUser(user *User) error { - if user.Email == "" { // Empty string check - return errors.New("email is required") - } - return nil -} - -// After - explicit optional field -func validateUser(user *User) error { - if user.Email == nil { // Nil pointer check - return errors.New("email is required") - } - if *user.Email == "" { // Dereference to check empty - return errors.New("email cannot be empty") - } - return nil -} -``` - -## Migration Strategy - -1. **Add new field** with correct cardinality: - ```proto - string old_email = 2 [deprecated = true]; - optional string new_email = 5; // New field with desired cardinality - ``` - -2. **Dual-write period** - populate both fields during transition: - ```go - user := &User{ - Name: "John", - OldEmail: email, // Legacy field - NewEmail: &email, // New optional field - } - ``` - -3. **Update clients** to use new field gradually: - ```go - // Check both fields during migration - email := user.NewEmail - if email == nil && user.OldEmail != "" { - emailValue := user.OldEmail - email = &emailValue // Fallback to old field - } - ``` - -4. **Remove old field** in next major version: - ```proto - reserved 2, "old_email"; - optional string new_email = 5; - ``` - -## Common Scenarios - -### Proto2 to Proto3 Migration -```proto -// Instead of direct syntax migration -syntax = "proto3"; -message Order { - string id = 1; // BREAKING: was required in proto2 -} - -// Maintain semantics during migration -syntax = "proto3"; -message Order { - string id = 1; // Keep as implicit required - // Add explicit optional fields only when needed - optional string notes = 2; -} -``` - -### Making Optional Fields Required -```proto -// Instead of changing existing field -message CreateUserRequest { - string name = 1; - string email = 2; // BREAKING: was optional -} - -// Add new required field -message CreateUserRequest { - string name = 1; - optional string email = 2 [deprecated = true]; - string required_email = 3; // New required field -} -``` - -### Making Required Fields Optional -```proto -// Instead of changing existing field -message User { - optional string phone = 3; // BREAKING: was required -} - -// Add new optional field -message User { - string phone = 3 [deprecated = true]; // Keep required - optional string phone_optional = 4; // New optional field + string email = 2 [deprecated = true]; + repeated string tags = 3; + optional string email_address = 4; } ``` -## Cardinality Types in Protobuf - -### Proto3 Cardinality -- **Implicit optional**: `string name = 1;` (default in proto3) -- **Explicit optional**: `optional string email = 2;` -- **Repeated**: `repeated string tags = 3;` -- **Map**: `map metadata = 4;` - -### Proto2 Cardinality -- **Required**: `required string id = 1;` -- **Optional**: `optional string email = 2;` -- **Repeated**: `repeated string tags = 3;` - -### Breaking Changes Matrix +## Cardinality Matrix (`FILE` / `PACKAGE` vs `WIRE_JSON` / `WIRE`) -| From | To | Result | -|------|----|---------| -| Required | Optional | ❌ BREAKING | -| Optional | Required | ❌ BREAKING | -| Implicit | Explicit | ❌ BREAKING | -| Explicit | Implicit | ❌ BREAKING | -| Single | Repeated | ❌ BREAKING | -| Repeated | Single | ❌ BREAKING | -| Field | Map | ❌ BREAKING | -| Map | Field | ❌ BREAKING | +| Transition | `FILE` / `PACKAGE` | `WIRE_JSON` | `WIRE` | +| --- | --- | --- | --- | +| `optional_implicit` ↔ `optional_explicit` | Reject | Allow | Allow | +| `repeated` ↔ `map` (compatible entry message) | Reject | Reject | Allow | +| `singular` ↔ `repeated` or `map` | Reject | Reject | Reject | +| `required` ↔ anything else | Reject | Reject | Reject | diff --git a/content/docs/cli/breaking-changes/rules/field-same-cardinality.ru.mdx b/content/docs/cli/breaking-changes/rules/field-same-cardinality.ru.mdx index e504237..59577ad 100644 --- a/content/docs/cli/breaking-changes/rules/field-same-cardinality.ru.mdx +++ b/content/docs/cli/breaking-changes/rules/field-same-cardinality.ru.mdx @@ -1,18 +1,25 @@ --- title: "Field Same Cardinality" +description: "Проверяет, что поля сохраняют точную кардинальность и модель присутствия в профилях совместимости исходного кода." --- -Категории: +- **ID правила:** `FIELD_SAME_CARDINALITY` +- **Профили:** `FILE`, `PACKAGE` -- **WIRE+** +Это правило проверяет, что каждое поле сохраняет точную кардинальность и модель присутствия (`optional_implicit`, `optional_explicit`, `required`, `repeated` или `map`). -Правило проверяет, что поля сообщений сохраняют ту же кардинальность (обязательность / optional). Изменение кардинальности поля ломает совместимость по wire‑формату и сгенерированный код: семантика присутствия и ожидания клиентского кода отличаются для optional и required (implicit) полей. +В proto3 обычные одиночные поля (например, `string email = 2;`) **не являются** `required` — у них **неявное присутствие** (`optional_implicit`), тогда как у `optional string email = 2;` — **явное присутствие** (`optional_explicit`). Переключение между неявным и явным присутствием меняет типы и методы в сгенерированном коде (например, `string` и `*string` в Go), поэтому `FIELD_SAME_CARDINALITY` отклоняет такое изменение в профилях `FILE` и `PACKAGE`. + + +Переключение между неявным и явным `optional` (`string` ↔ `optional string`) совместимо по бинарному формату и JSON, поэтому допускается в профилях `WIRE` и `WIRE_JSON` (см. [`FIELD_WIRE_COMPATIBLE_CARDINALITY`](/ru/docs/cli/breaking-changes/rules/field-wire-compatible-cardinality) и [`FIELD_WIRE_JSON_COMPATIBLE_CARDINALITY`](/ru/docs/cli/breaking-changes/rules/field-wire-json-compatible-cardinality)). + ## Примеры -### Плохой (Breaking) +### Неправильно **До:** + ```proto syntax = "proto3"; @@ -21,17 +28,12 @@ package myapi.v1; message User { string name = 1; string email = 2; - int32 age = 3; -} - -message CreateUserRequest { - string name = 1; - optional string email = 2; - string phone = 3; + repeated string tags = 3; } ``` **После:** + ```proto syntax = "proto3"; @@ -39,244 +41,40 @@ package myapi.v1; message User { string name = 1; - optional string email = 2; // Было required (implicit), стало optional - int32 age = 3; -} - -message CreateUserRequest { - string name = 1; - string email = 2; // Было optional, стало требуемым (implicit required) - string phone = 3; + optional string email = 2; // optional_implicit -> optional_explicit + string tags = 3; // repeated -> optional_implicit } ``` **Ошибка:** -``` -user.proto:6:3: Field "2" with name "email" on message "User" became optional. (BREAKING_CHECK) -request.proto:7:3: Field "2" with name "email" on message "CreateUserRequest" became not optional. (BREAKING_CHECK) -``` -### Дополнительные примеры - -**Проблемы миграции Proto2 → Proto3:** - -```proto -// Before (proto2) -syntax = "proto2"; - -message Order { - required string id = 1; - optional string notes = 2; - repeated string tags = 3; -} - -// After (proto3) - BREAKING CHANGES! -syntax = "proto3"; - -message Order { - string id = 1; // BREAKING: required -> implicit optional - string notes = 2; // BREAKING: explicit optional -> implicit optional - repeated string tags = 3; // OK -} +```text +user.proto:7:3: Field "email" (2) on "myapi.v1.User" changed cardinality from optional_implicit to optional_explicit. (FIELD_SAME_CARDINALITY) +user.proto:8:3: Field "tags" (3) on "myapi.v1.User" changed cardinality from repeated to optional_implicit. (FIELD_SAME_CARDINALITY) ``` -### Хороший (Безопасный) +### Правильно -**Вместо изменения кардинальности — добавьте новое поле:** -```proto -syntax = "proto3"; - -package myapi.v1; - -message User { - string name = 1; - string email = 2 [deprecated = true]; // Сохраняем старую кардинальность - int32 age = 3; - optional string email_optional = 4; // Новое optional поле -} - -message CreateUserRequest { - string name = 1; - optional string email = 2 [deprecated = true]; - string phone = 3; - string email_required = 4; // Новое требуемое поле -} -``` +Сохраните кардинальность существующего поля и добавьте новое поле с нужной семантикой: -**Или создайте новую версию сообщения:** ```proto syntax = "proto3"; -package myapi.v2; +package myapi.v1; message User { string name = 1; - optional string email = 2; // Чистая модель в v2 - int32 age = 3; -} - -message CreateUserRequest { - string name = 1; - string email = 2; // Требуемое в v2 - string phone = 3; -} -``` - -## Влияние - -- **Wire Format:** Меняется семантика присутствия — клиенты неправильно ожидают поля -- **Generated Code:** Меняются методы доступа / проверки (has, clear) -- **Validation:** Правила проверки обязательности переписываются -- **Default Values:** Optional и required по‑разному обрабатывают отсутствие значения - -## Реальный пример - -**Код клиента ломается при смене кардинальности:** -```go -// Before - поле фактически требуется (implicit) -user := &myapi.User{ - Name: "John", - Email: "john@example.com", - Age: 30, -} - -if user.Email != "" { - // Есть значение -} - -// After - поле стало optional (pointer) -user := &myapi.User{ - Name: "John", - Age: 30, - // Email может отсутствовать -} - -if user.Email != nil && *user.Email != "" { - // Есть значение (новый способ) -} - -user.Email = &emailValue // Присваивание указателя вместо строки -``` - -**Валидация на сервере:** -```go -// Before -func validateUser(user *User) error { - if user.Email == "" { - return errors.New("email is required") - } - return nil -} - -// After -func validateUser(user *User) error { - if user.Email == nil { - return errors.New("email is required") - } - if *user.Email == "" { - return errors.New("email cannot be empty") - } - return nil -} -``` - -## Стратегия миграции - -1. **Добавьте новое поле** с нужной кардинальностью: - ```proto - string old_email = 2 [deprecated = true]; - optional string new_email = 5; - ``` - -2. **Период двойной записи** — заполняйте оба поля: - ```go - user := &User{ - Name: "John", - OldEmail: email, - NewEmail: &email, - } - ``` - -3. **Клиенты постепенно переходят**: - ```go - email := user.NewEmail - if email == nil && user.OldEmail != "" { - v := user.OldEmail - email = &v - } - ``` - -4. **Удаление старого поля** в следующей major‑версии: - ```proto - reserved 2, "old_email"; - optional string new_email = 5; - ``` - -## Типовые сценарии - -### Миграция Proto2 → Proto3 -```proto -syntax = "proto3"; -message Order { - string id = 1; // BREAKING если был required -} - -// Сохранить семантику: -syntax = "proto3"; -message Order { - string id = 1; - optional string notes = 2; -} -``` - -### Делать optional поле required -```proto -message CreateUserRequest { - string name = 1; - string email = 2; // BREAKING (раньше optional) -} - -message CreateUserRequest { - string name = 1; - optional string email = 2 [deprecated = true]; - string required_email = 3; -} -``` - -### Делать required поле optional -```proto -message User { - optional string phone = 3; // BREAKING (было implicit required) -} - -message User { - string phone = 3 [deprecated = true]; - optional string phone_optional = 4; + string email = 2 [deprecated = true]; + repeated string tags = 3; + optional string email_address = 4; } ``` -## Типы кардинальности в Protobuf - -### Proto3 -- **Implicit optional**: `string name = 1;` -- **Explicit optional**: `optional string email = 2;` -- **Repeated**: `repeated string tags = 3;` -- **Map**: `map metadata = 4;` - -### Proto2 -- **Required**: `required string id = 1;` -- **Optional**: `optional string email = 2;` -- **Repeated**: `repeated string tags = 3;` - -### Матрица Breaking изменений +## Матрица переходов (`FILE` / `PACKAGE` против `WIRE_JSON` / `WIRE`) -| From | To | Result | -|------|----|--------| -| Required | Optional | ❌ BREAKING | -| Optional | Required | ❌ BREAKING | -| Implicit | Explicit | ❌ BREAKING | -| Explicit | Implicit | ❌ BREAKING | -| Single | Repeated | ❌ BREAKING | -| Repeated | Single | ❌ BREAKING | -| Field | Map | ❌ BREAKING | -| Map | Field | ❌ BREAKING | +| Переход | `FILE` / `PACKAGE` | `WIRE_JSON` | `WIRE` | +| --- | --- | --- | --- | +| `optional_implicit` ↔ `optional_explicit` | Ошибка | Допустимо | Допустимо | +| `repeated` ↔ `map` (совместимое entry-сообщение) | Ошибка | Ошибка | Допустимо | +| одиночное ↔ `repeated` или `map` | Ошибка | Ошибка | Ошибка | +| `required` ↔ любой другой вариант | Ошибка | Ошибка | Ошибка | diff --git a/content/docs/cli/breaking-changes/rules/field-same-cpp-string-type.mdx b/content/docs/cli/breaking-changes/rules/field-same-cpp-string-type.mdx new file mode 100644 index 0000000..d14bb8e --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/field-same-cpp-string-type.mdx @@ -0,0 +1,58 @@ +--- +title: "Field Same Cpp String Type" +description: "Checks that string/bytes fields keep the same C++ string representation option." +--- + +- **Rule ID:** `FIELD_SAME_CPP_STRING_TYPE` +- **Profiles:** `FILE`, `PACKAGE` + +This rule checks that fields keep the same effective C++ string representation (`STRING`, `CORD`, or `VIEW`), whether configured via legacy `[ctype = CORD]` / `[ctype = STRING_PIECE]` or via Protobuf Editions `features.(pb.cpp).string_type`. Changing it alters generated C++ getter/setter types. + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Payload { + bytes body = 1; +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Payload { + bytes body = 1 [ctype = CORD]; +} +``` + +**Error:** + +```text +payload.proto:6:3: Field "myapi.v1.Payload.body" changed C++ string type option. (FIELD_SAME_CPP_STRING_TYPE) +``` + +### Good + +Keep the C++ string type option unchanged on existing fields; introduce a new field if you need a different C++ representation: + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Payload { + bytes body = 1; + bytes body_cord = 2 [ctype = CORD]; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/field-same-cpp-string-type.ru.mdx b/content/docs/cli/breaking-changes/rules/field-same-cpp-string-type.ru.mdx new file mode 100644 index 0000000..e50546c --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/field-same-cpp-string-type.ru.mdx @@ -0,0 +1,58 @@ +--- +title: "Field Same Cpp String Type" +description: "Проверяет, что поля string/bytes сохраняют прежний тип строки для C++." +--- + +- **ID правила:** `FIELD_SAME_CPP_STRING_TYPE` +- **Профили:** `FILE`, `PACKAGE` + +Это правило проверяет, что поля сохраняют прежнее эффективное представление строк в C++ (`STRING`, `CORD` или `VIEW`), заданное через `[ctype = CORD]` / `[ctype = STRING_PIECE]` или через `features.(pb.cpp).string_type` в Protobuf Editions. Изменение ломает сигнатуры сгенерированного C++-кода. + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Payload { + bytes body = 1; +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Payload { + bytes body = 1 [ctype = CORD]; +} +``` + +**Ошибка:** + +```text +payload.proto:6:3: Field "myapi.v1.Payload.body" changed C++ string type option. (FIELD_SAME_CPP_STRING_TYPE) +``` + +### Правильно + +Не меняйте опцию типа C++-строки на существующем поле; при необходимости добавьте новое поле: + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Payload { + bytes body = 1; + bytes body_cord = 2 [ctype = CORD]; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/field-same-default.mdx b/content/docs/cli/breaking-changes/rules/field-same-default.mdx new file mode 100644 index 0000000..278b316 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/field-same-default.mdx @@ -0,0 +1,58 @@ +--- +title: "Field Same Default" +description: "Checks that fields keep the same explicit or implicit default value." +--- + +- **Rule ID:** `FIELD_SAME_DEFAULT` +- **Profiles:** `FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE` + +This rule checks that every field keeps the same effective default value. This applies both to explicit `[default = ...]` options in `proto2` / Editions and to implicit enum defaults (the first declared enum value when a singular enum field has no explicit default). Changing a default alters how older and newer peers interpret omitted fields on the wire. + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto2"; + +package myapi.v1; + +message Config { + optional int32 timeout_ms = 1 [default = 1000]; +} +``` + +**After:** + +```proto +syntax = "proto2"; + +package myapi.v1; + +message Config { + optional int32 timeout_ms = 1 [default = 5000]; +} +``` + +**Error:** + +```text +config.proto:6:3: Field "timeout_ms" (1) default changed. (FIELD_SAME_DEFAULT) +``` + +### Good + +Keep the default value unchanged on existing fields; add a new field if a different default is required: + +```proto +syntax = "proto2"; + +package myapi.v1; + +message Config { + optional int32 timeout_ms = 1 [default = 1000, deprecated = true]; + optional int32 request_timeout_ms = 2 [default = 5000]; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/field-same-default.ru.mdx b/content/docs/cli/breaking-changes/rules/field-same-default.ru.mdx new file mode 100644 index 0000000..d39a3d5 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/field-same-default.ru.mdx @@ -0,0 +1,58 @@ +--- +title: "Field Same Default" +description: "Проверяет, что поля сохраняют прежнее явное или неявное значение по умолчанию." +--- + +- **ID правила:** `FIELD_SAME_DEFAULT` +- **Профили:** `FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE` + +Это правило проверяет, что каждое поле сохраняет прежнее эффективное значение по умолчанию. Это касается как явной опции `[default = ...]` в `proto2` / Editions, так и неявного значения по умолчанию для enum (первого объявленного значения enum у одиночного поля без явного default). Смена значения по умолчанию меняет интерпретацию пропущенных полей по сети. + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto2"; + +package myapi.v1; + +message Config { + optional int32 timeout_ms = 1 [default = 1000]; +} +``` + +**После:** + +```proto +syntax = "proto2"; + +package myapi.v1; + +message Config { + optional int32 timeout_ms = 1 [default = 5000]; +} +``` + +**Ошибка:** + +```text +config.proto:6:3: Field "timeout_ms" (1) default changed. (FIELD_SAME_DEFAULT) +``` + +### Правильно + +Сохраняйте значение по умолчанию неизменным; при необходимости другого значения добавьте новое поле: + +```proto +syntax = "proto2"; + +package myapi.v1; + +message Config { + optional int32 timeout_ms = 1 [default = 1000, deprecated = true]; + optional int32 request_timeout_ms = 2 [default = 5000]; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/field-same-java-utf8-validation.mdx b/content/docs/cli/breaking-changes/rules/field-same-java-utf8-validation.mdx new file mode 100644 index 0000000..6bab98e --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/field-same-java-utf8-validation.mdx @@ -0,0 +1,58 @@ +--- +title: "Field Same Java Utf8 Validation" +description: "Checks that string fields keep the same effective Java UTF-8 validation behavior." +--- + +- **Rule ID:** `FIELD_SAME_JAVA_UTF8_VALIDATION` +- **Profiles:** `FILE`, `PACKAGE` + +This rule checks that `string` fields preserve their effective Java UTF-8 validation mode, computed from `features.(pb.java).utf8_validation`, `features.utf8_validation`, syntax defaults (`proto3`/Editions verify by default), and file option `java_string_check_utf8`. Changing it alters whether generated Java code throws on invalid UTF-8. + +## Examples + +### Bad + +**Before:** + +```proto +edition = "2023"; + +package myapi.v1; + +message Note { + string text = 1 [features.utf8_validation = VERIFY]; +} +``` + +**After:** + +```proto +edition = "2023"; + +package myapi.v1; + +message Note { + string text = 1 [features.utf8_validation = NONE]; +} +``` + +**Error:** + +```text +note.proto:6:3: Field "myapi.v1.Note.text" changed Java UTF-8 validation behavior. (FIELD_SAME_JAVA_UTF8_VALIDATION) +``` + +### Good + +Keep Java UTF-8 validation behavior consistent on existing `string` fields (use `bytes` on a new field if arbitrary byte sequences must be allowed): + +```proto +edition = "2023"; + +package myapi.v1; + +message Note { + string text = 1 [features.utf8_validation = VERIFY]; + bytes raw_text = 2; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/field-same-java-utf8-validation.ru.mdx b/content/docs/cli/breaking-changes/rules/field-same-java-utf8-validation.ru.mdx new file mode 100644 index 0000000..861206e --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/field-same-java-utf8-validation.ru.mdx @@ -0,0 +1,58 @@ +--- +title: "Field Same Java Utf8 Validation" +description: "Проверяет, что строковые поля сохраняют прежнее поведение проверки UTF-8 в Java." +--- + +- **ID правила:** `FIELD_SAME_JAVA_UTF8_VALIDATION` +- **Профили:** `FILE`, `PACKAGE` + +Это правило проверяет, что строковые поля (`string`) сохраняют эффективный режим валидации UTF-8 в Java, определяемый из `features.(pb.java).utf8_validation`, `features.utf8_validation`, настроек синтаксиса по умолчанию и файловой опции `java_string_check_utf8`. Изменение меняет поведение сгенерированного Java-кода при невалидном UTF-8. + +## Примеры + +### Неправильно + +**До:** + +```proto +edition = "2023"; + +package myapi.v1; + +message Note { + string text = 1 [features.utf8_validation = VERIFY]; +} +``` + +**После:** + +```proto +edition = "2023"; + +package myapi.v1; + +message Note { + string text = 1 [features.utf8_validation = NONE]; +} +``` + +**Ошибка:** + +```text +note.proto:6:3: Field "myapi.v1.Note.text" changed Java UTF-8 validation behavior. (FIELD_SAME_JAVA_UTF8_VALIDATION) +``` + +### Правильно + +Сохраняйте режим валидации UTF-8 неизменным для существующих `string`-полей (для произвольных байтов добавьте новое поле типа `bytes`): + +```proto +edition = "2023"; + +package myapi.v1; + +message Note { + string text = 1 [features.utf8_validation = VERIFY]; + bytes raw_text = 2; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/field-same-json-name.mdx b/content/docs/cli/breaking-changes/rules/field-same-json-name.mdx new file mode 100644 index 0000000..128e55b --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/field-same-json-name.mdx @@ -0,0 +1,57 @@ +--- +title: "Field Same Json Name" +description: "Checks that fields keep the same protobuf JSON field name." +--- + +- **Rule ID:** `FIELD_SAME_JSON_NAME` +- **Profiles:** `FILE`, `PACKAGE`, `WIRE_JSON` + +This rule checks that a field with the same proto name preserves its effective JSON name (either the default lowerCamelCase name or an explicit `[json_name = "..."]` override). Changing the JSON name breaks protobuf JSON serialization and deserialization across `FILE`, `PACKAGE`, and `WIRE_JSON`. + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + string user_id = 1 [json_name = "userId"]; +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + string user_id = 1 [json_name = "uid"]; +} +``` + +**Error:** + +```text +user.proto:6:3: Field "user_id" (1) changed JSON name from "userId" to "uid". (FIELD_SAME_JSON_NAME) +``` + +### Good + +Keep the effective `json_name` unchanged on existing fields: + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + string user_id = 1 [json_name = "userId"]; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/field-same-json-name.ru.mdx b/content/docs/cli/breaking-changes/rules/field-same-json-name.ru.mdx new file mode 100644 index 0000000..c9865c1 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/field-same-json-name.ru.mdx @@ -0,0 +1,57 @@ +--- +title: "Field Same Json Name" +description: "Проверяет, что поля сохраняют прежнее JSON-имя поля." +--- + +- **ID правила:** `FIELD_SAME_JSON_NAME` +- **Профили:** `FILE`, `PACKAGE`, `WIRE_JSON` + +Это правило проверяет, что поле с тем же proto-именем сохраняет прежнее эффективное JSON-имя (автоматический lowerCamelCase или явный `[json_name = "..."]`). Изменение JSON-имени ломает JSON-сериализацию и десериализацию Protobuf в профилях `FILE`, `PACKAGE` и `WIRE_JSON`. + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + string user_id = 1 [json_name = "userId"]; +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + string user_id = 1 [json_name = "uid"]; +} +``` + +**Ошибка:** + +```text +user.proto:6:3: Field "user_id" (1) changed JSON name from "userId" to "uid". (FIELD_SAME_JSON_NAME) +``` + +### Правильно + +Сохраняйте эффективное `json_name` неизменным на существующих полях: + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + string user_id = 1 [json_name = "userId"]; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/field-same-jstype.mdx b/content/docs/cli/breaking-changes/rules/field-same-jstype.mdx new file mode 100644 index 0000000..84eb7d6 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/field-same-jstype.mdx @@ -0,0 +1,57 @@ +--- +title: "Field Same Jstype" +description: "Checks that fields keep the same jstype code-generation option." +--- + +- **Rule ID:** `FIELD_SAME_JSTYPE` +- **Profiles:** `FILE`, `PACKAGE` + +This rule checks that fields preserve their `[jstype = ...]` option (`JS_NORMAL`, `JS_STRING`, or `JS_NUMBER`). Changing `jstype` alters generated JavaScript/TypeScript field types for 64-bit integer fields. + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Account { + int64 balance_cents = 1 [jstype = JS_STRING]; +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Account { + int64 balance_cents = 1 [jstype = JS_NUMBER]; +} +``` + +**Error:** + +```text +account.proto:6:3: Field "myapi.v1.Account.balance_cents" changed jstype option. (FIELD_SAME_JSTYPE) +``` + +### Good + +Keep `[jstype = ...]` unchanged on existing fields: + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Account { + int64 balance_cents = 1 [jstype = JS_STRING]; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/field-same-jstype.ru.mdx b/content/docs/cli/breaking-changes/rules/field-same-jstype.ru.mdx new file mode 100644 index 0000000..f0ba545 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/field-same-jstype.ru.mdx @@ -0,0 +1,57 @@ +--- +title: "Field Same Jstype" +description: "Проверяет, что поля сохраняют прежнюю опцию кодогенерации jstype." +--- + +- **ID правила:** `FIELD_SAME_JSTYPE` +- **Профили:** `FILE`, `PACKAGE` + +Это правило проверяет, что поля сохраняют значение опции `[jstype = ...]` (`JS_NORMAL`, `JS_STRING` или `JS_NUMBER`). Изменение `jstype` меняет типы 64-битных целых полей в сгенерированном JavaScript/TypeScript-коде. + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Account { + int64 balance_cents = 1 [jstype = JS_STRING]; +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Account { + int64 balance_cents = 1 [jstype = JS_NUMBER]; +} +``` + +**Ошибка:** + +```text +account.proto:6:3: Field "myapi.v1.Account.balance_cents" changed jstype option. (FIELD_SAME_JSTYPE) +``` + +### Правильно + +Сохраняйте опцию `[jstype = ...]` неизменной на существующих полях: + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Account { + int64 balance_cents = 1 [jstype = JS_STRING]; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/field-same-name.mdx b/content/docs/cli/breaking-changes/rules/field-same-name.mdx new file mode 100644 index 0000000..340536a --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/field-same-name.mdx @@ -0,0 +1,58 @@ +--- +title: "Field Same Name" +description: "Checks that fields keep the same name for a given field number." +--- + +- **Rule ID:** `FIELD_SAME_NAME` +- **Profiles:** `FILE`, `PACKAGE`, `WIRE_JSON` + +This rule checks that a field at a given number keeps the same name. Renaming a field breaks generated code (`FILE`, `PACKAGE`) and protobuf JSON / text-format payloads (`WIRE_JSON`), even if you try to preserve `json_name`. In the `WIRE` profile, binary encoding identifies fields by number only, so renaming is allowed there. + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + string first_name = 1; +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + string given_name = 1; +} +``` + +**Error:** + +```text +user.proto:6:3: Field "first_name" (1) on "myapi.v1.User" changed name to "given_name". (FIELD_SAME_NAME) +``` + +### Good + +Keep the original field name and add a new field with the desired name: + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + string first_name = 1 [deprecated = true]; + string given_name = 2; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/field-same-name.ru.mdx b/content/docs/cli/breaking-changes/rules/field-same-name.ru.mdx new file mode 100644 index 0000000..4f0da50 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/field-same-name.ru.mdx @@ -0,0 +1,58 @@ +--- +title: "Field Same Name" +description: "Проверяет, что поля сохраняют прежнее имя для своего номера." +--- + +- **ID правила:** `FIELD_SAME_NAME` +- **Профили:** `FILE`, `PACKAGE`, `WIRE_JSON` + +Это правило проверяет, что поле с тем же номером сохраняет прежнее имя. Переименование поля ломает сгенерированный код (`FILE`, `PACKAGE`) и JSON/текстовый формат (`WIRE_JSON`), даже если сохранить прежний `json_name`. В профиле `WIRE` бинарный формат опирается только на номер поля, поэтому там переименование допустимо. + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + string first_name = 1; +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + string given_name = 1; +} +``` + +**Ошибка:** + +```text +user.proto:6:3: Field "first_name" (1) on "myapi.v1.User" changed name to "given_name". (FIELD_SAME_NAME) +``` + +### Правильно + +Сохраните исходное имя поля и добавьте новое поле с нужным именем: + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + string first_name = 1 [deprecated = true]; + string given_name = 2; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/field-same-oneof.mdx b/content/docs/cli/breaking-changes/rules/field-same-oneof.mdx new file mode 100644 index 0000000..92a1785 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/field-same-oneof.mdx @@ -0,0 +1,67 @@ +--- +title: "Field Same Oneof" +description: "Checks that fields do not move into, out of, or between real oneof blocks." +--- + +- **Rule ID:** `FIELD_SAME_ONEOF` +- **Profiles:** `FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE` + +This rule checks that a field keeps the same real `oneof` membership (synthetic oneofs created by proto3 `optional` fields are ignored). Moving a field into a `oneof`, moving it out of a `oneof`, or moving it to a different `oneof` changes mutual-exclusivity semantics and generated types across all four profiles (`FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE`). + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Contact { + oneof destination { + string email = 1; + string phone = 2; + } +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Contact { + oneof destination { + string email = 1; + } + string phone = 2; +} +``` + +**Error:** + +```text +contact.proto:8:5: Field "phone" (2) changed real oneof membership. (FIELD_SAME_ONEOF) +``` + +### Good + +Keep existing fields in their original `oneof` and add new fields outside or inside a new `oneof`: + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Contact { + oneof destination { + string email = 1; + string phone = 2 [deprecated = true]; + } + string secondary_phone = 3; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/field-same-oneof.ru.mdx b/content/docs/cli/breaking-changes/rules/field-same-oneof.ru.mdx new file mode 100644 index 0000000..ec2fea0 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/field-same-oneof.ru.mdx @@ -0,0 +1,67 @@ +--- +title: "Field Same Oneof" +description: "Проверяет, что поля не перемещаются в настоящий блок oneof, из него или между разными oneof." +--- + +- **ID правила:** `FIELD_SAME_ONEOF` +- **Профили:** `FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE` + +Это правило проверяет, что принадлежность поля к настоящему блоку `oneof` не меняется (синтетические oneof для `optional`-полей proto3 игнорируются). Перенос поля в `oneof`, вынос из `oneof` или перенос в другой `oneof` ломает семантику взаимной исключаемости и сгенерированные типы во всех четырёх профилях (`FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE`). + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Contact { + oneof destination { + string email = 1; + string phone = 2; + } +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Contact { + oneof destination { + string email = 1; + } + string phone = 2; +} +``` + +**Ошибка:** + +```text +contact.proto:8:5: Field "phone" (2) changed real oneof membership. (FIELD_SAME_ONEOF) +``` + +### Правильно + +Сохраните существующие поля в их исходном `oneof`, а новые добавьте отдельно или в новый `oneof`: + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Contact { + oneof destination { + string email = 1; + string phone = 2 [deprecated = true]; + } + string secondary_phone = 3; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/field-same-type.mdx b/content/docs/cli/breaking-changes/rules/field-same-type.mdx index 70f5503..35128c6 100644 --- a/content/docs/cli/breaking-changes/rules/field-same-type.mdx +++ b/content/docs/cli/breaking-changes/rules/field-same-type.mdx @@ -1,18 +1,26 @@ --- title: "Field Same Type" +description: "Checks that fields keep the exact same protobuf type in source-compatibility profiles." --- -Categories: +- **Rule ID:** `FIELD_SAME_TYPE` +- **Profiles:** `FILE`, `PACKAGE` -- **WIRE+** +This rule checks that message and extension fields keep their exact protobuf type (scalar kind or fully qualified message/enum name). Changing a field's type breaks generated source code because field types and method signatures change. -This rule checks that message fields maintain the same type. Changing a field's type breaks wire format compatibility and generated code, as the binary representation and client code expectations differ between types. + +`FIELD_SAME_TYPE` enforces strict type equality for `FILE` and `PACKAGE` profiles — even for transitions that are wire-compatible (such as `int32` → `int64` or `int32` → `uint32`). For binary or JSON compatibility instead of generated-source compatibility, use the `WIRE` or `WIRE_JSON` profile: + +- [`FIELD_WIRE_COMPATIBLE_TYPE`](/docs/cli/breaking-changes/rules/field-wire-compatible-type) (`WIRE`) allows binary-compatible transitions such as `int32` ↔ `uint32` ↔ `int64` ↔ `uint64` ↔ `bool`, `sint32` ↔ `sint64`, `fixed32` ↔ `sfixed32`, `fixed64` ↔ `sfixed64`, `string` → `bytes`, and structurally compatible message/enum types. +- [`FIELD_WIRE_JSON_COMPATIBLE_TYPE`](/docs/cli/breaking-changes/rules/field-wire-json-compatible-type) (`WIRE_JSON`) allows `int32` ↔ `uint32`, `int64` ↔ `uint64`, `fixed32` ↔ `sfixed32`, `fixed64` ↔ `sfixed64`, and JSON-compatible message/enum types (rejecting `int32` → `int64` because 64-bit integers serialize as JSON strings, and rejecting `string` → `bytes` because `bytes` uses base64). + ## Examples ### Bad **Before:** + ```proto syntax = "proto3"; @@ -26,6 +34,7 @@ message Product { ``` **After:** + ```proto syntax = "proto3"; @@ -39,35 +48,15 @@ message Product { ``` **Error:** -``` -product.proto:5:3: Field "2" with name "price" on message "Product" changed type from "int32" to "string". (BREAKING_CHECK) -``` - -### More Examples -**Incompatible type changes:** - -```proto -// Before -message Order { - string id = 1; - int64 timestamp = 2; - repeated string tags = 3; - OrderStatus status = 4; -} - -// After - ALL BREAKING CHANGES! -message Order { - int32 id = 1; // string -> int32: BREAKING - string timestamp = 2; // int64 -> string: BREAKING - string tags = 3; // repeated -> singular: BREAKING - int32 status = 4; // enum -> int32: BREAKING -} +```text +product.proto:7:3: Field "price" (2) on "myapi.v1.Product" changed type from int32 to string. (FIELD_SAME_TYPE) ``` ### Good -**Instead of changing type, add a new field:** +Add a new field with the desired type and deprecate the old field: + ```proto syntax = "proto3"; @@ -77,78 +66,8 @@ message Product { string name = 1; int32 price = 2 [deprecated = true]; bool available = 3; - string price_formatted = 4; // New field for string price -} -``` - -**Or create a new message version:** -```proto -syntax = "proto3"; - -package myapi.v2; // New package version - -message Product { - string name = 1; - string price = 2; // Now string in v2 - bool available = 3; + string price_formatted = 4; } ``` -## Impact - -- **Wire Format:** Binary data cannot be deserialized correctly between versions -- **Generated Code:** Field types change, breaking client compilation -- **Runtime Errors:** Type mismatches cause parsing failures -- **Data Corruption:** Incorrect interpretation of binary data - -## Common Type Change Issues - -### Numeric Types -```proto -// BREAKING: Different wire representations -int32 -> int64 // Different encoding -int32 -> uint32 // Different sign interpretation -int32 -> string // Completely different format -``` - -### Collection Types -```proto -// BREAKING: Structure changes -string -> repeated string // Singular to collection -repeated int32 -> map // Array to map -``` - -### Message Types -```proto -// BREAKING: Different message structure -UserInfo -> UserProfile // Different message types -string -> UserInfo // Scalar to message -``` - -## Migration Strategy - -1. **Add new field** with correct type: - ```proto - int32 old_price = 2 [deprecated = true]; - string new_price = 5; // New field - ``` - -2. **Dual-write period** - populate both fields during transition - -3. **Update clients** to use new field - -4. **Remove old field** in next major version: - ```proto - reserved 2, "old_price"; - string new_price = 5; - ``` - -## Safe Type Changes (Wire Compatible) - -Note: EasyP currently treats ALL type changes as breaking. However, some changes are technically wire-compatible: - -- `int32` ↔ `uint32` (same encoding) -- `int64` ↔ `uint64` (same encoding) -- `string` → `bytes` (if UTF-8 valid) - -These may be supported in future EasyP versions with different strictness levels. +Or change the type in a new major package version (for example, `myapi.v2`). diff --git a/content/docs/cli/breaking-changes/rules/field-same-type.ru.mdx b/content/docs/cli/breaking-changes/rules/field-same-type.ru.mdx index 82c6cef..55753d2 100644 --- a/content/docs/cli/breaking-changes/rules/field-same-type.ru.mdx +++ b/content/docs/cli/breaking-changes/rules/field-same-type.ru.mdx @@ -1,18 +1,26 @@ --- title: "Field Same Type" +description: "Проверяет, что поля сохраняют точный protobuf-тип в профилях совместимости исходного кода." --- -Категории: +- **ID правила:** `FIELD_SAME_TYPE` +- **Профили:** `FILE`, `PACKAGE` -- **WIRE+** +Это правило проверяет, что поля сообщений и расширений сохраняют точный protobuf-тип (скалярный тип или полное имя сообщения/enum). Изменение типа поля ломает сгенерированный исходный код, поскольку меняются типы полей и сигнатуры методов доступа. -Правило проверяет, что типы полей сообщений (message fields) не изменяются. Смена типа поля ломает совместимость по wire‑формату и сгенерированный код: бинарное представление и ожидания клиентского кода различаются для разных типов. + +`FIELD_SAME_TYPE` требует строгого совпадения типов в профилях `FILE` и `PACKAGE` — даже для wire-совместимых переходов (например, `int32` → `int64` или `int32` → `uint32`). Если требуется проверять бинарную или JSON-совместимость вместо совместимости сгенерированного кода, используйте профили `WIRE` или `WIRE_JSON`: + +- [`FIELD_WIRE_COMPATIBLE_TYPE`](/ru/docs/cli/breaking-changes/rules/field-wire-compatible-type) (`WIRE`) допускает бинарно совместимые переходы: `int32` ↔ `uint32` ↔ `int64` ↔ `uint64` ↔ `bool`, `sint32` ↔ `sint64`, `fixed32` ↔ `sfixed32`, `fixed64` ↔ `sfixed64`, `string` → `bytes`, а также структурно совместимые сообщения и enum. +- [`FIELD_WIRE_JSON_COMPATIBLE_TYPE`](/ru/docs/cli/breaking-changes/rules/field-wire-json-compatible-type) (`WIRE_JSON`) допускает `int32` ↔ `uint32`, `int64` ↔ `uint64`, `fixed32` ↔ `sfixed32`, `fixed64` ↔ `sfixed64` и JSON-совместимые сообщения/enum (отклоняя `int32` → `int64`, так как 64-битные числа сериализуются в JSON строками, и `string` → `bytes`, так как `bytes` кодируется в base64). + ## Примеры -### Плохой (Breaking) +### Неправильно **До:** + ```proto syntax = "proto3"; @@ -26,6 +34,7 @@ message Product { ``` **После:** + ```proto syntax = "proto3"; @@ -33,121 +42,32 @@ package myapi.v1; message Product { string name = 1; - string price = 2; // Changed from int32 to string (изменён тип) + string price = 2; // Изменено с int32 на string bool available = 3; } ``` **Ошибка:** -``` -product.proto:5:3: Field "2" with name "price" on message "Product" changed type from "int32" to "string". (BREAKING_CHECK) -``` - -### Дополнительные примеры -**Несовместимые изменения типов:** -```proto -// Before -message Order { - string id = 1; - int64 timestamp = 2; - repeated string tags = 3; - OrderStatus status = 4; -} - -// After - ВСЁ BREAKING -message Order { - int32 id = 1; // string -> int32: BREAKING - string timestamp = 2; // int64 -> string: BREAKING - string tags = 3; // repeated -> singular: BREAKING - int32 status = 4; // enum -> int32: BREAKING -} +```text +product.proto:7:3: Field "price" (2) on "myapi.v1.Product" changed type from int32 to string. (FIELD_SAME_TYPE) ``` -### Хороший (Безопасный) +### Правильно -**Вместо смены типа — добавьте новое поле:** -```proto -syntax = "proto3"; - -package myapi.v1; - -message Product { - string name = 1; - int32 price = 2 [deprecated = true]; // Старое поле помечено deprecated - bool available = 3; - string price_formatted = 4; // Новое поле со строковым представлением -} -``` +Добавьте новое поле с нужным типом и пометьте старое как `deprecated`: -**Или создайте новую версию сообщения:** ```proto syntax = "proto3"; -package myapi.v2; // Новая версия package +package myapi.v1; message Product { string name = 1; - string price = 2; // В v2 уже string + int32 price = 2 [deprecated = true]; bool available = 3; + string price_formatted = 4; } ``` -## Влияние - -- **Wire Format:** Старые бинарные данные не десериализуются корректно -- **Generated Code:** Меняются типы в сгенерированном коде — клиенты не компилируются -- **Runtime Errors:** Ошибки парсинга при несовпадении ожидаемого типа -- **Data Corruption:** Неверная интерпретация байтов данных - -## Типовые проблемы изменений типов - -### Числовые типы -```proto -// BREAKING: различное кодирование/семантика -int32 -> int64 // Иное кодирование -int32 -> uint32 // Меняется знак -int32 -> string // Совсем другой формат -``` - -### Коллекции -```proto -// BREAKING: изменяется структура -string -> repeated string // Одиночное -> коллекция -repeated int32 -> map // Массив -> map -``` - -### Message типы -```proto -// BREAKING: другая структура сообщения -UserInfo -> UserProfile // Совершенно разные сообщения -string -> UserInfo // Скаляр -> сообщение -``` - -## Стратегия миграции - -1. **Добавьте новое поле** с нужным типом: - ```proto - int32 old_price = 2 [deprecated = true]; - string new_price = 5; // Новое поле - ``` - -2. **Период двойной записи** — заполняйте оба поля для совместимости - -3. **Мигрируйте клиентов** на новое поле постепенно - -4. **Удалите старое поле** в следующей major‑версии: - ```proto - reserved 2, "old_price"; - string new_price = 5; - ``` - -## Безопасные изменения (Теоретически wire‑совместимые) - -Примечание: EasyP сейчас считает ЛЮБУЮ смену типа breaking. Однако технически некоторые случаи совместимы: - -- `int32` ↔ `uint32` (одно кодирование) -- `int64` ↔ `uint64` (одно кодирование) -- `string` → `bytes` (если все строки валидный UTF‑8) - -Эти исключения могут получить отдельную обработку в будущих версиях EasyP с более гибкими уровнями строгости. +Либо измените тип поля в новой мажорной версии пакета (например, `myapi.v2`). diff --git a/content/docs/cli/breaking-changes/rules/field-same-utf8-validation.mdx b/content/docs/cli/breaking-changes/rules/field-same-utf8-validation.mdx new file mode 100644 index 0000000..90405d7 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/field-same-utf8-validation.mdx @@ -0,0 +1,57 @@ +--- +title: "Field Same Utf8 Validation" +description: "Checks that string fields keep the same effective UTF-8 validation mode." +--- + +- **Rule ID:** `FIELD_SAME_UTF8_VALIDATION` +- **Profiles:** `FILE`, `PACKAGE` + +This rule checks that `string` fields preserve their effective UTF-8 validation behavior (`VERIFY` vs `NONE`), resolved from `features.utf8_validation` on the field or its enclosing scopes, or the file syntax default (`VERIFY` in `proto3` and Editions 2023; `NONE` in `proto2`). + +## Examples + +### Bad + +**Before:** + +```proto +edition = "2023"; + +package myapi.v1; + +message Label { + string value = 1 [features.utf8_validation = VERIFY]; +} +``` + +**After:** + +```proto +edition = "2023"; + +package myapi.v1; + +message Label { + string value = 1 [features.utf8_validation = NONE]; +} +``` + +**Error:** + +```text +label.proto:6:3: Field "myapi.v1.Label.value" changed UTF-8 validation behavior. (FIELD_SAME_UTF8_VALIDATION) +``` + +### Good + +Keep `features.utf8_validation` unchanged on existing `string` fields: + +```proto +edition = "2023"; + +package myapi.v1; + +message Label { + string value = 1 [features.utf8_validation = VERIFY]; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/field-same-utf8-validation.ru.mdx b/content/docs/cli/breaking-changes/rules/field-same-utf8-validation.ru.mdx new file mode 100644 index 0000000..541c422 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/field-same-utf8-validation.ru.mdx @@ -0,0 +1,57 @@ +--- +title: "Field Same Utf8 Validation" +description: "Проверяет, что строковые поля сохраняют прежний эффективный режим проверки UTF-8." +--- + +- **ID правила:** `FIELD_SAME_UTF8_VALIDATION` +- **Профили:** `FILE`, `PACKAGE` + +Это правило проверяет, что поля типа `string` сохраняют эффективный режим валидации UTF-8 (`VERIFY` или `NONE`), вычисляемый из `features.utf8_validation` на поле или охватывающих областях видимости либо из значения по умолчанию для синтаксиса (`VERIFY` в `proto3` и Editions 2023; `NONE` в `proto2`). + +## Примеры + +### Неправильно + +**До:** + +```proto +edition = "2023"; + +package myapi.v1; + +message Label { + string value = 1 [features.utf8_validation = VERIFY]; +} +``` + +**После:** + +```proto +edition = "2023"; + +package myapi.v1; + +message Label { + string value = 1 [features.utf8_validation = NONE]; +} +``` + +**Ошибка:** + +```text +label.proto:6:3: Field "myapi.v1.Label.value" changed UTF-8 validation behavior. (FIELD_SAME_UTF8_VALIDATION) +``` + +### Правильно + +Не изменяйте `features.utf8_validation` на существующих полях `string`: + +```proto +edition = "2023"; + +package myapi.v1; + +message Label { + string value = 1 [features.utf8_validation = VERIFY]; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/field-wire-compatible-cardinality.mdx b/content/docs/cli/breaking-changes/rules/field-wire-compatible-cardinality.mdx new file mode 100644 index 0000000..0864e02 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/field-wire-compatible-cardinality.mdx @@ -0,0 +1,58 @@ +--- +title: "Field Wire Compatible Cardinality" +description: "Checks that field cardinality changes remain binary wire-compatible in the WIRE profile." +--- + +- **Rule ID:** `FIELD_WIRE_COMPATIBLE_CARDINALITY` +- **Profiles:** `WIRE` + +In the `WIRE` profile, a field may change between implicit and explicit `optional` presence (`string` ↔ `optional string`), and between a `map` and a `repeated` message whose entry fields are wire-compatible. Switching between singular and `repeated`/`map`, or adding/removing `required`, is rejected. + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Article { + string tag = 1; +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Article { + repeated string tag = 1; +} +``` + +**Error:** + +```text +article.proto:6:3: Field "tag" (1) on "myapi.v1.Article" changed cardinality from optional_implicit to repeated. (FIELD_WIRE_COMPATIBLE_CARDINALITY) +``` + +### Good + +Keep wire-compatible cardinality (for example, adding explicit `optional` in proto3 is allowed in `WIRE`, whereas changing singular to `repeated` requires a new field): + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Article { + optional string tag = 1; + repeated string tags = 2; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/field-wire-compatible-cardinality.ru.mdx b/content/docs/cli/breaking-changes/rules/field-wire-compatible-cardinality.ru.mdx new file mode 100644 index 0000000..319fecb --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/field-wire-compatible-cardinality.ru.mdx @@ -0,0 +1,58 @@ +--- +title: "Field Wire Compatible Cardinality" +description: "Проверяет, что изменения кардинальности поля остаются совместимыми по бинарному формату в профиле WIRE." +--- + +- **ID правила:** `FIELD_WIRE_COMPATIBLE_CARDINALITY` +- **Профили:** `WIRE` + +В профиле `WIRE` допускается переключение между неявным и явным `optional` (`string` ↔ `optional string`), а также преобразование между `map` и `repeated`-сообщением с бинарно совместимыми entry-полями. Переход между одиночным полем и `repeated`/`map`, а также любые изменения `required`, отклоняются. + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Article { + string tag = 1; +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Article { + repeated string tag = 1; +} +``` + +**Ошибка:** + +```text +article.proto:6:3: Field "tag" (1) on "myapi.v1.Article" changed cardinality from optional_implicit to repeated. (FIELD_WIRE_COMPATIBLE_CARDINALITY) +``` + +### Правильно + +Используйте wire-совместимые переходы (например, добавление явного `optional` в proto3 допустимо в `WIRE`, а переход от одиночного поля к `repeated` требует нового поля): + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Article { + optional string tag = 1; + repeated string tags = 2; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/field-wire-compatible-type.mdx b/content/docs/cli/breaking-changes/rules/field-wire-compatible-type.mdx new file mode 100644 index 0000000..dd5883a --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/field-wire-compatible-type.mdx @@ -0,0 +1,57 @@ +--- +title: "Field Wire Compatible Type" +description: "Checks that field type changes remain binary wire-compatible in the WIRE profile." +--- + +- **Rule ID:** `FIELD_WIRE_COMPATIBLE_TYPE` +- **Profiles:** `WIRE` + +In the `WIRE` profile, type changes are allowed only within binary wire-compatible families: `int32`/`uint32`/`int64`/`uint64`/`bool`, `sint32`/`sint64`, `fixed32`/`sfixed32`, `fixed64`/`sfixed64`, one-way `string` → `bytes`, and structurally wire-compatible messages or enums. Incompatible changes (such as `int32` → `sint32`, `bytes` → `string`, or `int32` → `string`) are rejected. + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Metric { + int32 count = 1; +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Metric { + sint32 count = 1; // ZigZag encoding is not wire-compatible with int32 +} +``` + +**Error:** + +```text +metric.proto:6:3: Field "count" (1) on "myapi.v1.Metric" changed incompatibly from int32 to sint32. (FIELD_WIRE_COMPATIBLE_TYPE) +``` + +### Good + +Use only binary-compatible type transitions (such as `int32` → `int64`), or add a new field for incompatible types: + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Metric { + int64 count = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/field-wire-compatible-type.ru.mdx b/content/docs/cli/breaking-changes/rules/field-wire-compatible-type.ru.mdx new file mode 100644 index 0000000..7a217c1 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/field-wire-compatible-type.ru.mdx @@ -0,0 +1,57 @@ +--- +title: "Field Wire Compatible Type" +description: "Проверяет, что изменения типа поля остаются совместимыми по бинарному формату в профиле WIRE." +--- + +- **ID правила:** `FIELD_WIRE_COMPATIBLE_TYPE` +- **Профили:** `WIRE` + +В профиле `WIRE` смена типа допускается только внутри бинарно совместимых семейств: `int32`/`uint32`/`int64`/`uint64`/`bool`, `sint32`/`sint64`, `fixed32`/`sfixed32`, `fixed64`/`sfixed64`, односторонний переход `string` → `bytes`, а также структурно wire-совместимые сообщения и enum. Несовместимые переходы (например, `int32` → `sint32`, `bytes` → `string`, `int32` → `string`) отклоняются. + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Metric { + int32 count = 1; +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Metric { + sint32 count = 1; // ZigZag encoding is not wire-compatible with int32 +} +``` + +**Ошибка:** + +```text +metric.proto:6:3: Field "count" (1) on "myapi.v1.Metric" changed incompatibly from int32 to sint32. (FIELD_WIRE_COMPATIBLE_TYPE) +``` + +### Правильно + +Используйте только бинарно совместимые переходы (например, `int32` → `int64`), а для несовместимых типов добавьте новое поле: + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Metric { + int64 count = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/field-wire-json-compatible-cardinality.mdx b/content/docs/cli/breaking-changes/rules/field-wire-json-compatible-cardinality.mdx new file mode 100644 index 0000000..d7c288e --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/field-wire-json-compatible-cardinality.mdx @@ -0,0 +1,68 @@ +--- +title: "Field Wire Json Compatible Cardinality" +description: "Checks that field cardinality changes remain both binary and JSON wire-compatible in WIRE_JSON." +--- + +- **Rule ID:** `FIELD_WIRE_JSON_COMPATIBLE_CARDINALITY` +- **Profiles:** `WIRE_JSON` + +In the `WIRE_JSON` profile, toggling between implicit and explicit `optional` presence (`string` ↔ `optional string`) is allowed. Converting between `repeated` entry messages and `map` is rejected because protobuf JSON encodes `repeated` as a JSON array and `map` as a JSON object. + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message LabelEntry { + string key = 1; + string value = 2; +} + +message Resource { + repeated LabelEntry labels = 1; +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Resource { + map labels = 1; +} +``` + +**Error:** + +```text +resource.proto:11:3: Field "labels" (1) on "myapi.v1.Resource" changed cardinality from repeated to map. (FIELD_WIRE_JSON_COMPATIBLE_CARDINALITY) +``` + +### Good + +Add a new `map` field instead of converting an existing `repeated` field in place: + +```proto +syntax = "proto3"; + +package myapi.v1; + +message LabelEntry { + string key = 1; + string value = 2; +} + +message Resource { + repeated LabelEntry labels = 1 [deprecated = true]; + map label_map = 2; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/field-wire-json-compatible-cardinality.ru.mdx b/content/docs/cli/breaking-changes/rules/field-wire-json-compatible-cardinality.ru.mdx new file mode 100644 index 0000000..3d0ab0c --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/field-wire-json-compatible-cardinality.ru.mdx @@ -0,0 +1,68 @@ +--- +title: "Field Wire Json Compatible Cardinality" +description: "Проверяет, что изменения кардинальности поля остаются совместимыми по бинарному формату и JSON в профиле WIRE_JSON." +--- + +- **ID правила:** `FIELD_WIRE_JSON_COMPATIBLE_CARDINALITY` +- **Профили:** `WIRE_JSON` + +В профиле `WIRE_JSON` допускается переключение между неявным и явным `optional` (`string` ↔ `optional string`). Преобразование между `repeated` и `map` отклоняется, потому что в JSON `repeated` сериализуется как массив, а `map` — как объект. + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message LabelEntry { + string key = 1; + string value = 2; +} + +message Resource { + repeated LabelEntry labels = 1; +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Resource { + map labels = 1; +} +``` + +**Ошибка:** + +```text +resource.proto:11:3: Field "labels" (1) on "myapi.v1.Resource" changed cardinality from repeated to map. (FIELD_WIRE_JSON_COMPATIBLE_CARDINALITY) +``` + +### Правильно + +Добавьте новое поле `map` вместо замены существующего поля `repeated`: + +```proto +syntax = "proto3"; + +package myapi.v1; + +message LabelEntry { + string key = 1; + string value = 2; +} + +message Resource { + repeated LabelEntry labels = 1 [deprecated = true]; + map label_map = 2; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/field-wire-json-compatible-type.mdx b/content/docs/cli/breaking-changes/rules/field-wire-json-compatible-type.mdx new file mode 100644 index 0000000..b5f6675 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/field-wire-json-compatible-type.mdx @@ -0,0 +1,58 @@ +--- +title: "Field Wire Json Compatible Type" +description: "Checks that field type changes remain both binary and JSON compatible in WIRE_JSON." +--- + +- **Rule ID:** `FIELD_WIRE_JSON_COMPATIBLE_TYPE` +- **Profiles:** `WIRE_JSON` + +In the `WIRE_JSON` profile, scalar type changes are allowed only within JSON- and wire-compatible pairs: `int32`/`uint32`, `int64`/`uint64`, `fixed32`/`sfixed32`, and `fixed64`/`sfixed64` (plus JSON-compatible messages and enums). Transitions like `int32` → `int64` (JSON number vs JSON string) or `string` → `bytes` (UTF-8 string vs base64 string) are rejected. + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Item { + int32 count = 1; +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Item { + int64 count = 1; // Serialized as string in Protobuf JSON +} +``` + +**Error:** + +```text +item.proto:6:3: Field "count" (1) on "myapi.v1.Item" changed incompatibly from int32 to int64. (FIELD_WIRE_JSON_COMPATIBLE_TYPE) +``` + +### Good + +Add a new 64-bit field when JSON compatibility is required (or switch only between JSON-compatible pairs like `int32` ↔ `uint32`): + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Item { + int32 count = 1 [deprecated = true]; + int64 count_v2 = 2; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/field-wire-json-compatible-type.ru.mdx b/content/docs/cli/breaking-changes/rules/field-wire-json-compatible-type.ru.mdx new file mode 100644 index 0000000..0852bc6 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/field-wire-json-compatible-type.ru.mdx @@ -0,0 +1,58 @@ +--- +title: "Field Wire Json Compatible Type" +description: "Проверяет, что изменения типа поля остаются совместимыми по бинарному формату и JSON в профиле WIRE_JSON." +--- + +- **ID правила:** `FIELD_WIRE_JSON_COMPATIBLE_TYPE` +- **Профили:** `WIRE_JSON` + +В профиле `WIRE_JSON` смена скалярного типа допускается только внутри пар, совместимых и в бинарном формате, и в JSON: `int32`/`uint32`, `int64`/`uint64`, `fixed32`/`sfixed32` и `fixed64`/`sfixed64` (а также JSON-совместимые сообщения и enum). Переходы вроде `int32` → `int64` (число против строки в JSON) или `string` → `bytes` (строка против base64) отклоняются. + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Item { + int32 count = 1; +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Item { + int64 count = 1; // Serialized as string in Protobuf JSON +} +``` + +**Ошибка:** + +```text +item.proto:6:3: Field "count" (1) on "myapi.v1.Item" changed incompatibly from int32 to int64. (FIELD_WIRE_JSON_COMPATIBLE_TYPE) +``` + +### Правильно + +При требовании JSON-совместимости добавьте новое 64-битное поле (либо меняйте тип только внутри JSON-совместимых пар вроде `int32` ↔ `uint32`): + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Item { + int32 count = 1 [deprecated = true]; + int64 count_v2 = 2; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-no-delete.mdx b/content/docs/cli/breaking-changes/rules/file-no-delete.mdx new file mode 100644 index 0000000..5fd6b23 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-no-delete.mdx @@ -0,0 +1,54 @@ +--- +title: "File No Delete" +description: "Checks that no target .proto files are deleted or renamed." +--- + +- **Rule ID:** `FILE_NO_DELETE` +- **Profiles:** `FILE` + +This rule checks that no target `.proto` file present in the baseline is deleted or renamed. Deleting a file breaks downstream `.proto` imports and removes generated file-level artifacts. If you want to move declarations between files in the same package without triggering file-level errors, use the `PACKAGE` profile instead of `FILE`. + +## Examples + +### Bad + +**Before:** + +```proto +// File: myapi/v1/legacy.proto +syntax = "proto3"; + +package myapi.v1; + +message LegacyItem { + string id = 1; +} +``` + +**After:** + +```proto +// File myapi/v1/legacy.proto was deleted +``` + +**Error:** + +```text +myapi/v1/legacy.proto:1:1: File "myapi/v1/legacy.proto" was deleted. (FILE_NO_DELETE) +``` + +### Good + +Keep the file in place and deprecate its declarations until the next major package version: + +```proto +// File: myapi/v1/legacy.proto +syntax = "proto3"; + +package myapi.v1; + +message LegacyItem { + option deprecated = true; + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-no-delete.ru.mdx b/content/docs/cli/breaking-changes/rules/file-no-delete.ru.mdx new file mode 100644 index 0000000..d015efd --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-no-delete.ru.mdx @@ -0,0 +1,54 @@ +--- +title: "File No Delete" +description: "Проверяет, что ни один целевой .proto-файл не был удалён или переименован." +--- + +- **ID правила:** `FILE_NO_DELETE` +- **Профили:** `FILE` + +Это правило проверяет, что ни один целевой `.proto`-файл из базовой ревизии не был удалён или переименован. Удаление файла ломает `import` в зависимых схемах и убирает сгенерированные файловые артефакты. Если нужно переносить объявления между файлами внутри одного пакета, используйте профиль `PACKAGE` вместо `FILE`. + +## Примеры + +### Неправильно + +**До:** + +```proto +// File: myapi/v1/legacy.proto +syntax = "proto3"; + +package myapi.v1; + +message LegacyItem { + string id = 1; +} +``` + +**После:** + +```proto +// File myapi/v1/legacy.proto was deleted +``` + +**Ошибка:** + +```text +myapi/v1/legacy.proto:1:1: File "myapi/v1/legacy.proto" was deleted. (FILE_NO_DELETE) +``` + +### Правильно + +Оставьте файл на месте и пометьте его объявления как `deprecated` до следующей мажорной версии пакета: + +```proto +// File: myapi/v1/legacy.proto +syntax = "proto3"; + +package myapi.v1; + +message LegacyItem { + option deprecated = true; + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-cc-enable-arenas.mdx b/content/docs/cli/breaking-changes/rules/file-same-cc-enable-arenas.mdx new file mode 100644 index 0000000..30da840 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-cc-enable-arenas.mdx @@ -0,0 +1,63 @@ +--- +title: "File Same Cc Enable Arenas" +description: "Checks that files keep the same cc_enable_arenas option value." +--- + +- **Rule ID:** `FILE_SAME_CC_ENABLE_ARENAS` +- **Profiles:** `FILE`, `PACKAGE` + +This rule checks that the file-level `cc_enable_arenas` option does not change for a file or for any declaration moved to another file in the same package. Changing `cc_enable_arenas` alters arena allocation support in generated C++ classes, breaking source compatibility for C++ consumers. + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option cc_enable_arenas = true; + +message User { + string id = 1; +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option cc_enable_arenas = false; + +message User { + string id = 1; +} +``` + +**Error:** + +```text +user.proto:1:1: File option cc_enable_arenas changed. (FILE_SAME_CC_ENABLE_ARENAS) +``` + +### Good + +Keep `option cc_enable_arenas` unchanged in the existing package version; change it only in a new major package version (for example, `myapi.v2`). + +```proto +syntax = "proto3"; + +package myapi.v1; + +option cc_enable_arenas = true; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-cc-enable-arenas.ru.mdx b/content/docs/cli/breaking-changes/rules/file-same-cc-enable-arenas.ru.mdx new file mode 100644 index 0000000..36886b9 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-cc-enable-arenas.ru.mdx @@ -0,0 +1,63 @@ +--- +title: "File Same Cc Enable Arenas" +description: "Проверяет, что файлы сохраняют прежнее значение опции cc_enable_arenas." +--- + +- **ID правила:** `FILE_SAME_CC_ENABLE_ARENAS` +- **Профили:** `FILE`, `PACKAGE` + +Это правило проверяет, что файловая опция `cc_enable_arenas` не изменилась у файла (а также у объявлений, перенесённых в другой файл того же пакета). Изменение `cc_enable_arenas` меняет поддержку arena-аллокации в сгенерированных классах C++ и ломает совместимость сгенерированного кода для C++. + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option cc_enable_arenas = true; + +message User { + string id = 1; +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option cc_enable_arenas = false; + +message User { + string id = 1; +} +``` + +**Ошибка:** + +```text +user.proto:1:1: File option cc_enable_arenas changed. (FILE_SAME_CC_ENABLE_ARENAS) +``` + +### Правильно + +Сохраняйте `option cc_enable_arenas` неизменной в текущей мажорной версии пакета; меняйте её только в новой мажорной версии (например, `myapi.v2`). + +```proto +syntax = "proto3"; + +package myapi.v1; + +option cc_enable_arenas = true; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-cc-generic-services.mdx b/content/docs/cli/breaking-changes/rules/file-same-cc-generic-services.mdx new file mode 100644 index 0000000..41ab9dd --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-cc-generic-services.mdx @@ -0,0 +1,63 @@ +--- +title: "File Same Cc Generic Services" +description: "Checks that files keep the same cc_generic_services option value." +--- + +- **Rule ID:** `FILE_SAME_CC_GENERIC_SERVICES` +- **Profiles:** `FILE`, `PACKAGE` + +This rule checks that the file-level `cc_generic_services` option does not change for a file or for any declaration moved to another file in the same package. Changing `cc_generic_services` alters whether abstract C++ generic service stubs are generated, breaking source compatibility for C++ consumers. + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option cc_generic_services = true; + +message User { + string id = 1; +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option cc_generic_services = false; + +message User { + string id = 1; +} +``` + +**Error:** + +```text +user.proto:1:1: File option cc_generic_services changed. (FILE_SAME_CC_GENERIC_SERVICES) +``` + +### Good + +Keep `option cc_generic_services` unchanged in the existing package version; change it only in a new major package version (for example, `myapi.v2`). + +```proto +syntax = "proto3"; + +package myapi.v1; + +option cc_generic_services = true; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-cc-generic-services.ru.mdx b/content/docs/cli/breaking-changes/rules/file-same-cc-generic-services.ru.mdx new file mode 100644 index 0000000..a8021a6 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-cc-generic-services.ru.mdx @@ -0,0 +1,63 @@ +--- +title: "File Same Cc Generic Services" +description: "Проверяет, что файлы сохраняют прежнее значение опции cc_generic_services." +--- + +- **ID правила:** `FILE_SAME_CC_GENERIC_SERVICES` +- **Профили:** `FILE`, `PACKAGE` + +Это правило проверяет, что файловая опция `cc_generic_services` не изменилась у файла (а также у объявлений, перенесённых в другой файл того же пакета). Изменение `cc_generic_services` меняет генерацию абстрактных generic-стабов сервисов в C++ и ломает совместимость сгенерированного кода для C++. + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option cc_generic_services = true; + +message User { + string id = 1; +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option cc_generic_services = false; + +message User { + string id = 1; +} +``` + +**Ошибка:** + +```text +user.proto:1:1: File option cc_generic_services changed. (FILE_SAME_CC_GENERIC_SERVICES) +``` + +### Правильно + +Сохраняйте `option cc_generic_services` неизменной в текущей мажорной версии пакета; меняйте её только в новой мажорной версии (например, `myapi.v2`). + +```proto +syntax = "proto3"; + +package myapi.v1; + +option cc_generic_services = true; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-csharp-namespace.mdx b/content/docs/cli/breaking-changes/rules/file-same-csharp-namespace.mdx new file mode 100644 index 0000000..fcf49da --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-csharp-namespace.mdx @@ -0,0 +1,63 @@ +--- +title: "File Same Csharp Namespace" +description: "Checks that files keep the same csharp_namespace option value." +--- + +- **Rule ID:** `FILE_SAME_CSHARP_NAMESPACE` +- **Profiles:** `FILE`, `PACKAGE` + +This rule checks that the file-level `csharp_namespace` option does not change for a file or for any declaration moved to another file in the same package. Changing `csharp_namespace` alters the generated C# namespace for all types in the file, breaking source compatibility for C# consumers. + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option csharp_namespace = "MyApi.V1"; + +message User { + string id = 1; +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option csharp_namespace = "Acme.MyApi.V1"; + +message User { + string id = 1; +} +``` + +**Error:** + +```text +user.proto:1:1: File option csharp_namespace changed. (FILE_SAME_CSHARP_NAMESPACE) +``` + +### Good + +Keep `option csharp_namespace` unchanged in the existing package version; change it only in a new major package version (for example, `myapi.v2`). + +```proto +syntax = "proto3"; + +package myapi.v1; + +option csharp_namespace = "MyApi.V1"; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-csharp-namespace.ru.mdx b/content/docs/cli/breaking-changes/rules/file-same-csharp-namespace.ru.mdx new file mode 100644 index 0000000..166e820 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-csharp-namespace.ru.mdx @@ -0,0 +1,63 @@ +--- +title: "File Same Csharp Namespace" +description: "Проверяет, что файлы сохраняют прежнее значение опции csharp_namespace." +--- + +- **ID правила:** `FILE_SAME_CSHARP_NAMESPACE` +- **Профили:** `FILE`, `PACKAGE` + +Это правило проверяет, что файловая опция `csharp_namespace` не изменилась у файла (а также у объявлений, перенесённых в другой файл того же пакета). Изменение `csharp_namespace` меняет сгенерированное пространство имён C# для всех типов файла и ломает совместимость сгенерированного кода для C#. + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option csharp_namespace = "MyApi.V1"; + +message User { + string id = 1; +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option csharp_namespace = "Acme.MyApi.V1"; + +message User { + string id = 1; +} +``` + +**Ошибка:** + +```text +user.proto:1:1: File option csharp_namespace changed. (FILE_SAME_CSHARP_NAMESPACE) +``` + +### Правильно + +Сохраняйте `option csharp_namespace` неизменной в текущей мажорной версии пакета; меняйте её только в новой мажорной версии (например, `myapi.v2`). + +```proto +syntax = "proto3"; + +package myapi.v1; + +option csharp_namespace = "MyApi.V1"; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-go-package.mdx b/content/docs/cli/breaking-changes/rules/file-same-go-package.mdx new file mode 100644 index 0000000..4d3f335 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-go-package.mdx @@ -0,0 +1,63 @@ +--- +title: "File Same Go Package" +description: "Checks that files keep the same go_package option value." +--- + +- **Rule ID:** `FILE_SAME_GO_PACKAGE` +- **Profiles:** `FILE`, `PACKAGE` + +This rule checks that the file-level `go_package` option does not change for a file or for any declaration moved to another file in the same package. Changing `go_package` alters the generated Go import path and package identifier, breaking source compatibility for Go consumers. + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option go_package = "github.com/acme/myapi/gen/v1;myapiv1"; + +message User { + string id = 1; +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option go_package = "github.com/acme/myapi/gen/users/v1;usersv1"; + +message User { + string id = 1; +} +``` + +**Error:** + +```text +user.proto:1:1: File option go_package changed. (FILE_SAME_GO_PACKAGE) +``` + +### Good + +Keep `option go_package` unchanged in the existing package version; change it only in a new major package version (for example, `myapi.v2`). + +```proto +syntax = "proto3"; + +package myapi.v1; + +option go_package = "github.com/acme/myapi/gen/v1;myapiv1"; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-go-package.ru.mdx b/content/docs/cli/breaking-changes/rules/file-same-go-package.ru.mdx new file mode 100644 index 0000000..8fce366 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-go-package.ru.mdx @@ -0,0 +1,63 @@ +--- +title: "File Same Go Package" +description: "Проверяет, что файлы сохраняют прежнее значение опции go_package." +--- + +- **ID правила:** `FILE_SAME_GO_PACKAGE` +- **Профили:** `FILE`, `PACKAGE` + +Это правило проверяет, что файловая опция `go_package` не изменилась у файла (а также у объявлений, перенесённых в другой файл того же пакета). Изменение `go_package` меняет путь импорта и имя сгенерированного пакета Go и ломает совместимость сгенерированного кода для Go. + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option go_package = "github.com/acme/myapi/gen/v1;myapiv1"; + +message User { + string id = 1; +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option go_package = "github.com/acme/myapi/gen/users/v1;usersv1"; + +message User { + string id = 1; +} +``` + +**Ошибка:** + +```text +user.proto:1:1: File option go_package changed. (FILE_SAME_GO_PACKAGE) +``` + +### Правильно + +Сохраняйте `option go_package` неизменной в текущей мажорной версии пакета; меняйте её только в новой мажорной версии (например, `myapi.v2`). + +```proto +syntax = "proto3"; + +package myapi.v1; + +option go_package = "github.com/acme/myapi/gen/v1;myapiv1"; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-java-generic-services.mdx b/content/docs/cli/breaking-changes/rules/file-same-java-generic-services.mdx new file mode 100644 index 0000000..fb587f6 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-java-generic-services.mdx @@ -0,0 +1,63 @@ +--- +title: "File Same Java Generic Services" +description: "Checks that files keep the same java_generic_services option value." +--- + +- **Rule ID:** `FILE_SAME_JAVA_GENERIC_SERVICES` +- **Profiles:** `FILE`, `PACKAGE` + +This rule checks that the file-level `java_generic_services` option does not change for a file or for any declaration moved to another file in the same package. Changing `java_generic_services` alters whether abstract Java generic service classes are generated, breaking source compatibility for Java consumers. + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option java_generic_services = true; + +message User { + string id = 1; +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option java_generic_services = false; + +message User { + string id = 1; +} +``` + +**Error:** + +```text +user.proto:1:1: File option java_generic_services changed. (FILE_SAME_JAVA_GENERIC_SERVICES) +``` + +### Good + +Keep `option java_generic_services` unchanged in the existing package version; change it only in a new major package version (for example, `myapi.v2`). + +```proto +syntax = "proto3"; + +package myapi.v1; + +option java_generic_services = true; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-java-generic-services.ru.mdx b/content/docs/cli/breaking-changes/rules/file-same-java-generic-services.ru.mdx new file mode 100644 index 0000000..733976e --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-java-generic-services.ru.mdx @@ -0,0 +1,63 @@ +--- +title: "File Same Java Generic Services" +description: "Проверяет, что файлы сохраняют прежнее значение опции java_generic_services." +--- + +- **ID правила:** `FILE_SAME_JAVA_GENERIC_SERVICES` +- **Профили:** `FILE`, `PACKAGE` + +Это правило проверяет, что файловая опция `java_generic_services` не изменилась у файла (а также у объявлений, перенесённых в другой файл того же пакета). Изменение `java_generic_services` меняет генерацию абстрактных generic-классов сервисов в Java и ломает совместимость сгенерированного кода для Java. + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option java_generic_services = true; + +message User { + string id = 1; +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option java_generic_services = false; + +message User { + string id = 1; +} +``` + +**Ошибка:** + +```text +user.proto:1:1: File option java_generic_services changed. (FILE_SAME_JAVA_GENERIC_SERVICES) +``` + +### Правильно + +Сохраняйте `option java_generic_services` неизменной в текущей мажорной версии пакета; меняйте её только в новой мажорной версии (например, `myapi.v2`). + +```proto +syntax = "proto3"; + +package myapi.v1; + +option java_generic_services = true; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-java-multiple-files.mdx b/content/docs/cli/breaking-changes/rules/file-same-java-multiple-files.mdx new file mode 100644 index 0000000..0d663a5 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-java-multiple-files.mdx @@ -0,0 +1,63 @@ +--- +title: "File Same Java Multiple Files" +description: "Checks that files keep the same java_multiple_files option value." +--- + +- **Rule ID:** `FILE_SAME_JAVA_MULTIPLE_FILES` +- **Profiles:** `FILE`, `PACKAGE` + +This rule checks that the file-level `java_multiple_files` option does not change for a file or for any declaration moved to another file in the same package. Changing `java_multiple_files` alters whether top-level messages and enums are generated as separate classes or nested under the outer class, breaking source compatibility for Java consumers. + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option java_multiple_files = true; + +message User { + string id = 1; +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option java_multiple_files = false; + +message User { + string id = 1; +} +``` + +**Error:** + +```text +user.proto:1:1: File option java_multiple_files changed. (FILE_SAME_JAVA_MULTIPLE_FILES) +``` + +### Good + +Keep `option java_multiple_files` unchanged in the existing package version; change it only in a new major package version (for example, `myapi.v2`). + +```proto +syntax = "proto3"; + +package myapi.v1; + +option java_multiple_files = true; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-java-multiple-files.ru.mdx b/content/docs/cli/breaking-changes/rules/file-same-java-multiple-files.ru.mdx new file mode 100644 index 0000000..97aee98 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-java-multiple-files.ru.mdx @@ -0,0 +1,63 @@ +--- +title: "File Same Java Multiple Files" +description: "Проверяет, что файлы сохраняют прежнее значение опции java_multiple_files." +--- + +- **ID правила:** `FILE_SAME_JAVA_MULTIPLE_FILES` +- **Профили:** `FILE`, `PACKAGE` + +Это правило проверяет, что файловая опция `java_multiple_files` не изменилась у файла (а также у объявлений, перенесённых в другой файл того же пакета). Изменение `java_multiple_files` меняет размещение верхнеуровневых сообщений и enum (отдельные классы или вложенные во внешний класс) и ломает совместимость сгенерированного кода для Java. + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option java_multiple_files = true; + +message User { + string id = 1; +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option java_multiple_files = false; + +message User { + string id = 1; +} +``` + +**Ошибка:** + +```text +user.proto:1:1: File option java_multiple_files changed. (FILE_SAME_JAVA_MULTIPLE_FILES) +``` + +### Правильно + +Сохраняйте `option java_multiple_files` неизменной в текущей мажорной версии пакета; меняйте её только в новой мажорной версии (например, `myapi.v2`). + +```proto +syntax = "proto3"; + +package myapi.v1; + +option java_multiple_files = true; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-java-outer-classname.mdx b/content/docs/cli/breaking-changes/rules/file-same-java-outer-classname.mdx new file mode 100644 index 0000000..e6dceb0 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-java-outer-classname.mdx @@ -0,0 +1,63 @@ +--- +title: "File Same Java Outer Classname" +description: "Checks that files keep the same java_outer_classname option value." +--- + +- **Rule ID:** `FILE_SAME_JAVA_OUTER_CLASSNAME` +- **Profiles:** `FILE`, `PACKAGE` + +This rule checks that the file-level `java_outer_classname` option does not change for a file or for any declaration moved to another file in the same package. Changing `java_outer_classname` alters the name of the generated Java outer wrapper class, breaking source compatibility for Java consumers. + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option java_outer_classname = "UserProto"; + +message User { + string id = 1; +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option java_outer_classname = "UsersProto"; + +message User { + string id = 1; +} +``` + +**Error:** + +```text +user.proto:1:1: File option java_outer_classname changed. (FILE_SAME_JAVA_OUTER_CLASSNAME) +``` + +### Good + +Keep `option java_outer_classname` unchanged in the existing package version; change it only in a new major package version (for example, `myapi.v2`). + +```proto +syntax = "proto3"; + +package myapi.v1; + +option java_outer_classname = "UserProto"; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-java-outer-classname.ru.mdx b/content/docs/cli/breaking-changes/rules/file-same-java-outer-classname.ru.mdx new file mode 100644 index 0000000..ea29983 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-java-outer-classname.ru.mdx @@ -0,0 +1,63 @@ +--- +title: "File Same Java Outer Classname" +description: "Проверяет, что файлы сохраняют прежнее значение опции java_outer_classname." +--- + +- **ID правила:** `FILE_SAME_JAVA_OUTER_CLASSNAME` +- **Профили:** `FILE`, `PACKAGE` + +Это правило проверяет, что файловая опция `java_outer_classname` не изменилась у файла (а также у объявлений, перенесённых в другой файл того же пакета). Изменение `java_outer_classname` меняет имя сгенерированного внешнего класса-обёртки в Java и ломает совместимость сгенерированного кода для Java. + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option java_outer_classname = "UserProto"; + +message User { + string id = 1; +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option java_outer_classname = "UsersProto"; + +message User { + string id = 1; +} +``` + +**Ошибка:** + +```text +user.proto:1:1: File option java_outer_classname changed. (FILE_SAME_JAVA_OUTER_CLASSNAME) +``` + +### Правильно + +Сохраняйте `option java_outer_classname` неизменной в текущей мажорной версии пакета; меняйте её только в новой мажорной версии (например, `myapi.v2`). + +```proto +syntax = "proto3"; + +package myapi.v1; + +option java_outer_classname = "UserProto"; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-java-package.mdx b/content/docs/cli/breaking-changes/rules/file-same-java-package.mdx new file mode 100644 index 0000000..85a1010 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-java-package.mdx @@ -0,0 +1,63 @@ +--- +title: "File Same Java Package" +description: "Checks that files keep the same java_package option value." +--- + +- **Rule ID:** `FILE_SAME_JAVA_PACKAGE` +- **Profiles:** `FILE`, `PACKAGE` + +This rule checks that the file-level `java_package` option does not change for a file or for any declaration moved to another file in the same package. Changing `java_package` alters the generated Java package name for all classes in the file, breaking source compatibility for Java consumers. + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option java_package = "com.acme.myapi.v1"; + +message User { + string id = 1; +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option java_package = "com.acme.users.v1"; + +message User { + string id = 1; +} +``` + +**Error:** + +```text +user.proto:1:1: File option java_package changed. (FILE_SAME_JAVA_PACKAGE) +``` + +### Good + +Keep `option java_package` unchanged in the existing package version; change it only in a new major package version (for example, `myapi.v2`). + +```proto +syntax = "proto3"; + +package myapi.v1; + +option java_package = "com.acme.myapi.v1"; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-java-package.ru.mdx b/content/docs/cli/breaking-changes/rules/file-same-java-package.ru.mdx new file mode 100644 index 0000000..2ba7825 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-java-package.ru.mdx @@ -0,0 +1,63 @@ +--- +title: "File Same Java Package" +description: "Проверяет, что файлы сохраняют прежнее значение опции java_package." +--- + +- **ID правила:** `FILE_SAME_JAVA_PACKAGE` +- **Профили:** `FILE`, `PACKAGE` + +Это правило проверяет, что файловая опция `java_package` не изменилась у файла (а также у объявлений, перенесённых в другой файл того же пакета). Изменение `java_package` меняет имя сгенерированного Java-пакета для всех классов файла и ломает совместимость сгенерированного кода для Java. + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option java_package = "com.acme.myapi.v1"; + +message User { + string id = 1; +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option java_package = "com.acme.users.v1"; + +message User { + string id = 1; +} +``` + +**Ошибка:** + +```text +user.proto:1:1: File option java_package changed. (FILE_SAME_JAVA_PACKAGE) +``` + +### Правильно + +Сохраняйте `option java_package` неизменной в текущей мажорной версии пакета; меняйте её только в новой мажорной версии (например, `myapi.v2`). + +```proto +syntax = "proto3"; + +package myapi.v1; + +option java_package = "com.acme.myapi.v1"; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-java-string-check-utf8.mdx b/content/docs/cli/breaking-changes/rules/file-same-java-string-check-utf8.mdx new file mode 100644 index 0000000..5305e7d --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-java-string-check-utf8.mdx @@ -0,0 +1,63 @@ +--- +title: "File Same Java String Check Utf8" +description: "Checks that files keep the same java_string_check_utf8 option value." +--- + +- **Rule ID:** `FILE_SAME_JAVA_STRING_CHECK_UTF8` +- **Profiles:** `FILE`, `PACKAGE` + +This rule checks that the file-level `java_string_check_utf8` option does not change for a file or for any declaration moved to another file in the same package. Changing `java_string_check_utf8` alters UTF-8 validation checks in generated Java string accessors, breaking source compatibility for Java consumers. + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option java_string_check_utf8 = true; + +message User { + string id = 1; +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option java_string_check_utf8 = false; + +message User { + string id = 1; +} +``` + +**Error:** + +```text +user.proto:1:1: File option java_string_check_utf8 changed. (FILE_SAME_JAVA_STRING_CHECK_UTF8) +``` + +### Good + +Keep `option java_string_check_utf8` unchanged in the existing package version; change it only in a new major package version (for example, `myapi.v2`). + +```proto +syntax = "proto3"; + +package myapi.v1; + +option java_string_check_utf8 = true; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-java-string-check-utf8.ru.mdx b/content/docs/cli/breaking-changes/rules/file-same-java-string-check-utf8.ru.mdx new file mode 100644 index 0000000..af3ad48 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-java-string-check-utf8.ru.mdx @@ -0,0 +1,63 @@ +--- +title: "File Same Java String Check Utf8" +description: "Проверяет, что файлы сохраняют прежнее значение опции java_string_check_utf8." +--- + +- **ID правила:** `FILE_SAME_JAVA_STRING_CHECK_UTF8` +- **Профили:** `FILE`, `PACKAGE` + +Это правило проверяет, что файловая опция `java_string_check_utf8` не изменилась у файла (а также у объявлений, перенесённых в другой файл того же пакета). Изменение `java_string_check_utf8` меняет проверки валидности UTF-8 в сгенерированных Java-аксессорах строк и ломает совместимость сгенерированного кода для Java. + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option java_string_check_utf8 = true; + +message User { + string id = 1; +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option java_string_check_utf8 = false; + +message User { + string id = 1; +} +``` + +**Ошибка:** + +```text +user.proto:1:1: File option java_string_check_utf8 changed. (FILE_SAME_JAVA_STRING_CHECK_UTF8) +``` + +### Правильно + +Сохраняйте `option java_string_check_utf8` неизменной в текущей мажорной версии пакета; меняйте её только в новой мажорной версии (например, `myapi.v2`). + +```proto +syntax = "proto3"; + +package myapi.v1; + +option java_string_check_utf8 = true; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-objc-class-prefix.mdx b/content/docs/cli/breaking-changes/rules/file-same-objc-class-prefix.mdx new file mode 100644 index 0000000..c69497f --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-objc-class-prefix.mdx @@ -0,0 +1,63 @@ +--- +title: "File Same Objc Class Prefix" +description: "Checks that files keep the same objc_class_prefix option value." +--- + +- **Rule ID:** `FILE_SAME_OBJC_CLASS_PREFIX` +- **Profiles:** `FILE`, `PACKAGE` + +This rule checks that the file-level `objc_class_prefix` option does not change for a file or for any declaration moved to another file in the same package. Changing `objc_class_prefix` alters the prefix prepended to every generated Objective-C class and enum, breaking source compatibility for Objective-C consumers. + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option objc_class_prefix = "ACME"; + +message User { + string id = 1; +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option objc_class_prefix = "USR"; + +message User { + string id = 1; +} +``` + +**Error:** + +```text +user.proto:1:1: File option objc_class_prefix changed. (FILE_SAME_OBJC_CLASS_PREFIX) +``` + +### Good + +Keep `option objc_class_prefix` unchanged in the existing package version; change it only in a new major package version (for example, `myapi.v2`). + +```proto +syntax = "proto3"; + +package myapi.v1; + +option objc_class_prefix = "ACME"; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-objc-class-prefix.ru.mdx b/content/docs/cli/breaking-changes/rules/file-same-objc-class-prefix.ru.mdx new file mode 100644 index 0000000..3465cd5 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-objc-class-prefix.ru.mdx @@ -0,0 +1,63 @@ +--- +title: "File Same Objc Class Prefix" +description: "Проверяет, что файлы сохраняют прежнее значение опции objc_class_prefix." +--- + +- **ID правила:** `FILE_SAME_OBJC_CLASS_PREFIX` +- **Профили:** `FILE`, `PACKAGE` + +Это правило проверяет, что файловая опция `objc_class_prefix` не изменилась у файла (а также у объявлений, перенесённых в другой файл того же пакета). Изменение `objc_class_prefix` меняет префикс всех сгенерированных классов и enum в Objective-C и ломает совместимость сгенерированного кода для Objective-C. + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option objc_class_prefix = "ACME"; + +message User { + string id = 1; +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option objc_class_prefix = "USR"; + +message User { + string id = 1; +} +``` + +**Ошибка:** + +```text +user.proto:1:1: File option objc_class_prefix changed. (FILE_SAME_OBJC_CLASS_PREFIX) +``` + +### Правильно + +Сохраняйте `option objc_class_prefix` неизменной в текущей мажорной версии пакета; меняйте её только в новой мажорной версии (например, `myapi.v2`). + +```proto +syntax = "proto3"; + +package myapi.v1; + +option objc_class_prefix = "ACME"; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-optimize-for.mdx b/content/docs/cli/breaking-changes/rules/file-same-optimize-for.mdx new file mode 100644 index 0000000..8a01f9e --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-optimize-for.mdx @@ -0,0 +1,63 @@ +--- +title: "File Same Optimize For" +description: "Checks that files keep the same optimize_for option value." +--- + +- **Rule ID:** `FILE_SAME_OPTIMIZE_FOR` +- **Profiles:** `FILE`, `PACKAGE` + +This rule checks that the file-level `optimize_for` option does not change for a file or for any declaration moved to another file in the same package. Changing `optimize_for` alters generated reflection and runtime base classes (for example, `SPEED` vs `LITE_RUNTIME`), breaking source compatibility for Protobuf runtime consumers. + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option optimize_for = SPEED; + +message User { + string id = 1; +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option optimize_for = LITE_RUNTIME; + +message User { + string id = 1; +} +``` + +**Error:** + +```text +user.proto:1:1: File option optimize_for changed. (FILE_SAME_OPTIMIZE_FOR) +``` + +### Good + +Keep `option optimize_for` unchanged in the existing package version; change it only in a new major package version (for example, `myapi.v2`). + +```proto +syntax = "proto3"; + +package myapi.v1; + +option optimize_for = SPEED; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-optimize-for.ru.mdx b/content/docs/cli/breaking-changes/rules/file-same-optimize-for.ru.mdx new file mode 100644 index 0000000..0e3ec39 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-optimize-for.ru.mdx @@ -0,0 +1,63 @@ +--- +title: "File Same Optimize For" +description: "Проверяет, что файлы сохраняют прежнее значение опции optimize_for." +--- + +- **ID правила:** `FILE_SAME_OPTIMIZE_FOR` +- **Профили:** `FILE`, `PACKAGE` + +Это правило проверяет, что файловая опция `optimize_for` не изменилась у файла (а также у объявлений, перенесённых в другой файл того же пакета). Изменение `optimize_for` меняет поддержку рефлексии и базовые классы рантайма (например, `SPEED` против `LITE_RUNTIME`) и ломает совместимость сгенерированного кода для рантаймов Protobuf. + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option optimize_for = SPEED; + +message User { + string id = 1; +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option optimize_for = LITE_RUNTIME; + +message User { + string id = 1; +} +``` + +**Ошибка:** + +```text +user.proto:1:1: File option optimize_for changed. (FILE_SAME_OPTIMIZE_FOR) +``` + +### Правильно + +Сохраняйте `option optimize_for` неизменной в текущей мажорной версии пакета; меняйте её только в новой мажорной версии (например, `myapi.v2`). + +```proto +syntax = "proto3"; + +package myapi.v1; + +option optimize_for = SPEED; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-package.mdx b/content/docs/cli/breaking-changes/rules/file-same-package.mdx new file mode 100644 index 0000000..7e2cea3 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-package.mdx @@ -0,0 +1,57 @@ +--- +title: "File Same Package" +description: "Checks that a file keeps the same protobuf package declaration." +--- + +- **Rule ID:** `FILE_SAME_PACKAGE` +- **Profiles:** `FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE` + +This rule checks that a `.proto` file does not change its `package` declaration. Changing `package` alters every fully qualified type name, gRPC service path, and generated namespace across all four profiles (`FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE`). + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + string id = 1; +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package acme.users.v1; + +message User { + string id = 1; +} +``` + +**Error:** + +```text +user.proto:1:1: File "user.proto" changed package from "myapi.v1" to "acme.users.v1". (FILE_SAME_PACKAGE) +``` + +### Good + +Keep the package unchanged in existing files; create new files under a new package (such as `acme.users.v1` or `myapi.v2`) when restructuring. + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-package.ru.mdx b/content/docs/cli/breaking-changes/rules/file-same-package.ru.mdx new file mode 100644 index 0000000..d02a528 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-package.ru.mdx @@ -0,0 +1,57 @@ +--- +title: "File Same Package" +description: "Проверяет, что файл сохраняет прежнее объявление protobuf-пакета." +--- + +- **ID правила:** `FILE_SAME_PACKAGE` +- **Профили:** `FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE` + +Это правило проверяет, что `.proto`-файл не меняет объявление `package`. Смена `package` меняет полные имена всех типов, пути gRPC-сервисов и сгенерированные пространства имён во всех четырёх профилях (`FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE`). + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + string id = 1; +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package acme.users.v1; + +message User { + string id = 1; +} +``` + +**Ошибка:** + +```text +user.proto:1:1: File "user.proto" changed package from "myapi.v1" to "acme.users.v1". (FILE_SAME_PACKAGE) +``` + +### Правильно + +Не меняйте `package` в существующих файлах; при реструктуризации создавайте новые файлы в новом пакете (например, `acme.users.v1` или `myapi.v2`). + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-php-class-prefix.mdx b/content/docs/cli/breaking-changes/rules/file-same-php-class-prefix.mdx new file mode 100644 index 0000000..5a4c3d6 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-php-class-prefix.mdx @@ -0,0 +1,63 @@ +--- +title: "File Same Php Class Prefix" +description: "Checks that files keep the same php_class_prefix option value." +--- + +- **Rule ID:** `FILE_SAME_PHP_CLASS_PREFIX` +- **Profiles:** `FILE`, `PACKAGE` + +This rule checks that the file-level `php_class_prefix` option does not change for a file or for any declaration moved to another file in the same package. Changing `php_class_prefix` alters the prefix applied to generated PHP classes, breaking source compatibility for PHP consumers. + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option php_class_prefix = "Acme"; + +message User { + string id = 1; +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option php_class_prefix = "Users"; + +message User { + string id = 1; +} +``` + +**Error:** + +```text +user.proto:1:1: File option php_class_prefix changed. (FILE_SAME_PHP_CLASS_PREFIX) +``` + +### Good + +Keep `option php_class_prefix` unchanged in the existing package version; change it only in a new major package version (for example, `myapi.v2`). + +```proto +syntax = "proto3"; + +package myapi.v1; + +option php_class_prefix = "Acme"; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-php-class-prefix.ru.mdx b/content/docs/cli/breaking-changes/rules/file-same-php-class-prefix.ru.mdx new file mode 100644 index 0000000..e5a8fa7 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-php-class-prefix.ru.mdx @@ -0,0 +1,63 @@ +--- +title: "File Same Php Class Prefix" +description: "Проверяет, что файлы сохраняют прежнее значение опции php_class_prefix." +--- + +- **ID правила:** `FILE_SAME_PHP_CLASS_PREFIX` +- **Профили:** `FILE`, `PACKAGE` + +Это правило проверяет, что файловая опция `php_class_prefix` не изменилась у файла (а также у объявлений, перенесённых в другой файл того же пакета). Изменение `php_class_prefix` меняет префикс сгенерированных PHP-классов и ломает совместимость сгенерированного кода для PHP. + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option php_class_prefix = "Acme"; + +message User { + string id = 1; +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option php_class_prefix = "Users"; + +message User { + string id = 1; +} +``` + +**Ошибка:** + +```text +user.proto:1:1: File option php_class_prefix changed. (FILE_SAME_PHP_CLASS_PREFIX) +``` + +### Правильно + +Сохраняйте `option php_class_prefix` неизменной в текущей мажорной версии пакета; меняйте её только в новой мажорной версии (например, `myapi.v2`). + +```proto +syntax = "proto3"; + +package myapi.v1; + +option php_class_prefix = "Acme"; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-php-metadata-namespace.mdx b/content/docs/cli/breaking-changes/rules/file-same-php-metadata-namespace.mdx new file mode 100644 index 0000000..d039c13 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-php-metadata-namespace.mdx @@ -0,0 +1,63 @@ +--- +title: "File Same Php Metadata Namespace" +description: "Checks that files keep the same php_metadata_namespace option value." +--- + +- **Rule ID:** `FILE_SAME_PHP_METADATA_NAMESPACE` +- **Profiles:** `FILE`, `PACKAGE` + +This rule checks that the file-level `php_metadata_namespace` option does not change for a file or for any declaration moved to another file in the same package. Changing `php_metadata_namespace` alters the PHP namespace used for generated descriptor metadata classes, breaking source compatibility for PHP consumers. + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option php_metadata_namespace = "Acme\\MyApi\\GPBMetadata"; + +message User { + string id = 1; +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option php_metadata_namespace = "Acme\\Users\\GPBMetadata"; + +message User { + string id = 1; +} +``` + +**Error:** + +```text +user.proto:1:1: File option php_metadata_namespace changed. (FILE_SAME_PHP_METADATA_NAMESPACE) +``` + +### Good + +Keep `option php_metadata_namespace` unchanged in the existing package version; change it only in a new major package version (for example, `myapi.v2`). + +```proto +syntax = "proto3"; + +package myapi.v1; + +option php_metadata_namespace = "Acme\\MyApi\\GPBMetadata"; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-php-metadata-namespace.ru.mdx b/content/docs/cli/breaking-changes/rules/file-same-php-metadata-namespace.ru.mdx new file mode 100644 index 0000000..444d816 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-php-metadata-namespace.ru.mdx @@ -0,0 +1,63 @@ +--- +title: "File Same Php Metadata Namespace" +description: "Проверяет, что файлы сохраняют прежнее значение опции php_metadata_namespace." +--- + +- **ID правила:** `FILE_SAME_PHP_METADATA_NAMESPACE` +- **Профили:** `FILE`, `PACKAGE` + +Это правило проверяет, что файловая опция `php_metadata_namespace` не изменилась у файла (а также у объявлений, перенесённых в другой файл того же пакета). Изменение `php_metadata_namespace` меняет пространство имён PHP для сгенерированных классов метаданных дескрипторов и ломает совместимость сгенерированного кода для PHP. + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option php_metadata_namespace = "Acme\\MyApi\\GPBMetadata"; + +message User { + string id = 1; +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option php_metadata_namespace = "Acme\\Users\\GPBMetadata"; + +message User { + string id = 1; +} +``` + +**Ошибка:** + +```text +user.proto:1:1: File option php_metadata_namespace changed. (FILE_SAME_PHP_METADATA_NAMESPACE) +``` + +### Правильно + +Сохраняйте `option php_metadata_namespace` неизменной в текущей мажорной версии пакета; меняйте её только в новой мажорной версии (например, `myapi.v2`). + +```proto +syntax = "proto3"; + +package myapi.v1; + +option php_metadata_namespace = "Acme\\MyApi\\GPBMetadata"; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-php-namespace.mdx b/content/docs/cli/breaking-changes/rules/file-same-php-namespace.mdx new file mode 100644 index 0000000..1f566c3 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-php-namespace.mdx @@ -0,0 +1,63 @@ +--- +title: "File Same Php Namespace" +description: "Checks that files keep the same php_namespace option value." +--- + +- **Rule ID:** `FILE_SAME_PHP_NAMESPACE` +- **Profiles:** `FILE`, `PACKAGE` + +This rule checks that the file-level `php_namespace` option does not change for a file or for any declaration moved to another file in the same package. Changing `php_namespace` alters the generated PHP namespace for types in the file, breaking source compatibility for PHP consumers. + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option php_namespace = "Acme\\MyApi\\V1"; + +message User { + string id = 1; +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option php_namespace = "Acme\\Users\\V1"; + +message User { + string id = 1; +} +``` + +**Error:** + +```text +user.proto:1:1: File option php_namespace changed. (FILE_SAME_PHP_NAMESPACE) +``` + +### Good + +Keep `option php_namespace` unchanged in the existing package version; change it only in a new major package version (for example, `myapi.v2`). + +```proto +syntax = "proto3"; + +package myapi.v1; + +option php_namespace = "Acme\\MyApi\\V1"; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-php-namespace.ru.mdx b/content/docs/cli/breaking-changes/rules/file-same-php-namespace.ru.mdx new file mode 100644 index 0000000..7dba712 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-php-namespace.ru.mdx @@ -0,0 +1,63 @@ +--- +title: "File Same Php Namespace" +description: "Проверяет, что файлы сохраняют прежнее значение опции php_namespace." +--- + +- **ID правила:** `FILE_SAME_PHP_NAMESPACE` +- **Профили:** `FILE`, `PACKAGE` + +Это правило проверяет, что файловая опция `php_namespace` не изменилась у файла (а также у объявлений, перенесённых в другой файл того же пакета). Изменение `php_namespace` меняет сгенерированное пространство имён PHP для типов файла и ломает совместимость сгенерированного кода для PHP. + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option php_namespace = "Acme\\MyApi\\V1"; + +message User { + string id = 1; +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option php_namespace = "Acme\\Users\\V1"; + +message User { + string id = 1; +} +``` + +**Ошибка:** + +```text +user.proto:1:1: File option php_namespace changed. (FILE_SAME_PHP_NAMESPACE) +``` + +### Правильно + +Сохраняйте `option php_namespace` неизменной в текущей мажорной версии пакета; меняйте её только в новой мажорной версии (например, `myapi.v2`). + +```proto +syntax = "proto3"; + +package myapi.v1; + +option php_namespace = "Acme\\MyApi\\V1"; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-py-generic-services.mdx b/content/docs/cli/breaking-changes/rules/file-same-py-generic-services.mdx new file mode 100644 index 0000000..364a6e1 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-py-generic-services.mdx @@ -0,0 +1,63 @@ +--- +title: "File Same Py Generic Services" +description: "Checks that files keep the same py_generic_services option value." +--- + +- **Rule ID:** `FILE_SAME_PY_GENERIC_SERVICES` +- **Profiles:** `FILE`, `PACKAGE` + +This rule checks that the file-level `py_generic_services` option does not change for a file or for any declaration moved to another file in the same package. Changing `py_generic_services` alters whether Python generic service base classes are generated, breaking source compatibility for Python consumers. + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option py_generic_services = true; + +message User { + string id = 1; +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option py_generic_services = false; + +message User { + string id = 1; +} +``` + +**Error:** + +```text +user.proto:1:1: File option py_generic_services changed. (FILE_SAME_PY_GENERIC_SERVICES) +``` + +### Good + +Keep `option py_generic_services` unchanged in the existing package version; change it only in a new major package version (for example, `myapi.v2`). + +```proto +syntax = "proto3"; + +package myapi.v1; + +option py_generic_services = true; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-py-generic-services.ru.mdx b/content/docs/cli/breaking-changes/rules/file-same-py-generic-services.ru.mdx new file mode 100644 index 0000000..95d945b --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-py-generic-services.ru.mdx @@ -0,0 +1,63 @@ +--- +title: "File Same Py Generic Services" +description: "Проверяет, что файлы сохраняют прежнее значение опции py_generic_services." +--- + +- **ID правила:** `FILE_SAME_PY_GENERIC_SERVICES` +- **Профили:** `FILE`, `PACKAGE` + +Это правило проверяет, что файловая опция `py_generic_services` не изменилась у файла (а также у объявлений, перенесённых в другой файл того же пакета). Изменение `py_generic_services` меняет генерацию базовых generic-классов сервисов в Python и ломает совместимость сгенерированного кода для Python. + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option py_generic_services = true; + +message User { + string id = 1; +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option py_generic_services = false; + +message User { + string id = 1; +} +``` + +**Ошибка:** + +```text +user.proto:1:1: File option py_generic_services changed. (FILE_SAME_PY_GENERIC_SERVICES) +``` + +### Правильно + +Сохраняйте `option py_generic_services` неизменной в текущей мажорной версии пакета; меняйте её только в новой мажорной версии (например, `myapi.v2`). + +```proto +syntax = "proto3"; + +package myapi.v1; + +option py_generic_services = true; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-ruby-package.mdx b/content/docs/cli/breaking-changes/rules/file-same-ruby-package.mdx new file mode 100644 index 0000000..11ca82f --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-ruby-package.mdx @@ -0,0 +1,63 @@ +--- +title: "File Same Ruby Package" +description: "Checks that files keep the same ruby_package option value." +--- + +- **Rule ID:** `FILE_SAME_RUBY_PACKAGE` +- **Profiles:** `FILE`, `PACKAGE` + +This rule checks that the file-level `ruby_package` option does not change for a file or for any declaration moved to another file in the same package. Changing `ruby_package` alters the generated Ruby module hierarchy, breaking source compatibility for Ruby consumers. + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option ruby_package = "Acme::MyApi::V1"; + +message User { + string id = 1; +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option ruby_package = "Acme::Users::V1"; + +message User { + string id = 1; +} +``` + +**Error:** + +```text +user.proto:1:1: File option ruby_package changed. (FILE_SAME_RUBY_PACKAGE) +``` + +### Good + +Keep `option ruby_package` unchanged in the existing package version; change it only in a new major package version (for example, `myapi.v2`). + +```proto +syntax = "proto3"; + +package myapi.v1; + +option ruby_package = "Acme::MyApi::V1"; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-ruby-package.ru.mdx b/content/docs/cli/breaking-changes/rules/file-same-ruby-package.ru.mdx new file mode 100644 index 0000000..272a84c --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-ruby-package.ru.mdx @@ -0,0 +1,63 @@ +--- +title: "File Same Ruby Package" +description: "Проверяет, что файлы сохраняют прежнее значение опции ruby_package." +--- + +- **ID правила:** `FILE_SAME_RUBY_PACKAGE` +- **Профили:** `FILE`, `PACKAGE` + +Это правило проверяет, что файловая опция `ruby_package` не изменилась у файла (а также у объявлений, перенесённых в другой файл того же пакета). Изменение `ruby_package` меняет иерархию сгенерированных модулей Ruby и ломает совместимость сгенерированного кода для Ruby. + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option ruby_package = "Acme::MyApi::V1"; + +message User { + string id = 1; +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option ruby_package = "Acme::Users::V1"; + +message User { + string id = 1; +} +``` + +**Ошибка:** + +```text +user.proto:1:1: File option ruby_package changed. (FILE_SAME_RUBY_PACKAGE) +``` + +### Правильно + +Сохраняйте `option ruby_package` неизменной в текущей мажорной версии пакета; меняйте её только в новой мажорной версии (например, `myapi.v2`). + +```proto +syntax = "proto3"; + +package myapi.v1; + +option ruby_package = "Acme::MyApi::V1"; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-swift-prefix.mdx b/content/docs/cli/breaking-changes/rules/file-same-swift-prefix.mdx new file mode 100644 index 0000000..f6204de --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-swift-prefix.mdx @@ -0,0 +1,63 @@ +--- +title: "File Same Swift Prefix" +description: "Checks that files keep the same swift_prefix option value." +--- + +- **Rule ID:** `FILE_SAME_SWIFT_PREFIX` +- **Profiles:** `FILE`, `PACKAGE` + +This rule checks that the file-level `swift_prefix` option does not change for a file or for any declaration moved to another file in the same package. Changing `swift_prefix` alters the prefix prepended to generated Swift type names, breaking source compatibility for Swift consumers. + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option swift_prefix = "Acme"; + +message User { + string id = 1; +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option swift_prefix = "Users"; + +message User { + string id = 1; +} +``` + +**Error:** + +```text +user.proto:1:1: File option swift_prefix changed. (FILE_SAME_SWIFT_PREFIX) +``` + +### Good + +Keep `option swift_prefix` unchanged in the existing package version; change it only in a new major package version (for example, `myapi.v2`). + +```proto +syntax = "proto3"; + +package myapi.v1; + +option swift_prefix = "Acme"; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-swift-prefix.ru.mdx b/content/docs/cli/breaking-changes/rules/file-same-swift-prefix.ru.mdx new file mode 100644 index 0000000..3a0e531 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-swift-prefix.ru.mdx @@ -0,0 +1,63 @@ +--- +title: "File Same Swift Prefix" +description: "Проверяет, что файлы сохраняют прежнее значение опции swift_prefix." +--- + +- **ID правила:** `FILE_SAME_SWIFT_PREFIX` +- **Профили:** `FILE`, `PACKAGE` + +Это правило проверяет, что файловая опция `swift_prefix` не изменилась у файла (а также у объявлений, перенесённых в другой файл того же пакета). Изменение `swift_prefix` меняет префикс сгенерированных имён типов в Swift и ломает совместимость сгенерированного кода для Swift. + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option swift_prefix = "Acme"; + +message User { + string id = 1; +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +option swift_prefix = "Users"; + +message User { + string id = 1; +} +``` + +**Ошибка:** + +```text +user.proto:1:1: File option swift_prefix changed. (FILE_SAME_SWIFT_PREFIX) +``` + +### Правильно + +Сохраняйте `option swift_prefix` неизменной в текущей мажорной версии пакета; меняйте её только в новой мажорной версии (например, `myapi.v2`). + +```proto +syntax = "proto3"; + +package myapi.v1; + +option swift_prefix = "Acme"; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-syntax.mdx b/content/docs/cli/breaking-changes/rules/file-same-syntax.mdx new file mode 100644 index 0000000..fb61e52 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-syntax.mdx @@ -0,0 +1,57 @@ +--- +title: "File Same Syntax" +description: "Checks that a file keeps the same syntax or Protobuf edition." +--- + +- **Rule ID:** `FILE_SAME_SYNTAX` +- **Profiles:** `FILE`, `PACKAGE` + +This rule checks that a `.proto` file keeps the same `syntax` (`proto2` / `proto3`) and Protobuf `edition` (for example, `"2023"`). Switching syntax or edition changes default presence, enum openness, and generated API conventions. + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + string id = 1; +} +``` + +**After:** + +```proto +edition = "2023"; + +package myapi.v1; + +message User { + string id = 1; +} +``` + +**Error:** + +```text +user.proto:1:1: File "user.proto" changed syntax from proto3 to editions. (FILE_SAME_SYNTAX) +``` + +### Good + +Preserve the file `syntax` or `edition` within the same major version; adopt a new syntax or edition in a new major package version (for example, `myapi.v2`). + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/file-same-syntax.ru.mdx b/content/docs/cli/breaking-changes/rules/file-same-syntax.ru.mdx new file mode 100644 index 0000000..3fff535 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/file-same-syntax.ru.mdx @@ -0,0 +1,57 @@ +--- +title: "File Same Syntax" +description: "Проверяет, что файл сохраняет прежний синтаксис (syntax) или версию Protobuf Edition." +--- + +- **ID правила:** `FILE_SAME_SYNTAX` +- **Профили:** `FILE`, `PACKAGE` + +Это правило проверяет, что `.proto`-файл сохраняет прежнюю директиву `syntax` (`proto2` / `proto3`) и `edition` (например, `"2023"`). Смена синтаксиса или Edition меняет правила присутствия полей, открытость enum и сгенерированный API. + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + string id = 1; +} +``` + +**После:** + +```proto +edition = "2023"; + +package myapi.v1; + +message User { + string id = 1; +} +``` + +**Ошибка:** + +```text +user.proto:1:1: File "user.proto" changed syntax from proto3 to editions. (FILE_SAME_SYNTAX) +``` + +### Правильно + +Сохраняйте `syntax` или `edition` файла в рамках текущей мажорной версии; переходите на новый синтаксис или Edition в новой мажорной версии пакета (например, `myapi.v2`). + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/import-no-delete.mdx b/content/docs/cli/breaking-changes/rules/import-no-delete.mdx deleted file mode 100644 index e27b925..0000000 --- a/content/docs/cli/breaking-changes/rules/import-no-delete.mdx +++ /dev/null @@ -1,413 +0,0 @@ ---- -title: "Import No Delete" ---- - -Categories: - -- **WIRE+** - -This rule checks that no import statements are deleted from proto files. Deleting an import breaks both wire format compatibility and generated code, as the imported types may be referenced in the current file and removing the import makes those types unavailable. - -## Examples - -### Bad - -**Before:** -```proto -syntax = "proto3"; - -package myapi.v1; - -import "google/protobuf/timestamp.proto"; -import "google/protobuf/duration.proto"; -import "common/user.proto"; -import "common/address.proto"; - -message Order { - string id = 1; - google.protobuf.Timestamp created_at = 2; - google.protobuf.Duration processing_time = 3; - common.User customer = 4; - common.Address shipping_address = 5; -} -``` - -**After:** -```proto -syntax = "proto3"; - -package myapi.v1; - -import "google/protobuf/timestamp.proto"; -// import "google/protobuf/duration.proto"; // Deleted import - BREAKING! -// import "common/user.proto"; // Deleted import - BREAKING! -// import "common/address.proto"; // Deleted import - BREAKING! - -message Order { - string id = 1; - google.protobuf.Timestamp created_at = 2; - google.protobuf.Duration processing_time = 3; // ERROR: Duration not available - common.User customer = 4; // ERROR: User not available - common.Address shipping_address = 5; // ERROR: Address not available -} -``` - -**Error:** -``` -order.proto:5:1: Previously import "google/protobuf/duration.proto" was deleted. (BREAKING_CHECK) -order.proto:6:1: Previously import "common/user.proto" was deleted. (BREAKING_CHECK) -order.proto:7:1: Previously import "common/address.proto" was deleted. (BREAKING_CHECK) -``` - -### More Examples - -**Service definition breaks with deleted imports:** - -```proto -// Before -import "google/api/annotations.proto"; -import "google/protobuf/empty.proto"; -import "common/auth.proto"; - -service OrderService { - rpc GetOrder(GetOrderRequest) returns (Order) { - option (google.api.http) = { - get: "/v1/orders/{id}" - }; - } - - rpc DeleteOrder(common.AuthRequest) returns (google.protobuf.Empty); -} - -// After - BREAKING CHANGES! -// import "google/api/annotations.proto"; // BREAKING: deleted -// import "google/protobuf/empty.proto"; // BREAKING: deleted -// import "common/auth.proto"; // BREAKING: deleted - -service OrderService { - rpc GetOrder(GetOrderRequest) returns (Order) { - option (google.api.http) = { // ERROR: annotations not available - get: "/v1/orders/{id}" - }; - } - - rpc DeleteOrder(common.AuthRequest) returns (google.protobuf.Empty); // ERROR: types not available -} -``` - -### Good - -**Instead of deleting, keep unused imports:** -```proto -syntax = "proto3"; - -package myapi.v1; - -import "google/protobuf/timestamp.proto"; -import "google/protobuf/duration.proto"; // Keep even if unused -import "common/user.proto"; // Keep even if unused -import "common/address.proto"; // Keep even if unused - -message Order { - string id = 1; - google.protobuf.Timestamp created_at = 2; - // Removed fields that used Duration, User, Address but kept imports -} -``` - -**Or replace with equivalent types while keeping imports:** -```proto -syntax = "proto3"; - -package myapi.v1; - -import "google/protobuf/timestamp.proto"; -import "google/protobuf/duration.proto"; // Keep original import -import "common/user.proto"; // Keep original import -import "common/address.proto"; // Keep original import -import "common/v2/user.proto"; // Add new import - -message Order { - string id = 1; - google.protobuf.Timestamp created_at = 2; - google.protobuf.Duration processing_time = 3 [deprecated = true]; // Keep old field - common.User customer = 4 [deprecated = true]; // Keep old field - common.Address shipping_address = 5 [deprecated = true]; // Keep old field - - int32 processing_seconds = 6; // New field instead of Duration - common.v2.UserProfile customer_v2 = 7; // New field with updated type - string shipping_address_text = 8; // New field with simpler type -} -``` - -## Impact - -- **Generated Code:** Imported types become unavailable, breaking compilation -- **Wire Format:** Messages using imported types cannot be deserialized -- **Field References:** Any field using imported types becomes invalid -- **Service Definitions:** RPC methods using imported types break -- **Options Usage:** Custom options from imports become unavailable - -## Real-World Example - -**Client code breaks:** -```go -// Before - this code works -order := &myapi.Order{ - Id: "order123", - CreatedAt: timestamppb.New(time.Now()), // Uses google.protobuf.Timestamp - Customer: &common.User{ // ERROR after import deletion - Id: "user456", - Name: "John Doe", - }, - ShippingAddress: &common.Address{ // ERROR after import deletion - Street: "123 Main St", - City: "New York", - }, -} - -// Generated code compilation fails: -// undefined: common.User -// undefined: common.Address -``` - -**Server implementation breaks:** -```go -// Before - server uses imported types -func (s *server) CreateOrder(ctx context.Context, req *CreateOrderRequest) (*Order, error) { - return &Order{ - Id: generateOrderId(), - CreatedAt: timestamppb.New(time.Now()), - Customer: &common.User{ // ERROR after import deletion - Id: req.CustomerId, - Name: req.CustomerName, - }, - ShippingAddress: &common.Address{ // ERROR after import deletion - Street: req.ShippingStreet, - City: req.ShippingCity, - }, - }, nil -} -``` - -**Proto compilation breaks:** -```bash -# After deleting imports -$ protoc --go_out=. order.proto -order.proto:8:3: "common.User" is not defined. -order.proto:9:3: "common.Address" is not defined. -order.proto:10:3: "google.protobuf.Duration" is not defined. -``` - -## Migration Strategy - -1. **Keep imports even when unused:** - ```proto - // Always keep existing imports - import "common/user.proto"; // Keep even if no fields use it - ``` - -2. **Add new imports alongside old ones:** - ```proto - import "common/user.proto"; // Keep old import - import "common/v2/user.proto"; // Add new import - ``` - -3. **Deprecate fields using old imports gradually:** - ```proto - message Order { - common.User customer = 4 [deprecated = true]; - common.v2.UserProfile customer_v2 = 5; // New field - } - ``` - -4. **Update server code** to handle both old and new fields: - ```go - func convertToOrder(req *CreateOrderRequest) *Order { - order := &Order{Id: generateId()} - - // Handle new field first - if req.CustomerProfileV2 != nil { - order.CustomerV2 = req.CustomerProfileV2 - return order - } - - // Fall back to old field (still works due to kept import) - if req.CustomerProfile != nil { - order.Customer = req.CustomerProfile - } - - return order - } - ``` - -5. **Only remove imports in major version updates** after all fields are migrated - -## Common Scenarios - -### Replacing Dependencies -```proto -// Instead of deleting old import immediately -// import "old/user.proto"; // Don't delete! - -// Keep both during transition -import "old/user.proto"; // Keep for backward compatibility -import "new/user.proto"; // Add new dependency - -message Order { - old.User customer = 4 [deprecated = true]; - new.UserProfile customer_v2 = 5; -} -``` - -### Removing Unused Features -```proto -// Even if removing features, keep imports -import "feature/analytics.proto"; // Keep even if analytics removed - -message Order { - string id = 1; - // feature.AnalyticsData analytics = 2; // Field removed but import kept -} -``` - -### Protobuf Version Migration -```proto -// When migrating protobuf versions, keep old imports -import "google/protobuf/timestamp.proto"; // Keep standard imports -import "google/protobuf/duration.proto"; // Even if switching to alternatives - -// Prefer keeping both old and new approaches -message Event { - google.protobuf.Timestamp timestamp = 1; // Keep old - int64 timestamp_millis = 2; // Add alternative -} -``` - -### Simplifying Dependencies -```proto -// Instead of removing complex type imports -// import "complex/config.proto"; // Don't delete! - -// Keep complex import, add simple alternative -import "complex/config.proto"; - -message Settings { - complex.ConfigData config = 1 [deprecated = true]; // Keep complex option - string config_json = 2; // Add simple option -} -``` - -## Import Categories and Impact - -### Standard Google Imports -```proto -// Critical - used throughout protobuf ecosystem -import "google/protobuf/timestamp.proto"; // Never delete -import "google/protobuf/duration.proto"; // Never delete -import "google/protobuf/empty.proto"; // Never delete -import "google/api/annotations.proto"; // Never delete if using gRPC-Gateway -``` - -### Common Library Imports -```proto -// Shared types across services -import "common/user.proto"; // High impact - affects all user references -import "common/address.proto"; // High impact - affects all address fields -import "common/money.proto"; // High impact - affects all monetary fields -``` - -### Feature-Specific Imports -```proto -// Feature modules that might be deprecated -import "features/analytics.proto"; // Medium impact - specific feature -import "features/logging.proto"; // Medium impact - specific feature -import "internal/debug.proto"; // Low impact - internal use -``` - -## Wire Format Considerations - -### Import Deletion vs Field Usage -```proto -// Import deletion breaks even if types aren't directly used as fields -import "common/enums.proto"; - -message Order { - // Even if no fields directly use common.enums types, - // nested messages or oneof fields might use them - oneof payment { - CreditCardPayment card = 1; // This might internally use common.enums - } -} -``` - -### Transitive Dependencies -```proto -// Deleting an import can break transitive dependencies -import "user.proto"; // Don't delete even if not directly used - -message Order { - PaymentInfo payment = 1; // PaymentInfo might internally reference user.proto types -} -``` - -### JSON Serialization Impact -```proto -// Imports affect JSON field names and validation -import "google/protobuf/field_mask.proto"; - -message UpdateRequest { - google.protobuf.FieldMask update_mask = 1; // JSON serialization depends on import -} -``` - -## Prevention Strategies - -### Import Auditing -```bash -# Check which imports are actually used -$ grep -r "google.protobuf.Duration" *.proto -$ grep -r "common.User" *.proto - -# But still keep imports even if grep shows no usage! -``` - -### Linting Configuration -```yaml -# Configure linters to allow unused imports -lint: - ignore: - - IMPORT_UNUSED # Allow unused imports for backward compatibility -``` - -### Documentation -```proto -// Document why imports are kept -import "legacy/types.proto"; // Keep for backward compatibility with v1 clients -import "common/user.proto"; // Required for existing serialized data -``` - -## Import vs Field Deletion - -### Different Breaking Change Types -```proto -// Import deletion (this rule) -// import "user.proto"; // BREAKING: import deleted - -// vs Field deletion (different rule) -message Order { - string id = 1; - // User customer = 2; // BREAKING: field deleted (different from import) -} -``` - -### Compound Breaking Changes -```proto -// Worst case: both import AND field deleted -// import "user.proto"; // BREAKING: import deleted -message Order { - string id = 1; - // User customer = 2; // BREAKING: field also deleted -} -// This creates multiple breaking change violations -``` diff --git a/content/docs/cli/breaking-changes/rules/import-no-delete.ru.mdx b/content/docs/cli/breaking-changes/rules/import-no-delete.ru.mdx deleted file mode 100644 index c9adb8f..0000000 --- a/content/docs/cli/breaking-changes/rules/import-no-delete.ru.mdx +++ /dev/null @@ -1,357 +0,0 @@ ---- -title: "Import No Delete" ---- - -Категории: - -- **WIRE+** - -Это правило проверяет, что ни одна инструкция `import` не была удалена из proto‑файла. Удаление import ломает совместимость по wire‑формату и сгенерированный код: типы из импортируемых файлов могли использоваться в текущем файле, и их удаление делает эти типы недоступными. - -## Примеры - -### Плохой (Breaking) - -**До:** -```proto -syntax = "proto3"; - -package myapi.v1; - -import "google/protobuf/timestamp.proto"; -import "google/protobuf/duration.proto"; -import "common/user.proto"; -import "common/address.proto"; - -message Order { - string id = 1; - google.protobuf.Timestamp created_at = 2; - google.protobuf.Duration processing_time = 3; - common.User customer = 4; - common.Address shipping_address = 5; -} -``` - -**После:** -```proto -syntax = "proto3"; - -package myapi.v1; - -import "google/protobuf/timestamp.proto"; -// import "google/protobuf/duration.proto"; // Удалён import — BREAKING -// import "common/user.proto"; // Удалён import — BREAKING -// import "common/address.proto"; // Удалён import — BREAKING - -message Order { - string id = 1; - google.protobuf.Timestamp created_at = 2; - google.protobuf.Duration processing_time = 3; // ERROR: Duration недоступен - common.User customer = 4; // ERROR: User недоступен - common.Address shipping_address = 5; // ERROR: Address недоступен -} -``` - -**Ошибка:** -``` -order.proto:5:1: Previously import "google/protobuf/duration.proto" was deleted. (BREAKING_CHECK) -order.proto:6:1: Previously import "common/user.proto" was deleted. (BREAKING_CHECK) -order.proto:7:1: Previously import "common/address.proto" was deleted. (BREAKING_CHECK) -``` - -### Дополнительные примеры - -**Сервис ломается при удалённых import:** -```proto -// Before -import "google/api/annotations.proto"; -import "google/protobuf/empty.proto"; -import "common/auth.proto"; - -service OrderService { - rpc GetOrder(GetOrderRequest) returns (Order) { - option (google.api.http) = { - get: "/v1/orders/{id}" - }; - } - - rpc DeleteOrder(common.AuthRequest) returns (google.protobuf.Empty); -} - -// After - BREAKING CHANGES! -// import "google/api/annotations.proto"; // BREAKING: deleted -// import "google/protobuf/empty.proto"; // BREAKING: deleted -// import "common/auth.proto"; // BREAKING: deleted - -service OrderService { - rpc GetOrder(GetOrderRequest) returns (Order) { - option (google.api.http) = { // ERROR: annotations недоступен - get: "/v1/orders/{id}" - }; - } - - rpc DeleteOrder(common.AuthRequest) returns (google.protobuf.Empty); // ERROR: типы недоступны -} -``` - -### Хороший (Безопасный) - -**Вместо удаления оставьте неиспользуемые import:** -```proto -syntax = "proto3"; - -package myapi.v1; - -import "google/protobuf/timestamp.proto"; -import "google/protobuf/duration.proto"; // Оставляем даже если не используется -import "common/user.proto"; -import "common/address.proto"; - -message Order { - string id = 1; - google.protobuf.Timestamp created_at = 2; - // Поля, использовавшие Duration/User/Address, удалены — import оставлены -} -``` - -**Или добавьте новые типы, сохранив старые import:** -```proto -syntax = "proto3"; - -package myapi.v1; - -import "google/protobuf/timestamp.proto"; -import "google/protobuf/duration.proto"; -import "common/user.proto"; -import "common/address.proto"; -import "common/v2/user.proto"; // Новый import - -message Order { - string id = 1; - google.protobuf.Timestamp created_at = 2; - google.protobuf.Duration processing_time = 3 [deprecated = true]; - common.User customer = 4 [deprecated = true]; - common.Address shipping_address = 5 [deprecated = true]; - - int32 processing_seconds = 6; - common.v2.UserProfile customer_v2 = 7; - string shipping_address_text = 8; -} -``` - -## Влияние - -- **Generated Code:** Типы пропадают → ошибка компиляции -- **Wire Format:** Сообщения с удалёнными типами не десериализуются -- **Field References:** Поля с этими типами становятся невалидны -- **Service Definitions:** RPC с типами из удалённых файлов ломаются -- **Options Usage:** Пользовательские опции из импортов недоступны - -## Реальный пример - -**Код клиента ломается:** -```go -order := &myapi.Order{ - Id: "order123", - CreatedAt: timestamppb.New(time.Now()), - Customer: &common.User{ // ERROR после удаления import - Id: "user456", - Name: "John Doe", - }, - ShippingAddress: &common.Address{ // ERROR после удаления import - Street: "123 Main St", - City: "New York", - }, -} -// undefined: common.User -// undefined: common.Address -``` - -**Серверная логика ломается:** -```go -func (s *server) CreateOrder(ctx context.Context, req *CreateOrderRequest) (*Order, error) { - return &Order{ - Id: generateOrderId(), - CreatedAt: timestamppb.New(time.Now()), - Customer: &common.User{ // ERROR - Id: req.CustomerId, - Name: req.CustomerName, - }, - ShippingAddress: &common.Address{ // ERROR - Street: req.ShippingStreet, - City: req.ShippingCity, - }, - }, nil -} -``` - -**Компиляция proto ломается:** -```bash -$ protoc --go_out=. order.proto -order.proto:8:3: "common.User" is not defined. -order.proto:9:3: "common.Address" is not defined. -order.proto:10:3: "google.protobuf.Duration" is not defined. -``` - -## Стратегия миграции - -1. Сохраняйте import даже если типы более не используются: - ```proto - import "common/user.proto"; // Оставить - ``` -2. Добавляйте новые import рядом со старыми: - ```proto - import "common/user.proto"; - import "common/v2/user.proto"; - ``` -3. Депрецируйте поля со старыми типами постепенно: - ```proto - message Order { - common.User customer = 4 [deprecated = true]; - common.v2.UserProfile customer_v2 = 5; - } - ``` -4. Сервер: поддерживайте оба варианта: - ```go - if req.CustomerProfileV2 != nil { order.CustomerV2 = req.CustomerProfileV2; return order } - if req.CustomerProfile != nil { order.Customer = req.CustomerProfile } - ``` -5. Удаляйте import только в следующей major‑версии после полной миграции. - -## Типовые сценарии - -### Замена зависимости -```proto -import "old/user.proto"; // Старый -import "new/user.proto"; // Новый - -message Order { - old.User customer = 4 [deprecated = true]; - new.UserProfile customer_v2 = 5; -} -``` - -### Удаление функционала -```proto -import "feature/analytics.proto"; // Оставить даже если поле удалено - -message Order { - string id = 1; - // feature.AnalyticsData analytics = 2; // Поле удалено, import остаётся -} -``` - -### Миграция версии protobuf -```proto -import "google/protobuf/timestamp.proto"; -import "google/protobuf/duration.proto"; - -message Event { - google.protobuf.Timestamp timestamp = 1; - int64 timestamp_millis = 2; -} -``` - -### Упрощение сложных зависимостей -```proto -import "complex/config.proto"; - -message Settings { - complex.ConfigData config = 1 [deprecated = true]; - string config_json = 2; -} -``` - -## Категории import и влияние - -### Стандартные Google imports -```proto -import "google/protobuf/timestamp.proto"; -import "google/protobuf/duration.proto"; -import "google/protobuf/empty.proto"; -import "google/api/annotations.proto"; -``` - -### Общие библиотечные imports -```proto -import "common/user.proto"; -import "common/address.proto"; -import "common/money.proto"; -``` - -### Фичевые imports -```proto -import "features/analytics.proto"; -import "features/logging.proto"; -import "internal/debug.proto"; -``` - -## Особенности wire‑формата - -### Удаление import vs использование поля -```proto -import "common/enums.proto"; -message Order { - oneof payment { - CreditCardPayment card = 1; - } -} -``` - -### Транзитивные зависимости -```proto -import "user.proto"; -message Order { - PaymentInfo payment = 1; -} -``` - -### JSON сериализация -```proto -import "google/protobuf/field_mask.proto"; -message UpdateRequest { - google.protobuf.FieldMask update_mask = 1; -} -``` - -## Профилактика - -### Аудит import -```bash -grep -r "google.protobuf.Duration" *.proto -grep -r "common.User" *.proto -``` -(Даже если не найдено — не удаляем.) - -### Настройка линтера -```yaml -lint: - ignore: - - IMPORT_UNUSED -``` - -### Документация -```proto -import "legacy/types.proto"; // Для обратной совместимости -import "common/user.proto"; // Требуется для уже сохранённых данных -``` - -## Import vs удаление поля - -### Разные типы breaking -```proto -// import "user.proto"; // BREAKING: удалён import -message Order { - string id = 1; - // User customer = 2; // BREAKING: удалено поле -} -``` - -### Составные нарушения -```proto -// import "user.proto"; // BREAKING -message Order { - string id = 1; - // User customer = 2; // BREAKING -} -``` diff --git a/content/docs/cli/breaking-changes/rules/message-moved.mdx b/content/docs/cli/breaking-changes/rules/message-moved.mdx new file mode 100644 index 0000000..b4b56a2 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/message-moved.mdx @@ -0,0 +1,60 @@ +--- +title: "Message Moved" +description: "Checks that messages are not moved to a different .proto file in the FILE profile." +--- + +- **Rule ID:** `MESSAGE_MOVED` +- **Profiles:** `FILE` + +In the `FILE` profile, moving a `message` to a different `.proto` file (even within the same protobuf package) is rejected because generated file-oriented imports (such as C++ headers, Python modules, or Java outer classes) depend on the declaring file path. Use the `PACKAGE` profile to allow moving messages between files within the same package. + +## Examples + +### Bad + +**Before:** + +```proto +// File: myapi/v1/user.proto +syntax = "proto3"; + +package myapi.v1; + +message Address { + string city = 1; +} +``` + +**After:** + +```proto +// File: myapi/v1/address.proto +syntax = "proto3"; + +package myapi.v1; + +message Address { + string city = 1; +} +``` + +**Error:** + +```text +myapi/v1/user.proto:6:1: Message "myapi.v1.Address" was moved from "myapi/v1/user.proto" to "myapi/v1/address.proto". (MESSAGE_MOVED) +``` + +### Good + +Keep the message in its original `.proto` file when using the `FILE` profile: + +```proto +// File: myapi/v1/user.proto +syntax = "proto3"; + +package myapi.v1; + +message Address { + string city = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/message-moved.ru.mdx b/content/docs/cli/breaking-changes/rules/message-moved.ru.mdx new file mode 100644 index 0000000..9f4168e --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/message-moved.ru.mdx @@ -0,0 +1,60 @@ +--- +title: "Message Moved" +description: "Проверяет, что сообщения не переносятся в другой .proto-файл в профиле FILE." +--- + +- **ID правила:** `MESSAGE_MOVED` +- **Профили:** `FILE` + +В профиле `FILE` перенос `message` в другой `.proto`-файл (даже внутри того же пакета) запрещён, поскольку файловые импорты в сгенерированном коде (например, заголовки C++, модули Python или внешние классы Java) зависят от пути файла. Для разрешённых переносов внутри пакета используйте профиль `PACKAGE`. + +## Примеры + +### Неправильно + +**До:** + +```proto +// File: myapi/v1/user.proto +syntax = "proto3"; + +package myapi.v1; + +message Address { + string city = 1; +} +``` + +**После:** + +```proto +// File: myapi/v1/address.proto +syntax = "proto3"; + +package myapi.v1; + +message Address { + string city = 1; +} +``` + +**Ошибка:** + +```text +myapi/v1/user.proto:6:1: Message "myapi.v1.Address" was moved from "myapi/v1/user.proto" to "myapi/v1/address.proto". (MESSAGE_MOVED) +``` + +### Правильно + +Оставьте сообщение в исходном `.proto`-файле при использовании профиля `FILE`: + +```proto +// File: myapi/v1/user.proto +syntax = "proto3"; + +package myapi.v1; + +message Address { + string city = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/message-no-delete.mdx b/content/docs/cli/breaking-changes/rules/message-no-delete.mdx index abbccc3..b47a4cd 100644 --- a/content/docs/cli/breaking-changes/rules/message-no-delete.mdx +++ b/content/docs/cli/breaking-changes/rules/message-no-delete.mdx @@ -1,18 +1,19 @@ --- title: "Message No Delete" +description: "Checks that no top-level or nested message declarations are deleted." --- -Categories: +- **Rule ID:** `MESSAGE_NO_DELETE` +- **Profiles:** `FILE`, `PACKAGE` -- **WIRE+** - -This rule checks that no messages are deleted from proto files. Deleting a message breaks both wire format compatibility and generated code, as existing data may reference the deleted message and client code depends on the generated types. +This rule checks that no top-level or nested `message` declarations are deleted from a protobuf package (synthetic map-entry messages are excluded). Deleting a message removes generated types and breaks compilation for consumers referencing it. ## Examples ### Bad **Before:** + ```proto syntax = "proto3"; @@ -20,23 +21,16 @@ package myapi.v1; message User { string name = 1; - string email = 2; - Address address = 3; } message Address { string street = 1; string city = 2; - string country = 3; -} - -message Order { - string id = 1; - User user = 2; } ``` **After:** + ```proto syntax = "proto3"; @@ -44,76 +38,21 @@ package myapi.v1; message User { string name = 1; - string email = 2; - Address address = 3; // ERROR: Address message no longer exists! } -// Address message was deleted - BREAKING CHANGE! - -message Order { - string id = 1; - User user = 2; -} +// Address message was deleted ``` **Error:** -``` -user.proto:8:1: Previously present message "Address" was deleted from file. (BREAKING_CHECK) -``` -### More Examples - -**Nested message deletion:** - -```proto -// Before -message User { - string name = 1; - Profile profile = 2; - - message Profile { - string bio = 1; - string avatar_url = 2; - } -} - -// After - BREAKING CHANGE! -message User { - string name = 1; - Profile profile = 2; // ERROR: Profile message deleted - - // Profile nested message was deleted -} +```text +user.proto:9:1: Message "myapi.v1.Address" was deleted. (MESSAGE_NO_DELETE) ``` ### Good -**Instead of deleting, deprecate the message:** -```proto -syntax = "proto3"; +Mark the message deprecated instead of deleting it in the same major version: -package myapi.v1; - -message User { - string name = 1; - string email = 2; - Address address = 3 [deprecated = true]; -} - -message Address { - option deprecated = true; - string street = 1; - string city = 2; - string country = 3; -} - -message Order { - string id = 1; - User user = 2; -} -``` - -**Or replace with new message version:** ```proto syntax = "proto3"; @@ -121,132 +60,23 @@ package myapi.v1; message User { string name = 1; - string email = 2; - Address address = 3 [deprecated = true]; // Old field - AddressV2 address_v2 = 4; // New field with better structure } message Address { option deprecated = true; string street = 1; string city = 2; - string country = 3; } message AddressV2 { string street_address = 1; string city = 2; - string state = 3; - string postal_code = 4; - string country = 5; -} - -message Order { - string id = 1; - User user = 2; + string postal_code = 3; } ``` -## Impact - -- **Wire Format:** Existing data with the deleted message cannot be deserialized -- **Generated Code:** Message classes/structs are removed, breaking client compilation -- **Field References:** Fields using the deleted message type become invalid -- **Nested Dependencies:** All messages referencing the deleted message break - -## Real-World Example - -**Client code breaks:** -```go -// Before - this code works -user := &myapi.User{ - Name: "John Doe", - Email: "john@example.com", - Address: &myapi.Address{ // ERROR after deletion - Street: "123 Main St", - City: "New York", - Country: "USA", - }, -} - -// Generated code compilation fails: -// undefined: myapi.Address -``` - -**Existing data becomes unreadable:** -```json -// Serialized data before deletion -{ - "name": "John Doe", - "email": "john@example.com", - "address": { - "street": "123 Main St", - "city": "New York", - "country": "USA" - } -} - -// After Address deletion - deserialization fails -// Parser doesn't know how to handle "address" field -``` - ## Migration Strategy -1. **Deprecate the message first:** - ```proto - message OldMessage { - option deprecated = true; - // ... fields - } - ``` - -2. **Stop using in new fields** and deprecate existing fields that use it: - ```proto - OldMessage old_data = 5 [deprecated = true]; - ``` - -3. **Create replacement** with new structure if needed: - ```proto - NewMessage new_data = 6; // Better design - ``` - -4. **Remove after migration period** in a new major version - -## Common Scenarios - -### Refactoring Message Structure -```proto -// Instead of deleting UserInfo and creating UserProfile -message UserInfo { - option deprecated = true; // Deprecate old - string name = 1; - string email = 2; -} - -message UserProfile { // Create new alongside - string full_name = 1; - string email_address = 2; - string phone = 3; - // Better field organization -} -``` - -### Removing Unused Messages -```proto -// Even if message seems unused, it might be in serialized data -message OldConfig { - option deprecated = true; // Always deprecate first - // Don't delete immediately - data might exist -} -``` - -### Version Migration -```proto -// Clean approach - new package version -package myapi.v2; - -message User { - // Redesigned message structure - // No deprecated Address references -} -``` +1. Add `option deprecated = true;` to the message and deprecate fields referencing it. +2. Introduce a replacement message if needed. +3. Remove the deprecated message only in a new major package version (for example, `myapi.v2`). diff --git a/content/docs/cli/breaking-changes/rules/message-no-delete.ru.mdx b/content/docs/cli/breaking-changes/rules/message-no-delete.ru.mdx index 88af5cf..4c47d8e 100644 --- a/content/docs/cli/breaking-changes/rules/message-no-delete.ru.mdx +++ b/content/docs/cli/breaking-changes/rules/message-no-delete.ru.mdx @@ -1,18 +1,19 @@ --- title: "Message No Delete" +description: "Проверяет, что ни одно объявление сообщения (верхнего уровня или вложенное) не было удалено." --- -Категории: +- **ID правила:** `MESSAGE_NO_DELETE` +- **Профили:** `FILE`, `PACKAGE` -- **WIRE+** - -Это правило проверяет, что ни одно сообщение (message) не было удалено из proto‑файлов. Удаление message ломает совместимость по wire‑формату и сгенерированный код: в существующих данных могут присутствовать экземпляры удалённого типа, а клиентский код зависит от сгенерированных структур и классов. +Это правило проверяет, что из protobuf-пакета не удалено ни одно объявление `message` (верхнего уровня или вложенное; синтетические entry-сообщения `map` не проверяются). Удаление сообщения убирает сгенерированные типы и ломает компиляцию клиентов. ## Примеры -### Плохой (Breaking) +### Неправильно **До:** + ```proto syntax = "proto3"; @@ -20,23 +21,16 @@ package myapi.v1; message User { string name = 1; - string email = 2; - Address address = 3; } message Address { string street = 1; string city = 2; - string country = 3; -} - -message Order { - string id = 1; - User user = 2; } ``` **После:** + ```proto syntax = "proto3"; @@ -44,76 +38,21 @@ package myapi.v1; message User { string name = 1; - string email = 2; - Address address = 3; // ERROR: Address больше не существует } -// Address удалён — BREAKING CHANGE! - -message Order { - string id = 1; - User user = 2; -} +// Сообщение Address удалено ``` **Ошибка:** -``` -user.proto:8:1: Previously present message "Address" was deleted from file. (BREAKING_CHECK) -``` - -### Дополнительные примеры - -**Удаление вложенного сообщения:** - -```proto -// Before -message User { - string name = 1; - Profile profile = 2; - - message Profile { - string bio = 1; - string avatar_url = 2; - } -} -// After - BREAKING CHANGE! -message User { - string name = 1; - Profile profile = 2; // ERROR: Profile удалён - - // Вложенное сообщение Profile удалено -} +```text +user.proto:9:1: Message "myapi.v1.Address" was deleted. (MESSAGE_NO_DELETE) ``` -### Хороший (Безопасный) - -**Вместо удаления — пометить как deprecated:** -```proto -syntax = "proto3"; - -package myapi.v1; +### Правильно -message User { - string name = 1; - string email = 2; - Address address = 3 [deprecated = true]; -} +Вместо удаления пометьте сообщение как устаревшее в текущей мажорной версии: -message Address { - option deprecated = true; - string street = 1; - string city = 2; - string country = 3; -} - -message Order { - string id = 1; - User user = 2; -} -``` - -**Или заменить новой версией сообщения:** ```proto syntax = "proto3"; @@ -121,120 +60,23 @@ package myapi.v1; message User { string name = 1; - string email = 2; - Address address = 3 [deprecated = true]; // Старое поле - AddressV2 address_v2 = 4; // Новая улучшенная структура } message Address { option deprecated = true; string street = 1; string city = 2; - string country = 3; } message AddressV2 { string street_address = 1; string city = 2; - string state = 3; - string postal_code = 4; - string country = 5; -} - -message Order { - string id = 1; - User user = 2; -} -``` - -## Влияние - -- **Wire Format:** Старые данные с удалённым сообщением не десериализуются -- **Generated Code:** Классы/структуры удаляются — компиляция клиента ломается -- **Field References:** Поля, использующие удалённый тип, становятся невалидны -- **Nested Dependencies:** Все сообщения, ссылающиеся на удалённый тип, ломаются - -## Реальный пример - -**Код клиента ломается:** -```go -// Before -user := &myapi.User{ - Name: "John Doe", - Email: "john@example.com", - Address: &myapi.Address{ // ERROR после удаления - Street: "123 Main St", - City: "New York", - Country: "USA", - }, -} - -// undefined: myapi.Address -``` - -**Старые данные становятся нечитаемыми:** -```json -{ - "name": "John Doe", - "email": "john@example.com", - "address": { - "street": "123 Main St", - "city": "New York", - "country": "USA" - } + string postal_code = 3; } -// После удаления Address: парсер не знает поле address ``` ## Стратегия миграции -1. **Пометить как deprecated:** - ```proto - message OldMessage { - option deprecated = true; - // ... fields - } - ``` -2. **Пометить поля, использующие его:** - ```proto - OldMessage old_data = 5 [deprecated = true]; - ``` -3. **Добавить замену при необходимости:** - ```proto - NewMessage new_data = 6; - ``` -4. **Удалить в следующей major‑версии после периода миграции** - -## Типовые сценарии - -### Рефакторинг структуры -```proto -message UserInfo { - option deprecated = true; - string name = 1; - string email = 2; -} - -message UserProfile { - string full_name = 1; - string email_address = 2; - string phone = 3; -} -``` - -### Удаление «неиспользуемых» сообщений -```proto -message OldConfig { - option deprecated = true; - // Не удалять сразу — могут быть сохранённые данные -} -``` - -### Миграция версии -```proto -package myapi.v2; - -message User { - // Новая структура без устаревших ссылок -} -``` +1. Добавьте `option deprecated = true;` к сообщению и пометьте устаревшими поля, которые на него ссылаются. +2. При необходимости введите новое сообщение-замену. +3. Удалите устаревшее сообщение только в новой мажорной версии пакета (например, `myapi.v2`). diff --git a/content/docs/cli/breaking-changes/rules/message-no-remove-standard-descriptor-accessor.mdx b/content/docs/cli/breaking-changes/rules/message-no-remove-standard-descriptor-accessor.mdx new file mode 100644 index 0000000..536ed9a --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/message-no-remove-standard-descriptor-accessor.mdx @@ -0,0 +1,58 @@ +--- +title: "Message No Remove Standard Descriptor Accessor" +description: "Checks that messages do not enable no_standard_descriptor_accessor after previously generating descriptor accessors." +--- + +- **Rule ID:** `MESSAGE_NO_REMOVE_STANDARD_DESCRIPTOR_ACCESSOR` +- **Profiles:** `FILE`, `PACKAGE` + +This rule checks that a message does not change `option no_standard_descriptor_accessor` from `false` (default) to `true`. Enabling `no_standard_descriptor_accessor` removes generated `descriptor()` / `GetDescriptor()` methods and breaks consumers that rely on reflection accessors. + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Event { + string id = 1; +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Event { + option no_standard_descriptor_accessor = true; + string id = 1; +} +``` + +**Error:** + +```text +event.proto:5:1: Message "myapi.v1.Event" disabled standard descriptor accessors. (MESSAGE_NO_REMOVE_STANDARD_DESCRIPTOR_ACCESSOR) +``` + +### Good + +Do not set `no_standard_descriptor_accessor = true` on existing messages: + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Event { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/message-no-remove-standard-descriptor-accessor.ru.mdx b/content/docs/cli/breaking-changes/rules/message-no-remove-standard-descriptor-accessor.ru.mdx new file mode 100644 index 0000000..68a0fed --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/message-no-remove-standard-descriptor-accessor.ru.mdx @@ -0,0 +1,58 @@ +--- +title: "Message No Remove Standard Descriptor Accessor" +description: "Проверяет, что на сообщениях не включается no_standard_descriptor_accessor после того, как стандартные аксессоры дескриптора уже генерировались." +--- + +- **ID правила:** `MESSAGE_NO_REMOVE_STANDARD_DESCRIPTOR_ACCESSOR` +- **Профили:** `FILE`, `PACKAGE` + +Это правило проверяет, что на сообщении опция `option no_standard_descriptor_accessor` не меняется с `false` (по умолчанию) на `true`. Включение этой опции удаляет сгенерированные методы `descriptor()` / `GetDescriptor()` и ломает код, использующий рефлексию. + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Event { + string id = 1; +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Event { + option no_standard_descriptor_accessor = true; + string id = 1; +} +``` + +**Ошибка:** + +```text +event.proto:5:1: Message "myapi.v1.Event" disabled standard descriptor accessors. (MESSAGE_NO_REMOVE_STANDARD_DESCRIPTOR_ACCESSOR) +``` + +### Правильно + +Не включайте `no_standard_descriptor_accessor = true` на существующих сообщениях: + +```proto +syntax = "proto3"; + +package myapi.v1; + +message Event { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/message-same-json-format.mdx b/content/docs/cli/breaking-changes/rules/message-same-json-format.mdx new file mode 100644 index 0000000..94f1c60 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/message-same-json-format.mdx @@ -0,0 +1,58 @@ +--- +title: "Message Same Json Format" +description: "Checks that messages do not downgrade JSON format support from ALLOW to LEGACY_BEST_EFFORT." +--- + +- **Rule ID:** `MESSAGE_SAME_JSON_FORMAT` +- **Profiles:** `FILE`, `PACKAGE`, `WIRE_JSON` + +This rule checks that a message whose effective `features.json_format` is `ALLOW` (the default in `proto3` and Editions 2023) does not downgrade to `LEGACY_BEST_EFFORT`. Downgrading breaks JSON serialization guarantees in `FILE`, `PACKAGE`, and `WIRE_JSON`. + +## Examples + +### Bad + +**Before:** + +```proto +edition = "2023"; + +package myapi.v1; + +message User { + string id = 1; +} +``` + +**After:** + +```proto +edition = "2023"; + +package myapi.v1; + +message User { + option features.json_format = LEGACY_BEST_EFFORT; + string id = 1; +} +``` + +**Error:** + +```text +user.proto:5:1: Message "myapi.v1.User" changed JSON format support. (MESSAGE_SAME_JSON_FORMAT) +``` + +### Good + +Keep `features.json_format = ALLOW` on messages that already support standard JSON: + +```proto +edition = "2023"; + +package myapi.v1; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/message-same-json-format.ru.mdx b/content/docs/cli/breaking-changes/rules/message-same-json-format.ru.mdx new file mode 100644 index 0000000..0d12f54 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/message-same-json-format.ru.mdx @@ -0,0 +1,58 @@ +--- +title: "Message Same Json Format" +description: "Проверяет, что сообщения не понижают поддержку формата JSON с ALLOW до LEGACY_BEST_EFFORT." +--- + +- **ID правила:** `MESSAGE_SAME_JSON_FORMAT` +- **Профили:** `FILE`, `PACKAGE`, `WIRE_JSON` + +Это правило проверяет, что сообщение с эффективной опцией `features.json_format = ALLOW` (по умолчанию в `proto3` и Editions 2023) не понижает её до `LEGACY_BEST_EFFORT`. Такое понижение нарушает гарантии JSON-сериализации в профилях `FILE`, `PACKAGE` и `WIRE_JSON`. + +## Примеры + +### Неправильно + +**До:** + +```proto +edition = "2023"; + +package myapi.v1; + +message User { + string id = 1; +} +``` + +**После:** + +```proto +edition = "2023"; + +package myapi.v1; + +message User { + option features.json_format = LEGACY_BEST_EFFORT; + string id = 1; +} +``` + +**Ошибка:** + +```text +user.proto:5:1: Message "myapi.v1.User" changed JSON format support. (MESSAGE_SAME_JSON_FORMAT) +``` + +### Правильно + +Сохраняйте `features.json_format = ALLOW` для сообщений, уже поддерживающих стандартный JSON: + +```proto +edition = "2023"; + +package myapi.v1; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/message-same-message-set-wire-format.mdx b/content/docs/cli/breaking-changes/rules/message-same-message-set-wire-format.mdx new file mode 100644 index 0000000..e3c22b3 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/message-same-message-set-wire-format.mdx @@ -0,0 +1,58 @@ +--- +title: "Message Same Message Set Wire Format" +description: "Checks that messages keep the same message_set_wire_format option." +--- + +- **Rule ID:** `MESSAGE_SAME_MESSAGE_SET_WIRE_FORMAT` +- **Profiles:** `FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE` + +This rule checks that a message does not toggle `option message_set_wire_format`. Enabling or disabling MessageSet wire encoding completely changes the binary framing of extensions on that message and breaks compatibility across all four profiles (`FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE`). + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto2"; + +package myapi.v1; + +message Envelope { + extensions 100 to max; +} +``` + +**After:** + +```proto +syntax = "proto2"; + +package myapi.v1; + +message Envelope { + option message_set_wire_format = true; + extensions 4 to max; +} +``` + +**Error:** + +```text +envelope.proto:5:1: Message "myapi.v1.Envelope" changed message-set encoding. (MESSAGE_SAME_MESSAGE_SET_WIRE_FORMAT) +``` + +### Good + +Keep `message_set_wire_format` unchanged on existing messages: + +```proto +syntax = "proto2"; + +package myapi.v1; + +message Envelope { + extensions 100 to max; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/message-same-message-set-wire-format.ru.mdx b/content/docs/cli/breaking-changes/rules/message-same-message-set-wire-format.ru.mdx new file mode 100644 index 0000000..d1acb23 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/message-same-message-set-wire-format.ru.mdx @@ -0,0 +1,58 @@ +--- +title: "Message Same Message Set Wire Format" +description: "Проверяет, что сообщения сохраняют прежнее значение опции message_set_wire_format." +--- + +- **ID правила:** `MESSAGE_SAME_MESSAGE_SET_WIRE_FORMAT` +- **Профили:** `FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE` + +Это правило проверяет, что на сообщении не переключается `option message_set_wire_format`. Включение или выключение формата MessageSet полностью меняет бинарное кодирование расширений сообщения и ломает совместимость во всех четырёх профилях (`FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE`). + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto2"; + +package myapi.v1; + +message Envelope { + extensions 100 to max; +} +``` + +**После:** + +```proto +syntax = "proto2"; + +package myapi.v1; + +message Envelope { + option message_set_wire_format = true; + extensions 4 to max; +} +``` + +**Ошибка:** + +```text +envelope.proto:5:1: Message "myapi.v1.Envelope" changed message-set encoding. (MESSAGE_SAME_MESSAGE_SET_WIRE_FORMAT) +``` + +### Правильно + +Не изменяйте `message_set_wire_format` на существующих сообщениях: + +```proto +syntax = "proto2"; + +package myapi.v1; + +message Envelope { + extensions 100 to max; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/message-same-required-fields.mdx b/content/docs/cli/breaking-changes/rules/message-same-required-fields.mdx new file mode 100644 index 0000000..1b9a4a3 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/message-same-required-fields.mdx @@ -0,0 +1,62 @@ +--- +title: "Message Same Required Fields" +description: "Checks that messages do not add or remove required fields." +--- + +- **Rule ID:** `MESSAGE_SAME_REQUIRED_FIELDS` +- **Profiles:** `FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE` + +This rule checks that a message keeps the exact same set of required field numbers (proto2 `required` or Editions `LEGACY_REQUIRED`). Adding a new required field makes previously valid messages fail validation; removing a required field breaks older readers that reject payloads missing that field. Enforced across all four profiles (`FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE`). + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto2"; + +package myapi.v1; + +message Record { + required string id = 1; + optional string label = 2; +} +``` + +**After:** + +```proto +syntax = "proto2"; + +package myapi.v1; + +message Record { + required string id = 1; + optional string label = 2; + required int64 created_at = 3; +} +``` + +**Error:** + +```text +record.proto:8:3: Message "myapi.v1.Record" added required field number 3. (MESSAGE_SAME_REQUIRED_FIELDS) +``` + +### Good + +Add new fields as `optional` (never `required`) and never remove existing `required` fields in the same major version: + +```proto +syntax = "proto2"; + +package myapi.v1; + +message Record { + required string id = 1; + optional string label = 2; + optional int64 created_at = 3; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/message-same-required-fields.ru.mdx b/content/docs/cli/breaking-changes/rules/message-same-required-fields.ru.mdx new file mode 100644 index 0000000..d52b208 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/message-same-required-fields.ru.mdx @@ -0,0 +1,62 @@ +--- +title: "Message Same Required Fields" +description: "Проверяет, что в сообщениях не добавляются и не удаляются обязательные (required) поля." +--- + +- **ID правила:** `MESSAGE_SAME_REQUIRED_FIELDS` +- **Профили:** `FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE` + +Это правило проверяет, что набор номеров обязательных полей сообщения (`required` в proto2 или `LEGACY_REQUIRED` в Editions) остаётся неизменным. Добавление нового `required`-поля делает старые сообщения невалидными, а удаление — ломает старых получателей. Применяется во всех четырёх профилях (`FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE`). + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto2"; + +package myapi.v1; + +message Record { + required string id = 1; + optional string label = 2; +} +``` + +**После:** + +```proto +syntax = "proto2"; + +package myapi.v1; + +message Record { + required string id = 1; + optional string label = 2; + required int64 created_at = 3; +} +``` + +**Ошибка:** + +```text +record.proto:8:3: Message "myapi.v1.Record" added required field number 3. (MESSAGE_SAME_REQUIRED_FIELDS) +``` + +### Правильно + +Добавляйте новые поля как `optional` (а не `required`) и не удаляйте существующие `required`-поля в текущей мажорной версии: + +```proto +syntax = "proto2"; + +package myapi.v1; + +message Record { + required string id = 1; + optional string label = 2; + optional int64 created_at = 3; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/meta.json b/content/docs/cli/breaking-changes/rules/meta.json index f040a92..bc77fae 100644 --- a/content/docs/cli/breaking-changes/rules/meta.json +++ b/content/docs/cli/breaking-changes/rules/meta.json @@ -1,20 +1,74 @@ { "title": "Rules", "pages": [ + "enum-moved", "enum-no-delete", + "enum-same-json-format", + "enum-same-type", "enum-value-no-delete", + "enum-value-no-delete-unless-name-reserved", + "enum-value-no-delete-unless-number-reserved", "enum-value-same-name", + "extension-message-no-delete", + "extension-moved", + "extension-no-delete", + "extension-same-extendee", + "extension-same-number", "field-no-delete", + "field-no-delete-unless-name-reserved", + "field-no-delete-unless-number-reserved", "field-same-cardinality", + "field-same-cpp-string-type", + "field-same-default", + "field-same-java-utf8-validation", + "field-same-json-name", + "field-same-jstype", + "field-same-name", + "field-same-oneof", "field-same-type", - "import-no-delete", + "field-same-utf8-validation", + "field-wire-compatible-cardinality", + "field-wire-compatible-type", + "field-wire-json-compatible-cardinality", + "field-wire-json-compatible-type", + "file-no-delete", + "file-same-cc-enable-arenas", + "file-same-cc-generic-services", + "file-same-csharp-namespace", + "file-same-go-package", + "file-same-java-generic-services", + "file-same-java-multiple-files", + "file-same-java-outer-classname", + "file-same-java-package", + "file-same-java-string-check-utf8", + "file-same-objc-class-prefix", + "file-same-optimize-for", + "file-same-package", + "file-same-php-class-prefix", + "file-same-php-metadata-namespace", + "file-same-php-namespace", + "file-same-py-generic-services", + "file-same-ruby-package", + "file-same-swift-prefix", + "file-same-syntax", + "message-moved", "message-no-delete", - "oneof-field-no-delete", - "oneof-field-same-type", + "message-no-remove-standard-descriptor-accessor", + "message-same-json-format", + "message-same-message-set-wire-format", + "message-same-required-fields", + "oneof-moved", "oneof-no-delete", + "package-no-delete", + "reserved-enum-no-delete", + "reserved-message-no-delete", "rpc-no-delete", + "rpc-same-client-streaming", + "rpc-same-idempotency-level", "rpc-same-request-type", "rpc-same-response-type", + "rpc-same-server-streaming", + "service-moved", "service-no-delete" ] } diff --git a/content/docs/cli/breaking-changes/rules/meta.ru.json b/content/docs/cli/breaking-changes/rules/meta.ru.json new file mode 100644 index 0000000..be91265 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/meta.ru.json @@ -0,0 +1,74 @@ +{ + "title": "Правила", + "pages": [ + "enum-moved", + "enum-no-delete", + "enum-same-json-format", + "enum-same-type", + "enum-value-no-delete", + "enum-value-no-delete-unless-name-reserved", + "enum-value-no-delete-unless-number-reserved", + "enum-value-same-name", + "extension-message-no-delete", + "extension-moved", + "extension-no-delete", + "extension-same-extendee", + "extension-same-number", + "field-no-delete", + "field-no-delete-unless-name-reserved", + "field-no-delete-unless-number-reserved", + "field-same-cardinality", + "field-same-cpp-string-type", + "field-same-default", + "field-same-java-utf8-validation", + "field-same-json-name", + "field-same-jstype", + "field-same-name", + "field-same-oneof", + "field-same-type", + "field-same-utf8-validation", + "field-wire-compatible-cardinality", + "field-wire-compatible-type", + "field-wire-json-compatible-cardinality", + "field-wire-json-compatible-type", + "file-no-delete", + "file-same-cc-enable-arenas", + "file-same-cc-generic-services", + "file-same-csharp-namespace", + "file-same-go-package", + "file-same-java-generic-services", + "file-same-java-multiple-files", + "file-same-java-outer-classname", + "file-same-java-package", + "file-same-java-string-check-utf8", + "file-same-objc-class-prefix", + "file-same-optimize-for", + "file-same-package", + "file-same-php-class-prefix", + "file-same-php-metadata-namespace", + "file-same-php-namespace", + "file-same-py-generic-services", + "file-same-ruby-package", + "file-same-swift-prefix", + "file-same-syntax", + "message-moved", + "message-no-delete", + "message-no-remove-standard-descriptor-accessor", + "message-same-json-format", + "message-same-message-set-wire-format", + "message-same-required-fields", + "oneof-moved", + "oneof-no-delete", + "package-no-delete", + "reserved-enum-no-delete", + "reserved-message-no-delete", + "rpc-no-delete", + "rpc-same-client-streaming", + "rpc-same-idempotency-level", + "rpc-same-request-type", + "rpc-same-response-type", + "rpc-same-server-streaming", + "service-moved", + "service-no-delete" + ] +} diff --git a/content/docs/cli/breaking-changes/rules/oneof-field-no-delete.mdx b/content/docs/cli/breaking-changes/rules/oneof-field-no-delete.mdx deleted file mode 100644 index 067acdc..0000000 --- a/content/docs/cli/breaking-changes/rules/oneof-field-no-delete.mdx +++ /dev/null @@ -1,415 +0,0 @@ ---- -title: "Oneof Field No Delete" ---- - -Categories: - -- **WIRE+** - -This rule checks that no fields are deleted from oneOf groups. Deleting a field from a oneOf breaks both wire format compatibility and generated code, as existing data may use the deleted oneOf option and client code depends on the generated field types and accessor methods. - -## Examples - -### Bad - -**Before:** -```proto -syntax = "proto3"; - -package myapi.v1; - -message LoginRequest { - string username = 1; - - oneof credentials { - string password = 2; - string api_key = 3; - string oauth_token = 4; - string certificate = 5; - } -} - -message SearchQuery { - oneof filter { - string text = 1; - int32 user_id = 2; - string category = 3; - DateRange date_range = 4; - } -} -``` - -**After:** -```proto -syntax = "proto3"; - -package myapi.v1; - -message LoginRequest { - string username = 1; - - oneof credentials { - string password = 2; - string api_key = 3; - // string oauth_token = 4; // Deleted oneOf field - BREAKING! - // string certificate = 5; // Deleted oneOf field - BREAKING! - } -} - -message SearchQuery { - oneof filter { - string text = 1; - int32 user_id = 2; - // string category = 3; // Deleted oneOf field - BREAKING! - // DateRange date_range = 4; // Deleted oneOf field - BREAKING! - } -} -``` - -**Error:** -``` -login.proto:7:5: Previously present field "4" with name "oauth_token" on OneOf "credentials" was deleted. (BREAKING_CHECK) -login.proto:8:5: Previously present field "5" with name "certificate" on OneOf "credentials" was deleted. (BREAKING_CHECK) -search.proto:6:5: Previously present field "3" with name "category" on OneOf "filter" was deleted. (BREAKING_CHECK) -search.proto:7:5: Previously present field "4" with name "date_range" on OneOf "filter" was deleted. (BREAKING_CHECK) -``` - -### More Examples - -**Nested message oneOf field deletion:** - -```proto -// Before -message PaymentRequest { - string order_id = 1; - - oneof payment_method { - CreditCardPayment credit_card = 2; - BankTransferPayment bank_transfer = 3; - CryptoPayment crypto = 4; - GiftCardPayment gift_card = 5; - } -} - -// After - BREAKING CHANGES! -message PaymentRequest { - string order_id = 1; - - oneof payment_method { - CreditCardPayment credit_card = 2; - BankTransferPayment bank_transfer = 3; - // CryptoPayment crypto = 4; // BREAKING: deleted - // GiftCardPayment gift_card = 5; // BREAKING: deleted - } -} -``` - -### Good - -**Instead of deleting, deprecate the oneOf fields:** -```proto -syntax = "proto3"; - -package myapi.v1; - -message LoginRequest { - string username = 1; - - oneof credentials { - string password = 2; - string api_key = 3; - string oauth_token = 4 [deprecated = true]; - string certificate = 5 [deprecated = true]; - } -} - -message SearchQuery { - oneof filter { - string text = 1; - int32 user_id = 2; - string category = 3 [deprecated = true]; - DateRange date_range = 4 [deprecated = true]; - } -} -``` - -**Or add new oneOf fields while keeping old ones:** -```proto -syntax = "proto3"; - -package myapi.v1; - -message LoginRequest { - string username = 1; - - oneof credentials { - string password = 2; - string api_key = 3; - string oauth_token = 4 [deprecated = true]; // Keep old field - string certificate = 5 [deprecated = true]; // Keep old field - - OAuthCredentials oauth_v2 = 6; // New structured approach - CertificateCredentials cert_v2 = 7; // New structured approach - } -} -``` - -## Impact - -- **Wire Format:** Existing data with deleted oneOf fields cannot be deserialized properly -- **Generated Code:** OneOf field accessor methods are removed, breaking client compilation -- **Type Safety:** Generated oneOf wrapper types lose options, breaking switch statements -- **Business Logic:** Client code handling specific oneOf cases breaks - -## Real-World Example - -**Client code breaks:** -```go -// Before - this code works -loginReq := &myapi.LoginRequest{ - Username: "user123", -} - -// Set OAuth token (oneOf field) -loginReq.Credentials = &myapi.LoginRequest_OauthToken{ - OauthToken: "token123", // ERROR after field deletion -} - -// Switch on oneOf field types -switch cred := loginReq.Credentials.(type) { -case *myapi.LoginRequest_Password: - return authenticatePassword(cred.Password) -case *myapi.LoginRequest_OauthToken: // ERROR: undefined type after deletion - return authenticateOAuth(cred.OauthToken) -case *myapi.LoginRequest_Certificate: // ERROR: undefined type after deletion - return authenticateCert(cred.Certificate) -default: - return errors.New("unsupported credential type") -} - -// Generated code compilation fails: -// undefined: myapi.LoginRequest_OauthToken -// undefined: myapi.LoginRequest_Certificate -``` - -**Server handling breaks:** -```go -// Before - server handles all oneOf field types -func authenticateUser(req *LoginRequest) error { - switch cred := req.Credentials.(type) { - case *LoginRequest_Password: - return validatePassword(cred.Password) - case *LoginRequest_ApiKey: - return validateApiKey(cred.ApiKey) - case *LoginRequest_OauthToken: // ERROR after deletion - return validateOAuth(cred.OauthToken) - case *LoginRequest_Certificate: // ERROR after deletion - return validateCertificate(cred.Certificate) - default: - return errors.New("no valid credentials provided") - } -} -``` - -**Existing data becomes unreadable:** -```json -// Serialized data before deletion -{ - "username": "user123", - "oauth_token": "abc123xyz" -} - -// After oneOf field deletion -// Data deserializes but oauth_token is lost or causes parsing errors -// User authentication fails due to missing credential data -``` - -## Migration Strategy - -1. **Deprecate oneOf fields first:** - ```proto - oneof credentials { - string password = 2; - string oauth_token = 4 [deprecated = true]; - } - ``` - -2. **Add new fields** if replacement is needed: - ```proto - oneof credentials { - string password = 2; - string oauth_token = 4 [deprecated = true]; - OAuthCredentials oauth_v2 = 6; // New structured field - } - ``` - -3. **Update server code** to handle both old and new fields: - ```go - func authenticateUser(req *LoginRequest) error { - switch cred := req.Credentials.(type) { - case *LoginRequest_OauthV2: - // Handle new structured OAuth - return validateOAuthV2(cred.OauthV2) - case *LoginRequest_OauthToken: - // Handle legacy OAuth (deprecated) - log.Warn("Using deprecated oauth_token field") - return validateOAuthLegacy(cred.OauthToken) - // ... other cases - } - } - ``` - -4. **Migrate clients** to use new fields: - ```go - // Update client to use new structured field - loginReq.Credentials = &LoginRequest_OauthV2{ - OauthV2: &OAuthCredentials{ - Token: "token123", - RefreshToken: "refresh456", - ExpiresAt: timestamp, - }, - } - ``` - -5. **Reserve field numbers** after removal in next major version: - ```proto - oneof credentials { - reserved 4, 5; - reserved "oauth_token", "certificate"; - - string password = 2; - string api_key = 3; - OAuthCredentials oauth_v2 = 6; - } - ``` - -## Common Scenarios - -### Removing Unsupported Authentication Methods -```proto -// Instead of deleting discontinued auth methods -message AuthRequest { - oneof method { - PasswordAuth password = 1; - ApiKeyAuth api_key = 2; - // LdapAuth ldap = 3; // Don't delete even if LDAP discontinued! - - // Better approach: - LdapAuth ldap = 3 [deprecated = true]; // Mark as deprecated - OidcAuth oidc = 4; // Add new method - } -} -``` - -### Simplifying OneOf Options -```proto -// Instead of removing complex options -message SearchRequest { - oneof query_type { - string simple_text = 1; - // ComplexQuery complex = 2; // Don't delete complex queries! - - // Better approach: - ComplexQuery complex = 2 [deprecated = true]; - AdvancedQuery advanced = 3; // Replacement with better design - } -} -``` - -### Business Logic Changes -```proto -// Instead of removing payment methods -message PaymentRequest { - oneof payment_method { - CreditCard credit_card = 1; - // Check check = 2; // Don't delete even if checks discontinued! - BankTransfer bank_transfer = 3; - - // Better approach: - Check check = 2 [deprecated = true]; // Keep for existing data - DigitalWallet digital_wallet = 4; // Add new methods - } -} -``` - -## OneOf Field Deletion vs Other Deletions - -### Different from Regular Field Deletion -```proto -// Regular field deletion (also breaking) -message User { - string name = 1; - // string email = 2; // BREAKING: regular field deletion -} - -// OneOf field deletion (breaks oneOf semantics) -message User { - oneof contact { - string email = 1; - // string phone = 2; // BREAKING: oneOf field deletion - } -} -``` - -### Impact on Generated Code -```go -// Regular field - simple accessor removed -// user.GetEmail() // Method removed - -// OneOf field - wrapper type removed -// *LoginRequest_OauthToken // Entire type removed -// switch statement cases break completely -``` - -### Wire Format Considerations -```proto -// OneOf fields share the same "choice" semantics -// Removing a choice breaks clients that made that choice - -message Request { - oneof data { - string text = 1; // Choice A - bytes binary = 2; // Choice B - if removed, clients using B break - JsonData json = 3; // Choice C - } -} -``` - -## Validation and Error Handling - -### Before Deletion (Type Safe) -```go -func validateRequest(req *Request) error { - switch data := req.Data.(type) { - case *Request_Text: - return validateText(data.Text) - case *Request_Binary: // Type exists - return validateBinary(data.Binary) - case *Request_Json: - return validateJson(data.Json) - case nil: - return errors.New("no data provided") - default: - return errors.New("unknown data type") - } -} -``` - -### After Deletion (Broken) -```go -func validateRequest(req *Request) error { - switch data := req.Data.(type) { - case *Request_Text: - return validateText(data.Text) - // case *Request_Binary: // ERROR: type no longer exists - // return validateBinary(data.Binary) - case *Request_Json: - return validateJson(data.Json) - case nil: - return errors.New("no data provided") - default: - // Existing binary data falls here now! - return errors.New("unknown data type") - } -} -``` diff --git a/content/docs/cli/breaking-changes/rules/oneof-field-no-delete.ru.mdx b/content/docs/cli/breaking-changes/rules/oneof-field-no-delete.ru.mdx deleted file mode 100644 index 4e6909b..0000000 --- a/content/docs/cli/breaking-changes/rules/oneof-field-no-delete.ru.mdx +++ /dev/null @@ -1,373 +0,0 @@ ---- -title: "Oneof Field No Delete" ---- - -Категории: - -- **WIRE+** - -Правило проверяет, что ни одно поле внутри `oneof` группы не было удалено. Удаление поля из `oneof` ломает совместимость по wire‑формату и сгенерированный код: в сохранённых данных может присутствовать выбранный вариант, а клиентский код опирается на сгенерированные типы‑обёртки и методы доступа. - -## Примеры - -### Плохой (Breaking) - -**До:** -```proto -syntax = "proto3"; - -package myapi.v1; - -message LoginRequest { - string username = 1; - - oneof credentials { - string password = 2; - string api_key = 3; - string oauth_token = 4; - string certificate = 5; - } -} - -message SearchQuery { - oneof filter { - string text = 1; - int32 user_id = 2; - string category = 3; - DateRange date_range = 4; - } -} -``` - -**После:** -```proto -syntax = "proto3"; - -package myapi.v1; - -message LoginRequest { - string username = 1; - - oneof credentials { - string password = 2; - string api_key = 3; - // string oauth_token = 4; // Удалено поле oneof — BREAKING! - // string certificate = 5; // Удалено поле oneof — BREAKING! - } -} - -message SearchQuery { - oneof filter { - string text = 1; - int32 user_id = 2; - // string category = 3; // Удалено поле oneof — BREAKING! - // DateRange date_range = 4; // Удалено поле oneof — BREAKING! - } -} -``` - -**Ошибка:** -``` -login.proto:7:5: Previously present field "4" with name "oauth_token" on OneOf "credentials" was deleted. (BREAKING_CHECK) -login.proto:8:5: Previously present field "5" with name "certificate" on OneOf "credentials" was deleted. (BREAKING_CHECK) -search.proto:6:5: Previously present field "3" with name "category" on OneOf "filter" was deleted. (BREAKING_CHECK) -search.proto:7:5: Previously present field "4" with name "date_range" on OneOf "filter" was deleted. (BREAKING_CHECK) -``` - -### Дополнительные примеры - -**Удаление вложенных oneof полей:** -```proto -// Before -message PaymentRequest { - string order_id = 1; - - oneof payment_method { - CreditCardPayment credit_card = 2; - BankTransferPayment bank_transfer = 3; - CryptoPayment crypto = 4; - GiftCardPayment gift_card = 5; - } -} - -// After - BREAKING CHANGES! -message PaymentRequest { - string order_id = 1; - - oneof payment_method { - CreditCardPayment credit_card = 2; - BankTransferPayment bank_transfer = 3; - // CryptoPayment crypto = 4; // BREAKING: deleted - // GiftCardPayment gift_card = 5; // BREAKING: deleted - } -} -``` - -### Хороший (Безопасный) - -**Вместо удаления — пометить поля deprecated:** -```proto -syntax = "proto3"; - -package myapi.v1; - -message LoginRequest { - string username = 1; - - oneof credentials { - string password = 2; - string api_key = 3; - string oauth_token = 4 [deprecated = true]; - string certificate = 5 [deprecated = true]; - } -} - -message SearchQuery { - oneof filter { - string text = 1; - int32 user_id = 2; - string category = 3 [deprecated = true]; - DateRange date_range = 4 [deprecated = true]; - } -} -``` - -**Или добавить новые поля, оставив старые:** -```proto -syntax = "proto3"; - -package myapi.v1; - -message LoginRequest { - string username = 1; - - oneof credentials { - string password = 2; - string api_key = 3; - string oauth_token = 4 [deprecated = true]; // Старое поле - string certificate = 5 [deprecated = true]; - - OAuthCredentials oauth_v2 = 6; // Новый структурированный вариант - CertificateCredentials cert_v2 = 7; - } -} -``` - -## Влияние - -- **Wire Format:** Данные, содержащие удалённый вариант, не десериализуются корректно -- **Generated Code:** Удаляются типы‑обёртки и accessor методы — компиляция клиентов ломается -- **Type Safety:** Логика `switch` по типам oneof разваливается -- **Business Logic:** Код, ожидающий конкретный вариант, перестаёт работать - -## Реальный пример - -**Код клиента ломается:** -```go -// Before -loginReq := &myapi.LoginRequest{ - Username: "user123", -} - -loginReq.Credentials = &myapi.LoginRequest_OauthToken{ - OauthToken: "token123", // ERROR после удаления поля -} - -switch cred := loginReq.Credentials.(type) { -case *myapi.LoginRequest_Password: - return authenticatePassword(cred.Password) -case *myapi.LoginRequest_OauthToken: // ERROR: тип удалён - return authenticateOAuth(cred.OauthToken) -case *myapi.LoginRequest_Certificate: // ERROR: тип удалён - return authenticateCert(cred.Certificate) -default: - return errors.New("unsupported credential type") -} -// undefined: myapi.LoginRequest_OauthToken -// undefined: myapi.LoginRequest_Certificate -``` - -**Серверная логика ломается:** -```go -func authenticateUser(req *LoginRequest) error { - switch cred := req.Credentials.(type) { - case *LoginRequest_Password: - return validatePassword(cred.Password) - case *LoginRequest_ApiKey: - return validateApiKey(cred.ApiKey) - case *LoginRequest_OauthToken: // ERROR после удаления - return validateOAuth(cred.OauthToken) - case *LoginRequest_Certificate: // ERROR после удаления - return validateCertificate(cred.Certificate) - default: - return errors.New("no valid credentials provided") - } -} -``` - -**Старые данные становятся нечитаемыми:** -```json -{ - "username": "user123", - "oauth_token": "abc123xyz" -} -// После удаления: токен теряется или вызывает ошибку парсинга -``` - -## Стратегия миграции - -1. **Депрецируйте сначала:** - ```proto - oneof credentials { - string password = 2; - string oauth_token = 4 [deprecated = true]; - } - ``` -2. **Добавьте новые структурированные поля:** - ```proto - oneof credentials { - string password = 2; - string oauth_token = 4 [deprecated = true]; - OAuthCredentials oauth_v2 = 6; - } - ``` -3. **Сервер: поддерживайте оба варианта:** - ```go - switch cred := req.Credentials.(type) { - case *LoginRequest_OauthV2: - return validateOAuthV2(cred.OauthV2) - case *LoginRequest_OauthToken: - log.Warn("Deprecated oauth_token used") - return validateOAuthLegacy(cred.OauthToken) - } - ``` -4. **Мигрируйте клиентов на новое поле:** - ```go - loginReq.Credentials = &LoginRequest_OauthV2{ - OauthV2: &OAuthCredentials{ - Token: "token123", - RefreshToken: "refresh456", - ExpiresAt: timestamp, - }, - } - ``` -5. **Зарезервируйте номера удалённых полей в следующей major‑версии:** - ```proto - oneof credentials { - reserved 4, 5; - reserved "oauth_token", "certificate"; - string password = 2; - string api_key = 3; - OAuthCredentials oauth_v2 = 6; - } - ``` - -## Типовые сценарии - -### Удаление неподдерживаемых методов аутентификации -```proto -message AuthRequest { - oneof method { - PasswordAuth password = 1; - ApiKeyAuth api_key = 2; - // LdapAuth ldap = 3; // НЕЛЬЗЯ просто удалить - LdapAuth ldap = 3 [deprecated = true]; - OidcAuth oidc = 4; - } -} -``` - -### Упрощение вариантов oneof -```proto -message SearchRequest { - oneof query_type { - string simple_text = 1; - // ComplexQuery complex = 2; // Не удалять напрямую - ComplexQuery complex = 2 [deprecated = true]; - AdvancedQuery advanced = 3; - } -} -``` - -### Изменения бизнес‑логики платежей -```proto -message PaymentRequest { - oneof payment_method { - CreditCard credit_card = 1; - BankTransfer bank_transfer = 3; - // Check check = 2; // Не удалять - Check check = 2 [deprecated = true]; - DigitalWallet digital_wallet = 4; - } -} -``` - -## OneOf Field Deletion vs обычное удаление - -### Отличия от удаления обычного поля -```proto -message User { - string name = 1; - // string email = 2; // BREAKING: обычное поле -} - -message User { - oneof contact { - string email = 1; - // string phone = 2; // BREAKING: поле в oneof - } -} -``` - -### Влияние на сгенерированный код -```go -// Обычное поле: удаляется простой геттер -// user.GetEmail() - -// Поле в oneof: пропадает тип-обёртка, кейсы switch ломаются -// *LoginRequest_OauthToken -``` - -### Wire‑особенности -```proto -message Request { - oneof data { - string text = 1; - bytes binary = 2; // Если удалить — клиенты, использующие binary, ломаются - JsonData json = 3; - } -} -``` - -## Валидация и обработка ошибок - -### До удаления (типобезопасно) -```go -switch data := req.Data.(type) { -case *Request_Text: - return validateText(data.Text) -case *Request_Binary: - return validateBinary(data.Binary) -case *Request_Json: - return validateJson(data.Json) -case nil: - return errors.New("no data provided") -default: - return errors.New("unknown data type") -} -``` - -### После удаления (сломано) -```go -switch data := req.Data.(type) { -case *Request_Text: - return validateText(data.Text) -// case *Request_Binary: // Тип исчез — кейс не компилируется -case *Request_Json: - return validateJson(data.Json) -case nil: - return errors.New("no data provided") -default: - return errors.New("unknown data type") // Старые бинарные данные попадают сюда -} -``` diff --git a/content/docs/cli/breaking-changes/rules/oneof-field-same-type.mdx b/content/docs/cli/breaking-changes/rules/oneof-field-same-type.mdx deleted file mode 100644 index 0482508..0000000 --- a/content/docs/cli/breaking-changes/rules/oneof-field-same-type.mdx +++ /dev/null @@ -1,417 +0,0 @@ ---- -title: "Oneof Field Same Type" ---- - -Categories: - -- **WIRE+** - -This rule checks that oneOf field types cannot be changed. Changing the type of a field within a oneOf breaks both wire format compatibility and generated code, as existing data contains the old type and client code expects specific field types in oneOf wrapper structures. - -## Examples - -### Bad - -**Before:** -```proto -syntax = "proto3"; - -package myapi.v1; - -message SearchRequest { - string query = 1; - - oneof filter { - string category = 2; - int32 user_id = 3; - bool is_premium = 4; - DateRange date_range = 5; - } -} - -message NotificationSettings { - oneof delivery { - string email = 1; - int64 phone_number = 2; - WebhookConfig webhook = 3; - } -} -``` - -**After:** -```proto -syntax = "proto3"; - -package myapi.v1; - -message SearchRequest { - string query = 1; - - oneof filter { - int32 category = 2; // Changed from string to int32 - BREAKING! - string user_id = 3; // Changed from int32 to string - BREAKING! - string is_premium = 4; // Changed from bool to string - BREAKING! - string date_range = 5; // Changed from DateRange to string - BREAKING! - } -} - -message NotificationSettings { - oneof delivery { - EmailConfig email = 1; // Changed from string to EmailConfig - BREAKING! - string phone_number = 2; // Changed from int64 to string - BREAKING! - string webhook = 3; // Changed from WebhookConfig to string - BREAKING! - } -} -``` - -**Error:** -``` -search.proto:6:5: Field "2" with name "category" on OneOf "filter" changed type from "string" to "int32". (BREAKING_CHECK) -search.proto:7:5: Field "3" with name "user_id" on OneOf "filter" changed type from "int32" to "string". (BREAKING_CHECK) -search.proto:8:5: Field "4" with name "is_premium" on OneOf "filter" changed type from "bool" to "string". (BREAKING_CHECK) -search.proto:9:5: Field "5" with name "date_range" on OneOf "filter" changed type from "DateRange" to "string". (BREAKING_CHECK) -``` - -### More Examples - -**Complex type changes:** - -```proto -// Before -message PaymentRequest { - oneof payment_info { - CreditCardInfo credit_card = 1; - BankAccountInfo bank_account = 2; - string paypal_email = 3; - CryptoWalletInfo crypto = 4; - } -} - -// After - ALL BREAKING CHANGES! -message PaymentRequest { - oneof payment_info { - string credit_card = 1; // BREAKING: CreditCardInfo -> string - PayPalInfo bank_account = 2; // BREAKING: BankAccountInfo -> PayPalInfo - PayPalInfo paypal_email = 3; // BREAKING: string -> PayPalInfo - string crypto = 4; // BREAKING: CryptoWalletInfo -> string - } -} -``` - -### Good - -**Instead of changing type, add new oneOf field:** -```proto -syntax = "proto3"; - -package myapi.v1; - -message SearchRequest { - string query = 1; - - oneof filter { - string category = 2 [deprecated = true]; // Keep original type - int32 user_id = 3 [deprecated = true]; // Keep original type - bool is_premium = 4 [deprecated = true]; // Keep original type - DateRange date_range = 5 [deprecated = true]; // Keep original type - - int32 category_id = 6; // New field with desired type - string user_identifier = 7; // New field with desired type - string premium_status = 8; // New field with desired type - string date_filter = 9; // New field with desired type - } -} -``` - -**Or create a new oneOf group:** -```proto -syntax = "proto3"; - -package myapi.v1; - -message SearchRequest { - string query = 1; - - oneof filter { - option deprecated = true; // Deprecate old oneOf - string category = 2 [deprecated = true]; - int32 user_id = 3 [deprecated = true]; - bool is_premium = 4 [deprecated = true]; - DateRange date_range = 5 [deprecated = true]; - } - - oneof filter_v2 { // New oneOf with correct types - int32 category_id = 6; - string user_identifier = 7; - PremiumFilter premium_filter = 8; - TimeFilter time_filter = 9; - } -} -``` - -## Impact - -- **Wire Format:** Binary data cannot be deserialized correctly between versions -- **Generated Code:** OneOf wrapper types change, breaking client compilation -- **Type Safety:** Switch statements on oneOf types break with compilation errors -- **Runtime Errors:** Type mismatches cause parsing failures for existing data - -## Real-World Example - -**Client code breaks:** -```go -// Before - this code works -searchReq := &myapi.SearchRequest{ - Query: "golang jobs", -} - -// Set filter using oneOf (original types) -searchReq.Filter = &myapi.SearchRequest_Category{ - Category: "engineering", // string type -} - -// Handle filter types -switch filter := searchReq.Filter.(type) { -case *myapi.SearchRequest_Category: - return searchByCategory(filter.Category) // string parameter -case *myapi.SearchRequest_UserId: - return searchByUserId(filter.UserId) // int32 parameter -default: - return errors.New("unsupported filter") -} - -// After type change - compilation fails -searchReq.Filter = &myapi.SearchRequest_Category{ - Category: "engineering", // ERROR: expects int32, not string -} - -// Switch statement breaks -switch filter := searchReq.Filter.(type) { -case *myapi.SearchRequest_Category: - return searchByCategory(filter.Category) // ERROR: Category is now int32 -case *myapi.SearchRequest_UserId: - return searchByUserId(filter.UserId) // ERROR: UserId is now string -} -``` - -**Server implementation breaks:** -```go -// Before - server expects original types -func handleSearchFilter(req *SearchRequest) (*SearchResult, error) { - switch filter := req.Filter.(type) { - case *SearchRequest_Category: - categoryName := filter.Category // string - return searchDatabase("category", categoryName), nil - case *SearchRequest_UserId: - userId := filter.UserId // int32 - return searchDatabase("user_id", strconv.Itoa(int(userId))), nil - default: - return nil, errors.New("no filter specified") - } -} - -// After type change - runtime errors -func handleSearchFilter(req *SearchRequest) (*SearchResult, error) { - switch filter := req.Filter.(type) { - case *SearchRequest_Category: - categoryId := filter.Category // now int32, but code expects string - return searchDatabase("category", categoryId), nil // ERROR: type mismatch - case *SearchRequest_UserId: - userIdStr := filter.UserId // now string, but conversion logic expects int32 - userId, _ := strconv.Atoi(userIdStr) // Works but semantics changed - return searchDatabase("user_id", strconv.Itoa(userId)), nil - } -} -``` - -**Existing data corruption:** -```json -// Serialized data before type change -{ - "query": "golang jobs", - "category": "engineering" -} - -// After changing category from string to int32 -// Data cannot be deserialized - "engineering" is not a valid int32 -// Results in parsing errors or data loss -``` - -## Migration Strategy - -1. **Add new oneOf fields** with correct types: - ```proto - oneof filter { - string category = 2 [deprecated = true]; - int32 category_id = 6; // New field with desired type - } - ``` - -2. **Update server code** to handle both old and new fields: - ```go - func handleSearchFilter(req *SearchRequest) error { - switch filter := req.Filter.(type) { - case *SearchRequest_CategoryId: - // Handle new int32 field - return searchByCategoryId(filter.CategoryId) - case *SearchRequest_Category: - // Handle legacy string field (deprecated) - log.Warn("Using deprecated string category field") - categoryId := convertCategoryNameToId(filter.Category) - return searchByCategoryId(categoryId) - } - } - ``` - -3. **Migrate clients** to use new fields: - ```go - // Update client to use new typed field - searchReq.Filter = &SearchRequest_CategoryId{ - CategoryId: 123, // int32 instead of string - } - ``` - -4. **Provide migration utilities** for data conversion: - ```go - func MigrateSearchRequest(old *SearchRequestV1) *SearchRequestV2 { - new := &SearchRequestV2{Query: old.Query} - - switch filter := old.Filter.(type) { - case *SearchRequestV1_Category: - // Convert string category to int32 ID - categoryId := lookupCategoryId(filter.Category) - new.Filter = &SearchRequestV2_CategoryId{CategoryId: categoryId} - } - - return new - } - ``` - -5. **Remove old fields** in next major version: - ```proto - oneof filter { - reserved 2, "category"; - int32 category_id = 6; - } - ``` - -## Common Scenarios - -### Improving Type Safety -```proto -// Instead of changing loose string types to structured types -message ConfigRequest { - oneof setting { - // string database_url = 1; // Don't change type directly! - - // Add new structured field instead - string database_url = 1 [deprecated = true]; - DatabaseConfig database_config = 5; // New structured field - } -} -``` - -### Standardizing Field Types -```proto -// Instead of converting between numeric types -message FilterRequest { - oneof criteria { - // int32 timestamp = 1; // Don't change to int64 directly! - - // Add new field with correct type - int32 timestamp = 1 [deprecated = true]; - int64 timestamp_millis = 5; // New field with proper precision - } -} -``` - -### Message Structure Changes -```proto -// Instead of flattening/expanding message types -message PaymentRequest { - oneof payment { - // string card_number = 1; // Don't change to structured type! - - // Provide both options during transition - string card_number = 1 [deprecated = true]; - CreditCardDetails card_details = 5; // New structured approach - } -} -``` - -## Type Change Compatibility Matrix - -### Never Compatible (Always Breaking) -| From Type | To Type | Result | -|-----------|---------|---------| -| `string` | `int32/int64` | ❌ BREAKING | -| `int32` | `string` | ❌ BREAKING | -| `bool` | `string` | ❌ BREAKING | -| `message` | `string` | ❌ BREAKING | -| `string` | `message` | ❌ BREAKING | -| `enum` | `int32` | ❌ BREAKING | - -### Generated Code Impact -```go -// String to int32 change breaks wrapper types -// Before: -type SearchRequest_Category struct { - Category string -} - -// After: -type SearchRequest_Category struct { - Category int32 // Different type - compilation fails -} - -// All client code using SearchRequest_Category breaks -``` - -### Wire Format Considerations -```proto -// OneOf fields in wire format are identified by field number -// Type changes break deserialization even if field number stays same - -message Request { - oneof data { - string text = 1; // Wire tag: 1, type: string - // int32 text = 1; // Same wire tag, different type - BREAKING! - } -} -``` - -## Validation and Error Handling - -### Type-Safe Validation (Before Change) -```go -func validateSearchFilter(req *SearchRequest) error { - switch filter := req.Filter.(type) { - case *SearchRequest_Category: - if filter.Category == "" { // String validation - return errors.New("category cannot be empty") - } - case *SearchRequest_UserId: - if filter.UserId <= 0 { // Integer validation - return errors.New("user_id must be positive") - } - } - return nil -} -``` - -### Broken Validation (After Type Change) -```go -func validateSearchFilter(req *SearchRequest) error { - switch filter := req.Filter.(type) { - case *SearchRequest_Category: - if filter.Category <= 0 { // ERROR: Category is now int32, validation logic wrong - return errors.New("category must be positive") - } - case *SearchRequest_UserId: - if filter.UserId == "" { // ERROR: UserId is now string, validation logic wrong - return errors.New("user_id cannot be empty") - } - } - return nil -} -``` diff --git a/content/docs/cli/breaking-changes/rules/oneof-field-same-type.ru.mdx b/content/docs/cli/breaking-changes/rules/oneof-field-same-type.ru.mdx deleted file mode 100644 index 4433ce5..0000000 --- a/content/docs/cli/breaking-changes/rules/oneof-field-same-type.ru.mdx +++ /dev/null @@ -1,347 +0,0 @@ ---- -title: "Oneof Field Same Type" ---- - -Категории: - -- **WIRE+** - -Это правило проверяет, что тип поля внутри `oneof` НЕ меняется. Смена типа любого варианта `oneof` — несовместимое (breaking) изменение: существующие данные сериализованы с прежним типом, а клиентский код ожидает конкретные типы-обёртки и методы доступа, сгенерированные для каждого варианта. - -## Примеры - -### Плохой (Breaking) - -**До:** -```proto -syntax = "proto3"; - -package myapi.v1; - -message SearchRequest { - string query = 1; - - oneof filter { - string category = 2; - int32 user_id = 3; - bool is_premium = 4; - DateRange date_range = 5; - } -} - -message NotificationSettings { - oneof delivery { - string email = 1; - int64 phone_number = 2; - WebhookConfig webhook = 3; - } -} -``` - -**После:** -```proto -syntax = "proto3"; - -package myapi.v1; - -message SearchRequest { - string query = 1; - - oneof filter { - int32 category = 2; // Было string -> стало int32 (BREAKING) - string user_id = 3; // Было int32 -> стало string (BREAKING) - string is_premium = 4; // Было bool -> стало string (BREAKING) - string date_range = 5; // Было DateRange -> стало string (BREAKING) - } -} - -message NotificationSettings { - oneof delivery { - EmailConfig email = 1; // Было string -> стало EmailConfig (BREAKING) - string phone_number = 2; // Было int64 -> стало string (BREAKING) - string webhook = 3; // Было WebhookConfig -> стало string (BREAKING) - } -} -``` - -**Ошибка:** -``` -search.proto:6:5: Field "2" with name "category" on OneOf "filter" changed type from "string" to "int32". (BREAKING_CHECK) -search.proto:7:5: Field "3" with name "user_id" on OneOf "filter" changed type from "int32" to "string". (BREAKING_CHECK) -search.proto:8:5: Field "4" with name "is_premium" on OneOf "filter" changed type from "bool" to "string". (BREAKING_CHECK) -search.proto:9:5: Field "5" with name "date_range" on OneOf "filter" changed type from "DateRange" to "string". (BREAKING_CHECK) -``` - -### Дополнительные примеры - -**Комплексные изменения типов:** -```proto -// Before -message PaymentRequest { - oneof payment_info { - CreditCardInfo credit_card = 1; - BankAccountInfo bank_account = 2; - string paypal_email = 3; - CryptoWalletInfo crypto = 4; - } -} - -// After - ВСЁ BREAKING -message PaymentRequest { - oneof payment_info { - string credit_card = 1; // CreditCardInfo -> string - PayPalInfo bank_account = 2; // BankAccountInfo -> PayPalInfo - PayPalInfo paypal_email = 3; // string -> PayPalInfo - string crypto = 4; // CryptoWalletInfo -> string - } -} -``` - -### Хороший (Безопасный) - -**Вместо смены типа — добавьте новое поле в тот же oneof:** -```proto -syntax = "proto3"; - -package myapi.v1; - -message SearchRequest { - string query = 1; - - oneof filter { - string category = 2 [deprecated = true]; // Старый тип - int32 user_id = 3 [deprecated = true]; - bool is_premium = 4 [deprecated = true]; - DateRange date_range = 5 [deprecated = true]; - - int32 category_id = 6; // Новая версия - string user_identifier = 7; - string premium_status = 8; - string date_filter = 9; - } -} -``` - -**Или создайте новый oneof:** -```proto -syntax = "proto3"; - -package myapi.v1; - -message SearchRequest { - string query = 1; - - oneof filter { - option deprecated = true; - string category = 2 [deprecated = true]; - int32 user_id = 3 [deprecated = true]; - bool is_premium = 4 [deprecated = true]; - DateRange date_range = 5 [deprecated = true]; - } - - oneof filter_v2 { - int32 category_id = 6; - string user_identifier = 7; - PremiumFilter premium_filter = 8; - TimeFilter time_filter = 9; - } -} -``` - -## Влияние - -- **Wire Format:** Старые бинарные данные не читаются корректно -- **Generated Code:** Меняются типы-обёртки, код клиента не компилируется -- **Type Safety:** `switch` по варианту oneof ломается -- **Runtime Errors:** Ошибки десериализации и логики при несовпадении типов - -## Реальный пример - -**Ломается клиентский код:** -```go -// Before -searchReq := &myapi.SearchRequest{ - Query: "golang jobs", -} - -// Устанавливаем вариант oneof -searchReq.Filter = &myapi.SearchRequest_Category{ - Category: "engineering", -} - -// Обработка вариантов -switch filter := searchReq.Filter.(type) { -case *myapi.SearchRequest_Category: - return searchByCategory(filter.Category) -case *myapi.SearchRequest_UserId: - return searchByUserId(filter.UserId) -default: - return errors.New("unsupported filter") -} - -// After — тип Category стал int32 -searchReq.Filter = &myapi.SearchRequest_Category{ - Category: "engineering", // ERROR -} - -switch filter := searchReq.Filter.(type) { -case *myapi.SearchRequest_Category: - return searchByCategory(filter.Category) // ERROR -case *myapi.SearchRequest_UserId: - return searchByUserId(filter.UserId) // ERROR: UserId теперь string -} -``` - -**Ломается серверная логика:** -```go -// Before -func handleSearchFilter(req *SearchRequest) (*SearchResult, error) { - switch filter := req.Filter.(type) { - case *SearchRequest_Category: - return searchDatabase("category", filter.Category), nil - case *SearchRequest_UserId: - return searchDatabase("user_id", strconv.Itoa(int(filter.UserId))), nil - default: - return nil, errors.New("no filter specified") - } -} - -// After — несовпадения типов -func handleSearchFilter(req *SearchRequest) (*SearchResult, error) { - switch filter := req.Filter.(type) { - case *SearchRequest_Category: - // filter.Category теперь int32, а код ожидал string - return searchDatabase("category", filter.Category), nil // ERROR - case *SearchRequest_UserId: - userIdStr := filter.UserId // string вместо int32 - userId, _ := strconv.Atoi(userIdStr) - return searchDatabase("user_id", strconv.Itoa(userId)), nil - } -} -``` - -**Порча данных:** -```json -{ - "query": "golang jobs", - "category": "engineering" -} -// После смены типа: "engineering" не может быть интерпретировано как int32 -``` - -## Стратегия миграции - -1. Добавьте новое поле: - ```proto - oneof filter { - string category = 2 [deprecated = true]; - int32 category_id = 6; - } - ``` -2. Сервер поддерживает оба: - ```go - switch filter := req.Filter.(type) { - case *SearchRequest_CategoryId: - return searchByCategoryId(filter.CategoryId) - case *SearchRequest_Category: - log.Warn("Deprecated string category used") - id := convertCategoryNameToId(filter.Category) - return searchByCategoryId(id) - } - ``` -3. Клиенты переходят на `category_id`. -4. Скрипты миграции преобразуют старые данные. -5. В следующей major‑версии: - ```proto - oneof filter { - reserved 2, "category"; - int32 category_id = 6; - } - ``` - -## Типовые сценарии - -### Повышение типобезопасности -```proto -message ConfigRequest { - oneof setting { - string database_url = 1 [deprecated = true]; - DatabaseConfig database_config = 5; - } -} -``` - -### Стандартизация числовых типов -```proto -message FilterRequest { - oneof criteria { - int32 timestamp = 1 [deprecated = true]; - int64 timestamp_millis = 5; - } -} -``` - -### Переход к структурированным типам -```proto -message PaymentRequest { - oneof payment { - string card_number = 1 [deprecated = true]; - CreditCardDetails card_details = 5; - } -} -``` - -## Матрица совместимости - -| From Type | To Type | Результат | -|-----------|---------|-----------| -| `string` | `int32/int64` | ❌ BREAKING | -| `int32` | `string` | ❌ BREAKING | -| `bool` | `string` | ❌ BREAKING | -| `message` | `string` | ❌ BREAKING | -| `string` | `message` | ❌ BREAKING | -| `enum` | `int32` | ❌ BREAKING | - -### Влияние на сгенерированный код -```go -// Before: -type SearchRequest_Category struct { - Category string -} -// After: -type SearchRequest_Category struct { - Category int32 -} -``` - -### Wire‑формат -```proto -message Request { - oneof data { - string text = 1; - // int32 text = 1; // Тот же номер, другой тип — BREAKING - } -} -``` - -## Валидация - -**До:** -```go -switch f := req.Filter.(type) { -case *SearchRequest_Category: - if f.Category == "" { return errors.New("category cannot be empty") } -case *SearchRequest_UserId: - if f.UserId <= 0 { return errors.New("user_id must be positive") } -} -``` - -**После (сломано):** -```go -switch f := req.Filter.(type) { -case *SearchRequest_Category: - if f.Category <= 0 { return errors.New("category must be positive") } // Логика ожидала string -case *SearchRequest_UserId: - if f.UserId == "" { return errors.New("user_id cannot be empty") } // Был int32 -} -``` diff --git a/content/docs/cli/breaking-changes/rules/oneof-moved.mdx b/content/docs/cli/breaking-changes/rules/oneof-moved.mdx new file mode 100644 index 0000000..d4122a2 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/oneof-moved.mdx @@ -0,0 +1,69 @@ +--- +title: "Oneof Moved" +description: "Checks that oneofs are not moved to a different .proto file in the FILE profile." +--- + +- **Rule ID:** `ONEOF_MOVED` +- **Profiles:** `FILE` + +In the `FILE` profile, moving a message containing a real `oneof` to another `.proto` file reports `ONEOF_MOVED` in addition to `MESSAGE_MOVED`, because generated file-level wrapper types move to a different file. Use the `PACKAGE` profile if moving declarations within the same package is permitted. + +## Examples + +### Bad + +**Before:** + +```proto +// File: myapi/v1/auth.proto +syntax = "proto3"; + +package myapi.v1; + +message LoginRequest { + oneof credentials { + string password = 1; + string token = 2; + } +} +``` + +**After:** + +```proto +// File: myapi/v1/login.proto +syntax = "proto3"; + +package myapi.v1; + +message LoginRequest { + oneof credentials { + string password = 1; + string token = 2; + } +} +``` + +**Error:** + +```text +myapi/v1/auth.proto:7:3: Oneof "credentials" on "myapi.v1.LoginRequest" was moved from "myapi/v1/auth.proto" to "myapi/v1/login.proto". (ONEOF_MOVED) +``` + +### Good + +Keep the declaring message and its `oneof` in the original `.proto` file when using the `FILE` profile: + +```proto +// File: myapi/v1/auth.proto +syntax = "proto3"; + +package myapi.v1; + +message LoginRequest { + oneof credentials { + string password = 1; + string token = 2; + } +} +``` diff --git a/content/docs/cli/breaking-changes/rules/oneof-moved.ru.mdx b/content/docs/cli/breaking-changes/rules/oneof-moved.ru.mdx new file mode 100644 index 0000000..c083da8 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/oneof-moved.ru.mdx @@ -0,0 +1,69 @@ +--- +title: "Oneof Moved" +description: "Проверяет, что блоки oneof не переносятся в другой .proto-файл в профиле FILE." +--- + +- **ID правила:** `ONEOF_MOVED` +- **Профили:** `FILE` + +В профиле `FILE` перенос сообщения с настоящим блоком `oneof` в другой `.proto`-файл вызывает срабатывание `ONEOF_MOVED` (в дополнение к `MESSAGE_MOVED`), поскольку сгенерированные типы-обёртки перемещаются в другой файл. Если переносы внутри одного пакета допустимы, используйте профиль `PACKAGE`. + +## Примеры + +### Неправильно + +**До:** + +```proto +// File: myapi/v1/auth.proto +syntax = "proto3"; + +package myapi.v1; + +message LoginRequest { + oneof credentials { + string password = 1; + string token = 2; + } +} +``` + +**После:** + +```proto +// File: myapi/v1/login.proto +syntax = "proto3"; + +package myapi.v1; + +message LoginRequest { + oneof credentials { + string password = 1; + string token = 2; + } +} +``` + +**Ошибка:** + +```text +myapi/v1/auth.proto:7:3: Oneof "credentials" on "myapi.v1.LoginRequest" was moved from "myapi/v1/auth.proto" to "myapi/v1/login.proto". (ONEOF_MOVED) +``` + +### Правильно + +Оставьте сообщение и его `oneof` в исходном `.proto`-файле при использовании профиля `FILE`: + +```proto +// File: myapi/v1/auth.proto +syntax = "proto3"; + +package myapi.v1; + +message LoginRequest { + oneof credentials { + string password = 1; + string token = 2; + } +} +``` diff --git a/content/docs/cli/breaking-changes/rules/oneof-no-delete.mdx b/content/docs/cli/breaking-changes/rules/oneof-no-delete.mdx index 72b1c0b..ea3fcec 100644 --- a/content/docs/cli/breaking-changes/rules/oneof-no-delete.mdx +++ b/content/docs/cli/breaking-changes/rules/oneof-no-delete.mdx @@ -1,18 +1,23 @@ --- title: "Oneof No Delete" +description: "Checks that no real oneof blocks are deleted from messages." --- -Categories: +- **Rule ID:** `ONEOF_NO_DELETE` +- **Profiles:** `FILE`, `PACKAGE` -- **WIRE+** +This rule checks that no real `oneof` declarations are deleted from a message (synthetic oneofs created by proto3 `optional` fields are ignored). Deleting a `oneof` removes generated wrapper types and breaks mutual-exclusivity semantics. -This rule checks that no oneOf fields are deleted from messages. Deleting a oneOf breaks both wire format compatibility and generated code, as existing data may use the oneOf structure and client code depends on the generated oneOf types and accessor methods. + +Moving existing fields out of a real `oneof` also triggers [`FIELD_SAME_ONEOF`](/docs/cli/breaking-changes/rules/field-same-oneof) across all four profiles (`FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE`). + ## Examples ### Bad **Before:** + ```proto syntax = "proto3"; @@ -20,29 +25,16 @@ package myapi.v1; message LoginRequest { string username = 1; - + oneof credentials { string password = 2; string api_key = 3; - string oauth_token = 4; } } - -message PaymentMethod { - oneof method { - CreditCard credit_card = 1; - BankAccount bank_account = 2; - PayPal paypal = 3; - } -} - -message Order { - string id = 1; - PaymentMethod payment = 2; -} ``` **After:** + ```proto syntax = "proto3"; @@ -50,97 +42,21 @@ package myapi.v1; message LoginRequest { string username = 1; - - // credentials oneof was deleted - BREAKING CHANGE! - string password = 2; // Now regular fields - string api_key = 3; // Lost exclusive semantics - string oauth_token = 4; -} - -message PaymentMethod { - // method oneof was deleted - BREAKING CHANGE! - CreditCard credit_card = 1; // Now all can be set simultaneously - BankAccount bank_account = 2; - PayPal paypal = 3; -} - -message Order { - string id = 1; - PaymentMethod payment = 2; + string password = 2; + string api_key = 3; } ``` **Error:** -``` -login.proto:5:3: Previously present oneof "credentials" was deleted. (BREAKING_CHECK) -payment.proto:2:3: Previously present oneof "method" was deleted. (BREAKING_CHECK) -``` - -### More Examples - -**Nested oneOf deletion:** - -```proto -// Before -message UserProfile { - string name = 1; - - message ContactInfo { - oneof contact_method { - string email = 1; - string phone = 2; - string slack_id = 3; - } - } - - ContactInfo contact = 2; -} -// After - BREAKING CHANGE! -message UserProfile { - string name = 1; - - message ContactInfo { - // contact_method oneof was deleted - string email = 1; // No longer mutually exclusive - string phone = 2; // Can set all fields now - string slack_id = 3; - } - - ContactInfo contact = 2; -} +```text +login.proto:8:3: Oneof "credentials" on "myapi.v1.LoginRequest" was deleted. (ONEOF_NO_DELETE) ``` ### Good -**Instead of deleting, deprecate the oneOf:** -```proto -syntax = "proto3"; +Keep the existing `oneof`, deprecate its fields (note that Protobuf does not support `option deprecated = true;` directly on a `oneof`), and introduce a replacement `oneof` if needed: -package myapi.v1; - -message LoginRequest { - string username = 1; - - oneof credentials { - option deprecated = true; - string password = 2 [deprecated = true]; - string api_key = 3 [deprecated = true]; - string oauth_token = 4 [deprecated = true]; - } -} - -message PaymentMethod { - oneof method { - option deprecated = true; - CreditCard credit_card = 1 [deprecated = true]; - BankAccount bank_account = 2 [deprecated = true]; - PayPal paypal = 3 [deprecated = true]; - } -} -``` - -**Or replace with new structure:** ```proto syntax = "proto3"; @@ -148,269 +64,15 @@ package myapi.v1; message LoginRequest { string username = 1; - + oneof credentials { - option deprecated = true; // Old oneOf string password = 2 [deprecated = true]; string api_key = 3 [deprecated = true]; - string oauth_token = 4 [deprecated = true]; - } - - oneof auth_method { // New oneOf with better design - PasswordAuth password_auth = 5; - ApiKeyAuth api_auth = 6; - OAuthAuth oauth_auth = 7; } -} -``` - -## Impact - -- **Wire Format:** OneOf semantics are lost - fields are no longer mutually exclusive -- **Generated Code:** OneOf accessor methods are removed, breaking client compilation -- **Business Logic:** Mutual exclusivity constraints are violated -- **Validation:** Client code expecting only one field to be set may break - -## Real-World Example - -**Client code breaks:** -```go -// Before - oneOf provides mutual exclusivity -loginReq := &myapi.LoginRequest{ - Username: "user123", -} - -// Set one of the credential options (oneOf semantics) -loginReq.Credentials = &myapi.LoginRequest_Password{ - Password: "secret123", -} -// Check which credential type is set -switch cred := loginReq.Credentials.(type) { -case *myapi.LoginRequest_Password: // ERROR after oneOf deletion - return authenticatePassword(cred.Password) -case *myapi.LoginRequest_ApiKey: // ERROR after oneOf deletion - return authenticateApiKey(cred.ApiKey) -default: - return errors.New("no credentials provided") -} - -// Generated code compilation fails: -// undefined: myapi.LoginRequest_Password -// undefined field: loginReq.Credentials -``` - -**Server validation breaks:** -```go -// Before - server validates oneOf semantics -func validateLoginRequest(req *LoginRequest) error { - if req.Credentials == nil { - return errors.New("credentials required") - } - - // OneOf ensures only one credential type is set - switch req.Credentials.(type) { - case *LoginRequest_Password: - return validatePassword(req.GetPassword()) - case *LoginRequest_ApiKey: - return validateApiKey(req.GetApiKey()) - case *LoginRequest_OauthToken: - return validateOAuthToken(req.GetOauthToken()) - default: - return errors.New("unknown credential type") - } -} - -// After oneOf deletion - validation logic breaks -func validateLoginRequest(req *LoginRequest) error { - // No more oneOf - multiple fields can be set! - credCount := 0 - if req.Password != "" { credCount++ } - if req.ApiKey != "" { credCount++ } - if req.OauthToken != "" { credCount++ } - - if credCount == 0 { - return errors.New("no credentials provided") - } - if credCount > 1 { - return errors.New("multiple credentials provided") // Manual check needed! - } - - // Lost type safety - need manual checks - if req.Password != "" { - return validatePassword(req.Password) - } - // ... more manual validation -} -``` - -**Business logic problems:** -```go -// Before - oneOf guarantees mutual exclusivity -payment := &PaymentMethod{ - Method: &PaymentMethod_CreditCard{ - CreditCard: &CreditCard{Number: "1234"}, - }, -} -// Impossible to set multiple payment methods simultaneously - -// After oneOf deletion - business logic can break -payment := &PaymentMethod{ - CreditCard: &CreditCard{Number: "1234"}, - BankAccount: &BankAccount{Number: "5678"}, // Both set! Logic breaks! -} -``` - -## Migration Strategy - -1. **Deprecate the oneOf and all its fields:** - ```proto - oneof old_credentials { - option deprecated = true; - string password = 2 [deprecated = true]; - string api_key = 3 [deprecated = true]; - } - ``` - -2. **Create new structure** if needed: - ```proto - oneof new_auth_method { - PasswordAuth password_auth = 5; - ApiKeyAuth api_auth = 6; - } - ``` - -3. **Update server code** to handle both during transition: - ```go - func handleAuth(req *LoginRequest) error { - // Handle new structure first - if req.NewAuthMethod != nil { - return handleNewAuth(req.NewAuthMethod) - } - - // Fall back to old oneOf (deprecated) - if req.Credentials != nil { - return handleOldAuth(req.Credentials) - } - - return errors.New("no auth method provided") - } - ``` - -4. **Migrate clients** to use new structure: - ```go - // Update client to use new oneOf - loginReq.NewAuthMethod = &LoginRequest_PasswordAuth{ - PasswordAuth: &PasswordAuth{ - Username: "user123", - Password: "secret123", - }, - } - ``` - -5. **Remove old oneOf** in next major version - -## Common Scenarios - -### Replacing OneOf with Regular Fields -```proto -// Instead of removing oneOf structure entirely -message SearchRequest { - // Don't delete oneOf - breaks mutual exclusivity - string text_query = 1; // BREAKING: was in oneOf - int32 user_id = 2; // BREAKING: was in oneOf - string category = 3; // BREAKING: was in oneOf -} - -// Keep oneOf, add new fields if needed -message SearchRequest { - oneof query { - option deprecated = true; - string text_query = 1 [deprecated = true]; - int32 user_id = 2 [deprecated = true]; - string category = 3 [deprecated = true]; + oneof auth_method { + string password_v2 = 4; + string oauth_token = 5; } - - // Add new non-exclusive fields if that's the intent - string search_text = 4; - repeated string filters = 5; -} -``` - -### Simplifying Message Structure -```proto -// Instead of flattening oneOf structure -message NotificationSettings { - // Don't delete oneOf - loses type safety - string email = 1; // BREAKING: was in oneOf - string phone = 2; // BREAKING: was in oneOf - string webhook_url = 3; // BREAKING: was in oneOf -} - -// Keep oneOf for type safety -message NotificationSettings { - oneof delivery_method { - EmailNotification email = 1; - SmsNotification phone = 2; - WebhookNotification webhook = 3; - } -} -``` - -### Proto Syntax Migration -```proto -// When migrating from proto2 to proto3 -// Don't lose oneOf semantics during migration - -// proto2 -message Request { - optional string name = 1; - oneof data { - string text = 2; - int32 number = 3; - } -} - -// proto3 - keep oneOf structure -message Request { - string name = 1; - oneof data { // Don't delete this! - string text = 2; - int32 number = 3; - } -} -``` - -## OneOf Semantics - -### What OneOf Provides -- **Mutual Exclusivity**: Only one field can be set at a time -- **Type Safety**: Generated code enforces single choice -- **Clear Intent**: API design expresses "choose one" semantics -- **Efficient Wire Format**: Only selected field is serialized - -### What's Lost When Deleted -- **Business Logic**: No enforcement of mutual exclusivity -- **Generated Code**: No oneOf wrapper types or methods -- **Validation**: Manual checks needed for exclusivity -- **API Clarity**: Intent of "choose one" is lost - -### Generated Code Impact -```go -// With oneOf - type safe -type LoginRequest struct { - Username string - // Types that are assignable to Credentials: - // *LoginRequest_Password - // *LoginRequest_ApiKey - Credentials isLoginRequest_Credentials -} - -// Without oneOf - no type safety -type LoginRequest struct { - Username string - Password string // All can be set simultaneously - ApiKey string // No mutual exclusivity - OauthToken string } ``` diff --git a/content/docs/cli/breaking-changes/rules/oneof-no-delete.ru.mdx b/content/docs/cli/breaking-changes/rules/oneof-no-delete.ru.mdx index c330032..a3d8c72 100644 --- a/content/docs/cli/breaking-changes/rules/oneof-no-delete.ru.mdx +++ b/content/docs/cli/breaking-changes/rules/oneof-no-delete.ru.mdx @@ -1,18 +1,23 @@ --- title: "Oneof No Delete" +description: "Проверяет, что ни один настоящий блок oneof не был удалён из сообщения." --- -Категории: +- **ID правила:** `ONEOF_NO_DELETE` +- **Профили:** `FILE`, `PACKAGE` -- **WIRE+** +Это правило проверяет, что из сообщения не удалён ни один настоящий блок `oneof` (синтетические oneof для полей `optional` в proto3 не учитываются). Удаление `oneof` убирает сгенерированные типы-обёртки и нарушает семантику взаимной исключаемости. -Это правило проверяет, что ни один `oneof` блок не был удалён из сообщений. Удаление `oneof` ломает совместимость по wire‑формату и сгенерированный код: существующие данные могут содержать ранее выбранный вариант, а клиентский код зависит от типов-обёрток и методов доступа, генерируемых для `oneof`. + +Вынос существующих полей из настоящего `oneof` дополнительно вызывает срабатывание [`FIELD_SAME_ONEOF`](/ru/docs/cli/breaking-changes/rules/field-same-oneof) во всех четырёх профилях (`FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE`). + ## Примеры -### Плохой (Breaking) +### Неправильно **До:** + ```proto syntax = "proto3"; @@ -20,29 +25,16 @@ package myapi.v1; message LoginRequest { string username = 1; - + oneof credentials { string password = 2; string api_key = 3; - string oauth_token = 4; } } - -message PaymentMethod { - oneof method { - CreditCard credit_card = 1; - BankAccount bank_account = 2; - PayPal paypal = 3; - } -} - -message Order { - string id = 1; - PaymentMethod payment = 2; -} ``` **После:** + ```proto syntax = "proto3"; @@ -50,96 +42,21 @@ package myapi.v1; message LoginRequest { string username = 1; - - // credentials oneof удалён — BREAKING CHANGE! - string password = 2; // Теперь обычные поля - string api_key = 3; // Потеряна взаимная исключаемость - string oauth_token = 4; -} - -message PaymentMethod { - // method oneof удалён — BREAKING CHANGE! - CreditCard credit_card = 1; // Теперь можно установить все поля одновременно - BankAccount bank_account = 2; - PayPal paypal = 3; -} - -message Order { - string id = 1; - PaymentMethod payment = 2; + string password = 2; + string api_key = 3; } ``` **Ошибка:** -``` -login.proto:5:3: Previously present oneof "credentials" was deleted. (BREAKING_CHECK) -payment.proto:2:3: Previously present oneof "method" was deleted. (BREAKING_CHECK) -``` - -### Дополнительные примеры - -**Удаление вложенного oneof:** -```proto -// Before -message UserProfile { - string name = 1; - - message ContactInfo { - oneof contact_method { - string email = 1; - string phone = 2; - string slack_id = 3; - } - } - - ContactInfo contact = 2; -} -// After - BREAKING CHANGE! -message UserProfile { - string name = 1; - - message ContactInfo { - // contact_method oneof удалён - string email = 1; // Больше не эксклюзивно - string phone = 2; // Можно задать всё сразу - string slack_id = 3; - } - - ContactInfo contact = 2; -} +```text +login.proto:8:3: Oneof "credentials" on "myapi.v1.LoginRequest" was deleted. (ONEOF_NO_DELETE) ``` -### Хороший (Безопасный) - -**Вместо удаления — депрецируйте oneof:** -```proto -syntax = "proto3"; +### Правильно -package myapi.v1; +Сохраните существующий `oneof`, пометьте его поля опцией `[deprecated = true]` (в Protobuf нельзя задать `option deprecated = true;` непосредственно на самом блоке `oneof`), и при необходимости добавьте новый `oneof`: -message LoginRequest { - string username = 1; - - oneof credentials { - option deprecated = true; - string password = 2 [deprecated = true]; - string api_key = 3 [deprecated = true]; - string oauth_token = 4 [deprecated = true]; - } -} - -message PaymentMethod { - oneof method { - option deprecated = true; - CreditCard credit_card = 1 [deprecated = true]; - BankAccount bank_account = 2 [deprecated = true]; - PayPal paypal = 3 [deprecated = true]; - } -} -``` - -**Или заменить новой структурой:** ```proto syntax = "proto3"; @@ -147,246 +64,15 @@ package myapi.v1; message LoginRequest { string username = 1; - + oneof credentials { - option deprecated = true; // Старый oneof string password = 2 [deprecated = true]; string api_key = 3 [deprecated = true]; - string oauth_token = 4 [deprecated = true]; - } - - oneof auth_method { // Новый дизайн - PasswordAuth password_auth = 5; - ApiKeyAuth api_auth = 6; - OAuthAuth oauth_auth = 7; } -} -``` - -## Влияние - -- **Wire Format:** Теряются семантика взаимной исключаемости — больше одного поля может быть установлено -- **Generated Code:** Удаляются типы-обёртки и accessor методы — код клиента не компилируется -- **Business Logic:** Нарушаются инварианты «только один из» -- **Validation:** Логика проверок должна быть переписана вручную -## Реальный пример - -**Код клиента ломается:** -```go -// Before - oneOf даёт взаимную исключаемость -loginReq := &myapi.LoginRequest{ - Username: "user123", -} - -loginReq.Credentials = &myapi.LoginRequest_Password{ - Password: "secret123", -} - -switch cred := loginReq.Credentials.(type) { -case *myapi.LoginRequest_Password: // ERROR после удаления - return authenticatePassword(cred.Password) -case *myapi.LoginRequest_ApiKey: // ERROR после удаления - return authenticateApiKey(cred.ApiKey) -default: - return errors.New("no credentials provided") -} - -// Compilation errors: -// undefined: myapi.LoginRequest_Password -// undefined field: loginReq.Credentials -``` - -**Валидация на сервере ломается:** -```go -// Before -func validateLoginRequest(req *LoginRequest) error { - if req.Credentials == nil { - return errors.New("credentials required") - } - switch req.Credentials.(type) { - case *LoginRequest_Password: - return validatePassword(req.GetPassword()) - case *LoginRequest_ApiKey: - return validateApiKey(req.GetApiKey()) - case *LoginRequest_OauthToken: - return validateOAuthToken(req.GetOauthToken()) - default: - return errors.New("unknown credential type") - } -} - -// After -func validateLoginRequest(req *LoginRequest) error { - credCount := 0 - if req.Password != "" { credCount++ } - if req.ApiKey != "" { credCount++ } - if req.OauthToken != "" { credCount++ } - - if credCount == 0 { - return errors.New("no credentials provided") - } - if credCount > 1 { - return errors.New("multiple credentials provided") - } - - if req.Password != "" { - return validatePassword(req.Password) - } - // Дополнительные проверки вручную... - return nil -} -``` - -**Проблемы бизнес‑логики:** -```go -// Before -payment := &PaymentMethod{ - Method: &PaymentMethod_CreditCard{ - CreditCard: &CreditCard{Number: "1234"}, - }, -} - -// After — можно задать несколько способов сразу -payment := &PaymentMethod{ - CreditCard: &CreditCard{Number: "1234"}, - BankAccount: &BankAccount{Number: "5678"}, // Ломает бизнес-логику -} -``` - -## Стратегия миграции - -1. **Депрецируйте старый oneof и его поля:** - ```proto - oneof old_credentials { - option deprecated = true; - string password = 2 [deprecated = true]; - string api_key = 3 [deprecated = true]; - } - ``` - -2. **Создайте новый блок при необходимости:** - ```proto - oneof new_auth_method { - PasswordAuth password_auth = 5; - ApiKeyAuth api_auth = 6; - } - ``` - -3. **Сервер: поддерживайте оба до миграции:** - ```go - func handleAuth(req *LoginRequest) error { - if req.NewAuthMethod != nil { - return handleNewAuth(req.NewAuthMethod) - } - if req.Credentials != nil { - return handleOldAuth(req.Credentials) - } - return errors.New("no auth method provided") - } - ``` - -4. **Клиенты: переходите на новый oneof:** - ```go - loginReq.NewAuthMethod = &LoginRequest_PasswordAuth{ - PasswordAuth: &PasswordAuth{ - Username: "user123", - Password: "secret123", - }, - } - ``` - -5. **Удалите старый oneof** в следующей major‑версии. - -## Типовые сценарии - -### Замена oneof обычными полями -```proto -message SearchRequest { - // НЕЛЬЗЯ просто убрать oneof — ломает семантику - string text_query = 1; // BREAKING - int32 user_id = 2; // BREAKING - string category = 3; // BREAKING -} - -message SearchRequest { - oneof query { - option deprecated = true; - string text_query = 1 [deprecated = true]; - int32 user_id = 2 [deprecated = true]; - string category = 3 [deprecated = true]; - } - string search_text = 4; - repeated string filters = 5; -} -``` - -### Упрощение структуры сообщения -```proto -message NotificationSettings { - string email = 1; // BREAKING: был в oneof - string phone = 2; // BREAKING - string webhook_url = 3; // BREAKING -} - -message NotificationSettings { - oneof delivery_method { - EmailNotification email = 1; - SmsNotification phone = 2; - WebhookNotification webhook = 3; - } -} -``` - -### Миграция с proto2 на proto3 -```proto -// proto2 -message Request { - optional string name = 1; - oneof data { - string text = 2; - int32 number = 3; - } -} - -// proto3 — сохраняем oneof -message Request { - string name = 1; - oneof data { - string text = 2; - int32 number = 3; + oneof auth_method { + string password_v2 = 4; + string oauth_token = 5; } } ``` - -## Семантика OneOf - -### Что даёт oneof -- Взаимная исключаемость -- Типобезопасность в коде -- Ясность намерения API («выбери один») -- Эффективная сериализация — кодируется только выбранный вариант - -### Что теряется при удалении -- Инвариант «только один» -- Генерируемые wrapper-типы и методы -- Автоматическая валидация выбора -- Понятность контракта API - -### Влияние на код генерации -```go -// С oneof -type LoginRequest struct { - Username string - Credentials isLoginRequest_Credentials -} - -// Без oneof -type LoginRequest struct { - Username string - Password string - ApiKey string - OauthToken string - // Возможны многозначные конфликтующие состояния -} -``` diff --git a/content/docs/cli/breaking-changes/rules/package-no-delete.mdx b/content/docs/cli/breaking-changes/rules/package-no-delete.mdx new file mode 100644 index 0000000..c1d4dfd --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/package-no-delete.mdx @@ -0,0 +1,54 @@ +--- +title: "Package No Delete" +description: "Checks that no protobuf package present in the baseline is completely deleted." +--- + +- **Rule ID:** `PACKAGE_NO_DELETE` +- **Profiles:** `FILE`, `PACKAGE` + +This rule checks that every protobuf `package` present in the baseline still has at least one file in the current revision. Deleting an entire package breaks all imports and generated package modules for downstream consumers. + +## Examples + +### Bad + +**Before:** + +```proto +// File: myapi/v1/user.proto +syntax = "proto3"; + +package myapi.v1; + +message User { + string id = 1; +} +``` + +**After:** + +```proto +// All files in package myapi.v1 were deleted or moved to myapi.v2 +``` + +**Error:** + +```text +myapi/v1/user.proto:1:1: Package "myapi.v1" was deleted. (PACKAGE_NO_DELETE) +``` + +### Good + +Keep existing major-version packages intact while introducing new versions (such as `myapi.v2`) alongside them: + +```proto +// File: myapi/v1/user.proto (kept) +syntax = "proto3"; + +package myapi.v1; + +message User { + option deprecated = true; + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/package-no-delete.ru.mdx b/content/docs/cli/breaking-changes/rules/package-no-delete.ru.mdx new file mode 100644 index 0000000..d91cc1c --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/package-no-delete.ru.mdx @@ -0,0 +1,54 @@ +--- +title: "Package No Delete" +description: "Проверяет, что ни один protobuf-пакет из базовой ревизии не был полностью удалён." +--- + +- **ID правила:** `PACKAGE_NO_DELETE` +- **Профили:** `FILE`, `PACKAGE` + +Это правило проверяет, что каждый protobuf-пакет (`package`) из базовой ревизии по-прежнему представлен хотя бы одним файлом в текущей ревизии. Полное удаление пакета ломает все импорты и сгенерированные модули у потребителей. + +## Примеры + +### Неправильно + +**До:** + +```proto +// File: myapi/v1/user.proto +syntax = "proto3"; + +package myapi.v1; + +message User { + string id = 1; +} +``` + +**После:** + +```proto +// All files in package myapi.v1 were deleted or moved to myapi.v2 +``` + +**Ошибка:** + +```text +myapi/v1/user.proto:1:1: Package "myapi.v1" was deleted. (PACKAGE_NO_DELETE) +``` + +### Правильно + +Сохраняйте существующие мажорные пакеты и добавляйте новые версии (например, `myapi.v2`) параллельно: + +```proto +// File: myapi/v1/user.proto (kept) +syntax = "proto3"; + +package myapi.v1; + +message User { + option deprecated = true; + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/reserved-enum-no-delete.mdx b/content/docs/cli/breaking-changes/rules/reserved-enum-no-delete.mdx new file mode 100644 index 0000000..e236f94 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/reserved-enum-no-delete.mdx @@ -0,0 +1,66 @@ +--- +title: "Reserved Enum No Delete" +description: "Checks that existing reserved enum numbers and names are never released." +--- + +- **Rule ID:** `RESERVED_ENUM_NO_DELETE` +- **Profiles:** `FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE` + +This rule checks that no previously `reserved` enum value name or number range is removed or narrowed. Releasing a reservation allows future edits to reuse retired enum numbers or JSON names, causing silent data corruption across all four profiles (`FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE`). + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +enum Status { + reserved 2, 10 to 15; + reserved "STATUS_LEGACY"; + STATUS_UNSPECIFIED = 0; + STATUS_ACTIVE = 1; +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +enum Status { + reserved 10 to 15; + STATUS_UNSPECIFIED = 0; + STATUS_ACTIVE = 1; +} +``` + +**Error:** + +```text +status.proto:5:1: Enum "myapi.v1.Status" released reserved value name "STATUS_LEGACY". (RESERVED_ENUM_NO_DELETE) +status.proto:5:1: Enum "myapi.v1.Status" released a reserved number range. (RESERVED_ENUM_NO_DELETE) +``` + +### Good + +Keep all existing `reserved` ranges and names intact (adding more reservations or merging adjacent ranges is allowed): + +```proto +syntax = "proto3"; + +package myapi.v1; + +enum Status { + reserved 2, 10 to 20; + reserved "STATUS_LEGACY", "STATUS_OLD"; + STATUS_UNSPECIFIED = 0; + STATUS_ACTIVE = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/reserved-enum-no-delete.ru.mdx b/content/docs/cli/breaking-changes/rules/reserved-enum-no-delete.ru.mdx new file mode 100644 index 0000000..b6fda0c --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/reserved-enum-no-delete.ru.mdx @@ -0,0 +1,66 @@ +--- +title: "Reserved Enum No Delete" +description: "Проверяет, что существующие зарезервированные номера и имена в enum никогда не освобождаются." +--- + +- **ID правила:** `RESERVED_ENUM_NO_DELETE` +- **Профили:** `FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE` + +Это правило проверяет, что ни одно ранее зарезервированное имя или диапазон номеров в `enum` не были удалены или сужены. Снятие резервирования позволяет повторно занять выведенные из эксплуатации номера или JSON-имена, что ведёт к порче данных во всех четырёх профилях (`FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE`). + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +enum Status { + reserved 2, 10 to 15; + reserved "STATUS_LEGACY"; + STATUS_UNSPECIFIED = 0; + STATUS_ACTIVE = 1; +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +enum Status { + reserved 10 to 15; + STATUS_UNSPECIFIED = 0; + STATUS_ACTIVE = 1; +} +``` + +**Ошибка:** + +```text +status.proto:5:1: Enum "myapi.v1.Status" released reserved value name "STATUS_LEGACY". (RESERVED_ENUM_NO_DELETE) +status.proto:5:1: Enum "myapi.v1.Status" released a reserved number range. (RESERVED_ENUM_NO_DELETE) +``` + +### Правильно + +Сохраняйте все существующие директивы `reserved` (добавлять новые резервы или объединять смежные диапазоны безопасно): + +```proto +syntax = "proto3"; + +package myapi.v1; + +enum Status { + reserved 2, 10 to 20; + reserved "STATUS_LEGACY", "STATUS_OLD"; + STATUS_UNSPECIFIED = 0; + STATUS_ACTIVE = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/reserved-message-no-delete.mdx b/content/docs/cli/breaking-changes/rules/reserved-message-no-delete.mdx new file mode 100644 index 0000000..068d60e --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/reserved-message-no-delete.mdx @@ -0,0 +1,63 @@ +--- +title: "Reserved Message No Delete" +description: "Checks that existing reserved message field numbers and names are never released." +--- + +- **Rule ID:** `RESERVED_MESSAGE_NO_DELETE` +- **Profiles:** `FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE` + +This rule checks that no previously `reserved` field name or number range on a message is removed or narrowed. Releasing a reservation risks reusing retired field tags or names with incompatible types across all four profiles (`FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE`). + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + reserved 4, 10 to 20; + reserved "legacy_token"; + string id = 1; +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + reserved 10 to 20; + string id = 1; +} +``` + +**Error:** + +```text +user.proto:5:1: Message "myapi.v1.User" released reserved field name "legacy_token". (RESERVED_MESSAGE_NO_DELETE) +user.proto:5:1: Message "myapi.v1.User" released a reserved field number range. (RESERVED_MESSAGE_NO_DELETE) +``` + +### Good + +Keep all existing `reserved` ranges and names intact (expanding ranges or adding new reservations is allowed): + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + reserved 4, 10 to 25; + reserved "legacy_token", "old_email"; + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/reserved-message-no-delete.ru.mdx b/content/docs/cli/breaking-changes/rules/reserved-message-no-delete.ru.mdx new file mode 100644 index 0000000..28030ac --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/reserved-message-no-delete.ru.mdx @@ -0,0 +1,63 @@ +--- +title: "Reserved Message No Delete" +description: "Проверяет, что существующие зарезервированные номера и имена полей сообщения никогда не освобождаются." +--- + +- **ID правила:** `RESERVED_MESSAGE_NO_DELETE` +- **Профили:** `FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE` + +Это правило проверяет, что ни одно ранее зарезервированное имя или диапазон номеров полей сообщения не были удалены или сужены. Снятие резервирования создаёт риск повторного использования старых тегов или имён с несовместимыми типами во всех четырёх профилях (`FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE`). + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + reserved 4, 10 to 20; + reserved "legacy_token"; + string id = 1; +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + reserved 10 to 20; + string id = 1; +} +``` + +**Ошибка:** + +```text +user.proto:5:1: Message "myapi.v1.User" released reserved field name "legacy_token". (RESERVED_MESSAGE_NO_DELETE) +user.proto:5:1: Message "myapi.v1.User" released a reserved field number range. (RESERVED_MESSAGE_NO_DELETE) +``` + +### Правильно + +Сохраняйте все существующие директивы `reserved` (расширять диапазоны и добавлять новые резервы безопасно): + +```proto +syntax = "proto3"; + +package myapi.v1; + +message User { + reserved 4, 10 to 25; + reserved "legacy_token", "old_email"; + string id = 1; +} +``` diff --git a/content/docs/cli/breaking-changes/rules/rpc-no-delete.mdx b/content/docs/cli/breaking-changes/rules/rpc-no-delete.mdx index 5fa3560..ac41ab8 100644 --- a/content/docs/cli/breaking-changes/rules/rpc-no-delete.mdx +++ b/content/docs/cli/breaking-changes/rules/rpc-no-delete.mdx @@ -1,18 +1,19 @@ --- title: "Rpc No Delete" +description: "Checks that no RPC methods are deleted from a service." --- -Categories: +- **Rule ID:** `RPC_NO_DELETE` +- **Profiles:** `FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE` -- **WIRE+** - -This rule checks that no RPC methods are deleted from services. Deleting an RPC method breaks both generated code and client applications that call the method. +This rule checks that no RPC methods are deleted from a `service`. Deleting an RPC breaks both generated client/server stubs and live RPC calls on the wire. ## Examples ### Bad **Before:** + ```proto syntax = "proto3"; @@ -20,12 +21,12 @@ package myapi.v1; service UserService { rpc GetUser(GetUserRequest) returns (GetUserResponse); - rpc CreateUser(CreateUserRequest) returns (CreateUserResponse); rpc DeleteUser(DeleteUserRequest) returns (DeleteUserResponse); } ``` **After:** + ```proto syntax = "proto3"; @@ -33,19 +34,20 @@ package myapi.v1; service UserService { rpc GetUser(GetUserRequest) returns (GetUserResponse); - rpc CreateUser(CreateUserRequest) returns (CreateUserResponse); - // DeleteUser RPC was deleted - BREAKING CHANGE! + // DeleteUser RPC was deleted } ``` **Error:** -``` -services.proto:7:1: Previously present RPC "DeleteUser" on service "UserService" was deleted. (BREAKING_CHECK) + +```text +services.proto:7:3: RPC "DeleteUser" on service "myapi.v1.UserService" was deleted. (RPC_NO_DELETE) ``` ### Good -**Instead of deleting, deprecate the RPC:** +Mark the RPC deprecated instead of deleting it: + ```proto syntax = "proto3"; @@ -53,28 +55,14 @@ package myapi.v1; service UserService { rpc GetUser(GetUserRequest) returns (GetUserResponse); - rpc CreateUser(CreateUserRequest) returns (CreateUserResponse); rpc DeleteUser(DeleteUserRequest) returns (DeleteUserResponse) { option deprecated = true; } } ``` -## Impact - -- **Generated Code:** RPC method stubs are removed, breaking client compilation -- **Client Applications:** Existing calls to the RPC fail to compile -- **Runtime:** gRPC clients lose method definition - ## Migration Strategy -1. **Deprecate first:** - ```proto - rpc OldMethod(OldRequest) returns (OldResponse) { - option deprecated = true; - } - ``` - -2. **Return error from implementation** indicating method is no longer supported - -3. **Remove in next major version** after clients have migrated +1. Mark the RPC with `option deprecated = true;` and notify clients. +2. Keep the RPC handler returning a clear error or delegating to the replacement until clients migrate. +3. Remove the RPC only in a new major package version (for example, `myapi.v2`). diff --git a/content/docs/cli/breaking-changes/rules/rpc-no-delete.ru.mdx b/content/docs/cli/breaking-changes/rules/rpc-no-delete.ru.mdx index d347888..3ae7834 100644 --- a/content/docs/cli/breaking-changes/rules/rpc-no-delete.ru.mdx +++ b/content/docs/cli/breaking-changes/rules/rpc-no-delete.ru.mdx @@ -1,18 +1,19 @@ --- title: "Rpc No Delete" +description: "Проверяет, что ни один RPC-метод не был удалён из сервиса." --- -Категории: +- **ID правила:** `RPC_NO_DELETE` +- **Профили:** `FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE` -- **WIRE+** - -Правило проверяет, что ни один RPC‑метод не был удалён из service. Удаление RPC ломает сгенерированный код и клиентские приложения, которые этот метод вызывают. +Это правило проверяет, что из `service` не удалён ни один RPC-метод. Удаление RPC ломает как сгенерированный клиентский и серверный код, так и живые сетевые вызовы. ## Примеры -### Плохой (Breaking) +### Неправильно **До:** + ```proto syntax = "proto3"; @@ -20,12 +21,12 @@ package myapi.v1; service UserService { rpc GetUser(GetUserRequest) returns (GetUserResponse); - rpc CreateUser(CreateUserRequest) returns (CreateUserResponse); rpc DeleteUser(DeleteUserRequest) returns (DeleteUserResponse); } ``` **После:** + ```proto syntax = "proto3"; @@ -33,19 +34,20 @@ package myapi.v1; service UserService { rpc GetUser(GetUserRequest) returns (GetUserResponse); - rpc CreateUser(CreateUserRequest) returns (CreateUserResponse); - // DeleteUser RPC удалён — BREAKING CHANGE! + // RPC DeleteUser удалён } ``` **Ошибка:** -``` -services.proto:7:1: Previously present RPC "DeleteUser" on service "UserService" was deleted. (BREAKING_CHECK) + +```text +services.proto:7:3: RPC "DeleteUser" on service "myapi.v1.UserService" was deleted. (RPC_NO_DELETE) ``` -### Хороший (Безопасный) +### Правильно + +Вместо удаления пометьте RPC-метод как устаревший: -**Вместо удаления — пометить RPC deprecated:** ```proto syntax = "proto3"; @@ -53,28 +55,14 @@ package myapi.v1; service UserService { rpc GetUser(GetUserRequest) returns (GetUserResponse); - rpc CreateUser(CreateUserRequest) returns (CreateUserResponse); rpc DeleteUser(DeleteUserRequest) returns (DeleteUserResponse) { option deprecated = true; } } ``` -## Влияние - -- **Generated Code:** Stub/метод исчезает — клиенты не компилируются -- **Client Applications:** Существующие вызовы метода падают при сборке -- **Runtime:** gRPC клиенты теряют определение метода - ## Стратегия миграции -1. **Сначала деприкация:** - ```proto - rpc OldMethod(OldRequest) returns (OldResponse) { - option deprecated = true; - } - ``` - -2. **Имплементация может возвращать ошибку**, указывая что метод устарел (например, INTERNAL / UNIMPLEMENTED) - -3. **Удалить в следующей major‑версии** после миграции всех клиентов +1. Пометьте RPC опцией `option deprecated = true;` и предупредите потребителей API. +2. Сохраняйте обработчик на сервере до завершения миграции клиентов. +3. Удалите RPC только в новой мажорной версии пакета (например, `myapi.v2`). diff --git a/content/docs/cli/breaking-changes/rules/rpc-same-client-streaming.mdx b/content/docs/cli/breaking-changes/rules/rpc-same-client-streaming.mdx new file mode 100644 index 0000000..2b4c265 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/rpc-same-client-streaming.mdx @@ -0,0 +1,58 @@ +--- +title: "Rpc Same Client Streaming" +description: "Checks that RPC methods do not change client streaming behavior." +--- + +- **Rule ID:** `RPC_SAME_CLIENT_STREAMING` +- **Profiles:** `FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE` + +This rule checks that an RPC method does not toggle `stream` on its request type. Switching between unary and client-streaming changes both the RPC wire framing and generated client/server method signatures across all four profiles (`FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE`). + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +service UploadService { + rpc Upload(UploadRequest) returns (UploadResponse); +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +service UploadService { + rpc Upload(stream UploadRequest) returns (UploadResponse); +} +``` + +**Error:** + +```text +upload.proto:6:3: RPC "Upload" changed client streaming behavior. (RPC_SAME_CLIENT_STREAMING) +``` + +### Good + +Add a new streaming RPC method instead of changing the streaming mode of an existing RPC: + +```proto +syntax = "proto3"; + +package myapi.v1; + +service UploadService { + rpc Upload(UploadRequest) returns (UploadResponse); + rpc UploadStream(stream UploadStreamRequest) returns (UploadStreamResponse); +} +``` diff --git a/content/docs/cli/breaking-changes/rules/rpc-same-client-streaming.ru.mdx b/content/docs/cli/breaking-changes/rules/rpc-same-client-streaming.ru.mdx new file mode 100644 index 0000000..85dff3e --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/rpc-same-client-streaming.ru.mdx @@ -0,0 +1,58 @@ +--- +title: "Rpc Same Client Streaming" +description: "Проверяет, что RPC-методы не меняют режим клиентского стриминга (client streaming)." +--- + +- **ID правила:** `RPC_SAME_CLIENT_STREAMING` +- **Профили:** `FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE` + +Это правило проверяет, что у RPC-метода не добавляется и не убирается `stream` в типе запроса. Переключение между unary и client-streaming меняет и сетевой протокол вызова, и сгенерированные сигнатуры во всех четырёх профилях (`FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE`). + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +service UploadService { + rpc Upload(UploadRequest) returns (UploadResponse); +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +service UploadService { + rpc Upload(stream UploadRequest) returns (UploadResponse); +} +``` + +**Ошибка:** + +```text +upload.proto:6:3: RPC "Upload" changed client streaming behavior. (RPC_SAME_CLIENT_STREAMING) +``` + +### Правильно + +Добавьте новый потоковый RPC-метод вместо изменения режима стриминга у существующего: + +```proto +syntax = "proto3"; + +package myapi.v1; + +service UploadService { + rpc Upload(UploadRequest) returns (UploadResponse); + rpc UploadStream(stream UploadStreamRequest) returns (UploadStreamResponse); +} +``` diff --git a/content/docs/cli/breaking-changes/rules/rpc-same-idempotency-level.mdx b/content/docs/cli/breaking-changes/rules/rpc-same-idempotency-level.mdx new file mode 100644 index 0000000..70cc79f --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/rpc-same-idempotency-level.mdx @@ -0,0 +1,63 @@ +--- +title: "Rpc Same Idempotency Level" +description: "Checks that RPC methods keep the same idempotency_level option." +--- + +- **Rule ID:** `RPC_SAME_IDEMPOTENCY_LEVEL` +- **Profiles:** `FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE` + +This rule checks that an RPC method preserves its `option idempotency_level` (`IDEMPOTENCY_UNKNOWN`, `NO_SIDE_EFFECTS`, or `IDEMPOTENT`). Proxies, HTTP/GET transcoders, and retry policies rely on idempotency guarantees, so changing it is rejected across all four profiles (`FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE`). + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +service UserService { + rpc GetUser(GetUserRequest) returns (GetUserResponse) { + option idempotency_level = NO_SIDE_EFFECTS; + } +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +service UserService { + rpc GetUser(GetUserRequest) returns (GetUserResponse) { + option idempotency_level = IDEMPOTENT; + } +} +``` + +**Error:** + +```text +user.proto:6:3: RPC "GetUser" changed idempotency level. (RPC_SAME_IDEMPOTENCY_LEVEL) +``` + +### Good + +Keep `idempotency_level` unchanged on existing RPC methods (introduce a new RPC if side-effect semantics change): + +```proto +syntax = "proto3"; + +package myapi.v1; + +service UserService { + rpc GetUser(GetUserRequest) returns (GetUserResponse) { + option idempotency_level = NO_SIDE_EFFECTS; + } +} +``` diff --git a/content/docs/cli/breaking-changes/rules/rpc-same-idempotency-level.ru.mdx b/content/docs/cli/breaking-changes/rules/rpc-same-idempotency-level.ru.mdx new file mode 100644 index 0000000..c622bf1 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/rpc-same-idempotency-level.ru.mdx @@ -0,0 +1,63 @@ +--- +title: "Rpc Same Idempotency Level" +description: "Проверяет, что RPC-методы сохраняют прежнее значение опции idempotency_level." +--- + +- **ID правила:** `RPC_SAME_IDEMPOTENCY_LEVEL` +- **Профили:** `FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE` + +Это правило проверяет, что RPC-метод сохраняет значение `option idempotency_level` (`IDEMPOTENCY_UNKNOWN`, `NO_SIDE_EFFECTS` или `IDEMPOTENT`). Прокси, HTTP/GET-транскодеры и политики повторных попыток опираются на гарантии идемпотентности, поэтому её изменение отклоняется во всех четырёх профилях (`FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE`). + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +service UserService { + rpc GetUser(GetUserRequest) returns (GetUserResponse) { + option idempotency_level = NO_SIDE_EFFECTS; + } +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +service UserService { + rpc GetUser(GetUserRequest) returns (GetUserResponse) { + option idempotency_level = IDEMPOTENT; + } +} +``` + +**Ошибка:** + +```text +user.proto:6:3: RPC "GetUser" changed idempotency level. (RPC_SAME_IDEMPOTENCY_LEVEL) +``` + +### Правильно + +Не изменяйте `idempotency_level` на существующем RPC (при смене семантики побочных эффектов добавьте новый RPC): + +```proto +syntax = "proto3"; + +package myapi.v1; + +service UserService { + rpc GetUser(GetUserRequest) returns (GetUserResponse) { + option idempotency_level = NO_SIDE_EFFECTS; + } +} +``` diff --git a/content/docs/cli/breaking-changes/rules/rpc-same-request-type.mdx b/content/docs/cli/breaking-changes/rules/rpc-same-request-type.mdx index ff50af5..183a85a 100644 --- a/content/docs/cli/breaking-changes/rules/rpc-same-request-type.mdx +++ b/content/docs/cli/breaking-changes/rules/rpc-same-request-type.mdx @@ -1,18 +1,19 @@ --- title: "Rpc Same Request Type" +description: "Checks that every RPC method keeps the same fully qualified request message type." --- -Categories: +- **Rule ID:** `RPC_SAME_REQUEST_TYPE` +- **Profiles:** `FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE` -- **WIRE+** - -This rule checks that RPC methods maintain the same request message type. Changing an RPC's request type breaks both wire format compatibility and generated code, as clients expect specific message structures when calling the method. +This rule checks that an RPC method keeps the same fully qualified request message type. Changing the request type breaks generated client/server method signatures and can invalidate serialized requests sent by existing clients. ## Examples ### Bad **Before:** + ```proto syntax = "proto3"; @@ -20,239 +21,66 @@ package myapi.v1; service UserService { rpc GetUser(GetUserRequest) returns (GetUserResponse); - rpc UpdateUser(UpdateUserRequest) returns (UpdateUserResponse); } message GetUserRequest { string user_id = 1; } - -message UpdateUserRequest { - string user_id = 1; - string name = 2; - string email = 3; -} ``` **After:** + ```proto syntax = "proto3"; package myapi.v1; service UserService { - rpc GetUser(GetUserRequestV2) returns (GetUserResponse); // Changed request type - rpc UpdateUser(UserUpdateRequest) returns (UpdateUserResponse); // Changed request type + rpc GetUser(GetUserRequestV2) returns (GetUserResponse); } -message GetUserRequestV2 { // Different message type +message GetUserRequestV2 { string id = 1; bool include_profile = 2; } - -message UserUpdateRequest { // Different message type - string id = 1; - UserProfile profile = 2; -} ``` **Error:** -``` -user_service.proto:6:3: RPC "GetUser" on service "UserService" changed request type from "GetUserRequest" to "GetUserRequestV2". (BREAKING_CHECK) -user_service.proto:7:3: RPC "UpdateUser" on service "UserService" changed request type from "UpdateUserRequest" to "UserUpdateRequest". (BREAKING_CHECK) -``` - -### More Examples - -**Cross-package type changes:** - -```proto -// Before -import "common/user.proto"; -service UserService { - rpc CreateUser(CreateUserRequest) returns (CreateUserResponse); -} - -// After - BREAKING CHANGE! -import "v2/user.proto"; - -service UserService { - rpc CreateUser(v2.CreateUserRequest) returns (CreateUserResponse); // Different package -} +```text +user_service.proto:6:3: RPC "GetUser" request type changed from "myapi.v1.GetUserRequest" to "myapi.v1.GetUserRequestV2". (RPC_SAME_REQUEST_TYPE) ``` ### Good -**Instead of changing request type, version the RPC:** +Extend the existing request message with new fields when the change is additive: + ```proto syntax = "proto3"; package myapi.v1; service UserService { - rpc GetUser(GetUserRequest) returns (GetUserResponse) { - option deprecated = true; - } - rpc GetUserV2(GetUserRequestV2) returns (GetUserResponse); // New RPC method - rpc UpdateUser(UpdateUserRequest) returns (UpdateUserResponse) { - option deprecated = true; - } - rpc UpdateUserV2(UserUpdateRequest) returns (UpdateUserResponse); // New RPC method + rpc GetUser(GetUserRequest) returns (GetUserResponse); } -// Keep old messages for backward compatibility message GetUserRequest { string user_id = 1; -} - -// Add new messages for enhanced functionality -message GetUserRequestV2 { - string id = 1; bool include_profile = 2; } ``` -**Or create a new service version:** +Or add a new RPC method alongside the deprecated original when a completely new request message is required: + ```proto syntax = "proto3"; -package myapi.v2; // New package version +package myapi.v1; service UserService { - rpc GetUser(GetUserRequest) returns (GetUserResponse); // Clean interface in v2 - rpc UpdateUser(UpdateUserRequest) returns (UpdateUserResponse); -} - -message GetUserRequest { - string id = 1; // Improved field names - bool include_profile = 2; -} -``` - -## Impact - -- **Wire Format:** Existing client requests cannot be deserialized by new server -- **Generated Code:** Client stubs expect different request message types, breaking compilation -- **gRPC Calls:** Method signatures change in generated client code -- **Runtime Errors:** Type mismatches cause RPC call failures - -## Real-World Example - -**Client code breaks:** -```go -// Before - this code works -client := myapi.NewUserServiceClient(conn) -resp, err := client.GetUser(ctx, &myapi.GetUserRequest{ - UserId: "user123", -}) - -// After request type change - compilation fails -client := myapi.NewUserServiceClient(conn) -resp, err := client.GetUser(ctx, &myapi.GetUserRequest{ // ERROR: type not found - UserId: "user123", // ERROR: field not found -}) - -// Must use new type: -resp, err := client.GetUser(ctx, &myapi.GetUserRequestV2{ - Id: "user123", // Different field name - IncludeProfile: true, // New required field -}) -``` - -**Server implementation breaks:** -```go -// Before - server expects GetUserRequest -func (s *server) GetUser(ctx context.Context, req *GetUserRequest) (*GetUserResponse, error) { - userID := req.UserId // This field exists - // ... implementation -} - -// After - server must handle GetUserRequestV2 -func (s *server) GetUser(ctx context.Context, req *GetUserRequestV2) (*GetUserResponse, error) { - userID := req.Id // Different field name - includeProfile := req.IncludeProfile // New field to handle - // ... implementation must change -} -``` - -## Migration Strategy - -1. **Add new RPC method** with improved request type: - ```proto - rpc GetUser(GetUserRequest) returns (GetUserResponse) { - option deprecated = true; - } - rpc GetUserV2(GetUserRequestV2) returns (GetUserResponse); - ``` - -2. **Implement both methods** on server during transition: - ```go - func (s *server) GetUser(ctx context.Context, req *GetUserRequest) (*GetUserResponse, error) { - // Legacy implementation - return s.getUserInternal(req.UserId, false) - } - - func (s *server) GetUserV2(ctx context.Context, req *GetUserRequestV2) (*GetUserResponse, error) { - // New implementation - return s.getUserInternal(req.Id, req.IncludeProfile) - } - ``` - -3. **Migrate clients** to use new RPC method: - ```go - // Update client calls to use V2 - resp, err := client.GetUserV2(ctx, &myapi.GetUserRequestV2{ - Id: userID, - IncludeProfile: true, - }) - ``` - -4. **Remove old RPC** in next major version: - ```proto - // Only keep new version - rpc GetUserV2(GetUserRequestV2) returns (GetUserResponse); - ``` - -## Common Scenarios - -### Adding Required Fields -```proto -// Instead of modifying existing request -message GetUserRequest { - string user_id = 1; - bool include_deleted = 2; // BREAKING: new required field -} - -// Add new RPC method -message GetUserRequestV2 { - string user_id = 1; - bool include_deleted = 2; // Safe in new method -} -``` - -### Restructuring Request Data -```proto -// Instead of changing field structure -message UpdateUserRequest { - UserProfile profile = 1; // BREAKING: was individual fields -} - -// Version the RPC -rpc UpdateUser(UpdateUserRequest) returns (...) { - option deprecated = true; -} -rpc UpdateUserV2(UpdateUserRequestV2) returns (...); -``` - -### Package Migrations -```proto -// Instead of changing import packages -import "v2/messages.proto"; // BREAKING: different package - -// Keep old RPC, add new one -rpc OldMethod(v1.Request) returns (...) { - option deprecated = true; + rpc GetUser(GetUserRequest) returns (GetUserResponse) { + option deprecated = true; + } + rpc GetUserV2(GetUserRequestV2) returns (GetUserResponse); } -rpc NewMethod(v2.Request) returns (...); ``` diff --git a/content/docs/cli/breaking-changes/rules/rpc-same-request-type.ru.mdx b/content/docs/cli/breaking-changes/rules/rpc-same-request-type.ru.mdx index 3d48781..e297abc 100644 --- a/content/docs/cli/breaking-changes/rules/rpc-same-request-type.ru.mdx +++ b/content/docs/cli/breaking-changes/rules/rpc-same-request-type.ru.mdx @@ -1,18 +1,19 @@ --- title: "Rpc Same Request Type" +description: "Проверяет, что каждый RPC-метод сохраняет то же полное имя типа сообщения запроса." --- -Категории: +- **ID правила:** `RPC_SAME_REQUEST_TYPE` +- **Профили:** `FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE` -- **WIRE+** - -Это правило проверяет, что RPC‑методы сохраняют прежний тип сообщения запроса (request message type). Изменение типа запроса RPC ломает совместимость по wire‑формату и сгенерированный код: клиенты ожидают конкретную структуру при вызове метода. +Это правило проверяет, что RPC-метод сохраняет прежнее полное имя типа сообщения запроса. Изменение типа запроса ломает сигнатуры методов в сгенерированном коде и может сделать запросы существующих клиентов несовместимыми с сервером. ## Примеры -### Плохой (Breaking) +### Неправильно **До:** + ```proto syntax = "proto3"; @@ -20,234 +21,66 @@ package myapi.v1; service UserService { rpc GetUser(GetUserRequest) returns (GetUserResponse); - rpc UpdateUser(UpdateUserRequest) returns (UpdateUserResponse); } message GetUserRequest { string user_id = 1; } - -message UpdateUserRequest { - string user_id = 1; - string name = 2; - string email = 3; -} ``` **После:** + ```proto syntax = "proto3"; package myapi.v1; service UserService { - rpc GetUser(GetUserRequestV2) returns (GetUserResponse); // Изменён тип запроса - rpc UpdateUser(UserUpdateRequest) returns (UpdateUserResponse); // Изменён тип запроса + rpc GetUser(GetUserRequestV2) returns (GetUserResponse); } -message GetUserRequestV2 { // Новый тип запроса +message GetUserRequestV2 { string id = 1; bool include_profile = 2; } - -message UserUpdateRequest { // Новый тип запроса - string id = 1; - UserProfile profile = 2; -} ``` **Ошибка:** -``` -user_service.proto:6:3: RPC "GetUser" on service "UserService" changed request type from "GetUserRequest" to "GetUserRequestV2". (BREAKING_CHECK) -user_service.proto:7:3: RPC "UpdateUser" on service "UserService" changed request type from "UpdateUserRequest" to "UserUpdateRequest". (BREAKING_CHECK) -``` - -### Дополнительные примеры - -**Смена типа из другого пакета:** -```proto -// Before -import "common/user.proto"; - -service UserService { - rpc CreateUser(CreateUserRequest) returns (CreateUserResponse); -} -// After - BREAKING CHANGE! -import "v2/user.proto"; - -service UserService { - rpc CreateUser(v2.CreateUserRequest) returns (CreateUserResponse); // Другой package -} +```text +user_service.proto:6:3: RPC "GetUser" request type changed from "myapi.v1.GetUserRequest" to "myapi.v1.GetUserRequestV2". (RPC_SAME_REQUEST_TYPE) ``` -### Хороший (Безопасный) +### Правильно + +Если изменение аддитивно, просто добавьте новые поля в существующее сообщение запроса: -**Вместо изменения типа — версионируйте RPC:** ```proto syntax = "proto3"; package myapi.v1; service UserService { - rpc GetUser(GetUserRequest) returns (GetUserResponse) { - option deprecated = true; - } - rpc GetUserV2(GetUserRequestV2) returns (GetUserResponse); // Новый метод - rpc UpdateUser(UpdateUserRequest) returns (UpdateUserResponse) { - option deprecated = true; - } - rpc UpdateUserV2(UserUpdateRequest) returns (UpdateUserResponse); // Новый метод + rpc GetUser(GetUserRequest) returns (GetUserResponse); } -// Старые сообщения — для обратной совместимости message GetUserRequest { string user_id = 1; -} - -// Новая версия сообщения -message GetUserRequestV2 { - string id = 1; bool include_profile = 2; } ``` -**Или создайте новую версию сервиса (package v2):** +Если требуется полностью новая структура запроса, добавьте новый RPC-метод и пометьте старый как `deprecated`: + ```proto syntax = "proto3"; -package myapi.v2; +package myapi.v1; service UserService { - rpc GetUser(GetUserRequest) returns (GetUserResponse); - rpc UpdateUser(UpdateUserRequest) returns (UpdateUserResponse); -} - -message GetUserRequest { - string id = 1; - bool include_profile = 2; -} -``` - -## Влияние - -- **Wire Format:** Старые запросы клиентов не десериализуются новым сервером -- **Generated Code:** Сигнатуры методов в stubs меняются — компиляция клиентов падает -- **gRPC Calls:** Требуется использовать другую структуру запроса -- **Runtime Errors:** Несоответствие типов вызывает ошибки выполнения - -## Реальный пример - -**Код клиента ломается:** -```go -// Before -client := myapi.NewUserServiceClient(conn) -resp, err := client.GetUser(ctx, &myapi.GetUserRequest{ - UserId: "user123", -}) - -// After (тип запроса изменён) -client := myapi.NewUserServiceClient(conn) -resp, err := client.GetUser(ctx, &myapi.GetUserRequest{ // ERROR: тип не найден - UserId: "user123", // ERROR: поле не найдено -}) - -// Новый корректный вызов: -resp, err := client.GetUser(ctx, &myapi.GetUserRequestV2{ - Id: "user123", - IncludeProfile: true, -}) -``` - -**Серверная реализация ломается:** -```go -// Before -func (s *server) GetUser(ctx context.Context, req *GetUserRequest) (*GetUserResponse, error) { - userID := req.UserId - // ... -} - -// After -func (s *server) GetUser(ctx context.Context, req *GetUserRequestV2) (*GetUserResponse, error) { - userID := req.Id - include := req.IncludeProfile - // ... новая логика -} -``` - -## Стратегия миграции - -1. **Добавьте новый RPC с новым типом запроса:** - ```proto - rpc GetUser(GetUserRequest) returns (GetUserResponse) { - option deprecated = true; - } - rpc GetUserV2(GetUserRequestV2) returns (GetUserResponse); - ``` - -2. **Поддерживайте оба метода на сервере:** - ```go - func (s *server) GetUser(ctx context.Context, req *GetUserRequest) (*GetUserResponse, error) { - return s.getUserInternal(req.UserId, false) - } - - func (s *server) GetUserV2(ctx context.Context, req *GetUserRequestV2) (*GetUserResponse, error) { - return s.getUserInternal(req.Id, req.IncludeProfile) - } - ``` - -3. **Мигрируйте клиентов на V2:** - ```go - resp, err := client.GetUserV2(ctx, &myapi.GetUserRequestV2{ - Id: userID, - IncludeProfile: true, - }) - ``` - -4. **Удалите старый метод в следующей major‑версии:** - ```proto - rpc GetUserV2(GetUserRequestV2) returns (GetUserResponse); - ``` - -## Типовые сценарии - -### Добавление обязательных полей -```proto -// ПЛОХО: меняем существующий запрос -message GetUserRequest { - string user_id = 1; - bool include_deleted = 2; // BREAKING -} - -// Хорошо: новая версия -message GetUserRequestV2 { - string user_id = 1; - bool include_deleted = 2; -} -``` - -### Реструктуризация данных запроса -```proto -// ПЛОХО: меняем структуру прямо -message UpdateUserRequest { - UserProfile profile = 1; // BREAKING -} - -// Хорошо: версионирование -rpc UpdateUser(UpdateUserRequest) returns (...) { - option deprecated = true; -} -rpc UpdateUserV2(UpdateUserRequestV2) returns (...); -``` - -### Миграция пакета -```proto -// ПЛОХО: заменяем тип на пакет v2 прямо -import "v2/messages.proto"; // BREAKING - -// Хорошо: добавляем новый RPC -rpc OldMethod(v1.Request) returns (...) { - option deprecated = true; + rpc GetUser(GetUserRequest) returns (GetUserResponse) { + option deprecated = true; + } + rpc GetUserV2(GetUserRequestV2) returns (GetUserResponse); } -rpc NewMethod(v2.Request) returns (...); ``` diff --git a/content/docs/cli/breaking-changes/rules/rpc-same-response-type.mdx b/content/docs/cli/breaking-changes/rules/rpc-same-response-type.mdx index f8bb3be..07f5320 100644 --- a/content/docs/cli/breaking-changes/rules/rpc-same-response-type.mdx +++ b/content/docs/cli/breaking-changes/rules/rpc-same-response-type.mdx @@ -1,18 +1,19 @@ --- title: "Rpc Same Response Type" +description: "Checks that every RPC method keeps the same fully qualified response message type." --- -Categories: +- **Rule ID:** `RPC_SAME_RESPONSE_TYPE` +- **Profiles:** `FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE` -- **WIRE+** - -This rule checks that RPC methods maintain the same response message type. Changing an RPC's response type breaks both wire format compatibility and generated code, as clients expect specific message structures when receiving responses from the method. +This rule checks that an RPC method keeps the same fully qualified response message type. Changing the response type breaks generated client/server method signatures and can break deserialization for existing clients. ## Examples ### Bad **Before:** + ```proto syntax = "proto3"; @@ -20,304 +21,68 @@ package myapi.v1; service UserService { rpc GetUser(GetUserRequest) returns (GetUserResponse); - rpc UpdateUser(UpdateUserRequest) returns (UpdateUserResponse); } message GetUserResponse { string user_id = 1; string name = 2; - string email = 3; -} - -message UpdateUserResponse { - bool success = 1; - string message = 2; } ``` **After:** + ```proto syntax = "proto3"; package myapi.v1; service UserService { - rpc GetUser(GetUserRequest) returns (GetUserResponseV2); // Changed response type - rpc UpdateUser(UpdateUserRequest) returns (UserUpdateResponse); // Changed response type + rpc GetUser(GetUserRequest) returns (GetUserResponseV2); } -message GetUserResponseV2 { // Different message type +message GetUserResponseV2 { string id = 1; - UserProfile profile = 2; - repeated string permissions = 3; -} - -message UserUpdateResponse { // Different message type - UpdateResult result = 1; - UserProfile updated_profile = 2; + string full_name = 2; } ``` **Error:** -``` -user_service.proto:6:3: RPC "GetUser" on service "UserService" changed response type from "GetUserResponse" to "GetUserResponseV2". (BREAKING_CHECK) -user_service.proto:7:3: RPC "UpdateUser" on service "UserService" changed response type from "UpdateUserResponse" to "UserUpdateResponse". (BREAKING_CHECK) -``` - -### More Examples -**Cross-package type changes:** - -```proto -// Before -import "common/responses.proto"; - -service UserService { - rpc CreateUser(CreateUserRequest) returns (CreateUserResponse); -} - -// After - BREAKING CHANGE! -import "v2/responses.proto"; - -service UserService { - rpc CreateUser(CreateUserRequest) returns (v2.CreateUserResponse); // Different package -} +```text +user_service.proto:6:3: RPC "GetUser" response type changed from "myapi.v1.GetUserResponse" to "myapi.v1.GetUserResponseV2". (RPC_SAME_RESPONSE_TYPE) ``` ### Good -**Instead of changing response type, version the RPC:** +Extend the existing response message with new fields when the change is additive: + ```proto syntax = "proto3"; package myapi.v1; service UserService { - rpc GetUser(GetUserRequest) returns (GetUserResponse) { - option deprecated = true; - } - rpc GetUserV2(GetUserRequest) returns (GetUserResponseV2); // New RPC method - rpc UpdateUser(UpdateUserRequest) returns (UpdateUserResponse) { - option deprecated = true; - } - rpc UpdateUserV2(UpdateUserRequest) returns (UserUpdateResponse); // New RPC method + rpc GetUser(GetUserRequest) returns (GetUserResponse); } -// Keep old messages for backward compatibility message GetUserResponse { string user_id = 1; string name = 2; string email = 3; } - -// Add new messages for enhanced functionality -message GetUserResponseV2 { - string id = 1; - UserProfile profile = 2; - repeated string permissions = 3; -} ``` -**Or create a new service version:** +Or add a new RPC method alongside the deprecated original when a completely new response message is required: + ```proto syntax = "proto3"; -package myapi.v2; // New package version +package myapi.v1; service UserService { - rpc GetUser(GetUserRequest) returns (GetUserResponse); // Clean interface in v2 - rpc UpdateUser(UpdateUserRequest) returns (UpdateUserResponse); -} - -message GetUserResponse { - string id = 1; // Improved field names - UserProfile profile = 2; - repeated string permissions = 3; -} -``` - -## Impact - -- **Wire Format:** Server responses cannot be deserialized by existing clients -- **Generated Code:** Client stubs expect different response message types, breaking compilation -- **gRPC Calls:** Method signatures change in generated client code -- **Runtime Errors:** Type mismatches cause RPC response handling failures - -## Real-World Example - -**Client code breaks:** -```go -// Before - this code works -client := myapi.NewUserServiceClient(conn) -resp, err := client.GetUser(ctx, &myapi.GetUserRequest{ - UserId: "user123", -}) -if err != nil { - return err -} - -// Access response fields -userID := resp.UserId // This field exists -name := resp.Name // This field exists - -// After response type change - compilation fails -client := myapi.NewUserServiceClient(conn) -resp, err := client.GetUser(ctx, &myapi.GetUserRequest{ - UserId: "user123", -}) -if err != nil { - return err -} - -// Access response fields - COMPILATION ERRORS -userID := resp.UserId // ERROR: field not found -name := resp.Name // ERROR: field not found - -// Must use new fields: -userID := resp.Id // Different field name -profile := resp.Profile // New structure -permissions := resp.Permissions // New field -``` - -**Server implementation breaks:** -```go -// Before - server returns GetUserResponse -func (s *server) GetUser(ctx context.Context, req *GetUserRequest) (*GetUserResponse, error) { - return &GetUserResponse{ - UserId: "user123", - Name: "John Doe", - Email: "john@example.com", - }, nil -} - -// After - server must return GetUserResponseV2 -func (s *server) GetUser(ctx context.Context, req *GetUserRequest) (*GetUserResponseV2, error) { - return &GetUserResponseV2{ - Id: "user123", // Different field name - Profile: &UserProfile{ // New structure required - Name: "John Doe", - Email: "john@example.com", - }, - Permissions: []string{"read"}, // New field to populate - }, nil -} -``` - -## Migration Strategy - -1. **Add new RPC method** with improved response type: - ```proto - rpc GetUser(GetUserRequest) returns (GetUserResponse) { - option deprecated = true; - } - rpc GetUserV2(GetUserRequest) returns (GetUserResponseV2); - ``` - -2. **Implement both methods** on server during transition: - ```go - func (s *server) GetUser(ctx context.Context, req *GetUserRequest) (*GetUserResponse, error) { - // Legacy implementation - user := s.getUserInternal(req.UserId) - return &GetUserResponse{ - UserId: user.ID, - Name: user.Name, - Email: user.Email, - }, nil - } - - func (s *server) GetUserV2(ctx context.Context, req *GetUserRequest) (*GetUserResponseV2, error) { - // New implementation with enhanced response - user := s.getUserInternal(req.UserId) - return &GetUserResponseV2{ - Id: user.ID, - Profile: &UserProfile{ - Name: user.Name, - Email: user.Email, - }, - Permissions: user.Permissions, - }, nil - } - ``` - -3. **Migrate clients** to use new RPC method: - ```go - // Update client calls to use V2 - resp, err := client.GetUserV2(ctx, &myapi.GetUserRequest{ - UserId: userID, - }) - if err != nil { - return err - } - - // Handle new response structure - profile := resp.Profile - permissions := resp.Permissions - ``` - -4. **Remove old RPC** in next major version: - ```proto - // Only keep new version - rpc GetUserV2(GetUserRequest) returns (GetUserResponseV2); - ``` - -## Common Scenarios - -### Adding Fields to Response -```proto -// Instead of modifying existing response -message GetUserResponse { - string user_id = 1; - string name = 2; - UserProfile profile = 3; // BREAKING: new required field -} - -// Add new RPC method -message GetUserResponseV2 { - string user_id = 1; - string name = 2; - UserProfile profile = 3; // Safe in new method -} -``` - -### Restructuring Response Data -```proto -// Instead of changing field structure -message UpdateUserResponse { - UserDetails details = 1; // BREAKING: was individual fields -} - -// Version the RPC -rpc UpdateUser(UpdateUserRequest) returns (UpdateUserResponse) { - option deprecated = true; -} -rpc UpdateUserV2(UpdateUserRequest) returns (UpdateUserResponseV2); -``` - -### Error Handling Changes -```proto -// Instead of changing error structure -message CreateUserResponse { - ErrorDetails error = 1; // BREAKING: different error format -} - -// Keep old RPC, add new one -rpc CreateUser(CreateUserRequest) returns (CreateUserResponse) { - option deprecated = true; -} -rpc CreateUserV2(CreateUserRequest) returns (CreateUserResponseV2); -``` - -### Response Format Migration -```proto -// Instead of changing from simple to complex response -message GetUserResponse { - // BREAKING: changed from simple fields to nested structure - UserData data = 1; -} - -// Provide both formats during transition -rpc GetUser(GetUserRequest) returns (GetUserResponse) { - option deprecated = true; + rpc GetUser(GetUserRequest) returns (GetUserResponse) { + option deprecated = true; + } + rpc GetUserV2(GetUserRequest) returns (GetUserResponseV2); } -rpc GetUserDetailed(GetUserRequest) returns (GetUserDetailedResponse); ``` diff --git a/content/docs/cli/breaking-changes/rules/rpc-same-response-type.ru.mdx b/content/docs/cli/breaking-changes/rules/rpc-same-response-type.ru.mdx index ae97e13..5400a6a 100644 --- a/content/docs/cli/breaking-changes/rules/rpc-same-response-type.ru.mdx +++ b/content/docs/cli/breaking-changes/rules/rpc-same-response-type.ru.mdx @@ -1,18 +1,19 @@ --- title: "Rpc Same Response Type" +description: "Проверяет, что каждый RPC-метод сохраняет то же полное имя типа сообщения ответа." --- -Категории: +- **ID правила:** `RPC_SAME_RESPONSE_TYPE` +- **Профили:** `FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE` -- **WIRE+** - -Это правило проверяет, что RPC‑методы сохраняют тот же тип ответного сообщения (response message type). Изменение типа ответа RPC ломает совместимость по wire‑формату и сгенерированный код: клиенты ожидают конкретную структуру при получении ответа. +Это правило проверяет, что RPC-метод сохраняет прежнее полное имя типа сообщения ответа. Изменение типа ответа ломает сигнатуры методов в сгенерированном коде и может нарушить десериализацию ответов существующими клиентами. ## Примеры -### Плохой (Breaking) +### Неправильно **До:** + ```proto syntax = "proto3"; @@ -20,295 +21,68 @@ package myapi.v1; service UserService { rpc GetUser(GetUserRequest) returns (GetUserResponse); - rpc UpdateUser(UpdateUserRequest) returns (UpdateUserResponse); } message GetUserResponse { string user_id = 1; string name = 2; - string email = 3; -} - -message UpdateUserResponse { - bool success = 1; - string message = 2; } ``` **После:** + ```proto syntax = "proto3"; package myapi.v1; service UserService { - rpc GetUser(GetUserRequest) returns (GetUserResponseV2); // Изменён тип ответа - rpc UpdateUser(UpdateUserRequest) returns (UserUpdateResponse); // Изменён тип ответа + rpc GetUser(GetUserRequest) returns (GetUserResponseV2); } -message GetUserResponseV2 { // Другой тип сообщения +message GetUserResponseV2 { string id = 1; - UserProfile profile = 2; - repeated string permissions = 3; -} - -message UserUpdateResponse { // Другой тип сообщения - UpdateResult result = 1; - UserProfile updated_profile = 2; + string full_name = 2; } ``` **Ошибка:** -``` -user_service.proto:6:3: RPC "GetUser" on service "UserService" changed response type from "GetUserResponse" to "GetUserResponseV2". (BREAKING_CHECK) -user_service.proto:7:3: RPC "UpdateUser" on service "UserService" changed response type from "UpdateUserResponse" to "UserUpdateResponse". (BREAKING_CHECK) -``` - -### Дополнительные примеры -**Смена типа из другого пакета:** -```proto -// Before -import "common/responses.proto"; - -service UserService { - rpc CreateUser(CreateUserRequest) returns (CreateUserResponse); -} - -// After - BREAKING CHANGE! -import "v2/responses.proto"; - -service UserService { - rpc CreateUser(CreateUserRequest) returns (v2.CreateUserResponse); // Другой package -} +```text +user_service.proto:6:3: RPC "GetUser" response type changed from "myapi.v1.GetUserResponse" to "myapi.v1.GetUserResponseV2". (RPC_SAME_RESPONSE_TYPE) ``` -### Хороший (Безопасный) +### Правильно + +Если изменение аддитивно, добавьте новые поля в существующее сообщение ответа: -**Вместо изменения типа — версионируйте RPC:** ```proto syntax = "proto3"; package myapi.v1; service UserService { - rpc GetUser(GetUserRequest) returns (GetUserResponse) { - option deprecated = true; - } - rpc GetUserV2(GetUserRequest) returns (GetUserResponseV2); // Новый метод - rpc UpdateUser(UpdateUserRequest) returns (UpdateUserResponse) { - option deprecated = true; - } - rpc UpdateUserV2(UpdateUserRequest) returns (UserUpdateResponse); // Новый метод + rpc GetUser(GetUserRequest) returns (GetUserResponse); } -// Старые сообщения сохраняем для обратной совместимости message GetUserResponse { string user_id = 1; string name = 2; string email = 3; } - -// Новая расширенная версия -message GetUserResponseV2 { - string id = 1; - UserProfile profile = 2; - repeated string permissions = 3; -} ``` -**Или создайте новую версию сервиса (package v2):** +Если нужна совершенно новая структура ответа, добавьте новый RPC-метод и пометьте старый как `deprecated`: + ```proto syntax = "proto3"; -package myapi.v2; +package myapi.v1; service UserService { - rpc GetUser(GetUserRequest) returns (GetUserResponse); - rpc UpdateUser(UpdateUserRequest) returns (UpdateUserResponse); -} - -message GetUserResponse { - string id = 1; - UserProfile profile = 2; - repeated string permissions = 3; -} -``` - -## Влияние - -- **Wire Format:** Ответы сервера не десериализуются у старых клиентов -- **Generated Code:** Сигнатуры ожидают старый тип — компиляция падает -- **gRPC Calls:** Меняются типы в сгенерированных stub'ах -- **Runtime Errors:** Несоответствие типов ломает обработку ответа - -## Реальный пример - -**Код клиента ломается:** -```go -// Before -client := myapi.NewUserServiceClient(conn) -resp, err := client.GetUser(ctx, &myapi.GetUserRequest{ - UserId: "user123", -}) -if err != nil { - return err -} - -userID := resp.UserId -name := resp.Name - -// After (тип ответа изменён) -client := myapi.NewUserServiceClient(conn) -resp, err := client.GetUser(ctx, &myapi.GetUserRequest{ - UserId: "user123", -}) -if err != nil { - return err -} - -// Ошибки компиляции: -userID := resp.UserId // ERROR -name := resp.Name // ERROR - -// Новый способ: -userID := resp.Id -profile := resp.Profile -permissions := resp.Permissions -``` - -**Имплементация сервера также должна быть переписана:** -```go -// Before -func (s *server) GetUser(ctx context.Context, req *GetUserRequest) (*GetUserResponse, error) { - return &GetUserResponse{ - UserId: "user123", - Name: "John Doe", - Email: "john@example.com", - }, nil -} - -// After -func (s *server) GetUser(ctx context.Context, req *GetUserRequest) (*GetUserResponseV2, error) { - return &GetUserResponseV2{ - Id: "user123", - Profile: &UserProfile{ - Name: "John Doe", - Email: "john@example.com", - }, - Permissions: []string{"read"}, - }, nil -} -``` - -## Стратегия миграции - -1. **Добавьте новый RPC c новым типом ответа:** - ```proto - rpc GetUser(GetUserRequest) returns (GetUserResponse) { - option deprecated = true; - } - rpc GetUserV2(GetUserRequest) returns (GetUserResponseV2); - ``` - -2. **Поддерживайте оба на сервере:** - ```go - func (s *server) GetUser(ctx context.Context, req *GetUserRequest) (*GetUserResponse, error) { - user := s.getUserInternal(req.UserId) - return &GetUserResponse{ - UserId: user.ID, - Name: user.Name, - Email: user.Email, - }, nil - } - - func (s *server) GetUserV2(ctx context.Context, req *GetUserRequest) (*GetUserResponseV2, error) { - user := s.getUserInternal(req.UserId) - return &GetUserResponseV2{ - Id: user.ID, - Profile: &UserProfile{ - Name: user.Name, - Email: user.Email, - }, - Permissions: user.Permissions, - }, nil - } - ``` - -3. **Мигрируйте клиентов на новый RPC:** - ```go - resp, err := client.GetUserV2(ctx, &myapi.GetUserRequest{ - UserId: userID, - }) - if err != nil { - return err - } - profile := resp.Profile - permissions := resp.Permissions - ``` - -4. **Удалите старый RPC** в следующей major‑версии: - ```proto - rpc GetUserV2(GetUserRequest) returns (GetUserResponseV2); - ``` - -## Типовые сценарии - -### Добавление новых обязательных полей -```proto -// ПЛОХО: меняем существующий тип -message GetUserResponse { - string user_id = 1; - string name = 2; - UserProfile profile = 3; // BREAKING -} - -// Хорошо: новая версия -message GetUserResponseV2 { - string user_id = 1; - string name = 2; - UserProfile profile = 3; -} -``` - -### Реструктуризация ответа -```proto -// ПЛОХО: меняем структуру прямо -message UpdateUserResponse { - UserDetails details = 1; // BREAKING -} - -// Хорошо: версионирование -rpc UpdateUser(UpdateUserRequest) returns (UpdateUserResponse) { - option deprecated = true; -} -rpc UpdateUserV2(UpdateUserRequest) returns (UpdateUserResponseV2); -``` - -### Изменение формата ошибок -```proto -// ПЛОХО: меняем формат напрямую -message CreateUserResponse { - ErrorDetails error = 1; // BREAKING -} - -// Хорошо: новая версия -rpc CreateUser(CreateUserRequest) returns (CreateUserResponse) { - option deprecated = true; -} -rpc CreateUserV2(CreateUserRequest) returns (CreateUserResponseV2); -``` - -### Миграция формата -```proto -// ПЛОХО: перевод простой структуры в сложную -message GetUserResponse { - UserData data = 1; // BREAKING -} - -// Хорошо: предоставляем обе версии -rpc GetUser(GetUserRequest) returns (GetUserResponse) { - option deprecated = true; + rpc GetUser(GetUserRequest) returns (GetUserResponse) { + option deprecated = true; + } + rpc GetUserV2(GetUserRequest) returns (GetUserResponseV2); } -rpc GetUserDetailed(GetUserRequest) returns (GetUserDetailedResponse); ``` diff --git a/content/docs/cli/breaking-changes/rules/rpc-same-server-streaming.mdx b/content/docs/cli/breaking-changes/rules/rpc-same-server-streaming.mdx new file mode 100644 index 0000000..96a9528 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/rpc-same-server-streaming.mdx @@ -0,0 +1,58 @@ +--- +title: "Rpc Same Server Streaming" +description: "Checks that RPC methods do not change server streaming behavior." +--- + +- **Rule ID:** `RPC_SAME_SERVER_STREAMING` +- **Profiles:** `FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE` + +This rule checks that an RPC method does not toggle `stream` on its response type. Switching between unary and server-streaming breaks both live RPC framing and generated client/server interfaces across all four profiles (`FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE`). + +## Examples + +### Bad + +**Before:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +service EventService { + rpc WatchEvents(WatchEventsRequest) returns (WatchEventsResponse); +} +``` + +**After:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +service EventService { + rpc WatchEvents(WatchEventsRequest) returns (stream WatchEventsResponse); +} +``` + +**Error:** + +```text +event.proto:6:3: RPC "WatchEvents" changed server streaming behavior. (RPC_SAME_SERVER_STREAMING) +``` + +### Good + +Add a new server-streaming RPC method instead of altering an existing unary RPC: + +```proto +syntax = "proto3"; + +package myapi.v1; + +service EventService { + rpc WatchEvents(WatchEventsRequest) returns (WatchEventsResponse); + rpc StreamEvents(StreamEventsRequest) returns (stream StreamEventsResponse); +} +``` diff --git a/content/docs/cli/breaking-changes/rules/rpc-same-server-streaming.ru.mdx b/content/docs/cli/breaking-changes/rules/rpc-same-server-streaming.ru.mdx new file mode 100644 index 0000000..5fb1a91 --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/rpc-same-server-streaming.ru.mdx @@ -0,0 +1,58 @@ +--- +title: "Rpc Same Server Streaming" +description: "Проверяет, что RPC-методы не меняют режим серверного стриминга (server streaming)." +--- + +- **ID правила:** `RPC_SAME_SERVER_STREAMING` +- **Профили:** `FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE` + +Это правило проверяет, что у RPC-метода не добавляется и не убирается `stream` в типе ответа. Переключение между unary и server-streaming ломает сетевой протокол и сгенерированные интерфейсы во всех четырёх профилях (`FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE`). + +## Примеры + +### Неправильно + +**До:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +service EventService { + rpc WatchEvents(WatchEventsRequest) returns (WatchEventsResponse); +} +``` + +**После:** + +```proto +syntax = "proto3"; + +package myapi.v1; + +service EventService { + rpc WatchEvents(WatchEventsRequest) returns (stream WatchEventsResponse); +} +``` + +**Ошибка:** + +```text +event.proto:6:3: RPC "WatchEvents" changed server streaming behavior. (RPC_SAME_SERVER_STREAMING) +``` + +### Правильно + +Добавьте новый RPC с серверным стримингом вместо изменения существующего unary-метода: + +```proto +syntax = "proto3"; + +package myapi.v1; + +service EventService { + rpc WatchEvents(WatchEventsRequest) returns (WatchEventsResponse); + rpc StreamEvents(StreamEventsRequest) returns (stream StreamEventsResponse); +} +``` diff --git a/content/docs/cli/breaking-changes/rules/service-moved.mdx b/content/docs/cli/breaking-changes/rules/service-moved.mdx new file mode 100644 index 0000000..a4aa86c --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/service-moved.mdx @@ -0,0 +1,60 @@ +--- +title: "Service Moved" +description: "Checks that services are not moved to a different .proto file in the FILE profile." +--- + +- **Rule ID:** `SERVICE_MOVED` +- **Profiles:** `FILE` + +In the `FILE` profile, moving a `service` to a different `.proto` file (even within the same protobuf package) breaks generated file-level service stubs and language imports. Use the `PACKAGE` profile if moving declarations between files in the same package is allowed. + +## Examples + +### Bad + +**Before:** + +```proto +// File: myapi/v1/user.proto +syntax = "proto3"; + +package myapi.v1; + +service UserService { + rpc GetUser(GetUserRequest) returns (GetUserResponse); +} +``` + +**After:** + +```proto +// File: myapi/v1/user_service.proto +syntax = "proto3"; + +package myapi.v1; + +service UserService { + rpc GetUser(GetUserRequest) returns (GetUserResponse); +} +``` + +**Error:** + +```text +myapi/v1/user.proto:6:1: Service "myapi.v1.UserService" was moved from "myapi/v1/user.proto" to "myapi/v1/user_service.proto". (SERVICE_MOVED) +``` + +### Good + +Keep the service in its original `.proto` file when checking with `FILE`: + +```proto +// File: myapi/v1/user.proto +syntax = "proto3"; + +package myapi.v1; + +service UserService { + rpc GetUser(GetUserRequest) returns (GetUserResponse); +} +``` diff --git a/content/docs/cli/breaking-changes/rules/service-moved.ru.mdx b/content/docs/cli/breaking-changes/rules/service-moved.ru.mdx new file mode 100644 index 0000000..7febe9f --- /dev/null +++ b/content/docs/cli/breaking-changes/rules/service-moved.ru.mdx @@ -0,0 +1,60 @@ +--- +title: "Service Moved" +description: "Проверяет, что сервисы не переносятся в другой .proto-файл в профиле FILE." +--- + +- **ID правила:** `SERVICE_MOVED` +- **Профили:** `FILE` + +В профиле `FILE` перенос `service` в другой `.proto`-файл (даже внутри того же пакета) ломает сгенерированные файловые стабы сервисов и импорты. Если перенос объявлений внутри одного пакета допустим, используйте профиль `PACKAGE`. + +## Примеры + +### Неправильно + +**До:** + +```proto +// File: myapi/v1/user.proto +syntax = "proto3"; + +package myapi.v1; + +service UserService { + rpc GetUser(GetUserRequest) returns (GetUserResponse); +} +``` + +**После:** + +```proto +// File: myapi/v1/user_service.proto +syntax = "proto3"; + +package myapi.v1; + +service UserService { + rpc GetUser(GetUserRequest) returns (GetUserResponse); +} +``` + +**Ошибка:** + +```text +myapi/v1/user.proto:6:1: Service "myapi.v1.UserService" was moved from "myapi/v1/user.proto" to "myapi/v1/user_service.proto". (SERVICE_MOVED) +``` + +### Правильно + +Оставьте сервис в исходном `.proto`-файле при проверке профилем `FILE`: + +```proto +// File: myapi/v1/user.proto +syntax = "proto3"; + +package myapi.v1; + +service UserService { + rpc GetUser(GetUserRequest) returns (GetUserResponse); +} +``` diff --git a/content/docs/cli/breaking-changes/rules/service-no-delete.mdx b/content/docs/cli/breaking-changes/rules/service-no-delete.mdx index 0adf4d8..629626c 100644 --- a/content/docs/cli/breaking-changes/rules/service-no-delete.mdx +++ b/content/docs/cli/breaking-changes/rules/service-no-delete.mdx @@ -1,18 +1,19 @@ --- title: "Service No Delete" +description: "Checks that no service declarations are deleted." --- -Categories: +- **Rule ID:** `SERVICE_NO_DELETE` +- **Profiles:** `FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE` -- **WIRE+** - -This rule checks that no services are deleted from proto files. Deleting a service breaks both generated code and client applications that depend on the service. +This rule checks that no `service` declarations are deleted. Deleting a service removes generated client/server interfaces and breaks all RPC endpoints exposed under that service name. ## Examples ### Bad **Before:** + ```proto syntax = "proto3"; @@ -20,7 +21,6 @@ package myapi.v1; service UserService { rpc GetUser(GetUserRequest) returns (GetUserResponse); - rpc CreateUser(CreateUserRequest) returns (CreateUserResponse); } service OrderService { @@ -29,6 +29,7 @@ service OrderService { ``` **After:** + ```proto syntax = "proto3"; @@ -36,20 +37,21 @@ package myapi.v1; service UserService { rpc GetUser(GetUserRequest) returns (GetUserResponse); - rpc CreateUser(CreateUserRequest) returns (CreateUserResponse); } -// OrderService was deleted - BREAKING CHANGE! +// OrderService was deleted ``` **Error:** -``` -services.proto:8:1: Previously present service "OrderService" was deleted from file. (BREAKING_CHECK) + +```text +services.proto:9:1: Service "myapi.v1.OrderService" was deleted. (SERVICE_NO_DELETE) ``` ### Good -**Instead of deleting, deprecate the service:** +Mark the service deprecated instead of deleting it: + ```proto syntax = "proto3"; @@ -57,7 +59,6 @@ package myapi.v1; service UserService { rpc GetUser(GetUserRequest) returns (GetUserResponse); - rpc CreateUser(CreateUserRequest) returns (CreateUserResponse); } service OrderService { @@ -68,22 +69,8 @@ service OrderService { } ``` -## Impact - -- **Generated Code:** Service classes/interfaces are removed, breaking client compilation -- **Client Applications:** Existing client code fails to compile -- **Runtime:** gRPC clients lose service definition - ## Migration Strategy -1. **Deprecate first:** - ```proto - service OldService { - option deprecated = true; - // ... methods - } - ``` - -2. **Notify clients** about deprecation timeline - -3. **Remove after migration period** in a new major version +1. Mark the service with `option deprecated = true;` and communicate the sunset schedule. +2. Keep the service registered until active clients migrate. +3. Remove the service only in a new major package version (for example, `myapi.v2`). diff --git a/content/docs/cli/breaking-changes/rules/service-no-delete.ru.mdx b/content/docs/cli/breaking-changes/rules/service-no-delete.ru.mdx index ae9cb4e..20036a7 100644 --- a/content/docs/cli/breaking-changes/rules/service-no-delete.ru.mdx +++ b/content/docs/cli/breaking-changes/rules/service-no-delete.ru.mdx @@ -1,18 +1,19 @@ --- title: "Service No Delete" +description: "Проверяет, что ни одно объявление сервиса не было удалено." --- -Категории: +- **ID правила:** `SERVICE_NO_DELETE` +- **Профили:** `FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE` -- **WIRE+** - -Данное правило проверяет, что ни один service не был удалён из proto‑файлов. Удаление service ломает сгенерированный код и клиентские приложения, которые на него опираются. +Это правило проверяет, что ни одно объявление `service` не было удалено. Удаление сервиса убирает сгенерированные клиентские и серверные интерфейсы и ломает все RPC-эндпоинты этого сервиса. ## Примеры -### Плохой (Breaking) +### Неправильно **До:** + ```proto syntax = "proto3"; @@ -20,7 +21,6 @@ package myapi.v1; service UserService { rpc GetUser(GetUserRequest) returns (GetUserResponse); - rpc CreateUser(CreateUserRequest) returns (CreateUserResponse); } service OrderService { @@ -29,6 +29,7 @@ service OrderService { ``` **После:** + ```proto syntax = "proto3"; @@ -36,20 +37,21 @@ package myapi.v1; service UserService { rpc GetUser(GetUserRequest) returns (GetUserResponse); - rpc CreateUser(CreateUserRequest) returns (CreateUserResponse); } -// OrderService удалён — BREAKING CHANGE! +// Сервис OrderService удалён ``` **Ошибка:** -``` -services.proto:8:1: Previously present service "OrderService" was deleted from file. (BREAKING_CHECK) + +```text +services.proto:9:1: Service "myapi.v1.OrderService" was deleted. (SERVICE_NO_DELETE) ``` -### Хороший (Безопасный) +### Правильно + +Вместо удаления пометьте сервис как устаревший: -**Вместо удаления — отметьте service как deprecated:** ```proto syntax = "proto3"; @@ -57,7 +59,6 @@ package myapi.v1; service UserService { rpc GetUser(GetUserRequest) returns (GetUserResponse); - rpc CreateUser(CreateUserRequest) returns (CreateUserResponse); } service OrderService { @@ -68,22 +69,8 @@ service OrderService { } ``` -## Влияние - -- **Generated Code:** Классы / интерфейсы сервиса исчезают — клиенты не компилируются -- **Client Applications:** Существующие вызовы к удалённому сервису падают на этапе сборки -- **Runtime:** gRPC клиенты теряют определение метода/сервиса - ## Стратегия миграции -1. **Сначала деприкация:** - ```proto - service OldService { - option deprecated = true; - // ... methods - } - ``` - -2. **Уведомите клиентов** о сроках вывода из эксплуатации - -3. **Удалите после периода миграции** в следующей major‑версии +1. Пометьте сервис опцией `option deprecated = true;` и сообщите клиентам о сроках вывода из эксплуатации. +2. Сохраняйте сервис активным до завершения миграции клиентов. +3. Удалите сервис только в новой мажорной версии пакета (например, `myapi.v2`). diff --git a/content/docs/cli/linter/index.mdx b/content/docs/cli/linter/index.mdx index 9879f2c..b56a693 100644 --- a/content/docs/cli/linter/index.mdx +++ b/content/docs/cli/linter/index.mdx @@ -3,9 +3,9 @@ title: "Linter" description: "Configure and run the EasyP v1 protobuf linter." --- -easyp lint checks .proto files using the v1 policy in easyp.yaml, reporting source locations and rule names. +`easyp lint` checks `.proto` files using the v1 policy in `easyp.yaml`, reporting source locations and rule names. -~~~yaml +```yaml version: v1 linters: default: STANDARD @@ -20,29 +20,65 @@ issues: - path: legacy/**/*.proto linters: [COMMENT_FIELD] - path: generated -~~~ +``` -Presets are MINIMAL, BASIC, STANDARD, and COMMENTS. Enable/disable and exclusion lists accept implemented rules and groups. Repetition is idempotent; disabling wins. Unknown names are errors, including when repeated in the opposite list. PACKAGE_NO_IMPORT_CYCLE is reserved and cannot be selected. Supported settings are ENUM_ZERO_VALUE_SUFFIX.suffix and SERVICE_SUFFIX.suffix. linters.extends loads a local or locked-module base before local adjustments; see [shared policies](/docs/guides/organization-lint-style). +## Presets and rule groups -~~~bash +EasyP ships **44 lint rules** organized into **5 selectable rule groups**, which are combined into **4 `linters.default` presets**: + +### `linters.default` presets + +| Preset | Included groups | Rule count | Notes | +| --- | --- | ---: | --- | +| `MINIMAL` | `MINIMAL` | 5 | Package and directory layout, import cycles | +| `BASIC` | `MINIMAL`, `BASIC` | 27 | Core style, syntax, naming, and language package consistency | +| `STANDARD` | `MINIMAL`, `BASIC`, `DEFAULT` | 35 | Default when `linters.default` is omitted | +| `COMMENTS` | `MINIMAL`, `BASIC`, `DEFAULT`, `COMMENTS` | 42 | Adds required documentation comments on declarations | + +### Selectable rule groups + +| Group | Rule count | Purpose | +| --- | ---: | --- | +| `MINIMAL` | 5 | `DIRECTORY_SAME_PACKAGE`, `PACKAGE_DEFINED`, `PACKAGE_DIRECTORY_MATCH`, `PACKAGE_SAME_DIRECTORY`, `PACKAGE_NO_IMPORT_CYCLE` | +| `BASIC` | 22 | Naming conventions, import hygiene, `SYNTAX_SPECIFIED`, `FIELD_NOT_REQUIRED`, and per-language package options | +| `DEFAULT` | 8 | File naming, enum prefix/suffix, package version suffix, service suffix, and standard RPC message names | +| `COMMENTS` | 7 | Leading comments on enums, enum values, fields, messages, oneofs, RPCs, and services | +| `UNARY_RPC` | 2 | Opt-in via `linters.enable`: `RPC_NO_CLIENT_STREAMING` and `RPC_NO_SERVER_STREAMING` | + +`linters.enable`, `linters.disable`, and `issues.exclude-rules[].linters` accept both individual rule IDs and group keys (`MINIMAL`, `BASIC`, `DEFAULT`, `COMMENTS`, `UNARY_RPC`). Repetition is idempotent; disabling wins over enabling. Unknown names are rejected, even when repeated in both lists. + +Supported rule settings under `linters-settings` are `ENUM_ZERO_VALUE_SUFFIX.suffix` (default `NONE`) and `SERVICE_SUFFIX.suffix` (default `Service`). `linters.extends` loads a local or locked-module base before local adjustments; see [shared policies](/docs/guides/organization-lint-style). + +## Running the linter + +```bash easyp lint --path proto easyp --format json lint --path proto easyp lint --root ./contracts --path proto -~~~ +easyp lint --config ./policies/easyp.yaml --path proto +easyp lint --frozen --path proto +``` + +- `--path` (`-p`) selects a file or directory relative to the scan root (defaults to `.`). +- `--root` (`-r`) overrides the scan root, which otherwise defaults to the selected policy's directory. +- `--config` selects an explicit policy file instead of discovering `easyp.yaml`. Policy discovery searches upward within the workspace; without an ancestor policy, one unambiguous outermost descendant policy can be selected, while multiple independent policies require `--config`. An explicit `--config` takes precedence. Each nested policy section replaces the nearest inherited section as a whole. +- `--frozen` requires an existing `protobuf.mod` and verified `protobuf.lock` without resolving dependencies, writing files, or allowing local `replace` directives. ---path is relative to the scan root, which defaults to the selected policy's directory; --root changes it. Policy lookup searches upward within the workspace. Without an ancestor policy, one unambiguous outermost descendant policy can be selected; multiple independent policies require --cfg. An explicit config takes precedence. Each nested policy section replaces the nearest inherited section as a whole. +The linter resolves imports using the nearest module's source roots and local or locked dependencies. A policy can also run without `protobuf.mod` (unless `--frozen` is passed). Vendored sources and hidden storage/Git directories are excluded from lint target discovery, including explicit vendor paths; dependency sources remain available for imports. -The linter resolves imports using the nearest module's source roots and local or locked dependencies. A policy can also run without protobuf.mod. Vendored sources and hidden storage/Git directories are excluded from lint target discovery, including explicit vendor paths; dependency sources remain available for imports. + +Before running lint rules, EasyP compiles and links the target files. If any target file has syntax, import, or compilation errors, EasyP reports those compiler diagnostics and skips lint rule execution until the files compile cleanly. + ## Exclude paths -issues.exclude-rules.path is relative to the policy file supplying the effective issues section, even when that section is inherited. Patterns support *, ?, [], and complete ** segments. Single-segment wildcards do not cross /; ** matches zero or more segments. Literal directories include their subtree. A literal .proto path matches that file only. Absolute paths, backslashes, traversal, and malformed patterns are rejected. +`issues.exclude-rules.path` is relative to the policy file supplying the effective `issues` section, even when that section is inherited. Patterns support `*`, `?`, `[]`, and complete `**` segments. Single-segment wildcards do not cross `/`; `**` matches zero or more segments. Literal directories include their subtree. A literal `.proto` path matches that file only. Absolute paths, backslashes, traversal, and malformed patterns are rejected. -A pathless rule applies to all files covered by that issues section. An empty or omitted linters list excludes matching files entirely. An empty rule {} explicitly ignores all files. A nested issues: {} clears inherited exclusions. The example suppresses only COMMENT_FIELD in legacy files and excludes the generated subtree entirely. +A pathless rule applies to all files covered by that `issues` section. An empty or omitted `linters` list excludes matching files entirely. An empty rule `{}` explicitly ignores all files. A nested `issues: {}` clears inherited exclusions. The example above suppresses only `COMMENT_FIELD` in legacy files and excludes the `generated` subtree entirely. ## Suppress with comments -~~~proto +```proto // easyp:disable FIELD_LOWER_SNAKE_CASE message Example { string legacyField = 1; @@ -56,12 +92,12 @@ message Another { message old_name {} message another_old_name {} // easyp:enable MESSAGE_PASCAL_CASE -~~~ +``` An unpaired disable must annotate a declaration and covers that declaration's line or block. A paired disable/enable bounds a region in the same file; nested regions for the same rule are balanced. Suppressions do not leak to other files or policies. Rule names may be comma- or whitespace-separated; comment directives accept individual rules, not groups. -Legacy nolint:RULE and buf:lint:ignore RULE remain declaration annotations. An explanation may follow a space-delimited -- or // separator. Only parsed comments are interpreted. Empty directives, unknown rules, unsupported actions, and unmatched enables are errors with source locations. +Legacy `nolint:RULE` and `buf:lint:ignore RULE` remain declaration annotations. An explanation may follow a space-delimited `--` or `//` separator. Only parsed comments are interpreted. Empty directives, unknown rules, unsupported actions, and unmatched enables are errors with source locations. -linters.allow_comment_ignores defaults to true for each effective policy. Set it to false to disable comment suppression in that policy; malformed directives remain errors on files being linted. +`linters.allow_comment_ignores` defaults to `true` for each effective policy. Set it to `false` to disable comment suppression in that policy; malformed directives remain errors on files being linted. -See the [policy reference](/docs/reference/easyp-yaml). The older lint.use, lint.except, and lint.ignore_only configuration is not accepted by the v1 CLI. +See the [policy reference](/docs/reference/easyp-yaml). The older `lint.use`, `lint.except`, and `lint.ignore_only` configuration is not accepted by the v1 CLI. diff --git a/content/docs/cli/linter/index.ru.mdx b/content/docs/cli/linter/index.ru.mdx index 1be2feb..0ee4d24 100644 --- a/content/docs/cli/linter/index.ru.mdx +++ b/content/docs/cli/linter/index.ru.mdx @@ -3,9 +3,9 @@ title: "Линтер" description: "Настройка и запуск protobuf-линтера EasyP v1." --- -easyp lint проверяет .proto по политике v1 из easyp.yaml, указывая положение в исходнике и имя правила. +`easyp lint` проверяет `.proto`-файлы по политике v1 из `easyp.yaml`, указывая положение в исходнике и имя правила. -~~~yaml +```yaml version: v1 linters: default: STANDARD @@ -20,29 +20,65 @@ issues: - path: legacy/**/*.proto linters: [COMMENT_FIELD] - path: generated -~~~ +``` -Пресеты: MINIMAL, BASIC, STANDARD и COMMENTS. Списки enable/disable и исключений принимают реализованные правила и группы. Повторы не добавляют проверок; отключение приоритетнее включения. Неизвестные имена — ошибки, даже если повторены в противоположном списке. PACKAGE_NO_IMPORT_CYCLE зарезервировано и выбирать его нельзя. Поддерживаются настройки ENUM_ZERO_VALUE_SUFFIX.suffix и SERVICE_SUFFIX.suffix. linters.extends подключает локальную или закреплённую базу перед локальными изменениями; см. [общие политики](/ru/docs/guides/organization-lint-style). +## Пресеты и группы правил -~~~bash +EasyP включает **44 правила линтинга**, разделённые на **5 выбираемых групп**, из которых собираются **4 пресета `linters.default`**: + +### Пресеты `linters.default` + +| Пресет | Входящие группы | Правил | Примечание | +| --- | --- | ---: | --- | +| `MINIMAL` | `MINIMAL` | 5 | Структура пакетов и каталогов, циклы импортов | +| `BASIC` | `MINIMAL`, `BASIC` | 27 | Базовый стиль, синтаксис, именование и опции пакетов для языков | +| `STANDARD` | `MINIMAL`, `BASIC`, `DEFAULT` | 35 | Пресет по умолчанию, если `linters.default` не задан | +| `COMMENTS` | `MINIMAL`, `BASIC`, `DEFAULT`, `COMMENTS` | 42 | Добавляет обязательные комментарии к объявлениям | + +### Выбираемые группы правил + +| Группа | Правил | Назначение | +| --- | ---: | --- | +| `MINIMAL` | 5 | `DIRECTORY_SAME_PACKAGE`, `PACKAGE_DEFINED`, `PACKAGE_DIRECTORY_MATCH`, `PACKAGE_SAME_DIRECTORY`, `PACKAGE_NO_IMPORT_CYCLE` | +| `BASIC` | 22 | Соглашения об именах, чистота импортов, `SYNTAX_SPECIFIED`, `FIELD_NOT_REQUIRED` и согласованность языковых опций пакетов | +| `DEFAULT` | 8 | Имена файлов, префиксы/суффиксы enum, версионный суффикс пакета, суффикс сервисов и стандартные имена сообщений RPC | +| `COMMENTS` | 7 | Комментарии перед объявлениями enum, значений enum, полей, сообщений, oneof, RPC и сервисов | +| `UNARY_RPC` | 2 | Подключается отдельно через `linters.enable`: `RPC_NO_CLIENT_STREAMING` и `RPC_NO_SERVER_STREAMING` | + +Списки `linters.enable`, `linters.disable` и `issues.exclude-rules[].linters` принимают как имена отдельных правил, так и ключи групп (`MINIMAL`, `BASIC`, `DEFAULT`, `COMMENTS`, `UNARY_RPC`). Повторы идемпотентны; отключение приоритетнее включения. Неизвестные имена отклоняются с ошибкой, даже если указаны в обоих списках. + +Поддерживаются настройки в `linters-settings`: `ENUM_ZERO_VALUE_SUFFIX.suffix` (по умолчанию `NONE`) и `SERVICE_SUFFIX.suffix` (по умолчанию `Service`). `linters.extends` подключает локальную или закреплённую базу перед локальными изменениями; см. [общие политики](/ru/docs/guides/organization-lint-style). + +## Запуск линтера + +```bash easyp lint --path proto easyp --format json lint --path proto easyp lint --root ./contracts --path proto -~~~ +easyp lint --config ./policies/easyp.yaml --path proto +easyp lint --frozen --path proto +``` + +- `--path` (`-p`) задаёт файл или каталог относительно корня проверки (по умолчанию `.`). +- `--root` (`-r`) переопределяет корень проверки, который по умолчанию совпадает с каталогом выбранной политики. +- `--config` указывает явный файл политики вместо автоматического поиска `easyp.yaml`. Поиск идёт вверх в пределах workspace; без политики в предках может быть выбрана одна однозначная внешняя политика в потомках, а при нескольких независимых политиках требуется `--config`. Явный `--config` имеет приоритет. Каждая вложенная секция политики целиком заменяет ближайшую унаследованную секцию. +- `--frozen` требует наличия `protobuf.mod` и проверенного `protobuf.lock` без разрешения зависимостей, изменения файлов и локальных директив `replace`. ---path считается от корня проверки, по умолчанию — каталога выбранной политики; --root меняет его. Поиск политики идёт вверх в пределах workspace. Без политики в предках можно выбрать одну однозначную внешнюю политику в потомках; несколько независимых политик требуют --cfg. Явный конфиг имеет приоритет. Каждая вложенная секция целиком заменяет ближайшую унаследованную секцию. +Для импортов линтер использует корни ближайшего модуля и его локальные или зафиксированные зависимости. Политика может работать и без `protobuf.mod` (если не передан `--frozen`). Вендорные исходники и скрытые каталоги хранилищ/Git исключены из поиска целей линтинга, включая явные пути в vendor; исходники зависимостей при этом остаются доступными для импортов. -Для импортов линтер использует корни ближайшего модуля и его локальные или зафиксированные зависимости. Политика может работать без protobuf.mod. Вендорные исходники и скрытые каталоги хранилищ/Git исключены из поиска целей линтинга, включая явные пути в vendor; зависимости остаются доступными для импортов. + +Перед запуском правил линтера EasyP компилирует и линкует проверяемые файлы. Если в файлах есть синтаксические ошибки, отсутствующие импорты или другие ошибки компиляции, EasyP выводит диагностики компилятора и пропускает выполнение правил линтинга до исправления ошибок компиляции. + ## Исключение путей -issues.exclude-rules.path считается от файла политики, предоставляющего эффективную секцию issues, в том числе унаследованную. Поддерживаются *, ?, [] и полные сегменты **. Односегментные шаблоны не пересекают /; ** совпадает с нулём или более сегментами. Буквальный каталог включает своё поддерево. Буквальный путь с окончанием .proto совпадает только с файлом. Абсолютные пути, обратные слеши, переходы к родителю и некорректные шаблоны отклоняются. +`issues.exclude-rules.path` считается от файла политики, предоставляющего эффективную секцию `issues`, в том числе унаследованную. Поддерживаются `*`, `?`, `[]` и полные сегменты `**`. Односегментные шаблоны не пересекают `/`; `**` совпадает с нулём или более сегментами. Буквальный каталог включает своё поддерево. Буквальный путь с окончанием `.proto` совпадает только с этим файлом. Абсолютные пути, обратные слеши, переходы к родителю и некорректные шаблоны отклоняются. -Правило без пути действует на все файлы этой секции issues. Пустой или отсутствующий linters исключает совпавшие файлы целиком. Пустое правило {} явно исключает все файлы. Вложенная issues: {} очищает унаследованные исключения. В примере у legacy-файлов подавляется только COMMENT_FIELD, а поддерево generated исключено полностью. +Правило без пути действует на все файлы этой секции `issues`. Пустой или отсутствующий `linters` исключает совпавшие файлы целиком. Пустое правило `{}` явно исключает все файлы. Вложенная `issues: {}` очищает унаследованные исключения. В примере выше у legacy-файлов подавляется только `COMMENT_FIELD`, а поддерево `generated` исключено полностью. ## Подавление комментариями -~~~proto +```proto // easyp:disable FIELD_LOWER_SNAKE_CASE message Example { string legacyField = 1; @@ -56,12 +92,12 @@ message Another { message old_name {} message another_old_name {} // easyp:enable MESSAGE_PASCAL_CASE -~~~ +``` Непарный disable должен аннотировать объявление и действует на его строку или блок. Пара disable/enable ограничивает регион в одном файле; вложенные регионы одного правила сбалансированы. Подавления не переходят в другие файлы или политики. Имена правил разделяются запятыми или пробелами; группы в директивах комментариев не принимаются. -Старые nolint:RULE и buf:lint:ignore RULE остаются аннотациями объявлений. Пояснение можно добавить после отделённого пробелами -- или //. Интерпретируются только разобранные комментарии. Пустые директивы, неизвестные правила, неподдерживаемые действия и enable без пары — ошибки с координатами исходника. +Старые `nolint:RULE` и `buf:lint:ignore RULE` остаются аннотациями объявлений. Пояснение можно добавить после отделённого пробелами `--` или `//`. Интерпретируются только разобранные комментарии. Пустые директивы, неизвестные правила, неподдерживаемые действия и enable без пары — ошибки с координатами исходника. -linters.allow_comment_ignores по умолчанию равен true для каждой эффективной политики. False отключает подавление комментариями в этой политике; некорректные директивы в проверяемых файлах остаются ошибками. +`linters.allow_comment_ignores` по умолчанию равен `true` для каждой эффективной политики. Значение `false` отключает подавление комментариями в этой политике; некорректные директивы в проверяемых файлах остаются ошибками. -См. [справочник политики](/ru/docs/reference/easyp-yaml). Старые поля lint.use, lint.except и lint.ignore_only CLI v1 не принимает. +См. [справочник политики](/ru/docs/reference/easyp-yaml). Старые поля `lint.use`, `lint.except` и `lint.ignore_only` CLI v1 не принимает. diff --git a/content/docs/cli/linter/meta.ru.json b/content/docs/cli/linter/meta.ru.json new file mode 100644 index 0000000..1f8f2fd --- /dev/null +++ b/content/docs/cli/linter/meta.ru.json @@ -0,0 +1,7 @@ +{ + "title": "Линтер", + "pages": [ + "index", + "rules" + ] +} diff --git a/content/docs/cli/linter/rules/comment-enum-value.mdx b/content/docs/cli/linter/rules/comment-enum-value.mdx index ce2fce4..c2450cd 100644 --- a/content/docs/cli/linter/rules/comment-enum-value.mdx +++ b/content/docs/cli/linter/rules/comment-enum-value.mdx @@ -1,10 +1,11 @@ --- title: "Comment Enum Value" +description: "This rule checks that enum values have a comment." --- -Categories: - -- **COMMENT** +- **Rule ID:** `COMMENT_ENUM_VALUE` +- **Group:** `COMMENTS` +- **Included in presets (`linters.default`):** `COMMENTS` This rule checks that enum values have a comment. diff --git a/content/docs/cli/linter/rules/comment-enum-value.ru.mdx b/content/docs/cli/linter/rules/comment-enum-value.ru.mdx index 4acca2e..b40f3bc 100644 --- a/content/docs/cli/linter/rules/comment-enum-value.ru.mdx +++ b/content/docs/cli/linter/rules/comment-enum-value.ru.mdx @@ -1,16 +1,17 @@ --- title: "Comment Enum Value" +description: "Это правило проверяет, что все значения enum имеют комментарий." --- -Категории: - -- **COMMENT** +- **ID правила:** `COMMENT_ENUM_VALUE` +- **Группа:** `COMMENTS` +- **Входит в пресеты (`linters.default`):** `COMMENTS` Это правило проверяет, что все значения enum имеют комментарий. -## Examples +## Примеры -### Bad +### Неправильно ```proto syntax = "proto3"; @@ -21,7 +22,7 @@ enum Foo { } ``` -### Good +### Правильно ```proto syntax = "proto3"; diff --git a/content/docs/cli/linter/rules/comment-enum.mdx b/content/docs/cli/linter/rules/comment-enum.mdx index 2aaf113..e033c28 100644 --- a/content/docs/cli/linter/rules/comment-enum.mdx +++ b/content/docs/cli/linter/rules/comment-enum.mdx @@ -1,10 +1,11 @@ --- title: "Comment Enum" +description: "This rule checks that enum has a comment." --- -Categories: - -- **COMMENT** +- **Rule ID:** `COMMENT_ENUM` +- **Group:** `COMMENTS` +- **Included in presets (`linters.default`):** `COMMENTS` This rule checks that enum has a comment. diff --git a/content/docs/cli/linter/rules/comment-enum.ru.mdx b/content/docs/cli/linter/rules/comment-enum.ru.mdx index b4ccb33..6e410f6 100644 --- a/content/docs/cli/linter/rules/comment-enum.ru.mdx +++ b/content/docs/cli/linter/rules/comment-enum.ru.mdx @@ -1,16 +1,17 @@ --- title: "Comment Enum" +description: "Это правило проверяет, что enum имеет комментарий." --- -Категории: - -- **COMMENT** +- **ID правила:** `COMMENT_ENUM` +- **Группа:** `COMMENTS` +- **Входит в пресеты (`linters.default`):** `COMMENTS` Это правило проверяет, что enum имеет комментарий. ## Примеры -### Bad +### Неправильно ```proto syntax = "proto3"; @@ -21,7 +22,7 @@ enum Foo { } ``` -### Good +### Правильно ```proto syntax = "proto3"; diff --git a/content/docs/cli/linter/rules/comment-field.mdx b/content/docs/cli/linter/rules/comment-field.mdx index e08032b..4c113eb 100644 --- a/content/docs/cli/linter/rules/comment-field.mdx +++ b/content/docs/cli/linter/rules/comment-field.mdx @@ -1,10 +1,11 @@ --- title: "Comment Field" +description: "This rule checks that all message fields have a comment." --- -Categories: - -- **COMMENT** +- **Rule ID:** `COMMENT_FIELD` +- **Group:** `COMMENTS` +- **Included in presets (`linters.default`):** `COMMENTS` This rule checks that all message fields have a comment. diff --git a/content/docs/cli/linter/rules/comment-field.ru.mdx b/content/docs/cli/linter/rules/comment-field.ru.mdx index 589fb07..985377e 100644 --- a/content/docs/cli/linter/rules/comment-field.ru.mdx +++ b/content/docs/cli/linter/rules/comment-field.ru.mdx @@ -1,16 +1,17 @@ --- title: "Comment Field" +description: "Это правило проверяет, что все поля сообщений имеют комментарий." --- -Категории: - -- **COMMENT** +- **ID правила:** `COMMENT_FIELD` +- **Группа:** `COMMENTS` +- **Входит в пресеты (`linters.default`):** `COMMENTS` Это правило проверяет, что все поля сообщений имеют комментарий. ## Примеры -### Bad +### Неправильно ```proto syntax = "proto3"; @@ -21,7 +22,7 @@ message Foo { } ``` -### Good +### Правильно ```proto syntax = "proto3"; diff --git a/content/docs/cli/linter/rules/comment-message.mdx b/content/docs/cli/linter/rules/comment-message.mdx index d70959f..a747006 100644 --- a/content/docs/cli/linter/rules/comment-message.mdx +++ b/content/docs/cli/linter/rules/comment-message.mdx @@ -1,10 +1,11 @@ --- title: "Comment Message" +description: "This rule checks that message has a comment." --- -Categories: - -- **COMMENT** +- **Rule ID:** `COMMENT_MESSAGE` +- **Group:** `COMMENTS` +- **Included in presets (`linters.default`):** `COMMENTS` This rule checks that message has a comment. diff --git a/content/docs/cli/linter/rules/comment-message.ru.mdx b/content/docs/cli/linter/rules/comment-message.ru.mdx index d8946ab..b5d4830 100644 --- a/content/docs/cli/linter/rules/comment-message.ru.mdx +++ b/content/docs/cli/linter/rules/comment-message.ru.mdx @@ -1,16 +1,17 @@ --- title: "Comment Message" +description: "Это правило проверяет, что message имеет комментарий." --- -Категории: - -- **COMMENT** +- **ID правила:** `COMMENT_MESSAGE` +- **Группа:** `COMMENTS` +- **Входит в пресеты (`linters.default`):** `COMMENTS` Это правило проверяет, что message имеет комментарий. ## Примеры -### Bad +### Неправильно ```proto syntax = "proto3"; @@ -21,7 +22,7 @@ message Foo { } ``` -### Good +### Правильно ```proto syntax = "proto3"; diff --git a/content/docs/cli/linter/rules/comment-oneof.mdx b/content/docs/cli/linter/rules/comment-oneof.mdx index 73430f7..7242139 100644 --- a/content/docs/cli/linter/rules/comment-oneof.mdx +++ b/content/docs/cli/linter/rules/comment-oneof.mdx @@ -1,10 +1,11 @@ --- title: "Comment Oneof" +description: "This rule checks that oneof has a comment." --- -Categories: - -- **COMMENT** +- **Rule ID:** `COMMENT_ONEOF` +- **Group:** `COMMENTS` +- **Included in presets (`linters.default`):** `COMMENTS` This rule checks that oneof has a comment. diff --git a/content/docs/cli/linter/rules/comment-oneof.ru.mdx b/content/docs/cli/linter/rules/comment-oneof.ru.mdx index cd161fc..aa9dcab 100644 --- a/content/docs/cli/linter/rules/comment-oneof.ru.mdx +++ b/content/docs/cli/linter/rules/comment-oneof.ru.mdx @@ -1,16 +1,17 @@ --- title: "Comment Oneof" +description: "Это правило проверяет, что oneof имеет комментарий." --- -Категории: - -- **COMMENT** +- **ID правила:** `COMMENT_ONEOF` +- **Группа:** `COMMENTS` +- **Входит в пресеты (`linters.default`):** `COMMENTS` Это правило проверяет, что oneof имеет комментарий. ## Примеры -### Bad +### Неправильно ```proto syntax = "proto3"; @@ -23,7 +24,7 @@ message Foo { } ``` -### Good +### Правильно ```proto syntax = "proto3"; diff --git a/content/docs/cli/linter/rules/comment-rpc.mdx b/content/docs/cli/linter/rules/comment-rpc.mdx index aab9732..b372f2d 100644 --- a/content/docs/cli/linter/rules/comment-rpc.mdx +++ b/content/docs/cli/linter/rules/comment-rpc.mdx @@ -1,10 +1,11 @@ --- title: "Comment Rpc" +description: "This rule checks that rpc has a comment." --- -Categories: - -- **COMMENT** +- **Rule ID:** `COMMENT_RPC` +- **Group:** `COMMENTS` +- **Included in presets (`linters.default`):** `COMMENTS` This rule checks that rpc has a comment. diff --git a/content/docs/cli/linter/rules/comment-rpc.ru.mdx b/content/docs/cli/linter/rules/comment-rpc.ru.mdx index aab9732..bcfc470 100644 --- a/content/docs/cli/linter/rules/comment-rpc.ru.mdx +++ b/content/docs/cli/linter/rules/comment-rpc.ru.mdx @@ -1,35 +1,40 @@ --- title: "Comment Rpc" +description: "Проверяет, что каждый RPC-метод снабжён комментарием." --- -Categories: +- **ID правила:** `COMMENT_RPC` +- **Группа:** `COMMENTS` +- **Входит в пресеты (`linters.default`):** `COMMENTS` -- **COMMENT** +- **ID правила:** `COMMENT_RPC` +- **Группа:** `COMMENTS` +- **Входит в пресеты (`linters.default`):** `COMMENTS` -This rule checks that rpc has a comment. +Это правило проверяет, что у каждого RPC-метода есть документирующий комментарий непосредственно перед объявлением. -## Examples +## Примеры -### Bad +### Неправильно ```proto syntax = "proto3"; service Foo { - rpc Bar (BarRequest) returns (BarResponse) {} - rpc Baz (BazRequest) returns (BazResponse) {} + rpc Bar (BarRequest) returns (BarResponse) {} + rpc Baz (BazRequest) returns (BazResponse) {} } ``` -### Good +### Правильно ```proto syntax = "proto3"; service Foo { - // Bar rpc for bar logic - rpc Bar (BarRequest) returns (BarResponse) {} - // Baz rpc for baz logic - rpc Baz (BazRequest) returns (BazResponse) {} + // Bar выполняет операцию Bar. + rpc Bar (BarRequest) returns (BarResponse) {} + // Baz выполняет операцию Baz. + rpc Baz (BazRequest) returns (BazResponse) {} } ``` diff --git a/content/docs/cli/linter/rules/comment-service.mdx b/content/docs/cli/linter/rules/comment-service.mdx index 14836ec..d2c264e 100644 --- a/content/docs/cli/linter/rules/comment-service.mdx +++ b/content/docs/cli/linter/rules/comment-service.mdx @@ -1,10 +1,11 @@ --- title: "Comment Service" +description: "This rule checks that service has a comment." --- -Categories: - -- **COMMENT** +- **Rule ID:** `COMMENT_SERVICE` +- **Group:** `COMMENTS` +- **Included in presets (`linters.default`):** `COMMENTS` This rule checks that service has a comment. diff --git a/content/docs/cli/linter/rules/comment-service.ru.mdx b/content/docs/cli/linter/rules/comment-service.ru.mdx index bd9d008..87623db 100644 --- a/content/docs/cli/linter/rules/comment-service.ru.mdx +++ b/content/docs/cli/linter/rules/comment-service.ru.mdx @@ -1,16 +1,17 @@ --- title: "Comment Service" +description: "Это правило проверяет, что сервис имеет комментарий." --- -Категории: - -- **COMMENT** +- **ID правила:** `COMMENT_SERVICE` +- **Группа:** `COMMENTS` +- **Входит в пресеты (`linters.default`):** `COMMENTS` Это правило проверяет, что сервис имеет комментарий. ## Примеры -### Bad +### Неправильно ```proto syntax = "proto3"; @@ -20,7 +21,7 @@ service Foo { } ``` -### Good +### Правильно ```proto syntax = "proto3"; diff --git a/content/docs/cli/linter/rules/directory-same-package.mdx b/content/docs/cli/linter/rules/directory-same-package.mdx index 3a65e90..f2f98b8 100644 --- a/content/docs/cli/linter/rules/directory-same-package.mdx +++ b/content/docs/cli/linter/rules/directory-same-package.mdx @@ -1,40 +1,64 @@ --- title: "Directory Same Package" +description: "Checks that all .proto files in the same directory declare the same package." --- -Categories: -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **Rule ID:** `DIRECTORY_SAME_PACKAGE` +- **Group:** `MINIMAL` +- **Included in presets (`linters.default`):** `MINIMAL`, `BASIC`, `STANDARD`, `COMMENTS` -This rule checks that all files in a given directory are in the same package. +- **Rule ID:** `DIRECTORY_SAME_PACKAGE` +- **Group:** `MINIMAL` +- **Included in presets (`linters.default`):** `MINIMAL`, `BASIC`, `STANDARD`, `COMMENTS` + +This module-level rule checks that every `.proto` file located in the same directory declares the same `package`. If a directory contains files with different package declarations (or a mix of packaged and unpackaged files), every file in that directory is reported. ## Examples ### Bad ```proto -// File: dir/foo.proto +// File: foo/v1/user.proto +syntax = "proto3"; +package foo.v1; + +message User { + string id = 1; +} +``` + +```proto +// File: foo/v1/order.proto syntax = "proto3"; - -package foo; -message Foo { - string bar = 1; +package bar.v1; + +message Order { + string id = 1; } ``` ### Good ```proto -// File: dir/foo/foo.proto +// File: foo/v1/user.proto +syntax = "proto3"; +package foo.v1; + +message User { + string id = 1; +} +``` + +```proto +// File: foo/v1/order.proto syntax = "proto3"; -package dir.foo; +package foo.v1; -message Foo { - string bar = 1; +message Order { + string id = 1; } ``` diff --git a/content/docs/cli/linter/rules/directory-same-package.ru.mdx b/content/docs/cli/linter/rules/directory-same-package.ru.mdx index 924132a..3199083 100644 --- a/content/docs/cli/linter/rules/directory-same-package.ru.mdx +++ b/content/docs/cli/linter/rules/directory-same-package.ru.mdx @@ -1,40 +1,64 @@ --- title: "Directory Same Package" +description: "Проверяет, что все .proto-файлы в одном каталоге объявляют один и тот же пакет." --- -Категории: -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **ID правила:** `DIRECTORY_SAME_PACKAGE` +- **Группа:** `MINIMAL` +- **Входит в пресеты (`linters.default`):** `MINIMAL`, `BASIC`, `STANDARD`, `COMMENTS` -Это правило проверяет, что все файлы в заданной директории находятся в одном и том же package. +- **ID правила:** `DIRECTORY_SAME_PACKAGE` +- **Группа:** `MINIMAL` +- **Входит в пресеты (`linters.default`):** `MINIMAL`, `BASIC`, `STANDARD`, `COMMENTS` + +Это правило уровня модуля проверяет, что все `.proto`-файлы в одном каталоге объявляют одинаковый `package`. Если в каталоге находятся файлы с разными пакетами (или часть файлов без `package`), ошибка выдаётся для каждого файла в этом каталоге. ## Примеры -### Bad +### Неправильно ```proto -// File: dir/foo.proto +// File: foo/v1/user.proto +syntax = "proto3"; +package foo.v1; + +message User { + string id = 1; +} +``` + +```proto +// File: foo/v1/order.proto syntax = "proto3"; - -package foo; -message Foo { - string bar = 1; +package bar.v1; + +message Order { + string id = 1; } ``` -### Good +### Правильно ```proto -// File: dir/foo/foo.proto +// File: foo/v1/user.proto +syntax = "proto3"; +package foo.v1; + +message User { + string id = 1; +} +``` + +```proto +// File: foo/v1/order.proto syntax = "proto3"; -package dir.foo; +package foo.v1; -message Foo { - string bar = 1; +message Order { + string id = 1; } ``` diff --git a/content/docs/cli/linter/rules/enum-first-value-zero.mdx b/content/docs/cli/linter/rules/enum-first-value-zero.mdx index 51e1a73..2ae13f6 100644 --- a/content/docs/cli/linter/rules/enum-first-value-zero.mdx +++ b/content/docs/cli/linter/rules/enum-first-value-zero.mdx @@ -1,12 +1,11 @@ --- title: "Enum First Value Zero" +description: "This rule checks that the first value of an enum is zero." --- -Categories: - -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **Rule ID:** `ENUM_FIRST_VALUE_ZERO` +- **Group:** `BASIC` +- **Included in presets (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` This rule checks that the first value of an enum is zero. diff --git a/content/docs/cli/linter/rules/enum-first-value-zero.ru.mdx b/content/docs/cli/linter/rules/enum-first-value-zero.ru.mdx index 9e34bbe..8e9ad4e 100644 --- a/content/docs/cli/linter/rules/enum-first-value-zero.ru.mdx +++ b/content/docs/cli/linter/rules/enum-first-value-zero.ru.mdx @@ -1,18 +1,17 @@ --- title: "Enum First Value Zero" +description: "Это правило проверяет, что первое значение enum равно нулю." --- -Категории: - -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **ID правила:** `ENUM_FIRST_VALUE_ZERO` +- **Группа:** `BASIC` +- **Входит в пресеты (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` Это правило проверяет, что первое значение enum равно нулю. -## Examples +## Примеры -### Bad +### Неправильно ```proto syntax = "proto3"; @@ -25,7 +24,7 @@ enum Foo { } ``` -### Good +### Правильно ```proto syntax = "proto3"; diff --git a/content/docs/cli/linter/rules/enum-no-allow-alias.mdx b/content/docs/cli/linter/rules/enum-no-allow-alias.mdx index d0075e9..00af510 100644 --- a/content/docs/cli/linter/rules/enum-no-allow-alias.mdx +++ b/content/docs/cli/linter/rules/enum-no-allow-alias.mdx @@ -1,12 +1,11 @@ --- title: "Enum No Allow Alias" +description: "This rule checks that the allow_alias option is not set to true in an enum." --- -Categories: - -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **Rule ID:** `ENUM_NO_ALLOW_ALIAS` +- **Group:** `BASIC` +- **Included in presets (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` This rule checks that the `allow_alias` option is not set to `true` in an enum. diff --git a/content/docs/cli/linter/rules/enum-no-allow-alias.ru.mdx b/content/docs/cli/linter/rules/enum-no-allow-alias.ru.mdx index dea2c2e..b8c7f94 100644 --- a/content/docs/cli/linter/rules/enum-no-allow-alias.ru.mdx +++ b/content/docs/cli/linter/rules/enum-no-allow-alias.ru.mdx @@ -1,18 +1,17 @@ --- title: "Enum No Allow Alias" +description: "Это правило проверяет, что опция allow_alias не установлена в значение true внутри enum." --- -Категории: - -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **ID правила:** `ENUM_NO_ALLOW_ALIAS` +- **Группа:** `BASIC` +- **Входит в пресеты (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` Это правило проверяет, что опция `allow_alias` не установлена в значение `true` внутри enum. ## Примеры -### Bad +### Неправильно ```proto syntax = "proto3"; @@ -26,7 +25,7 @@ enum Foo { } ``` -### Good +### Правильно ```proto syntax = "proto3"; diff --git a/content/docs/cli/linter/rules/enum-pascal-case.mdx b/content/docs/cli/linter/rules/enum-pascal-case.mdx index 0f8dca8..d13c233 100644 --- a/content/docs/cli/linter/rules/enum-pascal-case.mdx +++ b/content/docs/cli/linter/rules/enum-pascal-case.mdx @@ -1,11 +1,11 @@ --- title: "Enum Pascal Case" +description: "This rule checks that enum names are in PascalCase." --- -Categories: -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **Rule ID:** `ENUM_PASCAL_CASE` +- **Group:** `BASIC` +- **Included in presets (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` This rule checks that enum names are in PascalCase. diff --git a/content/docs/cli/linter/rules/enum-pascal-case.ru.mdx b/content/docs/cli/linter/rules/enum-pascal-case.ru.mdx index c7f6917..e1bd2b6 100644 --- a/content/docs/cli/linter/rules/enum-pascal-case.ru.mdx +++ b/content/docs/cli/linter/rules/enum-pascal-case.ru.mdx @@ -1,17 +1,17 @@ --- title: "Enum Pascal Case" +description: "Это правило проверяет, что имена enum написаны в стиле PascalCase." --- -Категории: -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **ID правила:** `ENUM_PASCAL_CASE` +- **Группа:** `BASIC` +- **Входит в пресеты (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` Это правило проверяет, что имена enum написаны в стиле PascalCase. ## Примеры -### Bad +### Неправильно ```proto syntax = "proto3"; @@ -24,7 +24,7 @@ enum foo_bar { } ``` -### Good +### Правильно ```proto syntax = "proto3"; diff --git a/content/docs/cli/linter/rules/enum-value-prefix.mdx b/content/docs/cli/linter/rules/enum-value-prefix.mdx index a5ae455..44a0913 100644 --- a/content/docs/cli/linter/rules/enum-value-prefix.mdx +++ b/content/docs/cli/linter/rules/enum-value-prefix.mdx @@ -1,12 +1,11 @@ --- title: "Enum Value Prefix" +description: "This rule checks that all enum values are prefixed with the enum name." --- -Categories: - -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **Rule ID:** `ENUM_VALUE_PREFIX` +- **Group:** `DEFAULT` +- **Included in presets (`linters.default`):** `STANDARD`, `COMMENTS` This rule checks that all enum values are prefixed with the enum name. diff --git a/content/docs/cli/linter/rules/enum-value-prefix.ru.mdx b/content/docs/cli/linter/rules/enum-value-prefix.ru.mdx index 764944e..281e1ee 100644 --- a/content/docs/cli/linter/rules/enum-value-prefix.ru.mdx +++ b/content/docs/cli/linter/rules/enum-value-prefix.ru.mdx @@ -1,18 +1,17 @@ --- title: "Enum Value Prefix" +description: "Это правило проверяет, что все значения enum имеют префикс, совпадающий с именем enum." --- -Категории: - -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **ID правила:** `ENUM_VALUE_PREFIX` +- **Группа:** `DEFAULT` +- **Входит в пресеты (`linters.default`):** `STANDARD`, `COMMENTS` Это правило проверяет, что все значения enum имеют префикс, совпадающий с именем enum. -## Examples +## Примеры -### Bad +### Неправильно ```proto syntax = "proto3"; @@ -22,7 +21,7 @@ enum Foo { } ``` -### Good +### Правильно ```proto syntax = "proto3"; diff --git a/content/docs/cli/linter/rules/enum-value-upper-snake-case.mdx b/content/docs/cli/linter/rules/enum-value-upper-snake-case.mdx index 017487b..c1dee91 100644 --- a/content/docs/cli/linter/rules/enum-value-upper-snake-case.mdx +++ b/content/docs/cli/linter/rules/enum-value-upper-snake-case.mdx @@ -1,11 +1,11 @@ --- title: "Enum Value Upper Snake Case" +description: "This rule checks that enum values are in UPPER_SNAKE_CASE." --- -Categories: -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **Rule ID:** `ENUM_VALUE_UPPER_SNAKE_CASE` +- **Group:** `BASIC` +- **Included in presets (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` This rule checks that enum values are in UPPER_SNAKE_CASE. diff --git a/content/docs/cli/linter/rules/enum-value-upper-snake-case.ru.mdx b/content/docs/cli/linter/rules/enum-value-upper-snake-case.ru.mdx index 0179af6..fd5de18 100644 --- a/content/docs/cli/linter/rules/enum-value-upper-snake-case.ru.mdx +++ b/content/docs/cli/linter/rules/enum-value-upper-snake-case.ru.mdx @@ -1,17 +1,17 @@ --- title: "Enum Value Upper Snake Case" +description: "Это правило проверяет, что значения enum записаны в стиле UPPER_SNAKE_CASE." --- -Категории: -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **ID правила:** `ENUM_VALUE_UPPER_SNAKE_CASE` +- **Группа:** `BASIC` +- **Входит в пресеты (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` Это правило проверяет, что значения enum записаны в стиле UPPER_SNAKE_CASE. ## Примеры -### Bad +### Неправильно ```proto syntax = "proto3"; @@ -24,7 +24,7 @@ enum Foo { } ``` -### Good +### Правильно ```proto syntax = "proto3"; diff --git a/content/docs/cli/linter/rules/enum-zero-value-suffix.mdx b/content/docs/cli/linter/rules/enum-zero-value-suffix.mdx index 875f319..5fd31cf 100644 --- a/content/docs/cli/linter/rules/enum-zero-value-suffix.mdx +++ b/content/docs/cli/linter/rules/enum-zero-value-suffix.mdx @@ -1,14 +1,26 @@ --- title: "Enum Zero Value Suffix" +description: "Checks that every enum value numbered 0 ends with the configured suffix (default _NONE)." --- -Categories: +- **Rule ID:** `ENUM_ZERO_VALUE_SUFFIX` +- **Group:** `DEFAULT` +- **Included in presets (`linters.default`):** `STANDARD`, `COMMENTS` -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **Rule ID:** `ENUM_ZERO_VALUE_SUFFIX` +- **Group:** `DEFAULT` +- **Included in presets (`linters.default`):** `STANDARD`, `COMMENTS` -This rule checks that all enum zero values are suffixed with `_NONE` or your custom suffix. +This rule checks that every enum value with number `0` ends with `_NONE` or a custom suffix configured via `linters-settings.ENUM_ZERO_VALUE_SUFFIX.suffix` (with or without a leading underscore). + +## Configuration + +```yaml +version: v1 +linters-settings: + ENUM_ZERO_VALUE_SUFFIX: + suffix: UNSPECIFIED +``` ## Examples @@ -18,16 +30,28 @@ This rule checks that all enum zero values are suffixed with `_NONE` or your cus syntax = "proto3"; enum Foo { - BAR = 0; + FOO_BAR = 0; } ``` ### Good +With the default suffix (`NONE`): + +```proto +syntax = "proto3"; + +enum Foo { + FOO_NONE = 0; +} +``` + +With `suffix: UNSPECIFIED`: + ```proto syntax = "proto3"; enum Foo { - FOO_BAR_NONE = 0; + FOO_UNSPECIFIED = 0; } ``` diff --git a/content/docs/cli/linter/rules/enum-zero-value-suffix.ru.mdx b/content/docs/cli/linter/rules/enum-zero-value-suffix.ru.mdx index e8db39e..c39aae2 100644 --- a/content/docs/cli/linter/rules/enum-zero-value-suffix.ru.mdx +++ b/content/docs/cli/linter/rules/enum-zero-value-suffix.ru.mdx @@ -1,33 +1,57 @@ --- title: "Enum Zero Value Suffix" +description: "Проверяет, что каждое нулевое значение enum заканчивается на заданный суффикс (по умолчанию _NONE)." --- -Категории: +- **ID правила:** `ENUM_ZERO_VALUE_SUFFIX` +- **Группа:** `DEFAULT` +- **Входит в пресеты (`linters.default`):** `STANDARD`, `COMMENTS` -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **ID правила:** `ENUM_ZERO_VALUE_SUFFIX` +- **Группа:** `DEFAULT` +- **Входит в пресеты (`linters.default`):** `STANDARD`, `COMMENTS` -Это правило проверяет, что все нулевые значения enum имеют суффикс `_NONE` или ваш кастомный (пользовательский) суффикс. +Это правило проверяет, что каждое значение enum с номером `0` оканчивается на `_NONE` либо на пользовательский суффикс из `linters-settings.ENUM_ZERO_VALUE_SUFFIX.suffix` (можно указывать с ведущим подчёркиванием или без него). + +## Конфигурация + +```yaml +version: v1 +linters-settings: + ENUM_ZERO_VALUE_SUFFIX: + suffix: UNSPECIFIED +``` ## Примеры -### Bad +### Неправильно + +```proto +syntax = "proto3"; + +enum Foo { + FOO_BAR = 0; +} +``` + +### Правильно + +С суффиксом по умолчанию (`NONE`): ```proto syntax = "proto3"; enum Foo { - BAR = 0; + FOO_NONE = 0; } ``` -### Good +С настройкой `suffix: UNSPECIFIED`: ```proto syntax = "proto3"; enum Foo { - FOO_BAR_NONE = 0; + FOO_UNSPECIFIED = 0; } ``` diff --git a/content/docs/cli/linter/rules/field-lower-snake-case.mdx b/content/docs/cli/linter/rules/field-lower-snake-case.mdx index 3517470..33a4a2d 100644 --- a/content/docs/cli/linter/rules/field-lower-snake-case.mdx +++ b/content/docs/cli/linter/rules/field-lower-snake-case.mdx @@ -1,11 +1,11 @@ --- title: "Field Lower Snake Case" +description: "This rule checks that field names of messages are in lower_snake_case." --- -Categories: -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **Rule ID:** `FIELD_LOWER_SNAKE_CASE` +- **Group:** `BASIC` +- **Included in presets (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` This rule checks that field names of messages are in lower_snake_case. diff --git a/content/docs/cli/linter/rules/field-lower-snake-case.ru.mdx b/content/docs/cli/linter/rules/field-lower-snake-case.ru.mdx index db935f7..b32d9fd 100644 --- a/content/docs/cli/linter/rules/field-lower-snake-case.ru.mdx +++ b/content/docs/cli/linter/rules/field-lower-snake-case.ru.mdx @@ -1,18 +1,17 @@ --- title: "Field Lower Snake Case" +description: "Это правило проверяет, что имена полей сообщений записаны в стиле lower_snake_case." --- -Категории: - -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **ID правила:** `FIELD_LOWER_SNAKE_CASE` +- **Группа:** `BASIC` +- **Входит в пресеты (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` Это правило проверяет, что имена полей сообщений записаны в стиле lower_snake_case. ## Примеры -### Bad +### Неправильно ```proto syntax = "proto3"; @@ -24,7 +23,7 @@ message Foo { } ``` -### Good +### Правильно ```proto syntax = "proto3"; diff --git a/content/docs/cli/linter/rules/field-not-required.mdx b/content/docs/cli/linter/rules/field-not-required.mdx new file mode 100644 index 0000000..9c7f848 --- /dev/null +++ b/content/docs/cli/linter/rules/field-not-required.mdx @@ -0,0 +1,53 @@ +--- +title: "Field Not Required" +description: "Checks that message fields do not use the proto2 required label." +--- + +- **Rule ID:** `FIELD_NOT_REQUIRED` +- **Group:** `BASIC` +- **Included in presets (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` + +- **Rule ID:** `FIELD_NOT_REQUIRED` +- **Group:** `BASIC` +- **Included in presets (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` + +This rule checks that message fields do not use the `required` label. Proto2 `required` fields cannot be safely removed or changed later without breaking wire compatibility across producers and consumers; enforce presence requirements in application validation instead. + +## Examples + +### Bad + +```proto +syntax = "proto2"; + +package acme.users.v1; + +message User { + required string id = 1; + optional string email = 2; +} +``` + +### Good + +```proto +syntax = "proto2"; + +package acme.users.v1; + +message User { + optional string id = 1; + optional string email = 2; +} +``` + +```proto +syntax = "proto3"; + +package acme.users.v1; + +message User { + string id = 1; + string email = 2; +} +``` diff --git a/content/docs/cli/linter/rules/field-not-required.ru.mdx b/content/docs/cli/linter/rules/field-not-required.ru.mdx new file mode 100644 index 0000000..c55ddbc --- /dev/null +++ b/content/docs/cli/linter/rules/field-not-required.ru.mdx @@ -0,0 +1,53 @@ +--- +title: "Field Not Required" +description: "Проверяет, что поля сообщений не используют модификатор required из proto2." +--- + +- **ID правила:** `FIELD_NOT_REQUIRED` +- **Группа:** `BASIC` +- **Входит в пресеты (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` + +- **ID правила:** `FIELD_NOT_REQUIRED` +- **Группа:** `BASIC` +- **Входит в пресеты (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` + +Это правило проверяет, что в объявлениях полей не используется модификатор `required`. Поля `required` в proto2 невозможно безопасно удалить или сделать необязательными в будущем без нарушения wire-совместимости; обязательность данных лучше проверять на уровне прикладной валидации. + +## Примеры + +### Неправильно + +```proto +syntax = "proto2"; + +package acme.users.v1; + +message User { + required string id = 1; + optional string email = 2; +} +``` + +### Правильно + +```proto +syntax = "proto2"; + +package acme.users.v1; + +message User { + optional string id = 1; + optional string email = 2; +} +``` + +```proto +syntax = "proto3"; + +package acme.users.v1; + +message User { + string id = 1; + string email = 2; +} +``` diff --git a/content/docs/cli/linter/rules/file-lower-snake-case.mdx b/content/docs/cli/linter/rules/file-lower-snake-case.mdx index d8db7c3..d8d7828 100644 --- a/content/docs/cli/linter/rules/file-lower-snake-case.mdx +++ b/content/docs/cli/linter/rules/file-lower-snake-case.mdx @@ -1,12 +1,11 @@ --- title: "File Lower Snake Case" +description: "This rule checks that all files are in lower_snake_case." --- -Categories: - -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **Rule ID:** `FILE_LOWER_SNAKE_CASE` +- **Group:** `DEFAULT` +- **Included in presets (`linters.default`):** `STANDARD`, `COMMENTS` This rule checks that all files are in lower_snake_case. diff --git a/content/docs/cli/linter/rules/file-lower-snake-case.ru.mdx b/content/docs/cli/linter/rules/file-lower-snake-case.ru.mdx index e10f26c..8f19842 100644 --- a/content/docs/cli/linter/rules/file-lower-snake-case.ru.mdx +++ b/content/docs/cli/linter/rules/file-lower-snake-case.ru.mdx @@ -1,18 +1,17 @@ --- title: "File Lower Snake Case" +description: "Это правило проверяет, что все файлы имеют имя в формате lower_snake_case (только строчные буквы, цифры и символ подчеркивания, без пробелов и заглавных букв)." --- -Категории: - -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **ID правила:** `FILE_LOWER_SNAKE_CASE` +- **Группа:** `DEFAULT` +- **Входит в пресеты (`linters.default`):** `STANDARD`, `COMMENTS` Это правило проверяет, что все файлы имеют имя в формате lower_snake_case (только строчные буквы, цифры и символ подчеркивания, без пробелов и заглавных букв). -## Examples +## Примеры -### Bad +### Неправильно ```proto // File: bar/FooBaz.proto @@ -20,7 +19,7 @@ title: "File Lower Snake Case" syntax = "proto3"; ``` -### Good +### Правильно ```proto // File: bar/foo_baz.proto diff --git a/content/docs/cli/linter/rules/import-no-public.mdx b/content/docs/cli/linter/rules/import-no-public.mdx index c3993bd..1ce03b9 100644 --- a/content/docs/cli/linter/rules/import-no-public.mdx +++ b/content/docs/cli/linter/rules/import-no-public.mdx @@ -1,11 +1,11 @@ --- title: "Import No Public" +description: "This rule checks that no public imports are used in a proto file." --- -Categories: -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **Rule ID:** `IMPORT_NO_PUBLIC` +- **Group:** `BASIC` +- **Included in presets (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` This rule checks that no public imports are used in a proto file. diff --git a/content/docs/cli/linter/rules/import-no-public.ru.mdx b/content/docs/cli/linter/rules/import-no-public.ru.mdx index 6d9f432..4c63cb1 100644 --- a/content/docs/cli/linter/rules/import-no-public.ru.mdx +++ b/content/docs/cli/linter/rules/import-no-public.ru.mdx @@ -1,17 +1,17 @@ --- title: "Import No Public" +description: "Это правило проверяет, что в proto-файле не используются public импорты (оператор import public \"...\")." --- -Категории: -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **ID правила:** `IMPORT_NO_PUBLIC` +- **Группа:** `BASIC` +- **Входит в пресеты (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` Это правило проверяет, что в proto-файле не используются `public` импорты (оператор `import public "..."`). ## Примеры -### Bad +### Неправильно ```proto syntax = "proto3"; @@ -21,7 +21,7 @@ package foo; import public "bar.proto"; ``` -### Good +### Правильно ```proto syntax = "proto3"; diff --git a/content/docs/cli/linter/rules/import-no-weak.mdx b/content/docs/cli/linter/rules/import-no-weak.mdx index 4518a07..70ba599 100644 --- a/content/docs/cli/linter/rules/import-no-weak.mdx +++ b/content/docs/cli/linter/rules/import-no-weak.mdx @@ -1,11 +1,11 @@ --- title: "Import No Weak" +description: "This rule checks that no weak imports are used in a proto file." --- -Categories: -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **Rule ID:** `IMPORT_NO_WEAK` +- **Group:** `BASIC` +- **Included in presets (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` This rule checks that no weak imports are used in a proto file. diff --git a/content/docs/cli/linter/rules/import-no-weak.ru.mdx b/content/docs/cli/linter/rules/import-no-weak.ru.mdx index 7e7c436..9abcd8c 100644 --- a/content/docs/cli/linter/rules/import-no-weak.ru.mdx +++ b/content/docs/cli/linter/rules/import-no-weak.ru.mdx @@ -1,11 +1,11 @@ --- title: "Import No Weak" +description: "Это правило проверяет, что в proto‑файле не используются weak‑импорты (import weak \"...\")." --- -Категории: -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **ID правила:** `IMPORT_NO_WEAK` +- **Группа:** `BASIC` +- **Входит в пресеты (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` Это правило проверяет, что в proto‑файле не используются weak‑импорты (`import weak "..."`). @@ -13,7 +13,7 @@ Weak import (синтаксис `import weak`) допустим в proto2, но ## Примеры -### Bad +### Неправильно ```proto syntax = "proto2"; @@ -23,7 +23,7 @@ package foo; import weak "bar.proto"; ``` -### Good +### Правильно ```proto syntax = "proto2"; diff --git a/content/docs/cli/linter/rules/import-used.mdx b/content/docs/cli/linter/rules/import-used.mdx index 0b67435..eb5cd14 100644 --- a/content/docs/cli/linter/rules/import-used.mdx +++ b/content/docs/cli/linter/rules/import-used.mdx @@ -1,11 +1,11 @@ --- title: "Import Used" +description: "This rule checks that all imports are used in a proto file." --- -Categories: -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **Rule ID:** `IMPORT_USED` +- **Group:** `BASIC` +- **Included in presets (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` This rule checks that all imports are used in a proto file. diff --git a/content/docs/cli/linter/rules/import-used.ru.mdx b/content/docs/cli/linter/rules/import-used.ru.mdx index b960b09..1a7b7bd 100644 --- a/content/docs/cli/linter/rules/import-used.ru.mdx +++ b/content/docs/cli/linter/rules/import-used.ru.mdx @@ -1,17 +1,17 @@ --- title: "Import Used" +description: "Это правило проверяет, что все импорты используются в proto-файле." --- -Категории: -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **ID правила:** `IMPORT_USED` +- **Группа:** `BASIC` +- **Входит в пресеты (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` Это правило проверяет, что все импорты используются в proto-файле. ## Примеры -### Bad +### Неправильно ```proto syntax = "proto3"; @@ -21,7 +21,7 @@ package foo; import "bar.proto"; ``` -### Good +### Правильно ```proto syntax = "proto3"; diff --git a/content/docs/cli/linter/rules/message-pascal-case.mdx b/content/docs/cli/linter/rules/message-pascal-case.mdx index ddacff4..f85767d 100644 --- a/content/docs/cli/linter/rules/message-pascal-case.mdx +++ b/content/docs/cli/linter/rules/message-pascal-case.mdx @@ -1,11 +1,11 @@ --- title: "Message Pascal Case" +description: "This rule checks that message names are in PascalCase." --- -Categories: -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **Rule ID:** `MESSAGE_PASCAL_CASE` +- **Group:** `BASIC` +- **Included in presets (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` This rule checks that message names are in PascalCase. diff --git a/content/docs/cli/linter/rules/message-pascal-case.ru.mdx b/content/docs/cli/linter/rules/message-pascal-case.ru.mdx index 2303cc3..59ff607 100644 --- a/content/docs/cli/linter/rules/message-pascal-case.ru.mdx +++ b/content/docs/cli/linter/rules/message-pascal-case.ru.mdx @@ -1,17 +1,17 @@ --- title: "Message Pascal Case" +description: "Это правило проверяет, что имена сообщений (message) записаны в стиле PascalCase." --- -Категории: -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **ID правила:** `MESSAGE_PASCAL_CASE` +- **Группа:** `BASIC` +- **Входит в пресеты (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` Это правило проверяет, что имена сообщений (message) записаны в стиле PascalCase. ## Примеры -### Bad +### Неправильно ```proto syntax = "proto3"; @@ -23,7 +23,7 @@ message foo_bar { } ``` -### Good +### Правильно ```proto syntax = "proto3"; diff --git a/content/docs/cli/linter/rules/meta.json b/content/docs/cli/linter/rules/meta.json index 2cd033e..b326946 100644 --- a/content/docs/cli/linter/rules/meta.json +++ b/content/docs/cli/linter/rules/meta.json @@ -16,6 +16,7 @@ "enum-value-upper-snake-case", "enum-zero-value-suffix", "field-lower-snake-case", + "field-not-required", "file-lower-snake-case", "import-no-public", "import-no-weak", @@ -25,6 +26,7 @@ "package-defined", "package-directory-match", "package-lower-snake-case", + "package-no-import-cycle", "package-same-csharp-namespace", "package-same-directory", "package-same-go-package", @@ -41,6 +43,7 @@ "rpc-request-standard-name", "rpc-response-standard-name", "service-pascal-case", - "service-suffix" + "service-suffix", + "syntax-specified" ] } diff --git a/content/docs/cli/linter/rules/meta.ru.json b/content/docs/cli/linter/rules/meta.ru.json new file mode 100644 index 0000000..01159fa --- /dev/null +++ b/content/docs/cli/linter/rules/meta.ru.json @@ -0,0 +1,49 @@ +{ + "title": "Правила", + "pages": [ + "comment-enum", + "comment-enum-value", + "comment-field", + "comment-message", + "comment-oneof", + "comment-rpc", + "comment-service", + "directory-same-package", + "enum-first-value-zero", + "enum-no-allow-alias", + "enum-pascal-case", + "enum-value-prefix", + "enum-value-upper-snake-case", + "enum-zero-value-suffix", + "field-lower-snake-case", + "field-not-required", + "file-lower-snake-case", + "import-no-public", + "import-no-weak", + "import-used", + "message-pascal-case", + "oneof-lower-snake-case", + "package-defined", + "package-directory-match", + "package-lower-snake-case", + "package-no-import-cycle", + "package-same-csharp-namespace", + "package-same-directory", + "package-same-go-package", + "package-same-java-multiple-files", + "package-same-java-package", + "package-same-php-namespace", + "package-same-ruby-package", + "package-same-swift-prefix", + "package-version-suffix", + "rpc-no-client-streaming", + "rpc-no-server-streaming", + "rpc-pascal-case", + "rpc-request-response-unique", + "rpc-request-standard-name", + "rpc-response-standard-name", + "service-pascal-case", + "service-suffix", + "syntax-specified" + ] +} diff --git a/content/docs/cli/linter/rules/oneof-lower-snake-case.mdx b/content/docs/cli/linter/rules/oneof-lower-snake-case.mdx index 01770cb..9e7b8b8 100644 --- a/content/docs/cli/linter/rules/oneof-lower-snake-case.mdx +++ b/content/docs/cli/linter/rules/oneof-lower-snake-case.mdx @@ -1,11 +1,11 @@ --- title: "Oneof Lower Snake Case" +description: "This rule checks that oneof names are in lower_snake_case." --- -Categories: -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **Rule ID:** `ONEOF_LOWER_SNAKE_CASE` +- **Group:** `BASIC` +- **Included in presets (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` This rule checks that oneof names are in lower_snake_case. diff --git a/content/docs/cli/linter/rules/oneof-lower-snake-case.ru.mdx b/content/docs/cli/linter/rules/oneof-lower-snake-case.ru.mdx index 9b47c78..9eb1874 100644 --- a/content/docs/cli/linter/rules/oneof-lower-snake-case.ru.mdx +++ b/content/docs/cli/linter/rules/oneof-lower-snake-case.ru.mdx @@ -1,17 +1,17 @@ --- title: "Oneof Lower Snake Case" +description: "Это правило проверяет, что имена oneof записаны в стиле lower_snake_case." --- -Категории: -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **ID правила:** `ONEOF_LOWER_SNAKE_CASE` +- **Группа:** `BASIC` +- **Входит в пресеты (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` Это правило проверяет, что имена oneof записаны в стиле lower_snake_case. ## Примеры -### Bad +### Неправильно ```proto syntax = "proto3"; @@ -25,7 +25,7 @@ message Foo { } ``` -### Good +### Правильно ```proto syntax = "proto3"; diff --git a/content/docs/cli/linter/rules/package-defined.mdx b/content/docs/cli/linter/rules/package-defined.mdx index 5a715d1..f364633 100644 --- a/content/docs/cli/linter/rules/package-defined.mdx +++ b/content/docs/cli/linter/rules/package-defined.mdx @@ -1,11 +1,11 @@ --- title: "Package Defined" +description: "This rule checks that all files have a package declaration." --- -Categories: -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **Rule ID:** `PACKAGE_DEFINED` +- **Group:** `MINIMAL` +- **Included in presets (`linters.default`):** `MINIMAL`, `BASIC`, `STANDARD`, `COMMENTS` This rule checks that all files have a package declaration. diff --git a/content/docs/cli/linter/rules/package-defined.ru.mdx b/content/docs/cli/linter/rules/package-defined.ru.mdx index 4ad6219..33287a4 100644 --- a/content/docs/cli/linter/rules/package-defined.ru.mdx +++ b/content/docs/cli/linter/rules/package-defined.ru.mdx @@ -1,17 +1,17 @@ --- title: "Package Defined" +description: "Это правило проверяет, что во всех файлах присутствует директива package." --- -Категории: -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **ID правила:** `PACKAGE_DEFINED` +- **Группа:** `MINIMAL` +- **Входит в пресеты (`linters.default`):** `MINIMAL`, `BASIC`, `STANDARD`, `COMMENTS` Это правило проверяет, что во всех файлах присутствует директива package. ## Примеры -### Bad +### Неправильно ```proto syntax = "proto3"; @@ -22,7 +22,7 @@ message Foo { ``` -### Good +### Правильно ```proto syntax = "proto3"; diff --git a/content/docs/cli/linter/rules/package-directory-match.mdx b/content/docs/cli/linter/rules/package-directory-match.mdx index ad83cbc..5198c4e 100644 --- a/content/docs/cli/linter/rules/package-directory-match.mdx +++ b/content/docs/cli/linter/rules/package-directory-match.mdx @@ -1,41 +1,60 @@ --- title: "Package Directory Match" +description: "Checks that each file's package matches its module-relative directory path (or module-qualified .)." --- -Categories: -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **Rule ID:** `PACKAGE_DIRECTORY_MATCH` +- **Group:** `MINIMAL` +- **Included in presets (`linters.default`):** `MINIMAL`, `BASIC`, `STANDARD`, `COMMENTS` -This rule checks that all files are in a directory that matches their package name. +- **Rule ID:** `PACKAGE_DIRECTORY_MATCH` +- **Group:** `MINIMAL` +- **Included in presets (`linters.default`):** `MINIMAL`, `BASIC`, `STANDARD`, `COMMENTS` + +This rule checks that each `.proto` file resides in a directory matching its declared `package` (with `/` separators replaced by `.`). + +When a `protobuf.mod` manifest is present, EasyP accepts either: + +- the module-relative directory path (``, e.g. `users.v1` for `users/v1/user.proto`), or +- the module-qualified package `.` (e.g. `acme.users.v1` when `protobuf.mod` declares `module github.com/org/acme`, stripping any `/v2+` major-version suffix and `.git`). ## Examples ### Bad ```proto -// File: bar/foo.proto - +// File: bar/v1/foo.proto syntax = "proto3"; -package foo; +package foo.v1; message Foo { - string bar = 1; + string bar = 1; } - ``` ### Good ```proto -// File: bar/foo.proto +// File: bar/v1/foo.proto +syntax = "proto3"; + +package bar.v1; +message Foo { + string bar = 1; +} +``` + +With `module github.com/org/acme` in `protobuf.mod`: + +```proto +// File: bar/v1/foo.proto syntax = "proto3"; -package bar; +package acme.bar.v1; message Foo { - string bar = 1; + string bar = 1; } ``` diff --git a/content/docs/cli/linter/rules/package-directory-match.ru.mdx b/content/docs/cli/linter/rules/package-directory-match.ru.mdx index a1864d3..4e5ef35 100644 --- a/content/docs/cli/linter/rules/package-directory-match.ru.mdx +++ b/content/docs/cli/linter/rules/package-directory-match.ru.mdx @@ -1,40 +1,60 @@ --- title: "Package Directory Match" +description: "Проверяет, что пакет файла соответствует относительному пути его каталога (или форме . с префиксом модуля)." --- -Категории: -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **ID правила:** `PACKAGE_DIRECTORY_MATCH` +- **Группа:** `MINIMAL` +- **Входит в пресеты (`linters.default`):** `MINIMAL`, `BASIC`, `STANDARD`, `COMMENTS` -Это правило проверяет, что все файлы находятся в директории, имя которой соответствует имени их пакета. +- **ID правила:** `PACKAGE_DIRECTORY_MATCH` +- **Группа:** `MINIMAL` +- **Входит в пресеты (`linters.default`):** `MINIMAL`, `BASIC`, `STANDARD`, `COMMENTS` -## Examples +Это правило проверяет, что каждый `.proto`-файл находится в каталоге, путь которого соответствует объявленному `package` (с заменой `/` на `.`). -### Bad +Если в проекте есть манифест `protobuf.mod`, EasyP принимает оба варианта: -```proto -// File: bar/foo.proto +- путь каталога относительно корня модуля (``, например `users.v1` для `users/v1/user.proto`); +- квалифицированное именем модуля название `.` (например `acme.users.v1`, если в `protobuf.mod` указано `module github.com/org/acme`; суффиксы мажорной версии `/v2+` и `.git` при этом отбрасываются). + +## Примеры + +### Неправильно +```proto +// File: bar/v1/foo.proto syntax = "proto3"; -package foo; +package foo.v1; message Foo { - string bar = 1; + string bar = 1; } ``` -### Good +### Правильно ```proto -// File: bar/foo.proto +// File: bar/v1/foo.proto +syntax = "proto3"; + +package bar.v1; +message Foo { + string bar = 1; +} +``` + +При `module github.com/org/acme` в `protobuf.mod`: + +```proto +// File: bar/v1/foo.proto syntax = "proto3"; -package bar; +package acme.bar.v1; message Foo { - string bar = 1; + string bar = 1; } ``` diff --git a/content/docs/cli/linter/rules/package-lower-snake-case.mdx b/content/docs/cli/linter/rules/package-lower-snake-case.mdx index 92820b4..e6c519a 100644 --- a/content/docs/cli/linter/rules/package-lower-snake-case.mdx +++ b/content/docs/cli/linter/rules/package-lower-snake-case.mdx @@ -1,12 +1,11 @@ --- title: "Package Lower Snake Case" +description: "This rule checks that package names are in lower_snake_case." --- -Categories: - -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **Rule ID:** `PACKAGE_LOWER_SNAKE_CASE` +- **Group:** `BASIC` +- **Included in presets (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` This rule checks that package names are in lower_snake_case. diff --git a/content/docs/cli/linter/rules/package-lower-snake-case.ru.mdx b/content/docs/cli/linter/rules/package-lower-snake-case.ru.mdx index 3b6b3ba..1db79c1 100644 --- a/content/docs/cli/linter/rules/package-lower-snake-case.ru.mdx +++ b/content/docs/cli/linter/rules/package-lower-snake-case.ru.mdx @@ -1,18 +1,17 @@ --- title: "Package Lower Snake Case" +description: "Это правило проверяет, что имена package записаны в формате lower_snake_case (строчные буквы, при необходимости цифры и символ подчеркивания, без пробелов и заглавных букв)." --- -Категории: - -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **ID правила:** `PACKAGE_LOWER_SNAKE_CASE` +- **Группа:** `BASIC` +- **Входит в пресеты (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` Это правило проверяет, что имена package записаны в формате lower_snake_case (строчные буквы, при необходимости цифры и символ подчеркивания, без пробелов и заглавных букв). ## Примеры -### Bad +### Неправильно ```proto // File: bar/foo.proto @@ -21,7 +20,7 @@ syntax = "proto3"; package FooBar; ``` -### Good +### Правильно ```proto // File: bar/foo.proto diff --git a/content/docs/cli/linter/rules/package-no-import-cycle.mdx b/content/docs/cli/linter/rules/package-no-import-cycle.mdx new file mode 100644 index 0000000..79646e0 --- /dev/null +++ b/content/docs/cli/linter/rules/package-no-import-cycle.mdx @@ -0,0 +1,87 @@ +--- +title: "Package No Import Cycle" +description: "Checks that protobuf packages do not form direct or transitive import cycles." +--- + +- **Rule ID:** `PACKAGE_NO_IMPORT_CYCLE` +- **Group:** `MINIMAL` +- **Included in presets (`linters.default`):** `MINIMAL`, `BASIC`, `STANDARD`, `COMMENTS` + +- **Rule ID:** `PACKAGE_NO_IMPORT_CYCLE` +- **Group:** `MINIMAL` +- **Included in presets (`linters.default`):** `MINIMAL`, `BASIC`, `STANDARD`, `COMMENTS` + +This module-level rule checks that protobuf packages do not import each other in a cycle (directly or transitively). Imports between files within the same package are allowed. The package graph covers linted files and the packages of their direct imports, and every import leading into a cycle is reported. + +## Examples + +### Bad + +```proto +// File: foo/v1/foo.proto +syntax = "proto3"; + +package foo.v1; + +import "bar/v1/bar.proto"; + +message Foo { + bar.v1.Bar bar = 1; +} +``` + +```proto +// File: bar/v1/bar.proto +syntax = "proto3"; + +package bar.v1; + +import "foo/v1/foo.proto"; + +message Bar { + foo.v1.Foo foo = 1; +} +``` + +### Good + +Extract shared types into a common package so dependencies flow in one direction: + +```proto +// File: common/v1/types.proto +syntax = "proto3"; + +package common.v1; + +message SharedId { + string value = 1; +} +``` + +```proto +// File: foo/v1/foo.proto +syntax = "proto3"; + +package foo.v1; + +import "common/v1/types.proto"; + +message Foo { + common.v1.SharedId id = 1; +} +``` + +```proto +// File: bar/v1/bar.proto +syntax = "proto3"; + +package bar.v1; + +import "common/v1/types.proto"; +import "foo/v1/foo.proto"; + +message Bar { + common.v1.SharedId id = 1; + foo.v1.Foo foo = 2; +} +``` diff --git a/content/docs/cli/linter/rules/package-no-import-cycle.ru.mdx b/content/docs/cli/linter/rules/package-no-import-cycle.ru.mdx new file mode 100644 index 0000000..ddb2d62 --- /dev/null +++ b/content/docs/cli/linter/rules/package-no-import-cycle.ru.mdx @@ -0,0 +1,87 @@ +--- +title: "Package No Import Cycle" +description: "Проверяет отсутствие прямых и транзитивных циклических импортов между пакетами." +--- + +- **ID правила:** `PACKAGE_NO_IMPORT_CYCLE` +- **Группа:** `MINIMAL` +- **Входит в пресеты (`linters.default`):** `MINIMAL`, `BASIC`, `STANDARD`, `COMMENTS` + +- **ID правила:** `PACKAGE_NO_IMPORT_CYCLE` +- **Группа:** `MINIMAL` +- **Входит в пресеты (`linters.default`):** `MINIMAL`, `BASIC`, `STANDARD`, `COMMENTS` + +Это правило уровня модуля проверяет, что protobuf-пакеты не образуют циклических зависимостей импорта (прямых или транзитивных). Импорты между файлами внутри одного пакета допустимы. Граф строится по проверяемым файлам и пакетам их прямых импортов; сообщение об ошибке выдаётся для каждого импорта, ведущего в цикл. + +## Примеры + +### Неправильно + +```proto +// File: foo/v1/foo.proto +syntax = "proto3"; + +package foo.v1; + +import "bar/v1/bar.proto"; + +message Foo { + bar.v1.Bar bar = 1; +} +``` + +```proto +// File: bar/v1/bar.proto +syntax = "proto3"; + +package bar.v1; + +import "foo/v1/foo.proto"; + +message Bar { + foo.v1.Foo foo = 1; +} +``` + +### Правильно + +Вынесите общие типы в отдельный пакет, чтобы зависимости оставались однонаправленными: + +```proto +// File: common/v1/types.proto +syntax = "proto3"; + +package common.v1; + +message SharedId { + string value = 1; +} +``` + +```proto +// File: foo/v1/foo.proto +syntax = "proto3"; + +package foo.v1; + +import "common/v1/types.proto"; + +message Foo { + common.v1.SharedId id = 1; +} +``` + +```proto +// File: bar/v1/bar.proto +syntax = "proto3"; + +package bar.v1; + +import "common/v1/types.proto"; +import "foo/v1/foo.proto"; + +message Bar { + common.v1.SharedId id = 1; + foo.v1.Foo foo = 2; +} +``` diff --git a/content/docs/cli/linter/rules/package-same-csharp-namespace.mdx b/content/docs/cli/linter/rules/package-same-csharp-namespace.mdx index 864b9dd..5dda64e 100644 --- a/content/docs/cli/linter/rules/package-same-csharp-namespace.mdx +++ b/content/docs/cli/linter/rules/package-same-csharp-namespace.mdx @@ -1,11 +1,11 @@ --- title: "Package Same Csharp Namespace" +description: "This rule checks that all files with a given package are in the same C# namespace." --- -Categories: -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **Rule ID:** `PACKAGE_SAME_CSHARP_NAMESPACE` +- **Group:** `BASIC` +- **Included in presets (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` This rule checks that all files with a given package are in the same C# namespace. diff --git a/content/docs/cli/linter/rules/package-same-csharp-namespace.ru.mdx b/content/docs/cli/linter/rules/package-same-csharp-namespace.ru.mdx index 0d6158b..5288944 100644 --- a/content/docs/cli/linter/rules/package-same-csharp-namespace.ru.mdx +++ b/content/docs/cli/linter/rules/package-same-csharp-namespace.ru.mdx @@ -1,17 +1,17 @@ --- title: "Package Same Csharp Namespace" +description: "Это правило проверяет, что все файлы с заданным пакетом используют одно и то же пространство имён C# (csharp_namespace)." --- -Категории: -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **ID правила:** `PACKAGE_SAME_CSHARP_NAMESPACE` +- **Группа:** `BASIC` +- **Входит в пресеты (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` Это правило проверяет, что все файлы с заданным пакетом используют одно и то же пространство имён C# (`csharp_namespace`). ## Примеры -### Bad +### Неправильно ```proto // File: pkg/foo.proto @@ -33,7 +33,7 @@ package pkg; option csharp_namespace = "Foo.Baz"; ``` -### Good +### Правильно ```proto // File: pkg/foo.proto diff --git a/content/docs/cli/linter/rules/package-same-directory.mdx b/content/docs/cli/linter/rules/package-same-directory.mdx index e9507d0..970ca73 100644 --- a/content/docs/cli/linter/rules/package-same-directory.mdx +++ b/content/docs/cli/linter/rules/package-same-directory.mdx @@ -1,42 +1,64 @@ --- title: "Package Same Directory" +description: "Checks that all .proto files sharing a package are located in the same directory." --- -Categories: -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **Rule ID:** `PACKAGE_SAME_DIRECTORY` +- **Group:** `MINIMAL` +- **Included in presets (`linters.default`):** `MINIMAL`, `BASIC`, `STANDARD`, `COMMENTS` -This rule checks that all files with a given package are in the same directory. +- **Rule ID:** `PACKAGE_SAME_DIRECTORY` +- **Group:** `MINIMAL` +- **Included in presets (`linters.default`):** `MINIMAL`, `BASIC`, `STANDARD`, `COMMENTS` + +This module-level rule checks that all `.proto` files declaring the same `package` live in the same directory. If a package is split across multiple directories, every file in that package is reported. ## Examples ### Bad ```proto -// File: bar/foo.proto - +// File: foo/v1/user.proto syntax = "proto3"; -package foo; +package foo.v1; -message Foo { - string bar = 1; +message User { + string id = 1; } +``` + +```proto +// File: bar/v1/order.proto +syntax = "proto3"; +package foo.v1; + +message Order { + string id = 1; +} ``` ### Good ```proto -// File: bar/foo.proto - +// File: foo/v1/user.proto syntax = "proto3"; -package bar; +package foo.v1; -message Foo { - string bar = 1; +message User { + string id = 1; } +``` +```proto +// File: foo/v1/order.proto +syntax = "proto3"; + +package foo.v1; + +message Order { + string id = 1; +} ``` diff --git a/content/docs/cli/linter/rules/package-same-directory.ru.mdx b/content/docs/cli/linter/rules/package-same-directory.ru.mdx index 010f112..07cc535 100644 --- a/content/docs/cli/linter/rules/package-same-directory.ru.mdx +++ b/content/docs/cli/linter/rules/package-same-directory.ru.mdx @@ -1,40 +1,64 @@ --- title: "Package Same Directory" +description: "Проверяет, что все .proto-файлы одного пакета находятся в одном каталоге." --- -Категории: -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **ID правила:** `PACKAGE_SAME_DIRECTORY` +- **Группа:** `MINIMAL` +- **Входит в пресеты (`linters.default`):** `MINIMAL`, `BASIC`, `STANDARD`, `COMMENTS` -Это правило проверяет, что все файлы с данным package находятся в одной директории. +- **ID правила:** `PACKAGE_SAME_DIRECTORY` +- **Группа:** `MINIMAL` +- **Входит в пресеты (`linters.default`):** `MINIMAL`, `BASIC`, `STANDARD`, `COMMENTS` -## Examples +Это правило уровня модуля проверяет, что все `.proto`-файлы с одинаковым `package` расположены в одном каталоге. Если один пакет разнесён по нескольким каталогам, ошибка выдаётся для каждого файла этого пакета. -### Bad +## Примеры + +### Неправильно ```proto -// File: bar/foo.proto +// File: foo/v1/user.proto +syntax = "proto3"; +package foo.v1; + +message User { + string id = 1; +} +``` + +```proto +// File: bar/v1/order.proto syntax = "proto3"; -package foo; +package foo.v1; -message Foo { - string bar = 1; +message Order { + string id = 1; } ``` -### Good +### Правильно ```proto -// File: bar/foo.proto +// File: foo/v1/user.proto +syntax = "proto3"; + +package foo.v1; + +message User { + string id = 1; +} +``` +```proto +// File: foo/v1/order.proto syntax = "proto3"; -package bar; +package foo.v1; -message Foo { - string bar = 1; +message Order { + string id = 1; } ``` diff --git a/content/docs/cli/linter/rules/package-same-go-package.mdx b/content/docs/cli/linter/rules/package-same-go-package.mdx index ae5c604..5b607c6 100644 --- a/content/docs/cli/linter/rules/package-same-go-package.mdx +++ b/content/docs/cli/linter/rules/package-same-go-package.mdx @@ -1,11 +1,11 @@ --- title: "Package Same Go Package" +description: "This rule checks that all files with a given package are in the same Go package." --- -Categories: -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **Rule ID:** `PACKAGE_SAME_GO_PACKAGE` +- **Group:** `BASIC` +- **Included in presets (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` This rule checks that all files with a given package are in the same Go package. diff --git a/content/docs/cli/linter/rules/package-same-go-package.ru.mdx b/content/docs/cli/linter/rules/package-same-go-package.ru.mdx index 46c871a..b9dbe0c 100644 --- a/content/docs/cli/linter/rules/package-same-go-package.ru.mdx +++ b/content/docs/cli/linter/rules/package-same-go-package.ru.mdx @@ -1,17 +1,17 @@ --- title: "Package Same Go Package" +description: "Это правило проверяет, что все файлы с одним и тем же package используют одно и то же значение опции go_package." --- -Категории: -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **ID правила:** `PACKAGE_SAME_GO_PACKAGE` +- **Группа:** `BASIC` +- **Входит в пресеты (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` Это правило проверяет, что все файлы с одним и тем же package используют одно и то же значение опции `go_package`. ## Примеры -### Bad +### Неправильно ```proto // File: pkg/foo.proto @@ -33,7 +33,7 @@ package pkg; option go_package = "example.com/foo/baz"; ``` -### Good +### Правильно ```proto // File: pkg/foo.proto diff --git a/content/docs/cli/linter/rules/package-same-java-multiple-files.mdx b/content/docs/cli/linter/rules/package-same-java-multiple-files.mdx index 41a40e2..370e96a 100644 --- a/content/docs/cli/linter/rules/package-same-java-multiple-files.mdx +++ b/content/docs/cli/linter/rules/package-same-java-multiple-files.mdx @@ -1,13 +1,17 @@ --- title: "Package Same Java Multiple Files" +description: "Checks that all files in the same package set option java_multiple_files to the same value." --- -Categories: -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **Rule ID:** `PACKAGE_SAME_JAVA_MULTIPLE_FILES` +- **Group:** `BASIC` +- **Included in presets (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` -This rule checks that all files with a given package are in the same Java package. +- **Rule ID:** `PACKAGE_SAME_JAVA_MULTIPLE_FILES` +- **Group:** `BASIC` +- **Included in presets (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` + +This module-level rule checks that all files sharing the same protobuf `package` set `option java_multiple_files` to the same boolean value. A file that omits `option java_multiple_files` is treated as having a distinct value from files that set it explicitly; every file in a disagreeing package is reported. ## Examples @@ -15,43 +19,38 @@ This rule checks that all files with a given package are in the same Java packag ```proto // File: pkg/foo.proto - syntax = "proto3"; package pkg; -option java_package = "com.example.foo"; +option java_multiple_files = true; ``` ```proto - // File: pkg/bar.proto - syntax = "proto3"; package pkg; -option java_package = "com.example.bar"; +option java_multiple_files = false; ``` ### Good ```proto // File: pkg/foo.proto - syntax = "proto3"; package pkg; -option java_package = "com.example.foo"; +option java_multiple_files = true; ``` ```proto // File: pkg/bar.proto - syntax = "proto3"; package pkg; -option java_package = "com.example.foo"; +option java_multiple_files = true; ``` diff --git a/content/docs/cli/linter/rules/package-same-java-multiple-files.ru.mdx b/content/docs/cli/linter/rules/package-same-java-multiple-files.ru.mdx index b7fb299..b4e498f 100644 --- a/content/docs/cli/linter/rules/package-same-java-multiple-files.ru.mdx +++ b/content/docs/cli/linter/rules/package-same-java-multiple-files.ru.mdx @@ -1,56 +1,56 @@ --- title: "Package Same Java Multiple Files" +description: "Проверяет, что все файлы одного пакета задают одинаковое значение option java_multiple_files." --- -Категории: -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **ID правила:** `PACKAGE_SAME_JAVA_MULTIPLE_FILES` +- **Группа:** `BASIC` +- **Входит в пресеты (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` -Это правило проверяет, что все файлы с одним и тем же `package` используют одинаковое значение опции `java_package`. +- **ID правила:** `PACKAGE_SAME_JAVA_MULTIPLE_FILES` +- **Группа:** `BASIC` +- **Входит в пресеты (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` -## Examples +Это правило уровня модуля проверяет, что все файлы с одинаковым `package` задают одинаковое булево значение `option java_multiple_files`. Файл без этой опции считается отличным от файлов с явно заданной опцией; при расхождении ошибка выдаётся для каждого файла пакета. -### Bad +## Примеры + +### Неправильно ```proto // File: pkg/foo.proto - syntax = "proto3"; package pkg; -option java_package = "com.example.foo"; +option java_multiple_files = true; ``` ```proto // File: pkg/bar.proto - syntax = "proto3"; package pkg; -option java_package = "com.example.bar"; +option java_multiple_files = false; ``` -### Good +### Правильно ```proto // File: pkg/foo.proto - syntax = "proto3"; package pkg; -option java_package = "com.example.foo"; +option java_multiple_files = true; ``` ```proto // File: pkg/bar.proto - syntax = "proto3"; package pkg; -option java_package = "com.example.foo"; +option java_multiple_files = true; ``` diff --git a/content/docs/cli/linter/rules/package-same-java-package.mdx b/content/docs/cli/linter/rules/package-same-java-package.mdx index 9611a68..a6baa4d 100644 --- a/content/docs/cli/linter/rules/package-same-java-package.mdx +++ b/content/docs/cli/linter/rules/package-same-java-package.mdx @@ -1,12 +1,11 @@ --- title: "Package Same Java Package" +description: "This rule checks that all files with a given package are in the same Java package." --- -Categories: - -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **Rule ID:** `PACKAGE_SAME_JAVA_PACKAGE` +- **Group:** `BASIC` +- **Included in presets (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` This rule checks that all files with a given package are in the same Java package. diff --git a/content/docs/cli/linter/rules/package-same-java-package.ru.mdx b/content/docs/cli/linter/rules/package-same-java-package.ru.mdx index 9c91f1f..f26b527 100644 --- a/content/docs/cli/linter/rules/package-same-java-package.ru.mdx +++ b/content/docs/cli/linter/rules/package-same-java-package.ru.mdx @@ -1,18 +1,17 @@ --- title: "Package Same Java Package" +description: "Это правило проверяет, что все файлы с одним и тем же package используют одно и то же значение опции java_package." --- -Категории: - -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **ID правила:** `PACKAGE_SAME_JAVA_PACKAGE` +- **Группа:** `BASIC` +- **Входит в пресеты (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` Это правило проверяет, что все файлы с одним и тем же `package` используют одно и то же значение опции `java_package`. -## Examples +## Примеры -### Bad +### Неправильно ```proto // File: pkg/foo.proto @@ -34,7 +33,7 @@ package pkg; option java_package = "com.example.bar"; ``` -### Good +### Правильно ```proto // File: pkg/foo.proto diff --git a/content/docs/cli/linter/rules/package-same-php-namespace.mdx b/content/docs/cli/linter/rules/package-same-php-namespace.mdx index 065dc79..d9e0071 100644 --- a/content/docs/cli/linter/rules/package-same-php-namespace.mdx +++ b/content/docs/cli/linter/rules/package-same-php-namespace.mdx @@ -1,12 +1,11 @@ --- title: "Package Same Php Namespace" +description: "This rule checks that all files with a given package are in the same PHP namespace." --- -Categories: - -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **Rule ID:** `PACKAGE_SAME_PHP_NAMESPACE` +- **Group:** `BASIC` +- **Included in presets (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` This rule checks that all files with a given package are in the same PHP namespace. diff --git a/content/docs/cli/linter/rules/package-same-php-namespace.ru.mdx b/content/docs/cli/linter/rules/package-same-php-namespace.ru.mdx index 502da33..a839cef 100644 --- a/content/docs/cli/linter/rules/package-same-php-namespace.ru.mdx +++ b/content/docs/cli/linter/rules/package-same-php-namespace.ru.mdx @@ -1,18 +1,17 @@ --- title: "Package Same Php Namespace" +description: "Это правило проверяет, что все файлы с одним и тем же package используют одно и то же значение опции php_namespace." --- -Категории: - -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **ID правила:** `PACKAGE_SAME_PHP_NAMESPACE` +- **Группа:** `BASIC` +- **Входит в пресеты (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` Это правило проверяет, что все файлы с одним и тем же `package` используют одно и то же значение опции `php_namespace`. ## Примеры -### Bad +### Неправильно ```proto // File: pkg/foo.proto @@ -34,7 +33,7 @@ package pkg; option php_namespace = "Foo\\Baz"; ``` -### Good +### Правильно ```proto // File: pkg/foo.proto diff --git a/content/docs/cli/linter/rules/package-same-ruby-package.mdx b/content/docs/cli/linter/rules/package-same-ruby-package.mdx index 4d51e7d..cf5612d 100644 --- a/content/docs/cli/linter/rules/package-same-ruby-package.mdx +++ b/content/docs/cli/linter/rules/package-same-ruby-package.mdx @@ -1,12 +1,11 @@ --- title: "Package Same Ruby Package" +description: "This rule checks that all files with a given package are in the same Ruby package." --- -Categories: - -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **Rule ID:** `PACKAGE_SAME_RUBY_PACKAGE` +- **Group:** `BASIC` +- **Included in presets (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` This rule checks that all files with a given package are in the same Ruby package. diff --git a/content/docs/cli/linter/rules/package-same-ruby-package.ru.mdx b/content/docs/cli/linter/rules/package-same-ruby-package.ru.mdx index 4d51e7d..eaea8af 100644 --- a/content/docs/cli/linter/rules/package-same-ruby-package.ru.mdx +++ b/content/docs/cli/linter/rules/package-same-ruby-package.ru.mdx @@ -1,22 +1,24 @@ --- title: "Package Same Ruby Package" +description: "Проверяет, что все файлы одного пакета задают одинаковое значение option ruby_package." --- -Categories: +- **ID правила:** `PACKAGE_SAME_RUBY_PACKAGE` +- **Группа:** `BASIC` +- **Входит в пресеты (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **ID правила:** `PACKAGE_SAME_RUBY_PACKAGE` +- **Группа:** `BASIC` +- **Входит в пресеты (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` -This rule checks that all files with a given package are in the same Ruby package. +Это правило уровня модуля проверяет, что все файлы с одинаковым `package` задают одинаковое значение опции `ruby_package`. -## Examples +## Примеры -### Bad +### Неправильно ```proto // File: pkg/foo.proto - syntax = "proto3"; package pkg; @@ -26,7 +28,6 @@ option ruby_package = "Foo"; ```proto // File: pkg/bar.proto - syntax = "proto3"; package pkg; @@ -34,11 +35,10 @@ package pkg; option ruby_package = "Bar"; ``` -### Good +### Правильно ```proto // File: pkg/foo.proto - syntax = "proto3"; package pkg; @@ -48,7 +48,6 @@ option ruby_package = "Foo"; ```proto // File: pkg/bar.proto - syntax = "proto3"; package pkg; diff --git a/content/docs/cli/linter/rules/package-same-swift-prefix.mdx b/content/docs/cli/linter/rules/package-same-swift-prefix.mdx index c31cd35..11f3bad 100644 --- a/content/docs/cli/linter/rules/package-same-swift-prefix.mdx +++ b/content/docs/cli/linter/rules/package-same-swift-prefix.mdx @@ -1,12 +1,11 @@ --- title: "Package Same Swift Prefix" +description: "This rule checks that all files with a given package are in the same Swift prefix." --- -Categories: - -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **Rule ID:** `PACKAGE_SAME_SWIFT_PREFIX` +- **Group:** `BASIC` +- **Included in presets (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` This rule checks that all files with a given package are in the same Swift prefix. diff --git a/content/docs/cli/linter/rules/package-same-swift-prefix.ru.mdx b/content/docs/cli/linter/rules/package-same-swift-prefix.ru.mdx index 9dfdc23..dea20aa 100644 --- a/content/docs/cli/linter/rules/package-same-swift-prefix.ru.mdx +++ b/content/docs/cli/linter/rules/package-same-swift-prefix.ru.mdx @@ -1,18 +1,17 @@ --- title: "Package Same Swift Prefix" +description: "Это правило проверяет, что все файлы с одним и тем же package используют один и тот же swift_prefix." --- -Категории: - -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **ID правила:** `PACKAGE_SAME_SWIFT_PREFIX` +- **Группа:** `BASIC` +- **Входит в пресеты (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` Это правило проверяет, что все файлы с одним и тем же package используют один и тот же `swift_prefix`. -## Examples +## Примеры -### Bad +### Неправильно ```proto // File: pkg/foo.proto @@ -34,7 +33,7 @@ package pkg; option swift_prefix = "Bar"; ``` -### Good +### Правильно ```proto // File: pkg/foo.proto diff --git a/content/docs/cli/linter/rules/package-version-suffix.mdx b/content/docs/cli/linter/rules/package-version-suffix.mdx index 1290955..1fc5644 100644 --- a/content/docs/cli/linter/rules/package-version-suffix.mdx +++ b/content/docs/cli/linter/rules/package-version-suffix.mdx @@ -1,14 +1,24 @@ --- title: "Package Version Suffix" +description: "Checks that the last dot-separated package component is a valid version suffix such as v1 or v1beta1." --- -Categories: +- **Rule ID:** `PACKAGE_VERSION_SUFFIX` +- **Group:** `DEFAULT` +- **Included in presets (`linters.default`):** `STANDARD`, `COMMENTS` -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **Rule ID:** `PACKAGE_VERSION_SUFFIX` +- **Group:** `DEFAULT` +- **Included in presets (`linters.default`):** `STANDARD`, `COMMENTS` -This rule checks that the package version suffix is `_vX` where `X` is a number of version. +This rule checks that the package name has at least two dot-separated components and that its last component is a valid version suffix: + +- `vN` (for example, `foo.v1`, `acme.users.v2`) +- `vNalpha`, `vNalphaM`, `vNbeta`, `vNbetaM` (for example, `foo.v1alpha1`, `foo.v1beta2`) +- `vNpMalpha`, `vNpMalphaK`, `vNpMbeta`, `vNpMbetaK` (for example, `foo.v1p1alpha1`, `foo.v1p1beta1`) +- `vNtest...` (for example, `foo.v1test`, `foo.v1testfoo`) + +All version numbers (`N`, `M`, `K`) must be integers `>= 1`. Underscore-delimited suffixes like `_v1` or single-component packages like `v1` are rejected. ## Examples @@ -17,7 +27,25 @@ This rule checks that the package version suffix is `_vX` where `X` is a number ```proto syntax = "proto3"; -package foo; +package foo; +``` + +```proto +syntax = "proto3"; + +package foo_v1; +``` + +```proto +syntax = "proto3"; + +package v1; +``` + +```proto +syntax = "proto3"; + +package foo.v0; ``` ### Good @@ -27,3 +55,21 @@ syntax = "proto3"; package foo.v1; ``` + +```proto +syntax = "proto3"; + +package foo.v1beta1; +``` + +```proto +syntax = "proto3"; + +package foo.v1p1alpha1; +``` + +```proto +syntax = "proto3"; + +package foo.v1test; +``` diff --git a/content/docs/cli/linter/rules/package-version-suffix.ru.mdx b/content/docs/cli/linter/rules/package-version-suffix.ru.mdx index f504b7c..1842266 100644 --- a/content/docs/cli/linter/rules/package-version-suffix.ru.mdx +++ b/content/docs/cli/linter/rules/package-version-suffix.ru.mdx @@ -1,18 +1,28 @@ --- title: "Package Version Suffix" +description: "Проверяет, что последний сегмент имени пакета через точку является корректным суффиксом версии (например, v1 или v1beta1)." --- -Категории: +- **ID правила:** `PACKAGE_VERSION_SUFFIX` +- **Группа:** `DEFAULT` +- **Входит в пресеты (`linters.default`):** `STANDARD`, `COMMENTS` -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **ID правила:** `PACKAGE_VERSION_SUFFIX` +- **Группа:** `DEFAULT` +- **Входит в пресеты (`linters.default`):** `STANDARD`, `COMMENTS` -Это правило проверяет, что суффикс версии пакета имеет формат `_vX`, где `X` — числовая версия. +Это правило проверяет, что имя пакета состоит минимум из двух сегментов, разделённых точкой, а последний сегмент является корректным версионным суффиксом: + +- `vN` (например, `foo.v1`, `acme.users.v2`) +- `vNalpha`, `vNalphaM`, `vNbeta`, `vNbetaM` (например, `foo.v1alpha1`, `foo.v1beta2`) +- `vNpMalpha`, `vNpMalphaK`, `vNpMbeta`, `vNpMbetaK` (например, `foo.v1p1alpha1`, `foo.v1p1beta1`) +- `vNtest...` (например, `foo.v1test`, `foo.v1testfoo`) + +Все номера версий (`N`, `M`, `K`) должны быть целыми числами `>= 1`. Суффиксы через подчёркивание вроде `_v1` и односегментные пакеты вроде `v1` отклоняются. ## Примеры -### Bad +### Неправильно ```proto syntax = "proto3"; @@ -20,10 +30,46 @@ syntax = "proto3"; package foo; ``` -### Good +```proto +syntax = "proto3"; + +package foo_v1; +``` + +```proto +syntax = "proto3"; + +package v1; +``` + +```proto +syntax = "proto3"; + +package foo.v0; +``` + +### Правильно ```proto syntax = "proto3"; package foo.v1; ``` + +```proto +syntax = "proto3"; + +package foo.v1beta1; +``` + +```proto +syntax = "proto3"; + +package foo.v1p1alpha1; +``` + +```proto +syntax = "proto3"; + +package foo.v1test; +``` diff --git a/content/docs/cli/linter/rules/rpc-no-client-streaming.mdx b/content/docs/cli/linter/rules/rpc-no-client-streaming.mdx index fbfcbbf..b46ed7c 100644 --- a/content/docs/cli/linter/rules/rpc-no-client-streaming.mdx +++ b/content/docs/cli/linter/rules/rpc-no-client-streaming.mdx @@ -1,10 +1,11 @@ --- title: "Rpc No Client Streaming" +description: "This rule checks that rpc has no client streaming." --- -Categories: - -- **UNARY_RPC** +- **Rule ID:** `RPC_NO_CLIENT_STREAMING` +- **Group:** `UNARY_RPC` +- **Included in presets (`linters.default`):** None (opt-in via `linters.enable`) This rule checks that rpc has no client streaming. diff --git a/content/docs/cli/linter/rules/rpc-no-client-streaming.ru.mdx b/content/docs/cli/linter/rules/rpc-no-client-streaming.ru.mdx index 4415f6f..0b56c03 100644 --- a/content/docs/cli/linter/rules/rpc-no-client-streaming.ru.mdx +++ b/content/docs/cli/linter/rules/rpc-no-client-streaming.ru.mdx @@ -1,16 +1,17 @@ --- title: "Rpc No Client Streaming" +description: "Это правило проверяет, что RPC не использует клиентский стриминг (запрос не является stream ...)." --- -Категории: - -- **UNARY_RPC** +- **ID правила:** `RPC_NO_CLIENT_STREAMING` +- **Группа:** `UNARY_RPC` +- **Входит в пресеты (`linters.default`):** Нет (подключается через `linters.enable`) Это правило проверяет, что RPC не использует клиентский стриминг (запрос не является `stream ...`). ## Примеры -### Bad +### Неправильно ```proto syntax = "proto3"; @@ -20,7 +21,7 @@ service Foo { } ``` -### Good +### Правильно ```proto syntax = "proto3"; diff --git a/content/docs/cli/linter/rules/rpc-no-server-streaming.mdx b/content/docs/cli/linter/rules/rpc-no-server-streaming.mdx index 0555260..34babec 100644 --- a/content/docs/cli/linter/rules/rpc-no-server-streaming.mdx +++ b/content/docs/cli/linter/rules/rpc-no-server-streaming.mdx @@ -1,10 +1,11 @@ --- title: "Rpc No Server Streaming" +description: "This rule checks that rpc has no server streaming." --- -Categories: - -- **UNARY_RPC** +- **Rule ID:** `RPC_NO_SERVER_STREAMING` +- **Group:** `UNARY_RPC` +- **Included in presets (`linters.default`):** None (opt-in via `linters.enable`) This rule checks that rpc has no server streaming. diff --git a/content/docs/cli/linter/rules/rpc-no-server-streaming.ru.mdx b/content/docs/cli/linter/rules/rpc-no-server-streaming.ru.mdx index ecc13c9..56da9a1 100644 --- a/content/docs/cli/linter/rules/rpc-no-server-streaming.ru.mdx +++ b/content/docs/cli/linter/rules/rpc-no-server-streaming.ru.mdx @@ -1,16 +1,17 @@ --- title: "Rpc No Server Streaming" +description: "Это правило проверяет, что RPC не использует серверный стриминг (ответ не является stream ...)." --- -Категории: - -- **UNARY_RPC** +- **ID правила:** `RPC_NO_SERVER_STREAMING` +- **Группа:** `UNARY_RPC` +- **Входит в пресеты (`linters.default`):** Нет (подключается через `linters.enable`) Это правило проверяет, что RPC не использует серверный стриминг (ответ не является `stream ...`). ## Примеры -### Bad +### Неправильно ```proto syntax = "proto3"; @@ -20,7 +21,7 @@ service Foo { } ``` -### Good +### Правильно ```proto syntax = "proto3"; diff --git a/content/docs/cli/linter/rules/rpc-pascal-case.mdx b/content/docs/cli/linter/rules/rpc-pascal-case.mdx index cd20b52..eafd376 100644 --- a/content/docs/cli/linter/rules/rpc-pascal-case.mdx +++ b/content/docs/cli/linter/rules/rpc-pascal-case.mdx @@ -1,12 +1,11 @@ --- title: "Rpc Pascal Case" +description: "This rule checks that all RPC names are in PascalCase." --- -Categories: - -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **Rule ID:** `RPC_PASCAL_CASE` +- **Group:** `BASIC` +- **Included in presets (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` This rule checks that all RPC names are in PascalCase. diff --git a/content/docs/cli/linter/rules/rpc-pascal-case.ru.mdx b/content/docs/cli/linter/rules/rpc-pascal-case.ru.mdx index f04d9e6..4877493 100644 --- a/content/docs/cli/linter/rules/rpc-pascal-case.ru.mdx +++ b/content/docs/cli/linter/rules/rpc-pascal-case.ru.mdx @@ -1,18 +1,17 @@ --- title: "Rpc Pascal Case" +description: "Это правило проверяет, что все имена RPC написаны в стиле PascalCase." --- -Категории: - -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **ID правила:** `RPC_PASCAL_CASE` +- **Группа:** `BASIC` +- **Входит в пресеты (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` Это правило проверяет, что все имена RPC написаны в стиле PascalCase. ## Примеры -### Bad +### Неправильно ```proto syntax = "proto3"; @@ -22,7 +21,7 @@ service foo_bar { } ``` -### Good +### Правильно ```proto syntax = "proto3"; diff --git a/content/docs/cli/linter/rules/rpc-request-response-unique.mdx b/content/docs/cli/linter/rules/rpc-request-response-unique.mdx index 0531a3f..5363663 100644 --- a/content/docs/cli/linter/rules/rpc-request-response-unique.mdx +++ b/content/docs/cli/linter/rules/rpc-request-response-unique.mdx @@ -1,14 +1,20 @@ --- title: "Rpc Request Response Unique" +description: "Checks that every RPC request and response type is unique across all linted RPCs and not reused for both request and response." --- -Categories: +- **Rule ID:** `RPC_REQUEST_RESPONSE_UNIQUE` +- **Group:** `DEFAULT` +- **Included in presets (`linters.default`):** `STANDARD`, `COMMENTS` -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **Rule ID:** `RPC_REQUEST_RESPONSE_UNIQUE` +- **Group:** `DEFAULT` +- **Included in presets (`linters.default`):** `STANDARD`, `COMMENTS` -This rule checks that all RPC request and response messages are unique. +This module-level rule checks two constraints across all linted files: + +- No request or response message type may be reused by more than one RPC (even across different services or files). +- No single RPC may use the same message type for both its request and its response. ## Examples @@ -17,9 +23,13 @@ This rule checks that all RPC request and response messages are unique. ```proto syntax = "proto3"; -service Foo { - rpc GetFoo (FooRequest) returns (FooResponse) {} - rpc GetBar (FooRequest) returns (FooResponse) {} +service FooService { + // Reused request/response types across RPCs: + rpc GetFoo(FooRequest) returns (FooResponse) {} + rpc GetBar(FooRequest) returns (BarResponse) {} + + // Same type used for both request and response: + rpc Ping(PingPayload) returns (PingPayload) {} } ``` @@ -28,8 +38,9 @@ service Foo { ```proto syntax = "proto3"; -service Foo { - rpc GetFoo (FooRequest) returns (FooResponse) {} - rpc GetBar (BarRequest) returns (BarResponse) {} +service FooService { + rpc GetFoo(GetFooRequest) returns (GetFooResponse) {} + rpc GetBar(GetBarRequest) returns (GetBarResponse) {} + rpc Ping(PingRequest) returns (PingResponse) {} } ``` diff --git a/content/docs/cli/linter/rules/rpc-request-response-unique.ru.mdx b/content/docs/cli/linter/rules/rpc-request-response-unique.ru.mdx index 41a751b..22bd7c4 100644 --- a/content/docs/cli/linter/rules/rpc-request-response-unique.ru.mdx +++ b/content/docs/cli/linter/rules/rpc-request-response-unique.ru.mdx @@ -1,35 +1,46 @@ --- title: "Rpc Request Response Unique" +description: "Проверяет, что каждый тип запроса и ответа RPC уникален среди всех RPC и не используется одновременно как запрос и ответ." --- -Категории: +- **ID правила:** `RPC_REQUEST_RESPONSE_UNIQUE` +- **Группа:** `DEFAULT` +- **Входит в пресеты (`linters.default`):** `STANDARD`, `COMMENTS` -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **ID правила:** `RPC_REQUEST_RESPONSE_UNIQUE` +- **Группа:** `DEFAULT` +- **Входит в пресеты (`linters.default`):** `STANDARD`, `COMMENTS` -Это правило проверяет, что все сообщения запроса и ответа RPC уникальны: для каждого метода используются собственные (не переиспользуются одинаковые пары `Request` / `Response` у разных RPC). +Это правило уровня модуля проверяет два требования по всем проверяемым файлам: + +- Ни один тип сообщения запроса или ответа не должен повторно использоваться более чем в одном RPC (в том числе в разных сервисах или файлах). +- Один и тот же RPC не должен использовать один и тот же тип сообщения одновременно для запроса и для ответа. ## Примеры -### Bad +### Неправильно ```proto syntax = "proto3"; -service Foo { - rpc GetFoo (FooRequest) returns (FooResponse) {} - rpc GetBar (FooRequest) returns (FooResponse) {} +service FooService { + // Повторное использование типа запроса между RPC: + rpc GetFoo(FooRequest) returns (FooResponse) {} + rpc GetBar(FooRequest) returns (BarResponse) {} + + // Один и тот же тип для запроса и ответа: + rpc Ping(PingPayload) returns (PingPayload) {} } ``` -### Good +### Правильно ```proto syntax = "proto3"; -service Foo { - rpc GetFoo (FooRequest) returns (FooResponse) {} - rpc GetBar (BarRequest) returns (BarResponse) {} +service FooService { + rpc GetFoo(GetFooRequest) returns (GetFooResponse) {} + rpc GetBar(GetBarRequest) returns (GetBarResponse) {} + rpc Ping(PingRequest) returns (PingResponse) {} } ``` diff --git a/content/docs/cli/linter/rules/rpc-request-standard-name.mdx b/content/docs/cli/linter/rules/rpc-request-standard-name.mdx index 6c28b3a..11ce4f4 100644 --- a/content/docs/cli/linter/rules/rpc-request-standard-name.mdx +++ b/content/docs/cli/linter/rules/rpc-request-standard-name.mdx @@ -1,13 +1,17 @@ --- title: "Rpc Request Standard Name" +description: "Checks that RPC request messages are named Request or Request." --- -Categories: -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **Rule ID:** `RPC_REQUEST_STANDARD_NAME` +- **Group:** `DEFAULT` +- **Included in presets (`linters.default`):** `STANDARD`, `COMMENTS` -This rule checks that all RPC request messages are named `MethodRequest`. +- **Rule ID:** `RPC_REQUEST_STANDARD_NAME` +- **Group:** `DEFAULT` +- **Included in presets (`linters.default`):** `STANDARD`, `COMMENTS` + +This rule checks that every RPC request message name follows either `Request` or `Request` (using PascalCase for both the service and RPC names). ## Examples @@ -16,8 +20,8 @@ This rule checks that all RPC request messages are named `MethodRequest`. ```proto syntax = "proto3"; -service Foo { - rpc GetFoo (FooRequest) returns (FooResponse) {} +service FooService { + rpc GetFoo(FooRequest) returns (GetFooResponse) {} } ``` @@ -26,7 +30,8 @@ service Foo { ```proto syntax = "proto3"; -service Foo { - rpc GetFoo (GetFooRequest) returns (FooResponse) {} +service FooService { + rpc GetFoo(GetFooRequest) returns (GetFooResponse) {} + rpc ListFoos(FooServiceListFoosRequest) returns (FooServiceListFoosResponse) {} } ``` diff --git a/content/docs/cli/linter/rules/rpc-request-standard-name.ru.mdx b/content/docs/cli/linter/rules/rpc-request-standard-name.ru.mdx index bc5e898..3398cd2 100644 --- a/content/docs/cli/linter/rules/rpc-request-standard-name.ru.mdx +++ b/content/docs/cli/linter/rules/rpc-request-standard-name.ru.mdx @@ -1,32 +1,37 @@ --- title: "Rpc Request Standard Name" +description: "Проверяет, что сообщения запросов RPC имеют имя Request или Request." --- -Категории: -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **ID правила:** `RPC_REQUEST_STANDARD_NAME` +- **Группа:** `DEFAULT` +- **Входит в пресеты (`linters.default`):** `STANDARD`, `COMMENTS` -Это правило проверяет, что все сообщения запроса RPC названы в формате `MethodRequest`. +- **ID правила:** `RPC_REQUEST_STANDARD_NAME` +- **Группа:** `DEFAULT` +- **Входит в пресеты (`linters.default`):** `STANDARD`, `COMMENTS` + +Это правило проверяет, что имя сообщения запроса каждого RPC соответствует шаблону `Request` или `Request` (в PascalCase для имени сервиса и метода). ## Примеры -### Bad +### Неправильно ```proto syntax = "proto3"; -service Foo { - rpc GetFoo (FooRequest) returns (FooResponse) {} +service FooService { + rpc GetFoo(FooRequest) returns (GetFooResponse) {} } ``` -### Good +### Правильно ```proto syntax = "proto3"; -service Foo { - rpc GetFoo (GetFooRequest) returns (FooResponse) {} +service FooService { + rpc GetFoo(GetFooRequest) returns (GetFooResponse) {} + rpc ListFoos(FooServiceListFoosRequest) returns (FooServiceListFoosResponse) {} } ``` diff --git a/content/docs/cli/linter/rules/rpc-response-standard-name.mdx b/content/docs/cli/linter/rules/rpc-response-standard-name.mdx index e26b2f3..acf2d5f 100644 --- a/content/docs/cli/linter/rules/rpc-response-standard-name.mdx +++ b/content/docs/cli/linter/rules/rpc-response-standard-name.mdx @@ -1,14 +1,17 @@ --- title: "Rpc Response Standard Name" +description: "Checks that RPC response messages are named Response or Response." --- -Categories: +- **Rule ID:** `RPC_RESPONSE_STANDARD_NAME` +- **Group:** `DEFAULT` +- **Included in presets (`linters.default`):** `STANDARD`, `COMMENTS` -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **Rule ID:** `RPC_RESPONSE_STANDARD_NAME` +- **Group:** `DEFAULT` +- **Included in presets (`linters.default`):** `STANDARD`, `COMMENTS` -This rule checks that all RPC response messages are named `MethodResponse`. +This rule checks that every RPC response message name follows either `Response` or `Response` (using PascalCase for both the service and RPC names). ## Examples @@ -17,8 +20,8 @@ This rule checks that all RPC response messages are named `MethodResponse`. ```proto syntax = "proto3"; -service Foo { - rpc GetFoo (GetFooRequest) returns (Foo) {} +service FooService { + rpc GetFoo(GetFooRequest) returns (Foo) {} } ``` @@ -27,7 +30,8 @@ service Foo { ```proto syntax = "proto3"; -service Foo { - rpc GetFoo (GetFooRequest) returns (GetFooResponse) {} +service FooService { + rpc GetFoo(GetFooRequest) returns (GetFooResponse) {} + rpc ListFoos(FooServiceListFoosRequest) returns (FooServiceListFoosResponse) {} } ``` diff --git a/content/docs/cli/linter/rules/rpc-response-standard-name.ru.mdx b/content/docs/cli/linter/rules/rpc-response-standard-name.ru.mdx index c610e14..9bd5267 100644 --- a/content/docs/cli/linter/rules/rpc-response-standard-name.ru.mdx +++ b/content/docs/cli/linter/rules/rpc-response-standard-name.ru.mdx @@ -1,33 +1,37 @@ --- title: "Rpc Response Standard Name" +description: "Проверяет, что сообщения ответов RPC имеют имя Response или Response." --- -Категории: +- **ID правила:** `RPC_RESPONSE_STANDARD_NAME` +- **Группа:** `DEFAULT` +- **Входит в пресеты (`linters.default`):** `STANDARD`, `COMMENTS` -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **ID правила:** `RPC_RESPONSE_STANDARD_NAME` +- **Группа:** `DEFAULT` +- **Входит в пресеты (`linters.default`):** `STANDARD`, `COMMENTS` -Это правило проверяет, что все сообщения ответа RPC названы в формате `MethodResponse`. +Это правило проверяет, что имя сообщения ответа каждого RPC соответствует шаблону `Response` или `Response` (в PascalCase для имени сервиса и метода). ## Примеры -### Bad +### Неправильно ```proto syntax = "proto3"; -service Foo { - rpc GetFoo (GetFooRequest) returns (Foo) {} +service FooService { + rpc GetFoo(GetFooRequest) returns (Foo) {} } ``` -### Good +### Правильно ```proto syntax = "proto3"; -service Foo { - rpc GetFoo (GetFooRequest) returns (GetFooResponse) {} +service FooService { + rpc GetFoo(GetFooRequest) returns (GetFooResponse) {} + rpc ListFoos(FooServiceListFoosRequest) returns (FooServiceListFoosResponse) {} } ``` diff --git a/content/docs/cli/linter/rules/service-pascal-case.mdx b/content/docs/cli/linter/rules/service-pascal-case.mdx index aff7e5c..004d2df 100644 --- a/content/docs/cli/linter/rules/service-pascal-case.mdx +++ b/content/docs/cli/linter/rules/service-pascal-case.mdx @@ -1,11 +1,11 @@ --- title: "Service Pascal Case" +description: "This rule checks that all service names are in PascalCase." --- -Categories: -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **Rule ID:** `SERVICE_PASCAL_CASE` +- **Group:** `BASIC` +- **Included in presets (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` This rule checks that all service names are in PascalCase. diff --git a/content/docs/cli/linter/rules/service-pascal-case.ru.mdx b/content/docs/cli/linter/rules/service-pascal-case.ru.mdx index a829f10..01da469 100644 --- a/content/docs/cli/linter/rules/service-pascal-case.ru.mdx +++ b/content/docs/cli/linter/rules/service-pascal-case.ru.mdx @@ -1,18 +1,17 @@ --- title: "Service Pascal Case" +description: "Это правило проверяет, что все имена сервисов написаны в стиле PascalCase." --- -Категории: - -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **ID правила:** `SERVICE_PASCAL_CASE` +- **Группа:** `BASIC` +- **Входит в пресеты (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` Это правило проверяет, что все имена сервисов написаны в стиле PascalCase. ## Примеры -### Bad +### Неправильно ```proto syntax = "proto3"; @@ -22,7 +21,7 @@ service foo_bar { } ``` -### Good +### Правильно ```proto syntax = "proto3"; diff --git a/content/docs/cli/linter/rules/service-suffix.mdx b/content/docs/cli/linter/rules/service-suffix.mdx index e19366e..51f89d4 100644 --- a/content/docs/cli/linter/rules/service-suffix.mdx +++ b/content/docs/cli/linter/rules/service-suffix.mdx @@ -1,14 +1,26 @@ --- title: "Service Suffix" +description: "Checks that all service names end with the configured suffix (default Service)." --- -Categories: +- **Rule ID:** `SERVICE_SUFFIX` +- **Group:** `DEFAULT` +- **Included in presets (`linters.default`):** `STANDARD`, `COMMENTS` -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **Rule ID:** `SERVICE_SUFFIX` +- **Group:** `DEFAULT` +- **Included in presets (`linters.default`):** `STANDARD`, `COMMENTS` -This rule checks that all services are suffixed with `Service` or your custom suffix. +This rule checks that all `service` names end with `Service` or a custom suffix configured via `linters-settings.SERVICE_SUFFIX.suffix`. + +## Configuration + +```yaml +version: v1 +linters-settings: + SERVICE_SUFFIX: + suffix: API +``` ## Examples @@ -18,16 +30,28 @@ This rule checks that all services are suffixed with `Service` or your custom su syntax = "proto3"; service Foo { - rpc Bar(BarRequest) returns (BarResponse); + rpc Bar(BarRequest) returns (BarResponse); } ``` ### Good +With the default suffix (`Service`): + ```proto syntax = "proto3"; service FooService { - rpc Bar(BarRequest) returns (BarResponse); + rpc Bar(BarRequest) returns (BarResponse); +} +``` + +With `suffix: API`: + +```proto +syntax = "proto3"; + +service FooAPI { + rpc Bar(BarRequest) returns (BarResponse); } ``` diff --git a/content/docs/cli/linter/rules/service-suffix.ru.mdx b/content/docs/cli/linter/rules/service-suffix.ru.mdx index 03bf568..e8f3041 100644 --- a/content/docs/cli/linter/rules/service-suffix.ru.mdx +++ b/content/docs/cli/linter/rules/service-suffix.ru.mdx @@ -1,33 +1,57 @@ --- title: "Service Suffix" +description: "Проверяет, что имена всех сервисов заканчиваются на заданный суффикс (по умолчанию Service)." --- -Категории: +- **ID правила:** `SERVICE_SUFFIX` +- **Группа:** `DEFAULT` +- **Входит в пресеты (`linters.default`):** `STANDARD`, `COMMENTS` -- **MINIMAL** -- **BASIC** -- **DEFAULT** +- **ID правила:** `SERVICE_SUFFIX` +- **Группа:** `DEFAULT` +- **Входит в пресеты (`linters.default`):** `STANDARD`, `COMMENTS` -Это правило проверяет, что все сервисы имеют суффикс `Service` или ваш пользовательский суффикс. +Это правило проверяет, что имена всех `service` оканчиваются на `Service` либо на пользовательский суффикс из `linters-settings.SERVICE_SUFFIX.suffix`. + +## Конфигурация + +```yaml +version: v1 +linters-settings: + SERVICE_SUFFIX: + suffix: API +``` ## Примеры -### Bad +### Неправильно ```proto syntax = "proto3"; service Foo { - rpc Bar(BarRequest) returns (BarResponse); + rpc Bar(BarRequest) returns (BarResponse); } ``` -### Good +### Правильно + +С суффиксом по умолчанию (`Service`): ```proto syntax = "proto3"; service FooService { - rpc Bar(BarRequest) returns (BarResponse); + rpc Bar(BarRequest) returns (BarResponse); +} +``` + +С настройкой `suffix: API`: + +```proto +syntax = "proto3"; + +service FooAPI { + rpc Bar(BarRequest) returns (BarResponse); } ``` diff --git a/content/docs/cli/linter/rules/syntax-specified.mdx b/content/docs/cli/linter/rules/syntax-specified.mdx new file mode 100644 index 0000000..588a540 --- /dev/null +++ b/content/docs/cli/linter/rules/syntax-specified.mdx @@ -0,0 +1,48 @@ +--- +title: "Syntax Specified" +description: "Checks that every .proto file explicitly declares a syntax or edition statement." +--- + +- **Rule ID:** `SYNTAX_SPECIFIED` +- **Group:** `BASIC` +- **Included in presets (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` + +- **Rule ID:** `SYNTAX_SPECIFIED` +- **Group:** `BASIC` +- **Included in presets (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` + +This rule checks that every `.proto` file explicitly specifies either a `syntax` declaration (such as `"proto3"` or `"proto2"`) or an `edition` declaration (such as `"2023"`). Omitting it causes compilers to silently default to `proto2`. + +## Examples + +### Bad + +```proto +package acme.users.v1; + +message User { + string id = 1; +} +``` + +### Good + +```proto +syntax = "proto3"; + +package acme.users.v1; + +message User { + string id = 1; +} +``` + +```proto +edition = "2023"; + +package acme.users.v1; + +message User { + string id = 1; +} +``` diff --git a/content/docs/cli/linter/rules/syntax-specified.ru.mdx b/content/docs/cli/linter/rules/syntax-specified.ru.mdx new file mode 100644 index 0000000..fee002f --- /dev/null +++ b/content/docs/cli/linter/rules/syntax-specified.ru.mdx @@ -0,0 +1,48 @@ +--- +title: "Syntax Specified" +description: "Проверяет, что каждый .proto-файл явно указывает директиву syntax или edition." +--- + +- **ID правила:** `SYNTAX_SPECIFIED` +- **Группа:** `BASIC` +- **Входит в пресеты (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` + +- **ID правила:** `SYNTAX_SPECIFIED` +- **Группа:** `BASIC` +- **Входит в пресеты (`linters.default`):** `BASIC`, `STANDARD`, `COMMENTS` + +Это правило проверяет, что каждый `.proto`-файл явно объявляет `syntax` (например, `"proto3"` или `"proto2"`) или `edition` (например, `"2023"`). Без этой директивы компилятор неявно считает файл `proto2`. + +## Примеры + +### Неправильно + +```proto +package acme.users.v1; + +message User { + string id = 1; +} +``` + +### Правильно + +```proto +syntax = "proto3"; + +package acme.users.v1; + +message User { + string id = 1; +} +``` + +```proto +edition = "2023"; + +package acme.users.v1; + +message User { + string id = 1; +} +``` diff --git a/next.config.mjs b/next.config.mjs index cc861de..fe52238 100644 --- a/next.config.mjs +++ b/next.config.mjs @@ -86,6 +86,37 @@ const config = { destination: '/ru/docs/cli/auto-completion', permanent: true, }, + // Removed breaking-change rules + { + source: '/docs/cli/breaking-changes/rules/import-no-delete', + destination: '/docs/cli/breaking-changes', + permanent: true, + }, + { + source: '/docs/cli/breaking-changes/rules/oneof-field-no-delete', + destination: '/docs/cli/breaking-changes', + permanent: true, + }, + { + source: '/docs/cli/breaking-changes/rules/oneof-field-same-type', + destination: '/docs/cli/breaking-changes', + permanent: true, + }, + { + source: '/ru/docs/cli/breaking-changes/rules/import-no-delete', + destination: '/ru/docs/cli/breaking-changes', + permanent: true, + }, + { + source: '/ru/docs/cli/breaking-changes/rules/oneof-field-no-delete', + destination: '/ru/docs/cli/breaking-changes', + permanent: true, + }, + { + source: '/ru/docs/cli/breaking-changes/rules/oneof-field-same-type', + destination: '/ru/docs/cli/breaking-changes', + permanent: true, + }, ]; }, };