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

Add subcommand to apply profiles #1815

Merged
merged 1 commit into from
Dec 5, 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
72 changes: 72 additions & 0 deletions cmd/cli/app/profile/common.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
//
// 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 profile

import (
"fmt"
"io"

"github.com/olekukonko/tablewriter"

"github.com/stacklok/minder/internal/engine"
"github.com/stacklok/minder/internal/util"
minderv1 "github.com/stacklok/minder/pkg/api/protobuf/go/minder/v1"
)

func execOnOneProfile(
table *tablewriter.Table,
f string,
dashOpen io.Reader,
project string,
exec func(string, *minderv1.Profile) (*minderv1.Profile, error),
) error {
preader, closer, err := util.OpenFileArg(f, dashOpen)
if err != nil {
return fmt.Errorf("error opening file arg: %w", err)
}
defer closer()

p, err := parseProfile(preader, project)
if err != nil {
return fmt.Errorf("error parsing profile: %w", err)
}

// create a rule
respprof, err := exec(f, p)
if err != nil {
return err
}

RenderProfileTable(respprof, table)
return nil
}

func parseProfile(r io.Reader, proj string) (*minderv1.Profile, error) {
p, err := engine.ParseYAML(r)
if err != nil {
return nil, fmt.Errorf("error reading profile from file: %w", err)
}

if proj != "" {
if p.Context == nil {
p.Context = &minderv1.Context{}
}

p.Context.Project = &proj
}

return p, nil
}
102 changes: 102 additions & 0 deletions cmd/cli/app/profile/profile_apply.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
//
// 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 profile

import (
"fmt"
"os"

"github.com/spf13/cobra"
"github.com/spf13/viper"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"

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

// Profile_applyCmd represents the profile apply command
var Profile_applyCmd = &cobra.Command{
Use: "apply",
Short: "Create or update a profile within a minder control plane",
Long: `The minder profile apply subcommand lets you create or update new profiles for a project
within a 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\n", err)
}
},
RunE: func(cmd *cobra.Command, args []string) error {
f := util.GetConfigValue(viper.GetViper(), "file", "file", cmd, "").(string)
proj := viper.GetString("project")

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

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

table := InitializeTable(cmd)

applyFunc := func(f string, p *pb.Profile) (*pb.Profile, error) {
// create a profile
resp, err := client.CreateProfile(ctx, &pb.CreateProfileRequest{
Profile: p,
})
if err == nil {
return resp.GetProfile(), nil
}

st, ok := status.FromError(err)
if !ok {
// We can't parse the error, so just return it
return nil, fmt.Errorf("error creating rule type from %s: %w", f, err)
}

if st.Code() != codes.AlreadyExists {
return nil, fmt.Errorf("error creating rule type from %s: %w", f, err)
}

updateResp, err := client.UpdateProfile(ctx, &pb.UpdateProfileRequest{
Profile: p,
})
if err != nil {
return nil, fmt.Errorf("error updating rule type from %s: %w", f, err)
}

return updateResp.GetProfile(), nil
}

if err := execOnOneProfile(table, f, cmd.InOrStdin(), proj, applyFunc); err != nil {
return err
}

table.Render()
return nil
},
}

func init() {
ProfileCmd.AddCommand(Profile_applyCmd)
Profile_applyCmd.Flags().StringP("file", "f", "", "Path to the YAML defining the profile (or - for stdin)")
if err := Profile_applyCmd.MarkFlagRequired("file"); err != nil {
fmt.Fprintf(os.Stderr, "Error marking flag required: %s\n", err)
os.Exit(1)
}
Profile_applyCmd.Flags().StringP("project", "p", "", "Project to create the profile in")
}
56 changes: 15 additions & 41 deletions cmd/cli/app/profile/profile_create.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,11 @@ package profile

import (
"fmt"
"io"
"os"
"path/filepath"

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

"github.com/stacklok/minder/internal/engine"
"github.com/stacklok/minder/internal/util"
pb "github.com/stacklok/minder/pkg/api/protobuf/go/minder/v1"
)
Expand All @@ -44,28 +41,6 @@ within a minder control plane.`,
f := util.GetConfigValue(viper.GetViper(), "file", "file", cmd, "").(string)
proj := viper.GetString("project")

var err error

var preader io.Reader

if f == "" {
return fmt.Errorf("error: file must be set")
}

if f == "-" {
preader = os.Stdin
} else {
f = filepath.Clean(f)
fopen, err := os.Open(f)
if err != nil {
return fmt.Errorf("error opening file: %w", err)
}

defer fopen.Close()

preader = fopen
}

conn, err := util.GrpcForCommand(cmd, viper.GetViper())
util.ExitNicelyOnError(err, "Error getting grpc connection")
defer conn.Close()
Expand All @@ -74,29 +49,24 @@ within a minder control plane.`,
ctx, cancel := util.GetAppContext()
defer cancel()

p, err := engine.ParseYAML(preader)
if err != nil {
return fmt.Errorf("error reading profile from file: %w", err)
}
table := InitializeTable(cmd)

if proj != "" {
if p.Context == nil {
p.Context = &pb.Context{}
createFunc := func(f string, p *pb.Profile) (*pb.Profile, error) {
// create a profile
resp, err := client.CreateProfile(ctx, &pb.CreateProfileRequest{
Profile: p,
})
if err != nil {
return nil, err
}

p.Context.Project = &proj
return resp.GetProfile(), nil
}

// create a profile
resp, err := client.CreateProfile(ctx, &pb.CreateProfileRequest{
Profile: p,
})
if err != nil {
return fmt.Errorf("error creating profile: %w", err)
if err := execOnOneProfile(table, f, cmd.InOrStdin(), proj, createFunc); err != nil {
return err
}

table := InitializeTable(cmd)
RenderProfileTable(resp.GetProfile(), table)
table.Render()
return nil
},
Expand All @@ -105,5 +75,9 @@ within a minder control plane.`,
func init() {
ProfileCmd.AddCommand(Profile_createCmd)
Profile_createCmd.Flags().StringP("file", "f", "", "Path to the YAML defining the profile (or - for stdin)")
if err := Profile_createCmd.MarkFlagRequired("file"); err != nil {
fmt.Fprintf(os.Stderr, "Error marking flag required: %s\n", err)
os.Exit(1)
}
Profile_createCmd.Flags().StringP("project", "p", "", "Project to create the profile in")
}
Loading