mirror of
https://github.com/nestriness/cli.git
synced 2025-12-15 05:15:35 +02:00
✨ feat: Add viper config and basic arguments
This commit is contained in:
43
cmd/root.go
43
cmd/root.go
@@ -5,14 +5,18 @@ package cmd
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
//go:embed nestri.ascii
|
||||
var art string
|
||||
|
||||
var cfgFile string
|
||||
|
||||
type GameConfig struct {
|
||||
Directory string
|
||||
Executable string
|
||||
@@ -44,12 +48,49 @@ func Execute() {
|
||||
}
|
||||
|
||||
func init() {
|
||||
cobra.OnInitialize(initConfig)
|
||||
// Here you will define your flags and configuration settings.
|
||||
// Cobra supports persistent flags, which, if defined here,
|
||||
// will be global for your application.
|
||||
// rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cli.yaml)")
|
||||
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.nestri.yaml)")
|
||||
|
||||
// Cobra also supports local flags, which will only run
|
||||
// when this action is called directly.
|
||||
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
|
||||
// rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
|
||||
}
|
||||
|
||||
// initConfig reads in config file and ENV variables if set.
|
||||
func initConfig() {
|
||||
if cfgFile != "" {
|
||||
// Use config file from the flag.
|
||||
viper.SetConfigFile(cfgFile)
|
||||
} else {
|
||||
// Search for config in the current directory
|
||||
viper.AddConfigPath(".")
|
||||
viper.SetConfigName(".nestri")
|
||||
viper.SetConfigType("yaml")
|
||||
|
||||
// If not found in current directory, check in $HOME/.nestri/
|
||||
if err := viper.ReadInConfig(); err != nil {
|
||||
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
|
||||
// Find home directory.
|
||||
home, err := os.UserHomeDir()
|
||||
cobra.CheckErr(err)
|
||||
|
||||
// Search config in home directory with name ".nestri" (without extension).
|
||||
viper.AddConfigPath(home)
|
||||
viper.SetConfigType("yaml")
|
||||
viper.SetConfigName(".nestri")
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
viper.AutomaticEnv() // read in environment variables that match
|
||||
|
||||
// If a config file is found, read it in.
|
||||
if err := viper.ReadInConfig(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "Could not find a config file in local directory or in $HOME directory:")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user