This is an automated email from the ASF dual-hosted git repository. astefanutti pushed a commit to branch main in repository https://gitbox.apache.org/repos/asf/camel-k.git
commit 8cb181c6e057b068939f245cafcab3c58d9a0616 Author: Kuthumi Pepple <[email protected]> AuthorDate: Wed Mar 30 06:05:02 2022 +0100 fix: redirect ouput and errors to appropriate writer --- cmd/util/json-schema-gen/main.go | 2 +- cmd/util/license-check/main.go | 2 +- e2e/support/test_support.go | 4 ++-- pkg/cmd/bind.go | 4 ++-- pkg/cmd/completion_bash.go | 2 +- pkg/cmd/completion_zsh.go | 2 +- pkg/cmd/debug.go | 10 +++++----- pkg/cmd/delete.go | 24 +++++++++++------------ pkg/cmd/describe_integration.go | 6 +++--- pkg/cmd/describe_kamelet.go | 8 ++++---- pkg/cmd/describe_kit.go | 8 ++++---- pkg/cmd/describe_platform.go | 6 +++--- pkg/cmd/dump.go | 2 +- pkg/cmd/install.go | 14 +++++++------- pkg/cmd/kamelet_delete.go | 12 ++++++------ pkg/cmd/kamelet_get.go | 2 +- pkg/cmd/kit_create.go | 14 +++++++------- pkg/cmd/kit_delete.go | 14 +++++++------- pkg/cmd/kit_get.go | 2 +- pkg/cmd/local_build.go | 2 +- pkg/cmd/local_inspect.go | 8 ++++---- pkg/cmd/local_run.go | 4 ++-- pkg/cmd/log.go | 6 +++--- pkg/cmd/modeline.go | 8 ++++---- pkg/cmd/rebuild.go | 4 ++-- pkg/cmd/reset.go | 20 +++++++++---------- pkg/cmd/root.go | 2 +- pkg/cmd/run.go | 36 +++++++++++++++++----------------- pkg/cmd/run_help.go | 7 ++++--- pkg/cmd/run_test.go | 7 ++++--- pkg/cmd/uninstall.go | 42 ++++++++++++++++++++-------------------- pkg/cmd/util_commands.go | 2 +- pkg/cmd/util_containerization.go | 14 +++++++++----- pkg/cmd/util_dependencies.go | 15 +++++++------- pkg/cmd/util_sources.go | 5 +++-- pkg/cmd/version.go | 6 +++--- pkg/cmd/version_test.go | 15 +++++++------- pkg/install/operator.go | 31 +++++++++++++++-------------- pkg/util/kubernetes/log/util.go | 9 +++++---- pkg/util/tar/util_compress.go | 8 +++++--- 40 files changed, 201 insertions(+), 188 deletions(-) diff --git a/cmd/util/json-schema-gen/main.go b/cmd/util/json-schema-gen/main.go index 671bc178c..098274e4a 100644 --- a/cmd/util/json-schema-gen/main.go +++ b/cmd/util/json-schema-gen/main.go @@ -35,7 +35,7 @@ import ( func main() { if len(os.Args) != 6 { - fmt.Println(`Use "json-schema-gen <crd> <schema> <path> <isArray> <destination>`) + fmt.Fprintln(os.Stderr, `Use "json-schema-gen <crd> <schema> <path> <isArray> <destination>`) os.Exit(1) } crd := os.Args[1] diff --git a/cmd/util/license-check/main.go b/cmd/util/license-check/main.go index c2300e511..1d411ee31 100644 --- a/cmd/util/license-check/main.go +++ b/cmd/util/license-check/main.go @@ -27,7 +27,7 @@ import ( func main() { if len(os.Args) != 3 { - fmt.Println(`Use "license-check <file> <license>`) + fmt.Fprintln(os.Stderr, `Use "license-check <file> <license>`) os.Exit(1) } diff --git a/e2e/support/test_support.go b/e2e/support/test_support.go index b964f8a51..83f566251 100644 --- a/e2e/support/test_support.go +++ b/e2e/support/test_support.go @@ -1728,9 +1728,9 @@ func UserCleanup() { command.Stderr = os.Stderr command.Stdout = os.Stdout if err := command.Run(); err != nil { - fmt.Printf("An error occurred during user cleanup command execution: %v\n", err) + fmt.Fprintf(command.Stderr, "An error occurred during user cleanup command execution: %v\n", err) } else { - fmt.Printf("User cleanup command completed successfully\n") + fmt.Fprintf(command.Stdout, "User cleanup command completed successfully\n") } } } diff --git a/pkg/cmd/bind.go b/pkg/cmd/bind.go index e8c59e24c..c5f1a0f01 100644 --- a/pkg/cmd/bind.go +++ b/pkg/cmd/bind.go @@ -219,9 +219,9 @@ func (o *bindCmdOptions) run(cmd *cobra.Command, args []string) error { } if !existed { - fmt.Printf("kamelet binding \"%s\" created\n", name) + fmt.Fprintf(cmd.OutOrStdout(), "kamelet binding \"%s\" created\n", name) } else { - fmt.Printf("kamelet binding \"%s\" updated\n", name) + fmt.Fprintf(cmd.OutOrStdout(), "kamelet binding \"%s\" updated\n", name) } return nil } diff --git a/pkg/cmd/completion_bash.go b/pkg/cmd/completion_bash.go index 8fbaccdeb..0c751ef49 100644 --- a/pkg/cmd/completion_bash.go +++ b/pkg/cmd/completion_bash.go @@ -216,7 +216,7 @@ func newCmdCompletionBash(root *cobra.Command) *cobra.Command { Run: func(_ *cobra.Command, _ []string) { err := root.GenBashCompletion(root.OutOrStdout()) if err != nil { - fmt.Print(err.Error()) + fmt.Fprint(root.ErrOrStderr(), err.Error()) } }, Annotations: map[string]string{ diff --git a/pkg/cmd/completion_zsh.go b/pkg/cmd/completion_zsh.go index 4ecfd7549..3621c86a9 100644 --- a/pkg/cmd/completion_zsh.go +++ b/pkg/cmd/completion_zsh.go @@ -51,7 +51,7 @@ func newCmdCompletionZsh(root *cobra.Command) *cobra.Command { Run: func(_ *cobra.Command, _ []string) { err := root.GenZshCompletion(root.OutOrStdout()) if err != nil { - fmt.Print(err.Error()) + fmt.Fprint(root.ErrOrStderr(), err.Error()) } }, Annotations: map[string]string{ diff --git a/pkg/cmd/debug.go b/pkg/cmd/debug.go index e0702c40a..06986c931 100644 --- a/pkg/cmd/debug.go +++ b/pkg/cmd/debug.go @@ -100,15 +100,15 @@ func (o *debugCmdOptions) run(cmd *cobra.Command, args []string) error { // Context canceled return } - fmt.Printf("Disabling debug mode on integration %q\n", name) + fmt.Fprintf(cmd.OutOrStdout(), "Disabling debug mode on integration %q\n", name) it, err := c.Integrations(o.Namespace).Get(o.Context, name, metav1.GetOptions{}) if err != nil { - fmt.Println(err) + fmt.Fprintln(cmd.ErrOrStderr(), err.Error()) os.Exit(1) } _, err = o.toggleDebug(c, it, false) if err != nil { - fmt.Println(err) + fmt.Fprintln(cmd.ErrOrStderr(), err.Error()) os.Exit(1) } os.Exit(0) @@ -122,9 +122,9 @@ func (o *debugCmdOptions) run(cmd *cobra.Command, args []string) error { selector := fmt.Sprintf("camel.apache.org/debug=true,camel.apache.org/integration=%s", name) go func() { - err = k8slog.PrintUsingSelector(o.Context, cmdClient, o.Namespace, "integration", selector, cmd.OutOrStdout()) + err = k8slog.PrintUsingSelector(o.Context, cmd, cmdClient, o.Namespace, "integration", selector, cmd.OutOrStdout()) if err != nil { - fmt.Println(err) + fmt.Fprintln(cmd.ErrOrStderr(), err.Error()) } }() diff --git a/pkg/cmd/delete.go b/pkg/cmd/delete.go index 2eafc5753..509fc4bbe 100644 --- a/pkg/cmd/delete.go +++ b/pkg/cmd/delete.go @@ -42,12 +42,12 @@ func newCmdDelete(rootCmdOptions *RootCmdOptions) (*cobra.Command, *deleteCmdOpt Use: "delete [integration1] [integration2] ...", Short: "Delete integrations deployed on Kubernetes", PreRunE: decode(&options), - RunE: func(_ *cobra.Command, args []string) error { + RunE: func(cmd *cobra.Command, args []string) error { if err := options.validate(args); err != nil { return err } - if err := options.run(args); err != nil { - fmt.Println(err.Error()) + if err := options.run(cmd, args); err != nil { + fmt.Fprintln(cmd.ErrOrStderr(), err.Error()) } return nil @@ -75,7 +75,7 @@ func (command *deleteCmdOptions) validate(args []string) error { return nil } -func (command *deleteCmdOptions) run(args []string) error { +func (command *deleteCmdOptions) run(cmd *cobra.Command, args []string) error { c, err := command.GetCmdClient() if err != nil { return err @@ -86,16 +86,16 @@ func (command *deleteCmdOptions) run(args []string) error { integration, err := getIntegration(command.Context, c, name, command.Namespace) if err != nil { if k8errors.IsNotFound(err) { - fmt.Println("Integration " + name + " not found. Skipped.") + fmt.Fprintln(cmd.OutOrStdout(), "Integration "+name+" not found. Skipped.") } else { return err } } else { - err := deleteIntegration(command.Context, c, integration) + err := deleteIntegration(cmd, command.Context, c, integration) if err != nil { return err } - fmt.Println("Integration " + name + " deleted") + fmt.Fprintln(cmd.OutOrStdout(), "Integration "+name+" deleted") } } } else if command.DeleteAll { @@ -112,15 +112,15 @@ func (command *deleteCmdOptions) run(args []string) error { } for _, integration := range integrationList.Items { integration := integration // pin - err := deleteIntegration(command.Context, c, &integration) + err := deleteIntegration(cmd, command.Context, c, &integration) if err != nil { return err } } if len(integrationList.Items) == 0 { - fmt.Println("Nothing to delete") + fmt.Fprintln(cmd.OutOrStdout(), "Nothing to delete") } else { - fmt.Println(strconv.Itoa(len(integrationList.Items)) + " integration(s) deleted") + fmt.Fprintln(cmd.OutOrStdout(), strconv.Itoa(len(integrationList.Items))+" integration(s) deleted") } } @@ -139,14 +139,14 @@ func getIntegration(ctx context.Context, c client.Client, name string, namespace return &answer, nil } -func deleteIntegration(ctx context.Context, c client.Client, integration *v1.Integration) error { +func deleteIntegration(cmd *cobra.Command, ctx context.Context, c client.Client, integration *v1.Integration) error { deleted, binding, err := deleteKameletBindingIfExists(ctx, c, integration) if err != nil { return err } if deleted { // Deleting KameletBinding will automatically clean up the integration - fmt.Println("KameletBinding " + binding + " deleted") + fmt.Fprintln(cmd.OutOrStdout(),"KameletBinding " + binding + " deleted") return nil } return c.Delete(ctx, integration) diff --git a/pkg/cmd/describe_integration.go b/pkg/cmd/describe_integration.go index 0cfa292a9..5930a7146 100644 --- a/pkg/cmd/describe_integration.go +++ b/pkg/cmd/describe_integration.go @@ -47,7 +47,7 @@ func newDescribeIntegrationCmd(rootCmdOptions *RootCmdOptions) (*cobra.Command, return err } if err := options.run(cmd, args); err != nil { - fmt.Println(err.Error()) + fmt.Fprintln(cmd.ErrOrStderr(), err.Error()) } return nil @@ -85,9 +85,9 @@ func (command *describeIntegrationCommandOptions) run(cmd *cobra.Command, args [ if err := c.Get(command.Context, key, &ctx); err == nil { if desc, err := command.describeIntegration(cmd, ctx); err == nil { - fmt.Print(desc) + fmt.Fprint(cmd.OutOrStdout(), desc) } else { - fmt.Println(err) + fmt.Fprintln(cmd.ErrOrStderr(), err) } } else { fmt.Fprintf(cmd.OutOrStdout(), "Integration '%s' does not exist.\n", args[0]) diff --git a/pkg/cmd/describe_kamelet.go b/pkg/cmd/describe_kamelet.go index ad11ac5b2..4edb8ff54 100644 --- a/pkg/cmd/describe_kamelet.go +++ b/pkg/cmd/describe_kamelet.go @@ -47,7 +47,7 @@ func newDescribeKameletCmd(rootCmdOptions *RootCmdOptions) (*cobra.Command, *des return err } if err := options.run(cmd, args); err != nil { - fmt.Println(err.Error()) + fmt.Fprintln(cmd.ErrOrStderr(), err.Error()) } return nil @@ -82,12 +82,12 @@ func (command *describeKameletCommandOptions) run(cmd *cobra.Command, args []str if err := c.Get(command.Context, kameletKey, &kamelet); err == nil { if desc, err := command.describeKamelet(cmd, kamelet); err == nil { - fmt.Print(desc) + fmt.Fprint(cmd.OutOrStdout(), desc) } else { - fmt.Println(err) + fmt.Fprintln(cmd.ErrOrStderr(), err) } } else { - fmt.Printf("Kamelet '%s' does not exist.\n", args[0]) + fmt.Fprintf(cmd.OutOrStdout(), "Kamelet '%s' does not exist.\n", args[0]) } return nil diff --git a/pkg/cmd/describe_kit.go b/pkg/cmd/describe_kit.go index fd76c639d..ff40aea09 100644 --- a/pkg/cmd/describe_kit.go +++ b/pkg/cmd/describe_kit.go @@ -46,7 +46,7 @@ func newDescribeKitCmd(rootCmdOptions *RootCmdOptions) (*cobra.Command, *describ return err } if err := options.run(cmd, args); err != nil { - fmt.Println(err.Error()) + fmt.Fprintln(cmd.ErrOrStderr(), err.Error()) } return nil @@ -81,12 +81,12 @@ func (command *describeKitCommandOptions) run(cmd *cobra.Command, args []string) if err := c.Get(command.Context, kitKey, kit); err == nil { if desc, err := command.describeIntegrationKit(cmd, kit); err == nil { - fmt.Print(desc) + fmt.Fprint(cmd.OutOrStdout(), desc) } else { - fmt.Println(err) + fmt.Fprintln(cmd.ErrOrStderr(), err) } } else { - fmt.Printf("IntegrationKit '%s' does not exist.\n", args[0]) + fmt.Fprintf(cmd.OutOrStdout(), "IntegrationKit '%s' does not exist.\n", args[0]) } return nil diff --git a/pkg/cmd/describe_platform.go b/pkg/cmd/describe_platform.go index 5900ad031..619956cb8 100644 --- a/pkg/cmd/describe_platform.go +++ b/pkg/cmd/describe_platform.go @@ -46,7 +46,7 @@ func newDescribePlatformCmd(rootCmdOptions *RootCmdOptions) (*cobra.Command, *de return err } if err := options.run(cmd, args); err != nil { - fmt.Println(err.Error()) + fmt.Fprintln(cmd.OutOrStderr(), err.Error()) } return nil @@ -81,9 +81,9 @@ func (command *describePlatformCommandOptions) run(cmd *cobra.Command, args []st if err := c.Get(command.Context, platformKey, &platform); err == nil { if desc, err := command.describeIntegrationPlatform(cmd, platform); err == nil { - fmt.Print(desc) + fmt.Fprint(cmd.OutOrStdout(), desc) } else { - fmt.Println(err) + fmt.Fprintln(cmd.ErrOrStderr(), err) } } else { fmt.Fprintf(cmd.OutOrStdout(), "IntegrationPlatform '%s' does not exist.\n", args[0]) diff --git a/pkg/cmd/dump.go b/pkg/cmd/dump.go index a92f7f491..1fb6cdc65 100644 --- a/pkg/cmd/dump.go +++ b/pkg/cmd/dump.go @@ -75,7 +75,7 @@ func (o *dumpCmdOptions) dump(cmd *cobra.Command, args []string) (err error) { if err != nil { return err } - tar.CreateTarFile([]string{file.Name()}, "dump."+file.Name()+"."+time.Now().Format(time.RFC3339)+".tar.gz") + tar.CreateTarFile([]string{file.Name()}, "dump."+file.Name()+"."+time.Now().Format(time.RFC3339)+".tar.gz", cmd) return nil }) } else { diff --git a/pkg/cmd/install.go b/pkg/cmd/install.go index 504e098c8..1334695b9 100644 --- a/pkg/cmd/install.go +++ b/pkg/cmd/install.go @@ -302,7 +302,7 @@ func (o *installCmdOptions) install(cobraCmd *cobra.Command, _ []string) error { ResourcesRequirements: o.ResourcesRequirements, EnvVars: o.EnvVars, } - err = install.OperatorOrCollect(o.Context, c, cfg, collection, o.Force) + err = install.OperatorOrCollect(o.Context, cobraCmd, c, cfg, collection, o.Force) if err != nil { return err } @@ -474,15 +474,15 @@ func (o *installCmdOptions) install(cobraCmd *cobra.Command, _ []string) error { strategy = "via OLM subscription" } if o.Global { - fmt.Println("Camel K installed in namespace", namespace, strategy, "(global mode)") + fmt.Fprintln(cobraCmd.OutOrStdout(), "Camel K installed in namespace", namespace, strategy, "(global mode)") } else { - fmt.Println("Camel K installed in namespace", namespace, strategy) + fmt.Fprintln(cobraCmd.OutOrStdout(), "Camel K installed in namespace", namespace, strategy) } } } if collection != nil { - return o.printOutput(collection) + return o.printOutput(cobraCmd, collection) } return nil @@ -503,7 +503,7 @@ func (o *installCmdOptions) postRun(cmd *cobra.Command, _ []string) error { return nil } -func (o *installCmdOptions) printOutput(collection *kubernetes.Collection) error { +func (o *installCmdOptions) printOutput(cmd *cobra.Command, collection *kubernetes.Collection) error { lst := collection.AsKubernetesList() switch o.OutputFormat { case "yaml": @@ -511,13 +511,13 @@ func (o *installCmdOptions) printOutput(collection *kubernetes.Collection) error if err != nil { return err } - fmt.Print(string(data)) + fmt.Fprint(cmd.OutOrStdout(), string(data)) case "json": data, err := kubernetes.ToJSON(lst) if err != nil { return err } - fmt.Print(string(data)) + fmt.Fprint(cmd.OutOrStdout(), (data)) default: return errors.New("unknown output format: " + o.OutputFormat) } diff --git a/pkg/cmd/kamelet_delete.go b/pkg/cmd/kamelet_delete.go index 6c81ce5b8..38a070fa8 100644 --- a/pkg/cmd/kamelet_delete.go +++ b/pkg/cmd/kamelet_delete.go @@ -43,8 +43,8 @@ func newKameletDeleteCmd(rootCmdOptions *RootCmdOptions) (*cobra.Command, *kamel if err := options.validate(args); err != nil { return err } - if err := options.run(args); err != nil { - fmt.Println(err.Error()) + if err := options.run(cmd, args); err != nil { + fmt.Fprintln(cmd.ErrOrStderr(), err.Error()) } return nil @@ -72,7 +72,7 @@ func (command *kameletDeleteCommandOptions) validate(args []string) error { return nil } -func (command *kameletDeleteCommandOptions) run(args []string) error { +func (command *kameletDeleteCommandOptions) run(cmd *cobra.Command, args []string) error { names := args c, err := command.GetCmdClient() @@ -95,7 +95,7 @@ func (command *kameletDeleteCommandOptions) run(args []string) error { } for _, name := range names { - if err := command.delete(name); err != nil { + if err := command.delete(cmd, name); err != nil { return err } } @@ -103,7 +103,7 @@ func (command *kameletDeleteCommandOptions) run(args []string) error { return nil } -func (command *kameletDeleteCommandOptions) delete(name string) error { +func (command *kameletDeleteCommandOptions) delete(cmd *cobra.Command, name string) error { c, err := command.GetCmdClient() if err != nil { return err @@ -139,6 +139,6 @@ func (command *kameletDeleteCommandOptions) delete(name string) error { } return fmt.Errorf("error deleting kamelet \"%s\": %w", name, err) } - fmt.Printf("kamelet \"%s\" has been deleted\n", name) + fmt.Fprintf(cmd.OutOrStdout(), "kamelet \"%s\" has been deleted\n", name) return nil } diff --git a/pkg/cmd/kamelet_get.go b/pkg/cmd/kamelet_get.go index 5fb19f0ae..013e92c0f 100644 --- a/pkg/cmd/kamelet_get.go +++ b/pkg/cmd/kamelet_get.go @@ -45,7 +45,7 @@ func newKameletGetCmd(rootCmdOptions *RootCmdOptions) (*cobra.Command, *kameletG return err } if err := options.run(cmd); err != nil { - fmt.Println(err.Error()) + fmt.Fprintln(cmd.ErrOrStderr(), err.Error()) } return nil diff --git a/pkg/cmd/kit_create.go b/pkg/cmd/kit_create.go index 4c16aba49..3b295843f 100644 --- a/pkg/cmd/kit_create.go +++ b/pkg/cmd/kit_create.go @@ -82,7 +82,7 @@ func (command *kitCreateCommandOptions) validateArgs(_ *cobra.Command, args []st return nil } -func (command *kitCreateCommandOptions) run(_ *cobra.Command, args []string) error { +func (command *kitCreateCommandOptions) run(cmd *cobra.Command, args []string) error { c, err := command.GetCmdClient() if err != nil { return err @@ -94,7 +94,7 @@ func (command *kitCreateCommandOptions) run(_ *cobra.Command, args []string) err kv := strings.SplitN(t, "=", 2) if !util.StringSliceExists(tp, kv[0]) { - fmt.Printf("Error: %s is not a valid trait property\n", t) + fmt.Fprintf(cmd.OutOrStdout(), "Error: %s is not a valid trait property\n", t) return nil } } @@ -109,7 +109,7 @@ func (command *kitCreateCommandOptions) run(_ *cobra.Command, args []string) err // not a platform one which is supposed to be "read only" if kit.Labels[v1.IntegrationKitTypeLabel] == v1.IntegrationKitTypePlatform { - fmt.Printf("integration kit \"%s\" is not editable\n", kit.Name) + fmt.Fprintf(cmd.OutOrStdout(), "integration kit \"%s\" is not editable\n", kit.Name) return nil } } @@ -175,7 +175,7 @@ func (command *kitCreateCommandOptions) run(_ *cobra.Command, args []string) err existing := v1.NewIntegrationKit(kit.Namespace, kit.Name) err = c.Get(command.Context, key, existing) if err != nil { - fmt.Print(err.Error()) + fmt.Fprint(cmd.ErrOrStderr(), err.Error()) return nil } kit.ResourceVersion = existing.ResourceVersion @@ -183,14 +183,14 @@ func (command *kitCreateCommandOptions) run(_ *cobra.Command, args []string) err } if err != nil { - fmt.Print(err.Error()) + fmt.Fprint(cmd.ErrOrStderr(), err.Error()) return nil } if !existed { - fmt.Printf("integration kit \"%s\" created\n", kit.Name) + fmt.Fprintf(cmd.OutOrStdout(), "integration kit \"%s\" created\n", kit.Name) } else { - fmt.Printf("integration kit \"%s\" updated\n", kit.Name) + fmt.Fprintf(cmd.OutOrStdout(), "integration kit \"%s\" updated\n", kit.Name) } return nil diff --git a/pkg/cmd/kit_delete.go b/pkg/cmd/kit_delete.go index 57428a0a3..5999ec781 100644 --- a/pkg/cmd/kit_delete.go +++ b/pkg/cmd/kit_delete.go @@ -40,12 +40,12 @@ func newKitDeleteCmd(rootCmdOptions *RootCmdOptions) (*cobra.Command, *kitDelete Short: "Delete an Integration Kit", Long: `Delete an Integration Kit.`, PreRunE: decode(&options), - RunE: func(_ *cobra.Command, args []string) error { + RunE: func(cmd *cobra.Command, args []string) error { if err := options.validate(args); err != nil { return err } - if err := options.run(args); err != nil { - fmt.Println(err.Error()) + if err := options.run(cmd, args); err != nil { + fmt.Fprintln(cmd.ErrOrStderr(), err.Error()) } return nil @@ -73,7 +73,7 @@ func (command *kitDeleteCommandOptions) validate(args []string) error { return nil } -func (command *kitDeleteCommandOptions) run(args []string) error { +func (command *kitDeleteCommandOptions) run(cmd *cobra.Command, args []string) error { names := args c, err := command.GetCmdClient() @@ -97,7 +97,7 @@ func (command *kitDeleteCommandOptions) run(args []string) error { } for _, name := range names { - if err := command.delete(name); err != nil { + if err := command.delete(cmd, name); err != nil { return err } } @@ -105,7 +105,7 @@ func (command *kitDeleteCommandOptions) run(args []string) error { return nil } -func (command *kitDeleteCommandOptions) delete(name string) error { +func (command *kitDeleteCommandOptions) delete(cmd *cobra.Command, name string) error { kit := v1.NewIntegrationKit(command.Namespace, name) c, err := command.GetCmdClient() if err != nil { @@ -144,7 +144,7 @@ func (command *kitDeleteCommandOptions) delete(name string) error { return fmt.Errorf("no integration kit found with name \"%s\"", kit.Name) } - fmt.Printf("integration kit \"%s\" has been deleted\n", kit.Name) + fmt.Fprintf(cmd.OutOrStdout(), "integration kit \"%s\" has been deleted\n", kit.Name) return err } diff --git a/pkg/cmd/kit_get.go b/pkg/cmd/kit_get.go index ac6788223..e74864897 100644 --- a/pkg/cmd/kit_get.go +++ b/pkg/cmd/kit_get.go @@ -43,7 +43,7 @@ func newKitGetCmd(rootCmdOptions *RootCmdOptions) (*cobra.Command, *kitGetComman return err } if err := options.run(cmd); err != nil { - fmt.Println(err.Error()) + fmt.Fprintln(cmd.ErrOrStderr(), err.Error()) } return nil diff --git a/pkg/cmd/local_build.go b/pkg/cmd/local_build.go index e2b0322ec..222c510de 100644 --- a/pkg/cmd/local_build.go +++ b/pkg/cmd/local_build.go @@ -44,7 +44,7 @@ func newCmdLocalBuild(rootCmdOptions *RootCmdOptions) (*cobra.Command, *localBui return err } if err := options.run(cmd, args); err != nil { - fmt.Println(err.Error()) + fmt.Fprintln(cmd.ErrOrStderr(), err.Error()) } if err := options.deinit(); err != nil { return err diff --git a/pkg/cmd/local_inspect.go b/pkg/cmd/local_inspect.go index a5e1919be..e4e6c95cf 100644 --- a/pkg/cmd/local_inspect.go +++ b/pkg/cmd/local_inspect.go @@ -42,8 +42,8 @@ will be generated by calling Maven and then printed in the selected output forma if err := options.init(); err != nil { return err } - if err := options.run(args); err != nil { - fmt.Println(err.Error()) + if err := options.run(cmd, args); err != nil { + fmt.Fprintln(cmd.ErrOrStderr(), err.Error()) } if err := options.deinit(); err != nil { return err @@ -99,13 +99,13 @@ func (command *localInspectCmdOptions) init() error { return createMavenWorkingDirectory() } -func (command *localInspectCmdOptions) run(args []string) error { +func (command *localInspectCmdOptions) run(cmd *cobra.Command, args []string) error { dependencies, err := getDependencies(command.Context, args, command.AdditionalDependencies, command.MavenRepositories, command.AllDependencies) if err != nil { return err } - err = outputDependencies(dependencies, command.OutputFormat) + err = outputDependencies(dependencies, command.OutputFormat, cmd) if err != nil { return err } diff --git a/pkg/cmd/local_run.go b/pkg/cmd/local_run.go index f886dc34b..1e347608c 100644 --- a/pkg/cmd/local_run.go +++ b/pkg/cmd/local_run.go @@ -53,14 +53,14 @@ func newCmdLocalRun(rootCmdOptions *RootCmdOptions) (*cobra.Command, *localRunCm go func() { <-cs if err := options.deinit(); err != nil { - fmt.Println(err) + fmt.Fprintln(cmd.ErrOrStderr(), err) os.Exit(1) } os.Exit(0) }() if err := options.run(cmd, args); err != nil { - fmt.Println(err.Error()) + fmt.Fprintln(cmd.ErrOrStderr(), err.Error()) } if err := options.deinit(); err != nil { return err diff --git a/pkg/cmd/log.go b/pkg/cmd/log.go index c400dad4a..ceeeeb420 100644 --- a/pkg/cmd/log.go +++ b/pkg/cmd/log.go @@ -98,7 +98,7 @@ func (o *logCmdOptions) run(cmd *cobra.Command, args []string) error { // and checking if its different from the new message // if newLogMsg != currLogMsg { - fmt.Println(newLogMsg) + fmt.Fprintln(cmd.OutOrStdout(), newLogMsg) currLogMsg = newLogMsg } @@ -128,8 +128,8 @@ func (o *logCmdOptions) run(cmd *cobra.Command, args []string) error { // // Found the running integration so step over to scraping its pod log // - fmt.Printf("Integration '%s' is now running. Showing log ...\n", integrationID) - if err := k8slog.Print(o.Context, c, &integration, cmd.OutOrStdout()); err != nil { + fmt.Fprintf(cmd.OutOrStdout(), "Integration '%s' is now running. Showing log ...\n", integrationID) + if err := k8slog.Print(o.Context, cmd, c, &integration, cmd.OutOrStdout()); err != nil { return false, err } diff --git a/pkg/cmd/modeline.go b/pkg/cmd/modeline.go index e32d289f5..25205dc25 100644 --- a/pkg/cmd/modeline.go +++ b/pkg/cmd/modeline.go @@ -71,7 +71,7 @@ func NewKamelWithModelineCommand(ctx context.Context, osArgs []string) (*cobra.C originalFlags := osArgs[1:] rootCmd, flags, err := createKamelWithModelineCommand(ctx, originalFlags) if err != nil { - fmt.Printf("Error: %s\n", err.Error()) + fmt.Fprintf(rootCmd.ErrOrStderr(), "Error: %s\n", err.Error()) return rootCmd, flags, err } if len(originalFlags) != len(flags) { @@ -127,7 +127,7 @@ func createKamelWithModelineCommand(ctx context.Context, args []string) (*cobra. files = append(files, fg.Args()...) files = append(files, additionalSources...) - opts, err := extractModelineOptions(ctx, files) + opts, err := extractModelineOptions(ctx, files, rootCmd) if err != nil { return nil, nil, errors.Wrap(err, "cannot read sources") } @@ -191,10 +191,10 @@ func createKamelWithModelineCommand(ctx context.Context, args []string) (*cobra. return rootCmd, args, nil } -func extractModelineOptions(ctx context.Context, sources []string) ([]modeline.Option, error) { +func extractModelineOptions(ctx context.Context, sources []string, cmd *cobra.Command) ([]modeline.Option, error) { opts := make([]modeline.Option, 0) - resolvedSources, err := ResolveSources(ctx, sources, false) + resolvedSources, err := ResolveSources(ctx, sources, false, cmd) if err != nil { return opts, errors.Wrap(err, "cannot read sources") } diff --git a/pkg/cmd/rebuild.go b/pkg/cmd/rebuild.go index 57dcef2dd..e9f5f8b0c 100644 --- a/pkg/cmd/rebuild.go +++ b/pkg/cmd/rebuild.go @@ -48,7 +48,7 @@ type rebuildCmdOptions struct { *RootCmdOptions } -func (o *rebuildCmdOptions) rebuild(_ *cobra.Command, args []string) error { +func (o *rebuildCmdOptions) rebuild(cmd *cobra.Command, args []string) error { c, err := o.GetCmdClient() if err != nil { return err @@ -69,7 +69,7 @@ func (o *rebuildCmdOptions) rebuild(_ *cobra.Command, args []string) error { return err } - fmt.Printf("%d integrations have been rebuilt\n", len(integrations)) + fmt.Fprintf(cmd.OutOrStdout(),"%d integrations have been rebuilt\n", len(integrations)) return nil } diff --git a/pkg/cmd/reset.go b/pkg/cmd/reset.go index 240229675..22239e621 100644 --- a/pkg/cmd/reset.go +++ b/pkg/cmd/reset.go @@ -54,44 +54,44 @@ type resetCmdOptions struct { SkipKameletBindings bool `mapstructure:"skip-kamelet-bindings"` } -func (o *resetCmdOptions) reset(_ *cobra.Command, _ []string) { +func (o *resetCmdOptions) reset(cmd *cobra.Command, _ []string) { c, err := o.GetCmdClient() if err != nil { - fmt.Print(err) + fmt.Fprint(cmd.ErrOrStderr(), err) return } var n int if !o.SkipKameletBindings { if n, err = o.deleteAllKameletBindings(c); err != nil { - fmt.Print(err) + fmt.Fprint(cmd.ErrOrStderr(), err) return } - fmt.Printf("%d kamelet bindings deleted from namespace %s\n", n, o.Namespace) + fmt.Fprintf(cmd.OutOrStdout(), "%d kamelet bindings deleted from namespace %s\n", n, o.Namespace) } if !o.SkipIntegrations { if n, err = o.deleteAllIntegrations(c); err != nil { - fmt.Print(err) + fmt.Fprint(cmd.ErrOrStderr(), err) return } - fmt.Printf("%d integrations deleted from namespace %s\n", n, o.Namespace) + fmt.Fprintf(cmd.OutOrStdout(), "%d integrations deleted from namespace %s\n", n, o.Namespace) } if !o.SkipKits { if n, err = o.deleteAllIntegrationKits(c); err != nil { - fmt.Print(err) + fmt.Fprint(cmd.ErrOrStderr(), err) return } - fmt.Printf("%d integration kits deleted from namespace %s\n", n, o.Namespace) + fmt.Fprintf(cmd.OutOrStdout(), "%d integration kits deleted from namespace %s\n", n, o.Namespace) } if err = o.resetIntegrationPlatform(c); err != nil { - fmt.Println(err) + fmt.Fprintln(cmd.ErrOrStderr(), err) return } - fmt.Println("Camel K platform has been reset successfully!") + fmt.Fprintln(cmd.OutOrStdout(), "Camel K platform has been reset successfully!") } func (o *resetCmdOptions) deleteAllIntegrations(c client.Client) (int, error) { diff --git a/pkg/cmd/root.go b/pkg/cmd/root.go index 1035ae11a..a01a02a5d 100644 --- a/pkg/cmd/root.go +++ b/pkg/cmd/root.go @@ -207,7 +207,7 @@ func checkAndShowCompatibilityWarning(ctx context.Context, cmd *cobra.Command, c fmt.Fprintf(cmd.ErrOrStderr(), "Unable to retrieve the operator version: %s\n", err.Error()) } } else { - if operatorVersion != "" && !compatibleVersions(operatorVersion, defaults.Version) { + if operatorVersion != "" && !compatibleVersions(operatorVersion, defaults.Version, cmd) { fmt.Fprintf(cmd.ErrOrStderr(), "You're using Camel K %s client with a %s cluster operator, it's recommended to use the same version to improve compatibility.\n\n", defaults.Version, operatorVersion) } } diff --git a/pkg/cmd/run.go b/pkg/cmd/run.go index 4c7406597..37592b856 100644 --- a/pkg/cmd/run.go +++ b/pkg/cmd/run.go @@ -198,12 +198,12 @@ func (o *runCmdOptions) decode(cmd *cobra.Command, args []string) error { return o.validate() } -func (o *runCmdOptions) validateArgs(_ *cobra.Command, args []string) error { +func (o *runCmdOptions) validateArgs(cmd *cobra.Command, args []string) error { if len(args) < 1 { return errors.New("run expects at least 1 argument, received 0") } - if _, err := ResolveSources(context.Background(), args, false); err != nil { + if _, err := ResolveSources(context.Background(), args, false, cmd); err != nil { return errors.Wrap(err, "One of the provided sources is not reachable") } @@ -287,10 +287,10 @@ func (o *runCmdOptions) run(cmd *cobra.Command, args []string) error { // Context canceled return } - fmt.Printf("Run integration terminating\n") + fmt.Fprintf(cmd.OutOrStdout(), "Run integration terminating\n") err := DeleteIntegration(o.Context, c, integration.Name, integration.Namespace) if err != nil { - fmt.Println(err) + fmt.Fprintln(cmd.ErrOrStderr(), err) os.Exit(1) } os.Exit(0) @@ -334,7 +334,7 @@ func (o *runCmdOptions) run(cmd *cobra.Command, args []string) error { } } if o.Logs || o.Dev { - err = k8slog.Print(o.Context, c, integration, cmd.OutOrStdout()) + err = k8slog.Print(o.Context, cmd, c, integration, cmd.OutOrStdout()) if err != nil { return err } @@ -419,7 +419,7 @@ func (o *runCmdOptions) syncIntegration(cmd *cobra.Command, c client.Client, sou newCmd.SetOut(cmd.OutOrStdout()) newCmd.SetErr(cmd.ErrOrStderr()) if err != nil { - fmt.Println("Unable to sync integration: ", err.Error()) + fmt.Fprintln(newCmd.ErrOrStderr(), "Unable to sync integration: ", err.Error()) continue } @@ -436,7 +436,7 @@ func (o *runCmdOptions) syncIntegration(cmd *cobra.Command, c client.Client, sou // run the new one err = newCmd.Execute() if err != nil { - fmt.Println("Unable to sync integration: ", err.Error()) + fmt.Fprintln(newCmd.ErrOrStderr(), "Unable to sync integration: ", err.Error()) } } } @@ -520,7 +520,7 @@ func (o *runCmdOptions) createOrUpdateIntegration(cmd *cobra.Command, c client.C srcs = append(srcs, sources...) srcs = append(srcs, o.Sources...) - resolvedSources, err := ResolveSources(context.Background(), srcs, o.Compression) + resolvedSources, err := ResolveSources(context.Background(), srcs, o.Compression, cmd) if err != nil { return nil, err } @@ -543,20 +543,20 @@ func (o *runCmdOptions) createOrUpdateIntegration(cmd *cobra.Command, c client.C } } - err = resolvePodTemplate(context.Background(), o.PodTemplate, &integration.Spec) + err = resolvePodTemplate(context.Background(), cmd, o.PodTemplate, &integration.Spec) if err != nil { return nil, err } - err = o.parseAndConvertToTrait(c, integration, o.Resources, resource.ParseResource, func(c *resource.Config) string { return c.String() }, "mount.resources") + err = o.parseAndConvertToTrait(cmd, c, integration, o.Resources, resource.ParseResource, func(c *resource.Config) string { return c.String() }, "mount.resources") if err != nil { return nil, err } - err = o.parseAndConvertToTrait(c, integration, o.Configs, resource.ParseConfig, func(c *resource.Config) string { return c.String() }, "mount.configs") + err = o.parseAndConvertToTrait(cmd, c, integration, o.Configs, resource.ParseConfig, func(c *resource.Config) string { return c.String() }, "mount.configs") if err != nil { return nil, err } - err = o.parseAndConvertToTrait(c, integration, o.OpenAPIs, resource.ParseConfig, func(c *resource.Config) string { return c.Name() }, "openapi.configmaps") + err = o.parseAndConvertToTrait(cmd, c, integration, o.OpenAPIs, resource.ParseConfig, func(c *resource.Config) string { return c.Name() }, "openapi.configmaps") if err != nil { return nil, err } @@ -615,10 +615,10 @@ func (o *runCmdOptions) createOrUpdateIntegration(cmd *cobra.Command, c client.C if existing == nil { err = c.Create(o.Context, integration) - fmt.Printf("Integration \"%s\" created\n", name) + fmt.Fprintf(cmd.OutOrStdout(), "Integration \"%s\" created\n", name) } else { err = c.Patch(o.Context, integration, ctrl.MergeFromWithOptions(existing, ctrl.MergeFromWithOptimisticLock{})) - fmt.Printf("Integration \"%s\" updated\n", name) + fmt.Fprintf(cmd.OutOrStdout(), "Integration \"%s\" updated\n", name) } if err != nil { @@ -636,7 +636,7 @@ func showIntegrationOutput(cmd *cobra.Command, integration *v1.Integration, outp return printer.PrintObj(integration, cmd.OutOrStdout()) } -func (o *runCmdOptions) parseAndConvertToTrait( +func (o *runCmdOptions) parseAndConvertToTrait(cmd *cobra.Command, c client.Client, integration *v1.Integration, params []string, parse func(string) (*resource.Config, error), convert func(*resource.Config) string, @@ -647,7 +647,7 @@ func (o *runCmdOptions) parseAndConvertToTrait( return err } // We try to autogenerate a configmap - _, err = parseConfigAndGenCm(o.Context, c, config, integration, o.Compression) + _, err = parseConfigAndGenCm(o.Context, cmd, c, config, integration, o.Compression) if err != nil { return err } @@ -705,7 +705,7 @@ func loadPropertyFile(fileName string) (*properties.Properties, error) { return p, nil } -func resolvePodTemplate(ctx context.Context, templateSrc string, spec *v1.IntegrationSpec) (err error) { +func resolvePodTemplate(ctx context.Context, cmd *cobra.Command, templateSrc string, spec *v1.IntegrationSpec) (err error) { // check if template is set if templateSrc == "" { return nil @@ -714,7 +714,7 @@ func resolvePodTemplate(ctx context.Context, templateSrc string, spec *v1.Integr // check if value is a path to the file if _, err := os.Stat(templateSrc); err == nil { - rsc, err := ResolveSources(ctx, []string{templateSrc}, false) + rsc, err := ResolveSources(ctx, []string{templateSrc}, false, cmd) if err == nil && len(rsc) > 0 { templateSrc = rsc[0].Content } diff --git a/pkg/cmd/run_help.go b/pkg/cmd/run_help.go index 269015443..da91f36f3 100644 --- a/pkg/cmd/run_help.go +++ b/pkg/cmd/run_help.go @@ -29,6 +29,7 @@ import ( "github.com/apache/camel-k/pkg/util/kubernetes" "github.com/apache/camel-k/pkg/util/resource" "github.com/magiconair/properties" + "github.com/spf13/cobra" corev1 "k8s.io/api/core/v1" ) @@ -43,12 +44,12 @@ func hashFrom(contents ...[]byte) string { return fmt.Sprintf("%x", hash.Sum(nil)) } -func parseConfigAndGenCm(ctx context.Context, c client.Client, config *resource.Config, integration *v1.Integration, enableCompression bool) (*corev1.ConfigMap, error) { +func parseConfigAndGenCm(ctx context.Context, cmd *cobra.Command, c client.Client, config *resource.Config, integration *v1.Integration, enableCompression bool) (*corev1.ConfigMap, error) { switch config.StorageType() { case resource.StorageTypeConfigmap: cm := kubernetes.LookupConfigmap(ctx, c, integration.Namespace, config.Name()) if cm == nil { - fmt.Printf("Warn: %s Configmap not found in %s namespace, make sure to provide it before the Integration can run\n", + fmt.Fprintf(cmd.ErrOrStderr(), "Warn: %s Configmap not found in %s namespace, make sure to provide it before the Integration can run\n", config.Name(), integration.Namespace) } else if config.ContentType() != resource.ContentTypeData && cm.BinaryData != nil { return nil, fmt.Errorf("you cannot provide a binary config, use a text file instead") @@ -56,7 +57,7 @@ func parseConfigAndGenCm(ctx context.Context, c client.Client, config *resource. case resource.StorageTypeSecret: secret := kubernetes.LookupSecret(ctx, c, integration.Namespace, config.Name()) if secret == nil { - fmt.Printf("Warn: %s Secret not found in %s namespace, make sure to provide it before the Integration can run\n", + fmt.Fprintf(cmd.ErrOrStderr(), "Warn: %s Secret not found in %s namespace, make sure to provide it before the Integration can run\n", config.Name(), integration.Namespace) } case resource.StorageTypeFile: diff --git a/pkg/cmd/run_test.go b/pkg/cmd/run_test.go index 7f277edd6..cb31977e4 100644 --- a/pkg/cmd/run_test.go +++ b/pkg/cmd/run_test.go @@ -528,7 +528,7 @@ func TestRunTextCompressedResource(t *testing.T) { } func TestResolvePodTemplate(t *testing.T) { - // runCmdOptions, rootCmd, _ := initializeRunCmdOptions(t) + _, rootCmd, _ := initializeRunCmdOptions(t) templateText := ` containers: - name: integration @@ -544,7 +544,7 @@ volumes: ` integrationSpec := v1.IntegrationSpec{} - err := resolvePodTemplate(context.TODO(), templateText, &integrationSpec) + err := resolvePodTemplate(context.TODO(), rootCmd, templateText, &integrationSpec) assert.Nil(t, err) assert.NotNil(t, integrationSpec.PodTemplate) assert.Equal(t, 1, len(integrationSpec.PodTemplate.Spec.Containers)) @@ -552,10 +552,11 @@ volumes: } func TestResolveJsonPodTemplate(t *testing.T) { + _, rootCmd, _ := initializeRunCmdOptions(t) integrationSpec := v1.IntegrationSpec{} minifiedYamlTemplate := `{"containers": [{"name": "second"}, {"name": "integration", "env": [{"name": "CAMEL_K_DIGEST", "value": "new_value"}]}]}` - err := resolvePodTemplate(context.TODO(), minifiedYamlTemplate, &integrationSpec) + err := resolvePodTemplate(context.TODO(), rootCmd, minifiedYamlTemplate, &integrationSpec) assert.Nil(t, err) assert.NotNil(t, integrationSpec.PodTemplate) diff --git a/pkg/cmd/uninstall.go b/pkg/cmd/uninstall.go index 92d42a508..c68ecb036 100644 --- a/pkg/cmd/uninstall.go +++ b/pkg/cmd/uninstall.go @@ -143,7 +143,7 @@ func (o *uninstallCmdOptions) uninstall(cmd *cobra.Command, _ []string) error { fmt.Fprintf(cmd.OutOrStdout(), "Camel K Integration Platform removed from namespace %s\n", o.Namespace) } - if err = o.uninstallNamespaceResources(o.Context, c); err != nil { + if err = o.uninstallNamespaceResources(cmd, o.Context, c); err != nil { return err } @@ -155,11 +155,11 @@ func (o *uninstallCmdOptions) uninstall(cmd *cobra.Command, _ []string) error { fmt.Fprintf(cmd.OutOrStdout(), "Camel K Operator removed from namespace %s\n", o.Namespace) } - if err = o.uninstallNamespaceRoles(o.Context, c); err != nil { + if err = o.uninstallNamespaceRoles(cmd, o.Context, c); err != nil { return err } - if err = o.uninstallClusterWideResources(o.Context, c, o.Namespace); err != nil { + if err = o.uninstallClusterWideResources(cmd, o.Context, c, o.Namespace); err != nil { return err } @@ -186,21 +186,21 @@ func (o *uninstallCmdOptions) uninstallOperator(ctx context.Context, c client.Cl return nil } -func (o *uninstallCmdOptions) uninstallClusterWideResources(ctx context.Context, c client.Client, namespace string) error { +func (o *uninstallCmdOptions) uninstallClusterWideResources(cmd *cobra.Command, ctx context.Context, c client.Client, namespace string) error { if !o.SkipCrd || o.UninstallAll { if err := o.uninstallCrd(ctx, c); err != nil { if k8serrors.IsForbidden(err) { - return createActionNotAuthorizedError() + return createActionNotAuthorizedError(cmd) } return err } - fmt.Printf("Camel K Custom Resource Definitions removed from cluster\n") + fmt.Fprintf(cmd.OutOrStdout(), "Camel K Custom Resource Definitions removed from cluster\n") } if err := o.removeSubjectFromClusterRoleBindings(ctx, c, namespace); err != nil { if k8serrors.IsForbidden(err) { // Let's print a warning message and continue - fmt.Println("Current user is not authorized to remove the operator ServiceAccount from the cluster role bindings") + fmt.Fprintln(cmd.ErrOrStderr(), "Current user is not authorized to remove the operator ServiceAccount from the cluster role bindings") } else if err != nil { return err } @@ -209,71 +209,71 @@ func (o *uninstallCmdOptions) uninstallClusterWideResources(ctx context.Context, if !o.SkipClusterRoleBindings || o.UninstallAll { if err := o.uninstallClusterRoleBindings(ctx, c); err != nil { if k8serrors.IsForbidden(err) { - return createActionNotAuthorizedError() + return createActionNotAuthorizedError(cmd) } return err } - fmt.Printf("Camel K Cluster Role Bindings removed from cluster\n") + fmt.Fprintf(cmd.OutOrStdout(), "Camel K Cluster Role Bindings removed from cluster\n") } if !o.SkipClusterRoles || o.UninstallAll { if err := o.uninstallClusterRoles(ctx, c); err != nil { if k8serrors.IsForbidden(err) { - return createActionNotAuthorizedError() + return createActionNotAuthorizedError(cmd) } return err } - fmt.Printf("Camel K Cluster Roles removed from cluster\n") + fmt.Fprintf(cmd.OutOrStdout(), "Camel K Cluster Roles removed from cluster\n") } return nil } -func (o *uninstallCmdOptions) uninstallNamespaceRoles(ctx context.Context, c client.Client) error { +func (o *uninstallCmdOptions) uninstallNamespaceRoles(cmd *cobra.Command, ctx context.Context, c client.Client) error { if !o.SkipRoleBindings { if err := o.uninstallRoleBindings(ctx, c); err != nil { return err } - fmt.Printf("Camel K Role Bindings removed from namespace %s\n", o.Namespace) + fmt.Fprintf(cmd.OutOrStdout(), "Camel K Role Bindings removed from namespace %s\n", o.Namespace) } if !o.SkipRoles { if err := o.uninstallRoles(ctx, c); err != nil { return err } - fmt.Printf("Camel K Roles removed from namespace %s\n", o.Namespace) + fmt.Fprintf(cmd.OutOrStdout(), "Camel K Roles removed from namespace %s\n", o.Namespace) } if !o.SkipServiceAccounts { if err := o.uninstallServiceAccounts(ctx, c); err != nil { return err } - fmt.Printf("Camel K Service Accounts removed from namespace %s\n", o.Namespace) + fmt.Fprintf(cmd.OutOrStdout(), "Camel K Service Accounts removed from namespace %s\n", o.Namespace) } return nil } -func (o *uninstallCmdOptions) uninstallNamespaceResources(ctx context.Context, c client.Client) error { +func (o *uninstallCmdOptions) uninstallNamespaceResources(cmd *cobra.Command, ctx context.Context, c client.Client) error { if !o.SkipConfigMaps { if err := o.uninstallConfigMaps(ctx, c); err != nil { return err } - fmt.Printf("Camel K Config Maps removed from namespace %s\n", o.Namespace) + fmt.Fprintf(cmd.OutOrStdout(), "Camel K Config Maps removed from namespace %s\n", o.Namespace) } if !o.SkipRegistrySecret { if err := o.uninstallRegistrySecret(ctx, c); err != nil { return err } - fmt.Printf("Camel K Registry Secret removed from namespace %s\n", o.Namespace) + fmt.Fprintf(cmd.OutOrStdout(), "Camel K Registry Secret removed from namespace %s\n", o.Namespace) } if !o.SkipKamelets { if err := o.uninstallKamelets(ctx, c); err != nil { return err } - fmt.Printf("Camel K platform Kamelets removed from namespace %s\n", o.Namespace) + fmt.Fprintf(cmd.OutOrStdout(), "Camel K platform Kamelets removed from namespace %s\n", o.Namespace) } return nil @@ -486,8 +486,8 @@ func (o *uninstallCmdOptions) uninstallKamelets(ctx context.Context, c client.Cl return nil } -func createActionNotAuthorizedError() error { - fmt.Println("Current user is not authorized to remove cluster-wide objects like custom resource definitions or cluster roles") +func createActionNotAuthorizedError(cmd *cobra.Command) error { + fmt.Fprintln(cmd.ErrOrStderr(), "Current user is not authorized to remove cluster-wide objects like custom resource definitions or cluster roles") msg := `login as cluster-admin and execute "kamel uninstall" or use flags "--skip-crd --skip-cluster-roles --skip-cluster-role-bindings"` return errors.New(msg) } diff --git a/pkg/cmd/util_commands.go b/pkg/cmd/util_commands.go index 15a14c8e6..3ef33a477 100644 --- a/pkg/cmd/util_commands.go +++ b/pkg/cmd/util_commands.go @@ -108,7 +108,7 @@ func RunLocalIntegrationRunCommand(ctx context.Context, properties []string, dep } // Output command we are about to run. - fmt.Printf("Executing: %s\n", strings.Join(cmd.Args, " ")) + fmt.Fprintf(cmd.Stdout, "Executing: %s\n", strings.Join(cmd.Args, " ")) // Run integration locally. err = cmd.Run() diff --git a/pkg/cmd/util_containerization.go b/pkg/cmd/util_containerization.go index c7eac7379..c5a637efe 100644 --- a/pkg/cmd/util_containerization.go +++ b/pkg/cmd/util_containerization.go @@ -83,7 +83,7 @@ func setDockerEnvVars(envVars []string) { } } -func createAndBuildBaseImage(ctx context.Context) error { +func createAndBuildBaseImage(ctx context.Context, stdout, stderr io.Writer) error { // Create the base image Docker file. err := docker.CreateBaseImageDockerFile() if err != nil { @@ -94,8 +94,12 @@ func createAndBuildBaseImage(ctx context.Context) error { args := docker.BuildBaseImageArgs() cmd := exec.CommandContext(ctx, "docker", args...) + // Set stdout and stderr. + cmd.Stdout = stdout + cmd.Stderr = stderr + // Output executed command. - fmt.Printf("Executing: %s\n", strings.Join(cmd.Args, " ")) + fmt.Fprintf(cmd.Stdout, "Executing: %s\n", strings.Join(cmd.Args, " ")) // Run the command. if err := cmd.Run(); err != nil { @@ -126,7 +130,7 @@ func createAndBuildIntegrationImage(ctx context.Context, containerRegistry strin } // Create the Dockerfile and build the base image. - err := createAndBuildBaseImage(ctx) + err := createAndBuildBaseImage(ctx, stdout, stderr) if err != nil { return err } @@ -192,7 +196,7 @@ func createAndBuildIntegrationImage(ctx context.Context, containerRegistry strin cmd.Stdout = stdout // Output executed command. - fmt.Printf("Executing: %s\n", strings.Join(cmd.Args, " ")) + fmt.Fprintf(cmd.Stdout, "Executing: %s\n", strings.Join(cmd.Args, " ")) // Run the command. if err := cmd.Run(); err != nil { @@ -225,7 +229,7 @@ func runIntegrationImage(ctx context.Context, image string, stdout, stderr io.Wr cmd.Stdout = stdout // Output executed command. - fmt.Printf("Executing: %s\n", strings.Join(cmd.Args, " ")) + fmt.Fprintf(cmd.Stdout, "Executing: %s\n", strings.Join(cmd.Args, " ")) // Run the command. if err := cmd.Run(); err != nil { diff --git a/pkg/cmd/util_dependencies.go b/pkg/cmd/util_dependencies.go index dfabb923f..8110caff3 100644 --- a/pkg/cmd/util_dependencies.go +++ b/pkg/cmd/util_dependencies.go @@ -27,6 +27,7 @@ import ( "github.com/pkg/errors" "github.com/scylladb/go-set/strset" + "github.com/spf13/cobra" v1 "github.com/apache/camel-k/pkg/apis/camel/v1" "github.com/apache/camel-k/pkg/builder" @@ -230,37 +231,37 @@ func createCamelCatalog(ctx context.Context) (*camel.RuntimeCatalog, error) { return catalog, nil } -func outputDependencies(dependencies []string, format string) error { +func outputDependencies(dependencies []string, format string, cmd *cobra.Command) error { if format != "" { - err := printDependencies(format, dependencies) + err := printDependencies(format, dependencies, cmd) if err != nil { return err } } else { // Print output in text form - fmt.Println("dependencies:") + fmt.Fprintln(cmd.OutOrStdout(), "dependencies:") for _, dep := range dependencies { - fmt.Printf("%v\n", dep) + fmt.Fprintf(cmd.OutOrStdout(), "%v\n", dep) } } return nil } -func printDependencies(format string, dependencies []string) error { +func printDependencies(format string, dependencies []string, cmd *cobra.Command) error { switch format { case "yaml": data, err := util.DependenciesToYAML(dependencies) if err != nil { return err } - fmt.Print(string(data)) + fmt.Fprint(cmd.OutOrStdout(), string(data)) case "json": data, err := util.DependenciesToJSON(dependencies) if err != nil { return err } - fmt.Print(string(data)) + fmt.Fprint(cmd.OutOrStdout(),string(data)) default: return errors.New("unknown output format: " + format) } diff --git a/pkg/cmd/util_sources.go b/pkg/cmd/util_sources.go index 2ab6d7624..388a93f02 100644 --- a/pkg/cmd/util_sources.go +++ b/pkg/cmd/util_sources.go @@ -27,6 +27,7 @@ import ( "strings" "github.com/apache/camel-k/pkg/util" + "github.com/spf13/cobra" "golang.org/x/oauth2" @@ -60,7 +61,7 @@ func (s *Source) setContent(content []byte) error { } // ResolveSources ---. -func ResolveSources(ctx context.Context, locations []string, compress bool) ([]Source, error) { +func ResolveSources(ctx context.Context, locations []string, compress bool, cmd *cobra.Command) ([]Source, error) { sources := make([]Source, 0, len(locations)) for _, location := range locations { @@ -90,7 +91,7 @@ func ResolveSources(ctx context.Context, locations []string, compress bool) ([]S ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token}) tc = oauth2.NewClient(ctx, ts) - fmt.Println("GITHUB_TOKEN env var detected, using it for GitHub APIs authentication") + fmt.Fprintln(cmd.OutOrStdout(),"GITHUB_TOKEN env var detected, using it for GitHub APIs authentication") } gc := github.NewClient(tc) diff --git a/pkg/cmd/version.go b/pkg/cmd/version.go index 02993dd18..309d84dd1 100644 --- a/pkg/cmd/version.go +++ b/pkg/cmd/version.go @@ -171,15 +171,15 @@ func operatorVersion(ctx context.Context, c client.Client, namespace string) (st return infos[infoVersion], nil } -func compatibleVersions(aVersion, bVersion string) bool { +func compatibleVersions(aVersion, bVersion string, cmd *cobra.Command) bool { a, err := semver.NewVersion(aVersion) if err != nil { - fmt.Printf("Could not parse %s (error: %s)\n", a, err) + fmt.Fprintf(cmd.ErrOrStderr(), "Could not parse %s (error: %s)\n", a, err) return false } b, err := semver.NewVersion(bVersion) if err != nil { - fmt.Printf("Could not parse %s (error: %s)\n", b, err) + fmt.Fprintf(cmd.ErrOrStderr(), "Could not parse %s (error: %s)\n", b, err) return false } // We consider compatible when major and minor are equals diff --git a/pkg/cmd/version_test.go b/pkg/cmd/version_test.go index e1f4af780..7fd7ad489 100644 --- a/pkg/cmd/version_test.go +++ b/pkg/cmd/version_test.go @@ -77,11 +77,12 @@ func TestVersionClientVerbose(t *testing.T) { } func TestCompatibleVersions(t *testing.T) { - assert.Equal(t, true, compatibleVersions("1.3.0", "1.3.0")) - assert.Equal(t, true, compatibleVersions("1.3.0", "1.3.1")) - assert.Equal(t, true, compatibleVersions("1.3.0", "1.3.0-SNAPSHOT")) - assert.Equal(t, false, compatibleVersions("1.3.0", "1.2.0")) - assert.Equal(t, false, compatibleVersions("1.3.0", "2.3.0")) - assert.Equal(t, false, compatibleVersions("1.3.0", "dsadsa")) - assert.Equal(t, false, compatibleVersions("dsadsa", "1.3.4")) + _, rootCmd, _ := initializeVersionCmdOptions(t) + assert.Equal(t, true, compatibleVersions("1.3.0", "1.3.0", rootCmd)) + assert.Equal(t, true, compatibleVersions("1.3.0", "1.3.1", rootCmd)) + assert.Equal(t, true, compatibleVersions("1.3.0", "1.3.0-SNAPSHOT", rootCmd)) + assert.Equal(t, false, compatibleVersions("1.3.0", "1.2.0", rootCmd)) + assert.Equal(t, false, compatibleVersions("1.3.0", "2.3.0", rootCmd)) + assert.Equal(t, false, compatibleVersions("1.3.0", "dsadsa", rootCmd)) + assert.Equal(t, false, compatibleVersions("dsadsa", "1.3.4", rootCmd)) } diff --git a/pkg/install/operator.go b/pkg/install/operator.go index 7bafe0da7..90e3b930f 100644 --- a/pkg/install/operator.go +++ b/pkg/install/operator.go @@ -23,6 +23,7 @@ import ( "strings" "github.com/pkg/errors" + "github.com/spf13/cobra" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" @@ -70,7 +71,7 @@ type OperatorMonitoringConfiguration struct { } // OperatorOrCollect installs the operator resources or adds them to the collector if present. -func OperatorOrCollect(ctx context.Context, c client.Client, cfg OperatorConfiguration, collection *kubernetes.Collection, force bool) error { +func OperatorOrCollect(ctx context.Context, cmd *cobra.Command, c client.Client, cfg OperatorConfiguration, collection *kubernetes.Collection, force bool) error { isOpenShift, err := isOpenShift(c, cfg.ClusterType) if err != nil { return err @@ -98,7 +99,7 @@ func OperatorOrCollect(ctx context.Context, c client.Client, cfg OperatorConfigu if d.Labels["camel.apache.org/component"] == "operator" { tolerations, err := kubernetes.NewTolerations(cfg.Tolerations) if err != nil { - fmt.Println("Warning: could not parse the configured tolerations!") + fmt.Fprintln(cmd.ErrOrStderr(), "Warning: could not parse the configured tolerations!") } d.Spec.Template.Spec.Tolerations = tolerations } @@ -110,7 +111,7 @@ func OperatorOrCollect(ctx context.Context, c client.Client, cfg OperatorConfigu if d.Labels["camel.apache.org/component"] == "operator" { resourceReq, err := kubernetes.NewResourceRequirements(cfg.ResourcesRequirements) if err != nil { - fmt.Println("Warning: could not parse the configured resources requests!") + fmt.Fprintln(cmd.ErrOrStderr(), "Warning: could not parse the configured resources requests!") } for i := 0; i < len(d.Spec.Template.Spec.Containers); i++ { d.Spec.Template.Spec.Containers[i].Resources = resourceReq @@ -124,7 +125,7 @@ func OperatorOrCollect(ctx context.Context, c client.Client, cfg OperatorConfigu if d.Labels["camel.apache.org/component"] == "operator" { envVars, _, _, err := env.ParseEnv(cfg.EnvVars, nil) if err != nil { - fmt.Println("Warning: could not parse environment variables!") + fmt.Fprintln(cmd.ErrOrStderr(), "Warning: could not parse environment variables!") } for i := 0; i < len(d.Spec.Template.Spec.Containers); i++ { d.Spec.Template.Spec.Containers[i].Env = append(d.Spec.Template.Spec.Containers[i].Env, envVars...) @@ -138,7 +139,7 @@ func OperatorOrCollect(ctx context.Context, c client.Client, cfg OperatorConfigu if d.Labels["camel.apache.org/component"] == "operator" { nodeSelector, err := kubernetes.NewNodeSelectors(cfg.NodeSelectors) if err != nil { - fmt.Println("Warning: could not parse the configured node selectors!") + fmt.Fprintln(cmd.ErrOrStderr(), "Warning: could not parse the configured node selectors!") } d.Spec.Template.Spec.NodeSelector = nodeSelector } @@ -226,7 +227,7 @@ func OperatorOrCollect(ctx context.Context, c client.Client, cfg OperatorConfigu } if err := installClusterRoleBinding(ctx, c, collection, cfg.Namespace, "camel-k-operator-console-openshift", "/rbac/openshift/operator-cluster-role-console-binding-openshift.yaml"); err != nil { if k8serrors.IsForbidden(err) { - fmt.Println("Warning: the operator will not be able to manage ConsoleCLIDownload resources. Try installing the operator as cluster-admin.") + fmt.Fprintln(cmd.ErrOrStderr(), "Warning: the operator will not be able to manage ConsoleCLIDownload resources. Try installing the operator as cluster-admin.") } else { return err } @@ -249,7 +250,7 @@ func OperatorOrCollect(ctx context.Context, c client.Client, cfg OperatorConfigu } if err := installClusterRoleBinding(ctx, c, collection, cfg.Namespace, "camel-k-operator-bind-addressable-resolver", "/rbac/operator-cluster-role-binding-addressable-resolver.yaml"); err != nil { if k8serrors.IsForbidden(err) { - fmt.Println("Warning: the operator will not be able to bind Knative addressable-resolver ClusterRole. Try installing the operator as cluster-admin.") + fmt.Fprintln(cmd.ErrOrStderr(), "Warning: the operator will not be able to bind Knative addressable-resolver ClusterRole. Try installing the operator as cluster-admin.") } else { return err } @@ -260,48 +261,48 @@ func OperatorOrCollect(ctx context.Context, c client.Client, cfg OperatorConfigu if k8serrors.IsAlreadyExists(err) { return err } - fmt.Println("Warning: the operator will not be able to publish Kubernetes events. Try installing as cluster-admin to allow it to generate events.") + fmt.Fprintln(cmd.ErrOrStderr(), "Warning: the operator will not be able to publish Kubernetes events. Try installing as cluster-admin to allow it to generate events.") } if err = installKedaBindings(ctx, c, cfg.Namespace, customizer, collection, force); err != nil { if k8serrors.IsAlreadyExists(err) { return err } - fmt.Println("Warning: the operator will not be able to create KEDA resources. Try installing as cluster-admin.") + fmt.Fprintln(cmd.ErrOrStderr(), "Warning: the operator will not be able to create KEDA resources. Try installing as cluster-admin.") } if err = installPodMonitors(ctx, c, cfg.Namespace, customizer, collection, force); err != nil { if k8serrors.IsAlreadyExists(err) { return err } - fmt.Println("Warning: the operator will not be able to create PodMonitor resources. Try installing as cluster-admin.") + fmt.Fprintln(cmd.ErrOrStderr(), "Warning: the operator will not be able to create PodMonitor resources. Try installing as cluster-admin.") } if err := installStrimziBindings(ctx, c, cfg.Namespace, customizer, collection, force); err != nil { if k8serrors.IsAlreadyExists(err) { return err } - fmt.Println("Warning: the operator will not be able to lookup strimzi kafka resources. Try installing as cluster-admin to allow the lookup of strimzi kafka resources.") + fmt.Fprintln(cmd.ErrOrStderr(), "Warning: the operator will not be able to lookup strimzi kafka resources. Try installing as cluster-admin to allow the lookup of strimzi kafka resources.") } if err = installLeaseBindings(ctx, c, cfg.Namespace, customizer, collection, force); err != nil { if k8serrors.IsAlreadyExists(err) { return err } - fmt.Println("Warning: the operator will not be able to create Leases. Try installing as cluster-admin to allow management of Lease resources.") + fmt.Fprintln(cmd.ErrOrStderr(), "Warning: the operator will not be able to create Leases. Try installing as cluster-admin to allow management of Lease resources.") } if err = installClusterRoleBinding(ctx, c, collection, cfg.Namespace, "camel-k-operator-custom-resource-definitions", "/rbac/operator-cluster-role-binding-custom-resource-definitions.yaml"); err != nil { - fmt.Println("Warning: the operator will not be able to get CustomResourceDefinitions resources and the service-binding trait will fail if used. Try installing the operator as cluster-admin.") + fmt.Fprintln(cmd.ErrOrStderr(), "Warning: the operator will not be able to get CustomResourceDefinitions resources and the service-binding trait will fail if used. Try installing the operator as cluster-admin.") } if cfg.Monitoring.Enabled { if err := installMonitoringResources(ctx, c, cfg.Namespace, customizer, collection, force); err != nil { switch { case k8serrors.IsForbidden(err): - fmt.Println("Warning: the creation of monitoring resources is not allowed. Try installing as cluster-admin to allow the creation of monitoring resources.") + fmt.Fprintln(cmd.ErrOrStderr(), "Warning: the creation of monitoring resources is not allowed. Try installing as cluster-admin to allow the creation of monitoring resources.") case meta.IsNoMatchError(errors.Cause(err)): - fmt.Println("Warning: the creation of the monitoring resources failed: ", err) + fmt.Fprintln(cmd.ErrOrStderr(), "Warning: the creation of the monitoring resources failed: ", err) default: return err } diff --git a/pkg/util/kubernetes/log/util.go b/pkg/util/kubernetes/log/util.go index 407ea2a87..26bd2c158 100644 --- a/pkg/util/kubernetes/log/util.go +++ b/pkg/util/kubernetes/log/util.go @@ -24,22 +24,23 @@ import ( "io/ioutil" v1 "github.com/apache/camel-k/pkg/apis/camel/v1" + "github.com/spf13/cobra" "k8s.io/client-go/kubernetes" ) // Print prints integrations logs to the stdout. -func Print(ctx context.Context, client kubernetes.Interface, integration *v1.Integration, out io.Writer) error { - return PrintUsingSelector(ctx, client, integration.Namespace, integration.Name, v1.IntegrationLabel+"="+integration.Name, out) +func Print(ctx context.Context, cmd *cobra.Command, client kubernetes.Interface, integration *v1.Integration, out io.Writer) error { + return PrintUsingSelector(ctx, cmd, client, integration.Namespace, integration.Name, v1.IntegrationLabel+"="+integration.Name, out) } // PrintUsingSelector prints pod logs using a selector. -func PrintUsingSelector(ctx context.Context, client kubernetes.Interface, namespace, defaultContainerName, selector string, out io.Writer) error { +func PrintUsingSelector(ctx context.Context, cmd *cobra.Command, client kubernetes.Interface, namespace, defaultContainerName, selector string, out io.Writer) error { scraper := NewSelectorScraper(client, namespace, defaultContainerName, selector) reader := scraper.Start(ctx) if _, err := io.Copy(out, ioutil.NopCloser(reader)); err != nil { - fmt.Println(err.Error()) + fmt.Fprintln(cmd.ErrOrStderr(), err.Error()) } return nil diff --git a/pkg/util/tar/util_compress.go b/pkg/util/tar/util_compress.go index c3bcbc047..136f6fcb7 100644 --- a/pkg/util/tar/util_compress.go +++ b/pkg/util/tar/util_compress.go @@ -23,18 +23,20 @@ import ( "fmt" "io" "os" + + "github.com/spf13/cobra" ) -func CreateTarFile(fileNames []string, archiveName string) { +func CreateTarFile(fileNames []string, archiveName string, cmd *cobra.Command) { out, err := os.Create(archiveName) if err != nil { - fmt.Printf("Error writing archive: %v", err) + fmt.Fprintf(cmd.ErrOrStderr(), "Error writing archive: %v", err) } defer out.Close() err = createArchiveFile(fileNames, out) if err != nil { - fmt.Printf("Error writing archive: %v", err) + fmt.Fprintf(cmd.ErrOrStderr(), "Error writing archive: %v", err) } }
