Move connection opening to PersistentPreRun, and only attempt when needed

This commit is contained in:
Joel Elkins 2022-07-29 19:43:35 -05:00
parent 04e108100a
commit 1a0c00cb27
No known key found for this signature in database
GPG Key ID: 133589DC38921AE2

View File

@ -30,6 +30,7 @@ import (
"gitea.elkins.co/Networking/ccl/internal/pkg/config" "gitea.elkins.co/Networking/ccl/internal/pkg/config"
"github.com/containers/podman/v4/pkg/bindings" "github.com/containers/podman/v4/pkg/bindings"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"golang.org/x/exp/slices"
) )
// rootCmd represents the base command when called without any subcommands // rootCmd represents the base command when called without any subcommands
@ -42,12 +43,24 @@ to define, start, stop, or update the container images. Configuration is read
from a toml configuration file, and the utility uses this information to from a toml configuration file, and the utility uses this information to
execute the necessary podman commands.`, execute the necessary podman commands.`,
ValidArgsFunction: cobra.NoFileCompletions, ValidArgsFunction: cobra.NoFileCompletions,
PersistentPreRun: func(*cobra.Command, []string) { PersistentPreRun: func(cmd *cobra.Command, args []string) {
if incDisabled { if !incDisabled {
contMask = []string{}
} else {
contMask = []string{"disabled"} contMask = []string{"disabled"}
} }
requireConn := []string{"create", "ls", "pull", "recreate", "restart", "rm", "show", "start", "stop", "update"}
if slices.Contains(requireConn, cmd.Name()) {
// connect to podman
conn, err := bindings.NewConnection(context.Background(), socket)
if err != nil {
fmt.Fprintln(os.Stderr, "Could not connect:", err)
os.Exit(1)
}
err = config.Init(conn)
if err != nil {
fmt.Fprintln(os.Stderr, "Warning: Could not initialize configuration:", err)
}
}
}, },
} }
@ -76,17 +89,6 @@ func init() {
} else { } else {
output = io.Discard output = io.Discard
} }
// connect to podman
conn, err := bindings.NewConnection(context.Background(), socket)
if err != nil {
fmt.Fprintln(os.Stderr, "Could not connect:", err)
os.Exit(1)
}
err = config.Init(conn)
if err != nil {
fmt.Fprintln(os.Stderr, "Warning: Could not initialize configuration:", err)
}
}) })
rootCmd.PersistentFlags().StringVarP(&config.ConfigFile, "config", "c", config.CONFIG_FILE_DEFAULT, "pathname of config file") rootCmd.PersistentFlags().StringVarP(&config.ConfigFile, "config", "c", config.CONFIG_FILE_DEFAULT, "pathname of config file")
rootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "show additional info from command execution") rootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "show additional info from command execution")