breaktime/cmd/root.go

106 lines
2.6 KiB
Go

/*
Copyright © 2023 Brian Buller <brian@bullercodeworks.com>
*/
package cmd
import (
"fmt"
"os"
"time"
gap "github.com/muesli/go-app-paths"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var cfgFile string
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "breaktime",
Short: "A pomodoro-style timer app",
RunE: runRootCmd,
}
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
err := rootCmd.Execute()
if err != nil {
os.Exit(1)
}
}
func init() {
viper.SetDefault("lastbreak", time.Now())
p, _ := time.ParseDuration("25m")
viper.SetDefault("pomodoro", p)
viper.SetDefault("warnpct", 0.75)
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.breaktime.yaml)")
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
// initConfig reads in config file and ENV variables if set.
func initConfig() {
var firstDir string // in case we have to create directories
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
scope := gap.NewScope(gap.User, "breaktime")
dirs, err := scope.ConfigDirs()
if err != nil {
fmt.Println("Can't retrieve default config. Please manually pass a config file with '--config'")
os.Exit(1)
}
firstDir = dirs[0]
for _, v := range dirs {
viper.AddConfigPath(v)
}
cobra.CheckErr(err)
viper.SetConfigType("yaml")
viper.SetConfigName("breaktime")
}
var createConfig bool
v2Path := fmt.Sprintf("%s%s%s", firstDir, string(os.PathSeparator), "breaktime.yaml")
if err := viper.ReadInConfig(); err != nil {
createConfig = true
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
// Config file not found; Check if we have a v1 config file
fmt.Println("Config file not found.")
} else {
fmt.Println("Found config file, but another error occurred.")
fmt.Println(err)
}
}
if createConfig {
_, err := os.Stat(firstDir)
if os.IsNotExist(err) {
err := os.Mkdir(firstDir, 0755)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
if err = viper.WriteConfigAs(v2Path); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
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, "Using config file:", viper.ConfigFileUsed())
}
}
func runRootCmd(cmd *cobra.Command, args []string) error {
return nil
}