Skip to content
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

Implement repo delete for minder #1371

Merged
merged 1 commit into from
Nov 1, 2023
Merged
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
133 changes: 133 additions & 0 deletions cmd/cli/app/repo/repo_delete.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
//
// Copyright 2023 Stacklok, 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 repo

import (
"fmt"
"os"

"github.com/spf13/cobra"
"github.com/spf13/viper"

github "github.com/stacklok/mediator/internal/providers/github"
"github.com/stacklok/mediator/internal/util"
pb "github.com/stacklok/mediator/pkg/api/protobuf/go/minder/v1"
)

var repoDeleteCmd = &cobra.Command{
Use: "delete",
Short: "delete repository",
Long: `Repo delete is used to delete a repository within the minder control plane`,
PreRun: func(cmd *cobra.Command, args []string) {
if err := viper.BindPFlags(cmd.Flags()); err != nil {
fmt.Fprintf(os.Stderr, "error binding flags: %s", err)
}
},
RunE: func(cmd *cobra.Command, args []string) error {

provider := util.GetConfigValue(viper.GetViper(), "provider", "provider", cmd, "").(string)
repoid := viper.GetString("repo-id")
format := viper.GetString("output")
name := util.GetConfigValue(viper.GetViper(), "name", "name", cmd, "").(string)

// if name is set, repo-id cannot be set
if name != "" && repoid != "" {
return fmt.Errorf("cannot set both name and repo-id")
}

// either name or repoid needs to be set
if name == "" && repoid == "" {
return fmt.Errorf("either name or repo-id needs to be set")
}

// if name is set, provider needs to be set
if name != "" && provider == "" {
return fmt.Errorf("provider needs to be set if name is set")
}

switch format {
case formatJSON:
case formatYAML:
case formatDefault:
default:
return fmt.Errorf("invalid output format: %s", format)
}

conn, err := util.GrpcForCommand(cmd, viper.GetViper())
util.ExitNicelyOnError(err, "Error getting grpc connection")
defer conn.Close()

client := pb.NewRepositoryServiceClient(conn)
ctx, cancel := util.GetAppContext()
defer cancel()

deletedRepoID := &pb.DeleteRepositoryByIdResponse{}
deletedRepoName := &pb.DeleteRepositoryByNameResponse{}
// delete repo by id
if repoid != "" {
resp, err := client.DeleteRepositoryById(ctx, &pb.DeleteRepositoryByIdRequest{
RepositoryId: repoid,
})
util.ExitNicelyOnError(err, "Error deleting repo by id")
deletedRepoID = resp
} else {
if provider != github.Github {
return fmt.Errorf("only %s is supported at this time", github.Github)
}

// delete repo by name
resp, err := client.DeleteRepositoryByName(ctx, &pb.DeleteRepositoryByNameRequest{Provider: provider, Name: name})
util.ExitNicelyOnError(err, "Error deleting repo by name")
deletedRepoName = resp
}

status := util.GetConfigValue(viper.GetViper(), "status", "status", cmd, false).(bool)
if status {
// TODO: implement this
} else {
var out string
var err error
// print result just in JSON or YAML
if format == "" || format == formatJSON {
if repoid != "" {
out, err = util.GetJsonFromProto(deletedRepoID)
} else {
out, err = util.GetJsonFromProto(deletedRepoName)
}
util.ExitNicelyOnError(err, "Error getting json from proto")
fmt.Println(out)
} else {
if repoid != "" {
out, err = util.GetYamlFromProto(deletedRepoID)
} else {
out, err = util.GetYamlFromProto(deletedRepoName)
}
util.ExitNicelyOnError(err, "Error getting json from proto")
fmt.Println(out)
}
}
return nil
},
}

