Skip to content

Commit

Permalink
Handle all errors in main
Browse files Browse the repository at this point in the history
  • Loading branch information
mortent committed Aug 21, 2020
1 parent 9e8d6ee commit 30fa81a
Show file tree
Hide file tree
Showing 8 changed files with 39 additions and 77 deletions.
19 changes: 0 additions & 19 deletions commands/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import (
"github.com/GoogleContainerTools/kpt/internal/cmdinit"
"github.com/GoogleContainerTools/kpt/internal/cmdsync"
"github.com/GoogleContainerTools/kpt/internal/cmdupdate"
"github.com/GoogleContainerTools/kpt/internal/util/cmdutil"
"github.com/spf13/cobra"
"k8s.io/kubectl/pkg/cmd/util"
)
Expand All @@ -46,25 +45,7 @@ func GetAnthosCommands(name string) []*cobra.Command {
func NormalizeCommand(c ...*cobra.Command) {
for i := range c {
cmd := c[i]
// check if silencing errors is off
cmdutil.SetSilenceErrors(cmd)
cmd.Short = strings.TrimPrefix(cmd.Short, "[Alpha] ")

// check if stack printing is on
if cmd.PreRunE != nil {
fn := cmd.PreRunE
cmd.PreRunE = func(cmd *cobra.Command, args []string) error {
err := fn(cmd, args)
return cmdutil.HandlePreRunError(cmd, err)
}
}
if cmd.RunE != nil {
fn := cmd.RunE
cmd.RunE = func(cmd *cobra.Command, args []string) error {
err := fn(cmd, args)
return cmdutil.HandleError(cmd, err)
}
}
NormalizeCommand(cmd.Commands()...)
}
}
Expand Down
4 changes: 2 additions & 2 deletions commands/livecmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ func GetLiveCommand(name string, f util.Factory) *cobra.Command {
applyCmd.Long = livedocs.ApplyShort + "\n" + livedocs.ApplyLong
applyCmd.Example = livedocs.ApplyExamples

previewCmd := preview.NewCmdPreview(f, ioStreams)
previewCmd := preview.GetPreviewRunner(f, ioStreams).Command
previewCmd.Short = livedocs.PreviewShort
previewCmd.Long = livedocs.PreviewShort + "\n" + livedocs.PreviewLong
previewCmd.Example = livedocs.PreviewExamples
Expand All @@ -73,7 +73,7 @@ func GetLiveCommand(name string, f util.Factory) *cobra.Command {
diffCmd.Long = livedocs.DiffShort + "\n" + livedocs.DiffLong
diffCmd.Example = livedocs.DiffExamples

destroyCmd := destroy.NewCmdDestroy(f, ioStreams)
destroyCmd := destroy.GetDestroyRunner(f, ioStreams).Command
destroyCmd.Short = livedocs.DestroyShort
destroyCmd.Long = livedocs.DestroyShort + "\n" + livedocs.DestroyLong
destroyCmd.Example = livedocs.DestroyExamples
Expand Down
6 changes: 3 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ require (
// Currently, we have to import the latest version of kubectl.
// Once there is a 0.18 release, we can import a semver release.
k8s.io/kubectl v0.0.0-20191219154910-1528d4eea6dd
sigs.k8s.io/cli-utils v0.18.1
sigs.k8s.io/kustomize/cmd/config v0.6.1-0.20200819192723-596c39b7bcb7
sigs.k8s.io/kustomize/kyaml v0.6.1-0.20200819192723-596c39b7bcb7
sigs.k8s.io/cli-utils v0.19.1-0.20200821220340-1e5fb03eaa7d
sigs.k8s.io/kustomize/cmd/config v0.6.1-0.20200821211955-ff3f39d84bc8
sigs.k8s.io/kustomize/kyaml v0.6.1-0.20200821211955-ff3f39d84bc8
)
12 changes: 12 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -653,6 +653,10 @@ sigs.k8s.io/cli-utils v0.18.1 h1:K4usJmMlI98mL+z+TdAnKfzng64/m8bRXZKPwy3ZCWw=
sigs.k8s.io/cli-utils v0.18.1/go.mod h1:B7KdqkSkHNIUn3cFbaR4aKUZMKtr+Benboi1w/HW/Fg=
sigs.k8s.io/cli-utils v0.18.2-0.20200819040110-516c2d7596e9 h1:L+lyMbHUr1ibVQh3sl7PqRTzatQfz6chiRjxSFr5x2c=
sigs.k8s.io/cli-utils v0.18.2-0.20200819040110-516c2d7596e9/go.mod h1:B7KdqkSkHNIUn3cFbaR4aKUZMKtr+Benboi1w/HW/Fg=
sigs.k8s.io/cli-utils v0.19.0 h1:lAoR5okhSV/dIusodaQp5VbDpHMcKnvjqKYHU+AB3a4=
sigs.k8s.io/cli-utils v0.19.0/go.mod h1:B7KdqkSkHNIUn3cFbaR4aKUZMKtr+Benboi1w/HW/Fg=
sigs.k8s.io/cli-utils v0.19.1-0.20200821220340-1e5fb03eaa7d h1:ZSwyTEFU6ibLjZ9kD9OhocSwzD79PBiJ4Ddg8VwXO/g=
sigs.k8s.io/cli-utils v0.19.1-0.20200821220340-1e5fb03eaa7d/go.mod h1:B7KdqkSkHNIUn3cFbaR4aKUZMKtr+Benboi1w/HW/Fg=
sigs.k8s.io/controller-runtime v0.4.0 h1:wATM6/m+3w8lj8FXNaO6Fs/rq/vqoOjO1Q116Z9NPsg=
sigs.k8s.io/controller-runtime v0.4.0/go.mod h1:ApC79lpY3PHW9xj/w9pj+lYkLgwAAUZwfXkME1Lajns=
sigs.k8s.io/kustomize v2.0.3+incompatible h1:JUufWFNlI44MdtnjUqVnvh29rR37PQFzPbLXqhyOyX0=
Expand All @@ -663,6 +667,10 @@ sigs.k8s.io/kustomize/cmd/config v0.6.0 h1:03tjs3SjvsumZjabctLicNUQwYlAeUqmRk1H4
sigs.k8s.io/kustomize/cmd/config v0.6.0/go.mod h1:azYDRZ/lprMhKqF4DbquWS0cfBFaInLM3LN+zuAXRDI=
sigs.k8s.io/kustomize/cmd/config v0.6.1-0.20200819192723-596c39b7bcb7 h1:l9JWlX+QSIWu2jV3fcbPkcuVR5N5WOcoCSSvQobxhhk=
sigs.k8s.io/kustomize/cmd/config v0.6.1-0.20200819192723-596c39b7bcb7/go.mod h1:y2+Op5gW7quHA6s6y32YX6J6WLB/H/cFIak1p7peQLA=
sigs.k8s.io/kustomize/cmd/config v0.6.1-0.20200821151426-7833c6edcf2c h1:wrtDvd0iV/kqwuSXncne/FK8LzaoG+293cCwiLDjPEM=
sigs.k8s.io/kustomize/cmd/config v0.6.1-0.20200821151426-7833c6edcf2c/go.mod h1:ZZoulwUOBeva15nGEnY9/yEc+TVg78EdW7jgADptBCc=
sigs.k8s.io/kustomize/cmd/config v0.6.1-0.20200821211955-ff3f39d84bc8 h1:KeFdYzV+GzrsRhE7OSr2RF91h/cc86w7QLYUzs7kS/g=
sigs.k8s.io/kustomize/cmd/config v0.6.1-0.20200821211955-ff3f39d84bc8/go.mod h1:ZZoulwUOBeva15nGEnY9/yEc+TVg78EdW7jgADptBCc=
sigs.k8s.io/kustomize/kyaml v0.4.0 h1:jMQrJOJmiUz5Y018ki0mXWpEreEXjvad1NRfXTdi9vU=
sigs.k8s.io/kustomize/kyaml v0.4.0/go.mod h1:XJL84E6sOFeNrQ7CADiemc1B0EjIxHo3OhW4o1aJYNw=
sigs.k8s.io/kustomize/kyaml v0.5.0 h1:xufpSxgpugQxtd0aN1ZsWnr3Kj0fpAi7GN4dnEs4oPg=
Expand All @@ -671,6 +679,10 @@ sigs.k8s.io/kustomize/kyaml v0.6.0 h1:Z/9TxsiG21sbcd6JD4IeM6BVZ2+04001KKzbxCf+qe
sigs.k8s.io/kustomize/kyaml v0.6.0/go.mod h1:bEzbO5pN9OvlEeCLvFHo8Pu7SA26Herc2m60UeWZBdI=
sigs.k8s.io/kustomize/kyaml v0.6.1-0.20200819192723-596c39b7bcb7 h1:iQG6l9KYbKkOscdCtKoqPeMNKPdAuQmYz75h8H32V3k=
sigs.k8s.io/kustomize/kyaml v0.6.1-0.20200819192723-596c39b7bcb7/go.mod h1:bEzbO5pN9OvlEeCLvFHo8Pu7SA26Herc2m60UeWZBdI=
sigs.k8s.io/kustomize/kyaml v0.6.1-0.20200821151426-7833c6edcf2c h1:T00VIgIncSB9KoELC5BKBDhEkc5iWKqPkN9BV86d2j8=
sigs.k8s.io/kustomize/kyaml v0.6.1-0.20200821151426-7833c6edcf2c/go.mod h1:bEzbO5pN9OvlEeCLvFHo8Pu7SA26Herc2m60UeWZBdI=
sigs.k8s.io/kustomize/kyaml v0.6.1-0.20200821211955-ff3f39d84bc8 h1:Taf2IRt1OB+WTN6FekOoLUtiOESpRa72vNsFdvB4ou4=
sigs.k8s.io/kustomize/kyaml v0.6.1-0.20200821211955-ff3f39d84bc8/go.mod h1:bEzbO5pN9OvlEeCLvFHo8Pu7SA26Herc2m60UeWZBdI=
sigs.k8s.io/structured-merge-diff v0.0.0-20190525122527-15d366b2352e/go.mod h1:wWxsB5ozmmv/SG7nM11ayaAW51xMvak/t1r0CSlcokI=
sigs.k8s.io/structured-merge-diff v0.0.0-20190817042607-6149e4549fca/go.mod h1:IIgPezJWb76P0hotTxzDbWsMYB8APh18qZnxkomBpxA=
sigs.k8s.io/structured-merge-diff v1.0.1-0.20191108220359-b1b620dd3f06/go.mod h1:/ULNhyfzRopfcjskuui0cTITekDduZ7ycKN3oUT9R18=
Expand Down
33 changes: 1 addition & 32 deletions internal/util/cmdutil/cmdutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import (
)

const (
SilenceErrorsEnv = "COBRA_SILENCE_USAGE"
StackTraceOnErrors = "COBRA_STACK_TRACE_ON_ERRORS"
trueString = "true"
)
Expand All @@ -37,45 +36,15 @@ func FixDocs(old, new string, c *cobra.Command) {
c.Example = strings.ReplaceAll(c.Example, old, new)
}

func SetSilenceErrors(c *cobra.Command) {
e := os.Getenv(SilenceErrorsEnv)
if e == trueString || e == "1" {
c.SilenceUsage = true
}
}

func HandlePreRunError(c *cobra.Command, err error) error {
func PrintErrorStacktrace(err error) {
e := os.Getenv(StackTraceOnErrors)
if StackOnError || e == trueString || e == "1" {
if err, ok := err.(*errors.Error); ok {
fmt.Fprint(os.Stderr, fmt.Sprintf("%s", err.Stack()))
}
}
return err
}

func HandleError(c *cobra.Command, err error) error {
if err == nil {
return nil
}
e := os.Getenv(StackTraceOnErrors)
if StackOnError || e == trueString || e == "1" {
if err, ok := err.(*errors.Error); ok {
fmt.Fprint(os.Stderr, fmt.Sprintf("%s", err.Stack()))
}
}

if ExitOnError {
fmt.Fprintf(c.ErrOrStderr(), "Error: %v\n", err)
os.Exit(1)
}
return err
}

// ExitOnError if true, will cause commands to call os.Exit instead of returning an error.
// Used for skipping printing usage on failure.
var ExitOnError bool

// StackOnError if true, will print a stack trace on failure.
var StackOnError bool

Expand Down
8 changes: 7 additions & 1 deletion internal/util/functions/functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"github.com/GoogleContainerTools/kpt/internal/kptfile/kptfileutil"
"sigs.k8s.io/kustomize/kyaml/fn/runtime/container"
"sigs.k8s.io/kustomize/kyaml/fn/runtime/exec"
"sigs.k8s.io/kustomize/kyaml/fn/runtime/runtimeutil"
"sigs.k8s.io/kustomize/kyaml/fn/runtime/starlark"
"sigs.k8s.io/kustomize/kyaml/kio"
"sigs.k8s.io/kustomize/kyaml/runfn"
Expand All @@ -38,7 +39,12 @@ func RunFunctions(path string, functions []kptfile.Function) error {
f := functions[i]
var e exec.Filter
e.FunctionConfig = yaml.NewRNode(&f.Config)
fltrs = append(fltrs, &container.Filter{Image: f.Image, Exec: e})
fltrs = append(fltrs, &container.Filter{
ContainerSpec: runtimeutil.ContainerSpec{
Image: f.Image,
},
Exec: e,
})
}
if len(fltrs) == 0 {
return nil
Expand Down
9 changes: 6 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,21 @@
package main

import (
"os"

"github.com/GoogleContainerTools/kpt/internal/util/cmdutil"
"github.com/GoogleContainerTools/kpt/run"
_ "k8s.io/client-go/plugin/pkg/client/auth"
"k8s.io/kubectl/pkg/util/logs"
"sigs.k8s.io/cli-utils/pkg/errors"
)

func main() {
cmd := run.GetMain()
logs.InitLogs()
defer logs.FlushLogs()
if err := cmd.Execute(); err != nil {
os.Exit(1)
cmdutil.PrintErrorStacktrace(err)
// TODO: find a way to avoid having to provide `kpt live` as a
// parameter here.
errors.CheckErr(cmd.ErrOrStderr(), err, "kpt live")
}
}
25 changes: 8 additions & 17 deletions run/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,14 @@ func GetMain() *cobra.Command {
os.Setenv(commandutil.EnableAlphaCommmandsEnvName, "true")
installComp := false
cmd := &cobra.Command{
Use: "kpt",
Short: overview.ReferenceShort,
Long: overview.ReferenceLong,
Example: overview.ReferenceExamples,
Use: "kpt",
Short: overview.ReferenceShort,
Long: overview.ReferenceLong,
Example: overview.ReferenceExamples,
SilenceUsage: true,
// We handle all errors in main after return from cobra so we can
// adjust the error message coming from libraries
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
if installComp {
os.Setenv("COMP_INSTALL", "1")
Expand Down Expand Up @@ -151,14 +155,10 @@ func GetMain() *cobra.Command {
os.Exit(1)
}

// exit on an error
cmdutil.ExitOnError = true

replace(cmd)

cmd.AddCommand(versionCmd)
hideFlags(cmd)
silenceUsage(cmd)
return cmd
}

Expand Down Expand Up @@ -234,15 +234,6 @@ var versionCmd = &cobra.Command{
},
}

// silenceUsage silences the usage for all the sub commands recursively
// so that we don't display long usage messages for all errors
func silenceUsage(cmd *cobra.Command) {
for _, subCmd := range cmd.Commands() {
subCmd.SilenceUsage = true
silenceUsage(subCmd)
}
}

// hideFlags hides any cobra flags that are unlikely to be used by
// customers.
func hideFlags(cmd *cobra.Command) {
Expand Down

0 comments on commit 30fa81a

Please sign in to comment.