-
Notifications
You must be signed in to change notification settings - Fork 173
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
refactor(cli): restructure commands, option flags and validation #1547
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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 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 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 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 |
---|---|---|
@@ -1,6 +1,7 @@ | ||
package apply | ||
|
||
import ( | ||
"context" | ||
goerrors "errors" | ||
"fmt" | ||
|
||
|
@@ -20,104 +21,156 @@ | |
kargosvcapi "github.com/akuity/kargo/pkg/api/service/v1alpha1" | ||
) | ||
|
||
type applyOptions struct { | ||
*option.Option | ||
Config config.CLIConfig | ||
|
||
Filenames []string | ||
} | ||
|
||
func NewCommand(cfg config.CLIConfig, opt *option.Option) *cobra.Command { | ||
var filenames []string | ||
cmdOpts := &applyOptions{ | ||
Option: opt, | ||
Config: cfg, | ||
} | ||
|
||
cmd := &cobra.Command{ | ||
Use: "apply [--project=project] -f (FILENAME)", | ||
Short: "Apply a resource from a file or from stdin", | ||
Example: ` | ||
# Apply a stage using the data in stage.yaml | ||
kargo apply -f stage.yaml | ||
`, | ||
RunE: func(cmd *cobra.Command, args []string) error { | ||
ctx := cmd.Context() | ||
if len(filenames) == 0 { | ||
return errors.New("filename is required") | ||
RunE: func(cmd *cobra.Command, _ []string) error { | ||
if err := cmdOpts.validate(); err != nil { | ||
return err | ||
} | ||
|
||
rawManifest, err := yaml.Read(filenames) | ||
if err != nil { | ||
return errors.Wrap(err, "read manifests") | ||
} | ||
return cmdOpts.run(cmd.Context()) | ||
}, | ||
} | ||
|
||
var printer printers.ResourcePrinter | ||
if ptr.Deref(opt.PrintFlags.OutputFormat, "") != "" { | ||
printer, err = opt.PrintFlags.ToPrinter() | ||
if err != nil { | ||
return errors.Wrap(err, "new printer") | ||
} | ||
} | ||
// Register the option flags on the command. | ||
cmdOpts.addFlags(cmd) | ||
|
||
kargoSvcCli, err := client.GetClientFromConfig(ctx, cfg, opt) | ||
if err != nil { | ||
return errors.Wrap(err, "get client from config") | ||
} | ||
return cmd | ||
} | ||
|
||
// TODO: Current implementation of apply is not the same as `kubectl` does. | ||
// It actually "replaces" resource with the given file. | ||
// We should provide the same implementation as `kubectl` does. | ||
resp, err := kargoSvcCli.CreateOrUpdateResource(ctx, | ||
connect.NewRequest(&kargosvcapi.CreateOrUpdateResourceRequest{ | ||
Manifest: rawManifest, | ||
})) | ||
if err != nil { | ||
return errors.Wrap(err, "apply resource") | ||
} | ||
// addFlags adds the flags for the apply options to the provided command. | ||
func (o *applyOptions) addFlags(cmd *cobra.Command) { | ||
o.PrintFlags.AddFlags(cmd) | ||
|
||
resCap := len(resp.Msg.GetResults()) | ||
createdRes := make([]*kargosvcapi.CreateOrUpdateResourceResult_CreatedResourceManifest, 0, resCap) | ||
updatedRes := make([]*kargosvcapi.CreateOrUpdateResourceResult_UpdatedResourceManifest, 0, resCap) | ||
errs := make([]error, 0, resCap) | ||
for _, r := range resp.Msg.GetResults() { | ||
switch typedRes := r.GetResult().(type) { | ||
case *kargosvcapi.CreateOrUpdateResourceResult_CreatedResourceManifest: | ||
createdRes = append(createdRes, typedRes) | ||
case *kargosvcapi.CreateOrUpdateResourceResult_UpdatedResourceManifest: | ||
updatedRes = append(updatedRes, typedRes) | ||
case *kargosvcapi.CreateOrUpdateResourceResult_Error: | ||
errs = append(errs, errors.New(typedRes.Error)) | ||
} | ||
} | ||
for _, r := range createdRes { | ||
var obj unstructured.Unstructured | ||
if err := sigyaml.Unmarshal(r.CreatedResourceManifest, &obj); err != nil { | ||
fmt.Fprintf(opt.IOStreams.ErrOut, "%s", | ||
errors.Wrap(err, "Error: unmarshal created manifest")) | ||
continue | ||
} | ||
if printer == nil { | ||
name := types.NamespacedName{ | ||
Namespace: obj.GetNamespace(), | ||
Name: obj.GetName(), | ||
}.String() | ||
fmt.Fprintf(opt.IOStreams.Out, "%s Created: %q\n", obj.GetKind(), name) | ||
continue | ||
} | ||
_ = printer.PrintObj(&obj, opt.IOStreams.Out) | ||
} | ||
for _, r := range updatedRes { | ||
var obj unstructured.Unstructured | ||
if err := sigyaml.Unmarshal(r.UpdatedResourceManifest, &obj); err != nil { | ||
fmt.Fprintf(opt.IOStreams.ErrOut, "%s", | ||
errors.Wrap(err, "Error: unmarshal updated manifest")) | ||
continue | ||
} | ||
if printer == nil { | ||
name := types.NamespacedName{ | ||
Namespace: obj.GetNamespace(), | ||
Name: obj.GetName(), | ||
}.String() | ||
fmt.Fprintf(opt.IOStreams.Out, "%s Updated: %q\n", obj.GetKind(), name) | ||
continue | ||
} | ||
_ = printer.PrintObj(&obj, opt.IOStreams.Out) | ||
} | ||
return goerrors.Join(errs...) | ||
}, | ||
// TODO: Factor out server flags to a higher level (root?) as they are | ||
// common to almost all commands. | ||
option.InsecureTLS(cmd.PersistentFlags(), o.Option) | ||
option.LocalServer(cmd.PersistentFlags(), o.Option) | ||
|
||
option.Filenames(cmd.Flags(), &o.Filenames, "Filename or directory to use to apply the resource(s)") | ||
|
||
if err := cmd.MarkFlagRequired(option.FilenameFlag); err != nil { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. These are new since the last time I went deep on Cobra. I am super excited about how much this cleans things up. |
||
panic(errors.Wrap(err, "could not mark filename flag as required")) | ||
} | ||
opt.PrintFlags.AddFlags(cmd) | ||
option.Filenames(cmd.Flags(), &filenames, "apply") | ||
option.InsecureTLS(cmd.PersistentFlags(), opt) | ||
option.LocalServer(cmd.PersistentFlags(), opt) | ||
return cmd | ||
if err := cmd.MarkFlagFilename(option.FilenameFlag, ".yaml", ".yml"); err != nil { | ||
panic(errors.Wrap(err, "could not mark filename flag as filename")) | ||
} | ||
if err := cmd.MarkFlagDirname(option.FilenameFlag); err != nil { | ||
panic(errors.Wrap(err, "could not mark filename flag as dirname")) | ||
} | ||
} | ||
|
||
// validate performs validation of the options. If the options are invalid, an | ||
// error is returned. | ||
func (o *applyOptions) validate() error { | ||
// While the filename flag is marked as required, a user could still | ||
// provide an empty string. This is a check to ensure that the flag is | ||
// not empty. | ||
if len(o.Filenames) == 0 { | ||
return errors.New("filename is required") | ||
} | ||
return nil | ||
} | ||
|
||
// run performs the apply operation using the provided options. | ||
func (o *applyOptions) run(ctx context.Context) error { | ||
rawManifest, err := yaml.Read(o.Filenames) | ||
if err != nil { | ||
return errors.Wrap(err, "read manifests") | ||
} | ||
|
||
var printer printers.ResourcePrinter | ||
if ptr.Deref(o.PrintFlags.OutputFormat, "") != "" { | ||
printer, err = o.PrintFlags.ToPrinter() | ||
if err != nil { | ||
return errors.Wrap(err, "new printer") | ||
} | ||
} | ||
|
||
kargoSvcCli, err := client.GetClientFromConfig(ctx, o.Config, o.Option) | ||
if err != nil { | ||
return errors.Wrap(err, "get client from config") | ||
} | ||
|
||
// TODO: Current implementation of apply is not the same as `kubectl` does. | ||
// It actually "replaces" resource with the given file. | ||
// We should provide the same implementation as `kubectl` does. | ||
resp, err := kargoSvcCli.CreateOrUpdateResource(ctx, | ||
connect.NewRequest(&kargosvcapi.CreateOrUpdateResourceRequest{ | ||
Manifest: rawManifest, | ||
})) | ||
if err != nil { | ||
return errors.Wrap(err, "apply resource") | ||
} | ||
|
||
resCap := len(resp.Msg.GetResults()) | ||
createdRes := make([]*kargosvcapi.CreateOrUpdateResourceResult_CreatedResourceManifest, 0, resCap) | ||
updatedRes := make([]*kargosvcapi.CreateOrUpdateResourceResult_UpdatedResourceManifest, 0, resCap) | ||
errs := make([]error, 0, resCap) | ||
for _, r := range resp.Msg.GetResults() { | ||
switch typedRes := r.GetResult().(type) { | ||
case *kargosvcapi.CreateOrUpdateResourceResult_CreatedResourceManifest: | ||
createdRes = append(createdRes, typedRes) | ||
case *kargosvcapi.CreateOrUpdateResourceResult_UpdatedResourceManifest: | ||
updatedRes = append(updatedRes, typedRes) | ||
case *kargosvcapi.CreateOrUpdateResourceResult_Error: | ||
errs = append(errs, errors.New(typedRes.Error)) | ||
} | ||
} | ||
|
||
for _, res := range createdRes { | ||
var obj unstructured.Unstructured | ||
if err := sigyaml.Unmarshal(res.CreatedResourceManifest, &obj); err != nil { | ||
fmt.Fprintf(o.IOStreams.ErrOut, "%s", | ||
errors.Wrap(err, "Error: unmarshal created manifest")) | ||
continue | ||
} | ||
if printer == nil { | ||
name := types.NamespacedName{ | ||
Namespace: obj.GetNamespace(), | ||
Name: obj.GetName(), | ||
}.String() | ||
fmt.Fprintf(o.IOStreams.Out, "%s Created: %q\n", obj.GetKind(), name) | ||
continue | ||
} | ||
_ = printer.PrintObj(&obj, o.IOStreams.Out) | ||
} | ||
|
||
for _, res := range updatedRes { | ||
var obj unstructured.Unstructured | ||
if err := sigyaml.Unmarshal(res.UpdatedResourceManifest, &obj); err != nil { | ||
fmt.Fprintf(o.IOStreams.ErrOut, "%s", | ||
errors.Wrap(err, "Error: unmarshal updated manifest")) | ||
continue | ||
} | ||
if printer == nil { | ||
name := types.NamespacedName{ | ||
Namespace: obj.GetNamespace(), | ||
Name: obj.GetName(), | ||
}.String() | ||
fmt.Fprintf(o.IOStreams.Out, "%s Updated: %q\n", obj.GetKind(), name) | ||
continue | ||
} | ||
_ = printer.PrintObj(&obj, o.IOStreams.Out) | ||
} | ||
|
||
return goerrors.Join(errs...) | ||
} |
Oops, something went wrong.
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.
Ya... it's tricky. Almost but not all commands use them.
Personally, I'd rather repeat ourselves sometimes that have inapplicable flags show up on commands. i.e. If we had to choose, UX wins over DRY, imho.
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.
A problem I have observed though is that we sometimes ourselves forget to actually wire them in (see e.g. https://github.com/akuity/kargo/blob/5912e5a9dfd2912fdd6a46e1b35655b6225c4454/internal/cli/cmd/approve/approve.go in current
main
, which AFAIK should have the flags set).By registering them once at root and loading them into some config which is passed to downward commands, this could be avoided.
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.
Is there a way to do it at root and unregister them in spots?
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 think you can theoretically use
MarkHidden
to hide them from the help menu for specific commands.