Skip to content

Commit

Permalink
feat: Add config command
Browse files Browse the repository at this point in the history
Ref: #40
  • Loading branch information
caffeine-addictt committed Apr 19, 2024
1 parent 0b84c30 commit 3701621
Show file tree
Hide file tree
Showing 2 changed files with 83 additions and 0 deletions.
82 changes: 82 additions & 0 deletions src/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package src

import (
"fmt"
"os"
"path/filepath"

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

// Head
var configCommand = &cobra.Command{
Use: "config",
Short: "Manage your configuration",
}

// Sub
var configInitFlags struct {
yes bool
}
var configInitCommand = &cobra.Command{
Use: "init <path?>",
Short: "Initialize a new configuration file",
Long: utils.Multiline(
"Initialize a new configuration file at the specified path.",
"If no path is specified, it will be created in the current directory.",
),
Aliases: []string{"create", "new", "reset"},
Args: cobra.MaximumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
var newConfigPath string
if len(args) == 1 {
newConfigPath = args[0]
} else {
newConfigPath = "./.video-manager.yml"
}
newConfigPath = filepath.Clean(newConfigPath)

// Write config
if err := viper.SafeWriteConfigAs(newConfigPath); err != nil {
if _, ok := err.(viper.ConfigFileAlreadyExistsError); ok {
switch utils.InputPrompt("A configuration file already exists. Do you want to overwrite it? (y/n)") {
case "y", "Y":
default:
os.Exit(1)
}

// Force write
if err := viper.WriteConfigAs(newConfigPath); err != nil {
fmt.Println("Failed to write configuration file")
Debug(err.Error())
os.Exit(1)
}
} else {
fmt.Println("Failed to write configuration file")
Debug(err.Error())
os.Exit(1)
}
}
},
}

var configWhereCommand = &cobra.Command{
Use: "which",
Short: "Print the path to the loaded configuration file",
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println(viper.ConfigFileUsed())
},
}

func initConfigCmd() {
rootCommand.AddCommand(configCommand)
configCommand.AddCommand(
configInitCommand,
configWhereCommand,
)

configInitCommand.Flags().BoolVarP(&configInitFlags.yes, "yes", "y", false, "Skip the confirmation prompt")
}
1 change: 1 addition & 0 deletions src/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ func init() {

// Initialize subcommands
initCacheCmd()
initConfigCmd()
}

func initConfig() {
Expand Down

0 comments on commit 3701621

Please sign in to comment.