-
Notifications
You must be signed in to change notification settings - Fork 345
Add buf source edit deprecate command #4306
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
emcfarlane
wants to merge
6
commits into
main
Choose a base branch
from
ed/bufSourceEdit
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
e74c5e2
Add buf source edit deprecate command
emcfarlane d144959
CHANGELOG
emcfarlane 0c448dd
Cleanup matcher
emcfarlane f79f9e3
Error on no types match
emcfarlane 706b945
Fix lint
emcfarlane 9f54c65
Merge branch 'main' into ed/bufSourceEdit
emcfarlane File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
281 changes: 281 additions & 0 deletions
281
cmd/buf/internal/command/source/sourceedit/sourceeditdeprecate/sourceeditdeprecate.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,281 @@ | ||
| // Copyright 2020-2025 Buf Technologies, Inc. | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| package sourceeditdeprecate | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "context" | ||
| "errors" | ||
| "fmt" | ||
| "io" | ||
| "os" | ||
|
|
||
| "buf.build/go/app/appcmd" | ||
| "buf.build/go/app/appext" | ||
| "buf.build/go/standard/xslices" | ||
| "buf.build/go/standard/xstrings" | ||
| "github.com/bufbuild/buf/private/buf/bufcli" | ||
| "github.com/bufbuild/buf/private/buf/bufctl" | ||
| "github.com/bufbuild/buf/private/buf/buffetch" | ||
| "github.com/bufbuild/buf/private/buf/bufformat" | ||
| "github.com/bufbuild/buf/private/bufpkg/bufanalysis" | ||
| "github.com/bufbuild/buf/private/bufpkg/bufmodule" | ||
| "github.com/bufbuild/buf/private/pkg/storage" | ||
| "github.com/spf13/pflag" | ||
| ) | ||
|
|
||
| const ( | ||
| configFlagName = "config" | ||
| diffFlagName = "diff" | ||
| diffFlagShortName = "d" | ||
| disableSymlinksFlagName = "disable-symlinks" | ||
| errorFormatFlagName = "error-format" | ||
| excludePathsFlagName = "exclude-path" | ||
| pathsFlagName = "path" | ||
| prefixFlagName = "prefix" | ||
| ) | ||
|
|
||
| // NewCommand returns a new Command. | ||
| func NewCommand( | ||
| name string, | ||
| builder appext.SubCommandBuilder, | ||
| ) *appcmd.Command { | ||
| flags := newFlags() | ||
| return &appcmd.Command{ | ||
| Use: name + " <source>", | ||
| Short: "Deprecate Protobuf types", | ||
| Long: ` | ||
| Deprecate Protobuf types by adding the 'deprecated = true' option. | ||
|
|
||
| The --prefix flag is required and specifies the fully-qualified name prefix of the | ||
| types to deprecate. All types whose fully-qualified name starts with this prefix | ||
| will have the 'deprecated = true' option added. For fields and enum values, only | ||
| exact matches are deprecated. | ||
|
|
||
| Returns an error if no types match the specified prefixes. If matching types are | ||
| already deprecated, no changes are made and the command succeeds. | ||
|
|
||
| By default, the source is the current directory and files are formatted and rewritten in-place. | ||
|
|
||
| Examples: | ||
|
|
||
| Deprecate all types under a package prefix: | ||
|
|
||
| $ buf source edit deprecate --prefix foo.bar | ||
|
|
||
| Deprecate a specific message and all nested types: | ||
|
|
||
| $ buf source edit deprecate --prefix foo.bar.MyMessage | ||
|
|
||
| Deprecate a specific field: | ||
|
|
||
| $ buf source edit deprecate --prefix foo.bar.MyMessage.my_field | ||
|
|
||
| Multiple --prefix flags can be specified: | ||
|
|
||
| $ buf source edit deprecate --prefix foo.bar --prefix baz.qux | ||
|
|
||
| Display a diff of the changes instead of rewriting files: | ||
|
|
||
| $ buf source edit deprecate --prefix foo.bar -d | ||
| `, | ||
| Args: appcmd.MaximumNArgs(1), | ||
| Run: builder.NewRunFunc( | ||
| func(ctx context.Context, container appext.Container) error { | ||
| return run(ctx, container, flags) | ||
| }, | ||
| ), | ||
| BindFlags: flags.Bind, | ||
| } | ||
| } | ||
|
|
||
| type flags struct { | ||
| Config string | ||
| Diff bool | ||
| DisableSymlinks bool | ||
| ErrorFormat string | ||
| ExcludePaths []string | ||
| Paths []string | ||
| Prefixes []string | ||
| // special | ||
| InputHashtag string | ||
| } | ||
|
|
||
| func newFlags() *flags { | ||
| return &flags{} | ||
| } | ||
|
|
||
| func (f *flags) Bind(flagSet *pflag.FlagSet) { | ||
| bufcli.BindInputHashtag(flagSet, &f.InputHashtag) | ||
| bufcli.BindPaths(flagSet, &f.Paths, pathsFlagName) | ||
| bufcli.BindExcludePaths(flagSet, &f.ExcludePaths, excludePathsFlagName) | ||
| bufcli.BindDisableSymlinks(flagSet, &f.DisableSymlinks, disableSymlinksFlagName) | ||
| flagSet.BoolVarP( | ||
| &f.Diff, | ||
| diffFlagName, | ||
| diffFlagShortName, | ||
| false, | ||
| "Display diffs instead of rewriting files", | ||
| ) | ||
| flagSet.StringVar( | ||
| &f.ErrorFormat, | ||
| errorFormatFlagName, | ||
| "text", | ||
| fmt.Sprintf( | ||
| "The format for build errors printed to stderr. Must be one of %s", | ||
| xstrings.SliceToString(bufanalysis.AllFormatStrings), | ||
| ), | ||
| ) | ||
| flagSet.StringVar( | ||
| &f.Config, | ||
| configFlagName, | ||
| "", | ||
| `The buf.yaml file or data to use for configuration`, | ||
| ) | ||
| flagSet.StringSliceVar( | ||
| &f.Prefixes, | ||
| prefixFlagName, | ||
| nil, | ||
| `Required. The fully-qualified name prefix of types to deprecate. May be specified multiple times.`, | ||
| ) | ||
| _ = appcmd.MarkFlagRequired(flagSet, prefixFlagName) | ||
| } | ||
|
|
||
| func run( | ||
| ctx context.Context, | ||
| container appext.Container, | ||
| flags *flags, | ||
| ) (retErr error) { | ||
| source, err := bufcli.GetInputValue(container, flags.InputHashtag, ".") | ||
| if err != nil { | ||
| return err | ||
| } | ||
| // We use getDirOrProtoFileRef to see if we have a valid DirOrProtoFileRef. | ||
| // This is needed to write files in-place. | ||
| sourceDirOrProtoFileRef, sourceDirOrProtoFileRefErr := getDirOrProtoFileRef(ctx, container, source) | ||
| if sourceDirOrProtoFileRefErr != nil { | ||
| if errors.Is(sourceDirOrProtoFileRefErr, buffetch.ErrModuleFormatDetectedForDirOrProtoFileRef) { | ||
| return appcmd.NewInvalidArgumentErrorf("invalid input %q: must be a directory or proto file", source) | ||
| } | ||
| return appcmd.NewInvalidArgumentErrorf("invalid input %q: %v", source, sourceDirOrProtoFileRefErr) | ||
| } | ||
| if err := validateNoIncludePackageFiles(sourceDirOrProtoFileRef); err != nil { | ||
| return err | ||
| } | ||
|
|
||
| controller, err := bufcli.NewController( | ||
| container, | ||
| bufctl.WithDisableSymlinks(flags.DisableSymlinks), | ||
| bufctl.WithFileAnnotationErrorFormat(flags.ErrorFormat), | ||
| ) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| workspace, err := controller.GetWorkspace( | ||
| ctx, | ||
| source, | ||
| bufctl.WithTargetPaths(flags.Paths, flags.ExcludePaths), | ||
| bufctl.WithConfigOverride(flags.Config), | ||
| ) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| moduleReadBucket := bufmodule.ModuleReadBucketWithOnlyTargetFiles( | ||
| bufmodule.ModuleSetToModuleReadBucketWithOnlyProtoFilesForTargetModules(workspace), | ||
| ) | ||
| originalReadBucket := bufmodule.ModuleReadBucketToStorageReadBucket(moduleReadBucket) | ||
|
|
||
| // Build format options from all prefixes | ||
| var formatOpts []bufformat.FormatOption | ||
| for _, prefix := range flags.Prefixes { | ||
| formatOpts = append(formatOpts, bufformat.WithDeprecate(prefix)) | ||
| } | ||
|
|
||
| formattedReadBucket, err := bufformat.FormatBucket(ctx, originalReadBucket, formatOpts...) | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| // Find changed files. Only generate diff text if displaying diff. | ||
| var diffBuffer bytes.Buffer | ||
| diffWriter := io.Discard | ||
| if flags.Diff { | ||
| diffWriter = &diffBuffer | ||
| } | ||
| changedPaths, err := storage.DiffWithFilenames( | ||
| ctx, | ||
| diffWriter, | ||
| originalReadBucket, | ||
| formattedReadBucket, | ||
| storage.DiffWithExternalPaths(), | ||
| ) | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| // If no files changed, the matched types were already deprecated. This is not an error. | ||
| // Note: if no types matched the prefix at all, FormatBucket already returned an error above. | ||
| if len(changedPaths) == 0 { | ||
| return nil | ||
| } | ||
| if flags.Diff { | ||
| if _, err := io.Copy(container.Stdout(), &diffBuffer); err != nil { | ||
| return err | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| // Write files in-place (default behavior) | ||
| changedPathSet := xslices.ToStructMap(changedPaths) | ||
| return storage.WalkReadObjects( | ||
| ctx, | ||
| formattedReadBucket, | ||
| "", | ||
| func(readObject storage.ReadObject) error { | ||
| if _, ok := changedPathSet[readObject.Path()]; !ok { | ||
| // no change, nothing to re-write | ||
| return nil | ||
| } | ||
| file, err := os.OpenFile(readObject.ExternalPath(), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| defer func() { | ||
| retErr = errors.Join(retErr, file.Close()) | ||
| }() | ||
| if _, err := file.ReadFrom(readObject); err != nil { | ||
| return err | ||
| } | ||
| return nil | ||
| }, | ||
| ) | ||
| } | ||
|
|
||
| func getDirOrProtoFileRef( | ||
| ctx context.Context, | ||
| container appext.Container, | ||
| value string, | ||
| ) (buffetch.DirOrProtoFileRef, error) { | ||
| return buffetch.NewDirOrProtoFileRefParser( | ||
| container.Logger(), | ||
| ).GetDirOrProtoFileRef(ctx, value) | ||
| } | ||
|
|
||
| func validateNoIncludePackageFiles(dirOrProtoFileRef buffetch.DirOrProtoFileRef) error { | ||
| if protoFileRef, ok := dirOrProtoFileRef.(buffetch.ProtoFileRef); ok && protoFileRef.IncludePackageFiles() { | ||
| return appcmd.NewInvalidArgumentError("cannot specify include_package_files=true with source edit deprecate") | ||
| } | ||
| return nil | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The UX of this command as it currently stands is that even if nothing is deprecated (either they're already deprecated or there are no matches), this will always format the file. I'm undecided whether or not this is desirable... I think it's fine? In which case, related to my comment on the diff, maybe we do want to handle some kind of exit code when any diff exists.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I guess my vague notion would be that we ought to not format anything if we don't match, and perhaps even return an exit code of
1, in the same vein of doing anrg <match>that doesn't match anything?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Added a doc comment about the error handling. We now error if no provided prefix matches. If prefix match but already deprecated/format command succeeds. If prefix match but not formatted, still formats.