/* YetAnotherToDoList Copyright © 2023 gilex-dev gilex-dev@proton.me This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 3. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ package cmd import ( "fmt" "log" "os" "path/filepath" "strings" "time" "github.com/spf13/cobra" "github.com/spf13/viper" "somepi.ddns.net/gitea/gilex-dev/YetAnotherToDoList/globals" ) var cfgFile string var logger *log.Logger // rootCmd represents the base command when called without any subcommands var rootCmd = &cobra.Command{ Use: "YetAnotherToDoList", Version: fmt.Sprintf("%s %s", globals.Version, globals.CommitHash), Short: "Simple To Do List Web Application with Vue.js frontend and GraphQL API", Long: `YetAnotherToDoList 2023 by gilex-dev A simple To Do List Web Application with Go backend, Vue.js frontend and a GraphQL API `, // Uncomment the following line if your bare application // has an action associated with it: // Run: func(cmd *cobra.Command, args []string) { }, } // 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() { rootCmd.CompletionOptions.HiddenDefaultCmd = true // check if first argument needs init (inspired by https://github.com/spf13/cobra/issues/823#issuecomment-617863653) if len(os.Args) > 1 { noSetupRequired := []string{"__complete", "__completeNoDesc", "completion", "help", licenseCmd.Name()} for _, subcommand := range noSetupRequired { if subcommand != os.Args[1] { continue } return } } cobra.OnInitialize(initConfig, initLog) // Here you will define your flags and configuration settings. // Cobra supports persistent flags, which, if defined here, // will be global for your application. rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.YetAnotherToDoList.yaml)") rootCmd.PersistentFlags().String("log_file", "", "Path to log file") // Cobra also supports local flags, which will only run // when this action is called directly. // rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") } // initConfig reads in config file and ENV variables if set. func initConfig() { if cfgFile != "" { // Use config file from the flag. viper.SetConfigFile(cfgFile) } else { // Find home directory. home, err := os.UserHomeDir() cobra.CheckErr(err) wd, err := os.Getwd() cobra.CheckErr(err) // Search config in home directory with name ".YetAnotherToDoList" (without extension). viper.AddConfigPath(home) // Search config in working directory with name ".YetAnotherToDoList" (without extension). viper.AddConfigPath(wd) viper.SetConfigType("yaml") viper.SetConfigName(".YetAnotherToDoList") } 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()) } else { fmt.Fprintln(os.Stderr, "Unable to read in", viper.ConfigFileUsed(), err) } } func initLog() { var utc = 0 var time_zone_use, time_zone_alt string time_zone_local, _ := time.Now().Zone() time_zone_offset := strings.Split(time.Now().In(time.Local).String(), " ")[2] if viper.GetBool("log_UTC") { utc = log.LUTC time_zone_use = "UTC" time_zone_alt = time_zone_local time_zone_offset_rune := []rune(time_zone_offset) if time_zone_offset_rune[0] == '+' { time_zone_offset_rune[0] = '-' } time_zone_offset = string(time_zone_offset_rune) } else { time_zone_use = time_zone_local time_zone_alt = "UTC" } logger_flags := log.Ldate | log.Ltime | utc logger = log.New(os.Stdout, "", logger_flags) if err := viper.BindPFlag("log_file", rootCmd.Flags().Lookup("log_file")); err != nil { fmt.Println("Unable to bind flag:", err) } if viper.GetString("log_file") != "" { log_path, err := filepath.Abs(viper.GetString("log_file")) logger.SetOutput(os.Stdout) if err != nil { logger.Println("Invalid path for log file", log_path) } log_file, err := os.OpenFile(log_path, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) if err != nil { fmt.Println("Failed to write to log file:", err) } else { logger.Println("Switching to log file", log_path, os.Args, "🌵") logger.SetOutput(log_file) } } logger.SetFlags(0) logger.Println() logger.SetFlags(logger_flags) logger.Printf("Started YetAnotherToDoList with pid: %v\n", os.Getpid()) logger.Printf("Using %v (%v %v) in logs", time_zone_use, time_zone_alt, time_zone_offset) }