|
| 1 | +package cli |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "os" |
| 6 | + |
| 7 | + "github.com/larkinwc/proxmox-lxc-compose/pkg/logging" |
| 8 | + "github.com/spf13/cobra" |
| 9 | + "github.com/spf13/viper" |
| 10 | +) |
| 11 | + |
| 12 | +var ( |
| 13 | + cfgFile string |
| 14 | + debugMode bool |
| 15 | + development bool |
| 16 | + rootCmd *cobra.Command |
| 17 | +) |
| 18 | + |
| 19 | +func init() { |
| 20 | + cobra.OnInitialize(initConfig) |
| 21 | + rootCmd = &cobra.Command{ |
| 22 | + Use: "lxc-compose", |
| 23 | + Short: "A docker-compose like tool for managing LXC containers in Proxmox", |
| 24 | + } |
| 25 | + rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.lxc-compose.yaml)") |
| 26 | + rootCmd.PersistentFlags().BoolVar(&debugMode, "debug", false, "enable debug mode") |
| 27 | + rootCmd.PersistentFlags().BoolVar(&development, "dev", false, "enable development mode") |
| 28 | +} |
| 29 | + |
| 30 | +func initConfig() { |
| 31 | + if cfgFile != "" { |
| 32 | + viper.SetConfigFile(cfgFile) |
| 33 | + } else { |
| 34 | + home, err := os.UserHomeDir() |
| 35 | + cobra.CheckErr(err) |
| 36 | + viper.AddConfigPath(home) |
| 37 | + viper.SetConfigType("yaml") |
| 38 | + viper.SetConfigName(".lxc-compose") |
| 39 | + } |
| 40 | + |
| 41 | + viper.AutomaticEnv() |
| 42 | + |
| 43 | + if err := viper.ReadInConfig(); err == nil { |
| 44 | + fmt.Fprintln(os.Stderr, "Using config file:", viper.ConfigFileUsed()) |
| 45 | + } |
| 46 | + |
| 47 | + if debugMode { |
| 48 | + if err := logging.Init(logging.Config{ |
| 49 | + Level: "debug", |
| 50 | + Development: true, |
| 51 | + }); err != nil { |
| 52 | + fmt.Fprintf(os.Stderr, "Failed to initialize logger: %v\n", err) |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + if development { |
| 57 | + if err := logging.Init(logging.Config{ |
| 58 | + Level: "debug", |
| 59 | + Development: true, |
| 60 | + }); err != nil { |
| 61 | + fmt.Fprintf(os.Stderr, "Failed to initialize logger: %v\n", err) |
| 62 | + } |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +// Execute executes the root command |
| 67 | +func Execute() error { |
| 68 | + return rootCmd.Execute() |
| 69 | +} |
| 70 | + |
| 71 | +// GetRootCmd returns the root command for adding subcommands |
| 72 | +func GetRootCmd() *cobra.Command { |
| 73 | + return rootCmd |
| 74 | +} |
0 commit comments