/
root.go
92 lines (74 loc) · 1.94 KB
/
root.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package cmd
import (
"fmt"
"os"
"path/filepath"
"github.com/spf13/cobra"
homedir "github.com/mitchellh/go-homedir"
"github.com/spf13/viper"
)
// Global variable
var (
cfgFile string
todoFile string
taskDate string
)
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "todo",
Short: "Get things done.",
Long: `Get things done.`,
}
func Execute() {
cobra.CheckErr(rootCmd.Execute())
}
func init() {
var err error
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.todo.yaml)")
rootCmd.PersistentFlags().StringVar(&todoFile, "todo", "", "todo file (default is $HOME/todo.txt)")
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
todoFile, err = checkFilePath()
if err != nil {
fmt.Println(err)
}
}
// initConfig reads in config file and ENV variables if set.
func initConfig() {
if cfgFile != "" {
viper.SetConfigFile(cfgFile)
} else {
home, err := homedir.Dir()
cobra.CheckErr(err)
viper.AddConfigPath(home)
viper.SetConfigName(".todo")
}
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())
}
}
// checkFilePath checks if the todo.txt is created under root folder
// Create it if it doesnt exist
func checkFilePath() (string, error) {
home, err := homedir.Dir()
if err != nil {
return "", err
}
path := filepath.Join(home, "todo.txt")
if _, err := os.Stat(path); os.IsNotExist(err) {
file, err := os.Create(path)
if err != nil {
return "", err
}
defer file.Close()
// Create file
fmt.Printf("\nNo existing TODO file. \nNew TODO file created - %s \n\n", path)
return "", err
} else {
// Normal case
// fmt.Printf("\nUsing TODO file - %s \n\n", path)
}
return path, nil
}