root.go (2795B)
1 // Copyright © 2018 MTRNord <info@nordgedanken.de> 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package cmd 16 17 import ( 18 "fmt" 19 "os" 20 21 "github.com/Nordgedanken/Morpheusv2/pkg/app" 22 "github.com/Nordgedanken/Morpheusv2/pkg/db/sqlite" 23 "github.com/Nordgedanken/Morpheusv2/pkg/util" 24 "github.com/shibukawa/configdir" 25 "github.com/spf13/cobra" 26 "io" 27 "log" 28 "path/filepath" 29 ) 30 31 // rootCmd represents the base command when called without any subcommands 32 var rootCmd = &cobra.Command{ 33 Use: "Morpheusv2", 34 PreRunE: func(cmd *cobra.Command, args []string) error { 35 // Init Logs and folders 36 // configdir.New gets the Config Paths that are available on this system 37 configDirs := configdir.New("Nordgedanken", "Morpheusv2") 38 // path holds the global configdir of the system with the log folder appended 39 path := filepath.ToSlash(configDirs.QueryFolders(configdir.Global)[0].Path + "/log/") 40 logFilePath := filepath.ToSlash(path + "main.log") 41 42 // This checks if the directory is missing and if that's the case to generate the directory 43 if _, StatErr := os.Stat(path); os.IsNotExist(StatErr) { 44 MkdirErr := os.MkdirAll(path, os.ModeDir) 45 if MkdirErr != nil { 46 return MkdirErr 47 } 48 } 49 50 // os.OpenFile opens the file where the log is supposed to be written to 51 logFile, err := os.OpenFile(logFilePath, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0600) 52 if err != nil { 53 return err 54 } 55 56 // MultiWriter makes it possible to print log to both log File and console 57 mw := io.MultiWriter(os.Stdout, logFile) 58 59 // SetOutput tells the log where to write to 60 log.SetOutput(mw) 61 62 // dbImpl.Init() generates the needed tables if needed before the app starts 63 util.DB = &sqlite.SQLite{} 64 err = util.DB.Init() 65 if err != nil { 66 return err 67 } 68 69 log.Println("DB Set Up") 70 return nil 71 }, 72 // TODO add descriptions 73 Short: "", 74 Long: ``, 75 // Uncomment the following line if your bare application 76 // has an action associated with it: 77 RunE: func(cmd *cobra.Command, args []string) error { 78 return app.Start(args) 79 }, 80 } 81 82 // Execute adds all child commands to the root command and sets flags appropriately. 83 // This is called by main.main(). It only needs to happen once to the rootCmd. 84 func Execute() { 85 if err := rootCmd.Execute(); err != nil { 86 fmt.Println(err) 87 os.Exit(1) 88 } 89 }