From 73ce95d30b7057ec67ca27695ccfd9dc99dd81d2 Mon Sep 17 00:00:00 2001 From: Gregory Ballantine Date: Fri, 20 Jul 2018 13:42:09 -0400 Subject: [PATCH] Added a simple setup command --- cmd/setup.go | 81 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 cmd/setup.go diff --git a/cmd/setup.go b/cmd/setup.go new file mode 100644 index 0000000..bd642fe --- /dev/null +++ b/cmd/setup.go @@ -0,0 +1,81 @@ +package cmd + +import ( + "fmt" + "io" + "log" + "os" + "os/user" + "strings" + + "github.com/spf13/cobra" +) + +var ( + configDirectory string = strings.Join([]string{getHomeDir(), ".muldap"}, "/") + configFile string = "config.toml" + configFilePath string = strings.Join([]string{configDirectory, configFile}, "/") + defaultPerms os.FileMode = 0700 +) + +func init() { + rootCmd.AddCommand(setupCmd) +} + +var setupCmd = &cobra.Command{ + Use: "setup", + Short: "Set up your user environment for muldap", + Long: "An easy way to get your environment up and running using muldap", + Run: func(cmd *cobra.Command, args []string) { + // check if the configuration directory exists + if _, err := os.Stat(configDirectory); os.IsNotExist(err) { + fmt.Printf("Creating new configuration directory at %s\n", configDirectory) + _ = os.Mkdir(configDirectory, defaultPerms) + } + + // check if the configuration file exists + if _, err := os.Stat(configFilePath); os.IsNotExist(err) { + fmt.Printf("Creating new configuration file at %s\n", configFilePath) + _, err = os.Create(configFilePath) + if err != nil { + log.Fatal(err) + } + + // write the configuration to the new file + copyFile("./config.toml", configFilePath) + } else { + // notify the user the file already exists + fmt.Printf("Your configuration file already exists at %s\n", configFilePath) + } + }, +} + +// get user's home directory +func getHomeDir() string { + usr, err := user.Current() + if err != nil { + log.Fatal(err) + } + + return usr.HomeDir +} + +// copy a file +func copyFile(src, dst string) { + in, err := os.OpenFile(src, os.O_RDONLY, os.ModeAppend) + if err != nil { + log.Fatal(err) + } + defer in.Close() + + out, err := os.OpenFile(dst, os.O_WRONLY, os.ModeAppend) + if err != nil { + log.Fatal(err) + } + defer out.Close() + + _, err = io.Copy(out, in) + if err != nil { + log.Fatal(err) + } +}