From 803e1f014cc89c30bfb80549b64195235b8b9f62 Mon Sep 17 00:00:00 2001 From: Chris Lane Date: Fri, 6 Mar 2020 19:19:49 -0500 Subject: [PATCH] feat(config-init): platform-specific pathing Update `--init` subcommand to rely upon the same platform-detection intelligence that was previously implemented by the "installer". The installer and `--init` should now produce identical config files. --- cmd/cheat/cmd_init.go | 49 ++++++++++++++++++++++++++++++++++++++++++- cmd/cheat/main.go | 2 +- 2 files changed, 49 insertions(+), 2 deletions(-) diff --git a/cmd/cheat/cmd_init.go b/cmd/cheat/cmd_init.go index 48258bd..1c2891e 100644 --- a/cmd/cheat/cmd_init.go +++ b/cmd/cheat/cmd_init.go @@ -2,9 +2,56 @@ package main import ( "fmt" + "os" + "path" + "runtime" + "strings" + + "github.com/mitchellh/go-homedir" + + "github.com/cheat/cheat/internal/config" ) // cmdInit displays an example config file. func cmdInit() { - fmt.Println(configs()) + + // get the user's home directory + home, err := homedir.Dir() + if err != nil { + fmt.Fprintf(os.Stderr, "failed to get user home directory: %v\n", err) + os.Exit(1) + } + + // read the envvars into a map of strings + envvars := map[string]string{} + for _, e := range os.Environ() { + pair := strings.SplitN(e, "=", 2) + envvars[pair[0]] = pair[1] + } + + // load the config template + configs := configs() + + // identify the os-specifc paths at which configs may be located + confpaths, err := config.Paths(runtime.GOOS, home, envvars) + if err != nil { + fmt.Fprintf(os.Stderr, "failed to read config paths: %v\n", err) + os.Exit(1) + } + + // determine the appropriate paths for config data and (optional) community + // cheatsheets based on the user's platform + confpath := confpaths[0] + confdir := path.Dir(confpath) + + // create paths for community and personal cheatsheets + community := path.Join(confdir, "/cheatsheets/community") + personal := path.Join(confdir, "/cheatsheets/personal") + + // template the above paths into the default configs + configs = strings.Replace(configs, "COMMUNITY_PATH", community, -1) + configs = strings.Replace(configs, "PERSONAL_PATH", personal, -1) + + // output the templated configs + fmt.Println(configs) } diff --git a/cmd/cheat/main.go b/cmd/cheat/main.go index a696200..297fef0 100755 --- a/cmd/cheat/main.go +++ b/cmd/cheat/main.go @@ -49,7 +49,7 @@ func main() { envvars[pair[0]] = pair[1] } - // load the os-specifc paths at which the config file may be located + // identify the os-specifc paths at which configs may be located confpaths, err := config.Paths(runtime.GOOS, home, envvars) if err != nil { fmt.Fprintf(os.Stderr, "failed to load config: %v\n", err)