backy/cmd/root.go

70 lines
1.5 KiB
Go
Raw Normal View History

// root.go
// Copyright (C) Andrew Woodlee 2023
// License: Apache-2.0
2022-12-15 16:42:21 +00:00
package cmd
import (
"fmt"
"os"
"path"
"strings"
2022-12-15 16:42:21 +00:00
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var (
// Used for flags.
cfgFile string
verbose bool
rootCmd = &cobra.Command{
Use: "backy",
Short: "An easy-to-configure backup tool.",
Long: `Backy is a command-line application useful for configuring backups, or any commands run in sequence.`,
2022-12-15 16:42:21 +00:00
}
)
// Execute executes the root command.
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
2022-12-15 16:42:21 +00:00
}
func init() {
cobra.OnInitialize(initConfig)
2023-01-02 05:39:19 +00:00
rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "", "config file to read from")
2022-12-15 16:42:21 +00:00
rootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "Sets verbose level")
rootCmd.AddCommand(backupCmd)
rootCmd.AddCommand(execCmd)
2022-12-15 16:42:21 +00:00
}
func initConfig() {
backyConfig := viper.New()
if cfgFile != strings.TrimSpace("") {
2022-12-15 16:42:21 +00:00
// Use config file from the flag.
backyConfig.SetConfigFile(cfgFile)
} else {
// Find home directory.
home, err := os.UserHomeDir()
cobra.CheckErr(err)
configPath := path.Join(home, ".config", "backy")
// Search config in config directory with name "backy" (without extension).
backyConfig.AddConfigPath(configPath)
backyConfig.SetConfigType("yaml")
backyConfig.SetConfigName("backy")
}
backyConfig.AutomaticEnv()
if err := backyConfig.ReadInConfig(); err == nil {
// fmt.Println("Using config file:", backyConfig.ConfigFileUsed())
2022-12-15 16:42:21 +00:00
}
}