Skip to content

Add Policy registry commands #3806

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

Draft
wants to merge 2 commits into
base: ed/bufPolicyAPI
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions private/buf/bufcli/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,12 @@ func NewPluginNameAlreadyExistsError(name string) error {
return fmt.Errorf("a plugin named %q already exists", name)
}

// NewPolicyNameAlreadyExistsError informs the user that a policy
// with that name already exists.
func NewPolicyNameAlreadyExistsError(name string) error {
return fmt.Errorf("a policy named %q already exists", name)
}

// NewOrganizationNotFoundError informs the user that an organization with
// that name does not exist.
func NewOrganizationNotFoundError(name string) error {
Expand Down Expand Up @@ -100,6 +106,12 @@ func NewPluginNotFoundError(name string) error {
return fmt.Errorf("a plugin named %q does not exist", name)
}

// NewPolicyNotFoundError informs the user that a plugin with
// that name does not exist.
func NewPolicyNotFoundError(name string) error {
return fmt.Errorf("a plugin named %q does not exist", name)
}

// NewInvalidRemoteError informs the user that the given remote is invalid.
func NewInvalidRemoteError(err error, remote string, moduleFullName string) error {
var connectErr *connect.Error
Expand Down
30 changes: 30 additions & 0 deletions private/buf/bufcli/flags_args.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (

modulev1 "buf.build/gen/go/bufbuild/registry/protocolbuffers/go/buf/registry/module/v1"
pluginv1beta1 "buf.build/gen/go/bufbuild/registry/protocolbuffers/go/buf/registry/plugin/v1beta1"
policyv1beta1 "buf.build/gen/go/bufbuild/registry/protocolbuffers/go/buf/registry/policy/v1beta1"
"github.com/bufbuild/buf/private/buf/buffetch"
"github.com/bufbuild/buf/private/pkg/app"
"github.com/bufbuild/buf/private/pkg/app/appcmd"
Expand Down Expand Up @@ -319,6 +320,21 @@ func VisibilityFlagToPluginVisibilityAllowUnspecified(visibility string) (plugin
}
}

// VisibilityFlagToPolicyVisibilityAllowUnspecified parses the given string as a pluginv1.PolicyVisibility
// where an empty string will be parsed as unspecified.
func VisibilityFlagToPolicyVisibilityAllowUnspecified(visibility string) (policyv1beta1.PolicyVisibility, error) {
switch visibility {
case publicVisibility:
return policyv1beta1.PolicyVisibility_POLICY_VISIBILITY_PUBLIC, nil
case privateVisibility:
return policyv1beta1.PolicyVisibility_POLICY_VISIBILITY_PRIVATE, nil
case "":
return policyv1beta1.PolicyVisibility_POLICY_VISIBILITY_UNSPECIFIED, nil
default:
return 0, fmt.Errorf("invalid visibility: %s", visibility)
}
}

// ArchiveStatusFlagToModuleArchiveStatusFilter parses the given string as a modulev1.ListLabelsRequest_ArchiveFilter.
func ArchiveStatusFlagToModuleArchiveStatusFilter(archiveStatus string) (modulev1.ListLabelsRequest_ArchiveFilter, error) {
switch archiveStatus {
Expand Down Expand Up @@ -347,6 +363,20 @@ func ArchiveStatusFlagToPluginArchiveStatusFilter(archiveStatus string) (pluginv
}
}

// ArchiveStatusFlagToPolicyArchiveStatusFilter parses the given string as a pluginv1beta1.ListLabelsRequest_ArchiveFilter.
func ArchiveStatusFlagToPolicyArchiveStatusFilter(archiveStatus string) (policyv1beta1.ListLabelsRequest_ArchiveFilter, error) {
switch archiveStatus {
case archivedArchiveStatus:
return policyv1beta1.ListLabelsRequest_ARCHIVE_FILTER_ARCHIVED_ONLY, nil
case unarchivedArchiveStatus:
return policyv1beta1.ListLabelsRequest_ARCHIVE_FILTER_UNARCHIVED_ONLY, nil
case allArchiveStatus:
return policyv1beta1.ListLabelsRequest_ARCHIVE_FILTER_ALL, nil
default:
return 0, fmt.Errorf("invalid archive status: %s", archiveStatus)
}
}

// ValidateRequiredFlag validates that the required flag is set.
func ValidateRequiredFlag[T comparable](flagName string, value T) error {
var zero T
Expand Down
26 changes: 26 additions & 0 deletions private/buf/bufprint/bufprint.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import (
modulev1 "buf.build/gen/go/bufbuild/registry/protocolbuffers/go/buf/registry/module/v1"
ownerv1 "buf.build/gen/go/bufbuild/registry/protocolbuffers/go/buf/registry/owner/v1"
pluginv1beta1 "buf.build/gen/go/bufbuild/registry/protocolbuffers/go/buf/registry/plugin/v1beta1"
policyv1beta1 "buf.build/gen/go/bufbuild/registry/protocolbuffers/go/buf/registry/policy/v1beta1"
"github.com/bufbuild/buf/private/bufpkg/bufparse"
registryv1alpha1 "github.com/bufbuild/buf/private/gen/proto/go/buf/alpha/registry/v1alpha1"
"github.com/bufbuild/buf/private/pkg/protoencoding"
Expand Down Expand Up @@ -271,6 +272,18 @@ func NewPluginEntity(plugin *pluginv1beta1.Plugin, pluginFullName bufparse.FullN
}
}

// NewPolicyEntity returns a new plugin entity to print.
func NewPolicyEntity(policy *policyv1beta1.Policy, policyFullName bufparse.FullName) Entity {
return outputPolicy{
ID: policy.Id,
Remote: policyFullName.Registry(),
Owner: policyFullName.Owner(),
Name: policyFullName.Name(),
FullName: policyFullName.String(),
CreateTime: policy.CreateTime.AsTime(),
}
}

// NewUserEntity returns a new user entity to print.
func NewUserEntity(user *registryv1alpha1.User) Entity {
return outputUser{
Expand Down Expand Up @@ -502,6 +515,19 @@ func (m outputPlugin) fullName() string {
return m.FullName
}

type outputPolicy struct {
ID string `json:"id,omitempty"`
Remote string `json:"remote,omitempty"`
Owner string `json:"owner,omitempty"`
Name string `json:"name,omitempty"`
FullName string `json:"-" bufprint:"Name"`
CreateTime time.Time `json:"create_time,omitempty" bufprint:"Create Time"`
}

func (m outputPolicy) fullName() string {
return m.FullName
}

type outputUser struct {
Username string `json:"username,omitempty"`
FullName string `json:"-" bufprint:"Name"`
Expand Down
48 changes: 48 additions & 0 deletions private/buf/cmd/buf/buf.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,18 @@ import (
"github.com/bufbuild/buf/private/buf/cmd/buf/command/registry/plugin/pluginlabel/pluginlabellist"
"github.com/bufbuild/buf/private/buf/cmd/buf/command/registry/plugin/pluginlabel/pluginlabelunarchive"
"github.com/bufbuild/buf/private/buf/cmd/buf/command/registry/plugin/pluginsettings/pluginsettingsupdate"
"github.com/bufbuild/buf/private/buf/cmd/buf/command/registry/policy/policycommit/policycommitaddlabel"
"github.com/bufbuild/buf/private/buf/cmd/buf/command/registry/policy/policycommit/policycommitinfo"
"github.com/bufbuild/buf/private/buf/cmd/buf/command/registry/policy/policycommit/policycommitlist"
"github.com/bufbuild/buf/private/buf/cmd/buf/command/registry/policy/policycommit/policycommitresolve"
"github.com/bufbuild/buf/private/buf/cmd/buf/command/registry/policy/policycreate"
"github.com/bufbuild/buf/private/buf/cmd/buf/command/registry/policy/policydelete"
"github.com/bufbuild/buf/private/buf/cmd/buf/command/registry/policy/policyinfo"
"github.com/bufbuild/buf/private/buf/cmd/buf/command/registry/policy/policylabel/policylabelarchive"
"github.com/bufbuild/buf/private/buf/cmd/buf/command/registry/policy/policylabel/policylabelinfo"
"github.com/bufbuild/buf/private/buf/cmd/buf/command/registry/policy/policylabel/policylabellist"
"github.com/bufbuild/buf/private/buf/cmd/buf/command/registry/policy/policylabel/policylabelunarchive"
"github.com/bufbuild/buf/private/buf/cmd/buf/command/registry/policy/policysettings/policysettingsupdate"
"github.com/bufbuild/buf/private/buf/cmd/buf/command/registry/registrycc"
"github.com/bufbuild/buf/private/buf/cmd/buf/command/registry/registrylogin"
"github.com/bufbuild/buf/private/buf/cmd/buf/command/registry/registrylogout"
Expand Down Expand Up @@ -319,6 +331,42 @@ func NewRootCommand(name string) *appcmd.Command {
plugindelete.NewCommand("delete", builder),
},
},
{
Use: "policy",
Short: "Manage BSR policies",
SubCommands: []*appcmd.Command{
{
Use: "commit",
Short: "Manage a policy's commits",
SubCommands: []*appcmd.Command{
policycommitaddlabel.NewCommand("add-label", builder, ""),
policycommitinfo.NewCommand("info", builder, ""),
policycommitlist.NewCommand("list", builder, ""),
policycommitresolve.NewCommand("resolve", builder, ""),
},
},
{
Use: "label",
Short: "Manage a policy's labels",
SubCommands: []*appcmd.Command{
policylabelarchive.NewCommand("archive", builder, ""),
policylabelinfo.NewCommand("info", builder, ""),
policylabellist.NewCommand("list", builder, ""),
policylabelunarchive.NewCommand("unarchive", builder, ""),
},
},
{
Use: "settings",
Short: "Manage a policy's settings",
SubCommands: []*appcmd.Command{
policysettingsupdate.NewCommand("update", builder),
},
},
policycreate.NewCommand("create", builder),
policyinfo.NewCommand("info", builder),
policydelete.NewCommand("delete", builder),
},
},
},
},
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
// 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 policycommitaddlabel

import (
"context"
"fmt"

policyv1beta1 "buf.build/gen/go/bufbuild/registry/protocolbuffers/go/buf/registry/policy/v1beta1"
"connectrpc.com/connect"
"github.com/bufbuild/buf/private/buf/bufcli"
"github.com/bufbuild/buf/private/buf/bufprint"
"github.com/bufbuild/buf/private/bufpkg/bufparse"
"github.com/bufbuild/buf/private/bufpkg/bufregistryapi/bufregistryapipolicy"
"github.com/bufbuild/buf/private/pkg/app/appcmd"
"github.com/bufbuild/buf/private/pkg/app/appext"
"github.com/bufbuild/buf/private/pkg/slicesext"
"github.com/bufbuild/buf/private/pkg/uuidutil"
"github.com/spf13/pflag"
)

const (
formatFlagName = "format"
labelsFlagName = "label"
)

// NewCommand returns a new Command.
func NewCommand(
name string,
builder appext.SubCommandBuilder,
deprecated string,
) *appcmd.Command {
flags := newFlags()
return &appcmd.Command{
Use: name + " <remote/owner/policy:commit> --label <label>",
Short: "Add labels to a commit",
Args: appcmd.ExactArgs(1),
Deprecated: deprecated,
Run: builder.NewRunFunc(
func(ctx context.Context, container appext.Container) error {
return run(ctx, container, flags)
},
),
BindFlags: flags.Bind,
}
}

type flags struct {
Format string
Labels []string
}

func newFlags() *flags {
return &flags{}
}

func (f *flags) Bind(flagSet *pflag.FlagSet) {
flagSet.StringVar(
&f.Format,
formatFlagName,
bufprint.FormatText.String(),
fmt.Sprintf(`The output format to use. Must be one of %s`, bufprint.AllFormatsString),
)
flagSet.StringSliceVar(
&f.Labels,
labelsFlagName,
nil,
"The labels to add to the commit. Must have at least one",
)
}

func run(
ctx context.Context,
container appext.Container,
flags *flags,
) error {
policyRef, err := bufparse.ParseRef(container.Arg(0))
if err != nil {
return appcmd.WrapInvalidArgumentError(err)
}
if policyRef.Ref() == "" {
return appcmd.NewInvalidArgumentError("commit is required")
}
commitID := policyRef.Ref()
if _, err := uuidutil.FromDashless(commitID); err != nil {
return appcmd.NewInvalidArgumentErrorf("invalid commit: %w", err)
}
labels := flags.Labels
if len(labels) == 0 {
return appcmd.NewInvalidArgumentError("must create at least one label")
}
format, err := bufprint.ParseFormat(flags.Format)
if err != nil {
return appcmd.WrapInvalidArgumentError(err)
}
clientConfig, err := bufcli.NewConnectClientConfig(container)
if err != nil {
return err
}
policyClientProvider := bufregistryapipolicy.NewClientProvider(clientConfig)
labelServiceClient := policyClientProvider.V1Beta1LabelServiceClient(policyRef.FullName().Registry())
requestValues := slicesext.Map(labels, func(label string) *policyv1beta1.CreateOrUpdateLabelsRequest_Value {
return &policyv1beta1.CreateOrUpdateLabelsRequest_Value{
LabelRef: &policyv1beta1.LabelRef{
Value: &policyv1beta1.LabelRef_Name_{
Name: &policyv1beta1.LabelRef_Name{
Owner: policyRef.FullName().Owner(),
Policy: policyRef.FullName().Name(),
Label: label,
},
},
},
CommitId: commitID,
}
})
resp, err := labelServiceClient.CreateOrUpdateLabels(
ctx,
connect.NewRequest(
&policyv1beta1.CreateOrUpdateLabelsRequest{
Values: requestValues,
},
),
)
if err != nil {
// Not explicitly handling error with connect.CodeNotFound as
// it can be Policy or Commit not found error. May be caused by
// a misformatted ID.
return err
}
return bufprint.PrintNames(
container.Stdout(),
format,
slicesext.Map(resp.Msg.Labels, func(label *policyv1beta1.Label) bufprint.Entity {
return bufprint.NewLabelEntity(label, policyRef.FullName())
})...,
)
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading