Skip to content

Commit

Permalink
feat: Config files and verbosity flags
Browse files Browse the repository at this point in the history
This commit enables loading configuration from files, either explicity
with the -c or --config flag, the working directory PWD or the home
directory $HOME.

Only the $HOME configuration will be generated automatically.

Ref: #1
  • Loading branch information
caffeine-addictt committed Apr 4, 2024
1 parent 9cc0399 commit 5e58833
Showing 1 changed file with 62 additions and 0 deletions.
62 changes: 62 additions & 0 deletions src/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,19 @@ package src
import (
"fmt"
"os"
"path/filepath"

"github.com/caffeine-addictt/video-manager/src/utils"
"github.com/mitchellh/go-homedir"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)

// Global variables
var (
cfgFile string
verbose bool
debug bool
)

// Root command
Expand All @@ -18,6 +28,58 @@ var rootCommand = &cobra.Command{
),
}

// Configuration
func init() {
cobra.OnInitialize(initConfig)
rootCommand.PersistentFlags().StringVarP(&cfgFile, "config", "c", "", "config file (default is $HOME/.video-manager)")

// Verbosity
rootCommand.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "Verbose output")
rootCommand.PersistentFlags().BoolVarP(&debug, "debug", "d", false, "Debug output")
}

func initConfig() {
home, err := homedir.Dir()
if err != nil {
fmt.Println("Failed to get home directory")
Debug(err.Error())
os.Exit(1)
}

if cfgFile != "" {
// Reading provided configuration file
viper.SetConfigFile(cfgFile)
Debug("-c supplied at " + cfgFile)
} else {
// Reading configuration file from either pwd or $HOME
viper.AddConfigPath(".")
viper.AddConfigPath(home)
viper.SetConfigName(".video-manager")
viper.SetConfigType("yaml")
Debug("-c not supplied, looking for configuration file in " + home + " or pwd")
}

// Read file
if err := viper.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
fmt.Println("Configuration file not found")

// Create configuration at $HOME if it does not exist
if cfgFile != "" {
os.Exit(1)
}

viper.SafeWriteConfigAs(filepath.Join(home, ".video-manager"))
fmt.Println("Created default configuration file at " + home + "/.video-manager")
} else {
fmt.Println("Failed to read configuration file")
Debug(err.Error())
os.Exit(1)
}
}
Info("Loaded configuration from " + viper.ConfigFileUsed())
}

func Execute() {
if err := rootCommand.Execute(); err != nil {
fmt.Println(err)
Expand Down

0 comments on commit 5e58833

Please sign in to comment.