func init() {
RepoCmd.AddCommand(repoDeleteCmd)
repoDeleteCmd.Flags().StringP("output", "f", "", "Output format (json or yaml)")
repoDeleteCmd.Flags().StringP("provider", "p", "", "Name of the enrolled provider")
repoDeleteCmd.Flags().StringP("name", "n", "", "Name of the repository (owner/name format)")
repoDeleteCmd.Flags().StringP("repo-id", "r", "", "ID of the repo to delete")
repoDeleteCmd.Flags().BoolP("status", "s", false, "Only return the status of the profiles associated to this repo")
}
48 changes: 48 additions & 0 deletions docs/docs/ref/proto.md

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

83 changes: 83 additions & 0 deletions internal/controlplane/handlers_repositories.go
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,89 @@ func (s *Server) GetRepositoryByName(ctx context.Context,
}}, nil
}

// DeleteRepositoryById deletes a repository by name
func (s *Server) DeleteRepositoryById(ctx context.Context,
in *pb.DeleteRepositoryByIdRequest) (*pb.DeleteRepositoryByIdResponse, error) {
parsedRepositoryID, err := uuid.Parse(in.RepositoryId)
if err != nil {
return nil, util.UserVisibleError(codes.InvalidArgument, "invalid repository ID")
}

// read the repository
repo, err := s.store.GetRepositoryByID(ctx, parsedRepositoryID)
if errors.Is(err, sql.ErrNoRows) {
return nil, status.Errorf(codes.NotFound, "repository not found")
} else if err != nil {
return nil, status.Errorf(codes.Internal, "cannot read repository: %v", err)
}

// check if user is authorized
if err := AuthorizedOnProject(ctx, repo.ProjectID); err != nil {
return nil, err
}

// delete the repository
if err := s.store.DeleteRepository(ctx, repo.ID); err != nil {
return nil, err
}

// return the response with the id of the deleted repository
return &pb.DeleteRepositoryByIdResponse{
RepositoryId: in.RepositoryId,
}, nil
}

// DeleteRepositoryByName deletes a repository by name
func (s *Server) DeleteRepositoryByName(ctx context.Context,
in *pb.DeleteRepositoryByNameRequest) (*pb.DeleteRepositoryByNameResponse, error) {
// split repo name in owner and name
fragments := strings.Split(in.Name, "/")
if len(fragments) != 2 {
return nil, status.Errorf(codes.InvalidArgument, "invalid repository name, needs to have the format: owner/name")
}

projectID, err := getProjectFromRequestOrDefault(ctx, in)
if err != nil {
return nil, util.UserVisibleError(codes.InvalidArgument, err.Error())
}

// check if user is authorized
if err := AuthorizedOnProject(ctx, projectID); err != nil {
return nil, err
}

provider, err := s.store.GetProviderByName(ctx, db.GetProviderByNameParams{
Name: in.Provider,
ProjectID: projectID,
})
if err != nil {
return nil, providerError(fmt.Errorf("provider error: %w", err))
}

repo, err := s.store.GetRepositoryByRepoName(ctx,
db.GetRepositoryByRepoNameParams{Provider: provider.Name, RepoOwner: fragments[0], RepoName: fragments[1]})

if errors.Is(err, sql.ErrNoRows) {
return nil, status.Errorf(codes.NotFound, "repository not found")
} else if err != nil {
return nil, err
}
// check if user is authorized
if err := AuthorizedOnProject(ctx, repo.ProjectID); err != nil {
return nil, err
}

// delete the repository
if err := s.store.DeleteRepository(ctx, repo.ID); err != nil {
return nil, err
}

// return the response with the name of the deleted repository
return &pb.DeleteRepositoryByNameResponse{
Name: in.Name,
}, nil
}

// ListRemoteRepositoriesFromProvider returns a list of repositories from a provider
func (s *Server) ListRemoteRepositoriesFromProvider(
ctx context.Context,
Expand Down
84 changes: 84 additions & 0 deletions pkg/api/openapi/mediator/v1/mediator.swagger.json

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

Loading