From 3e3f7b80a6de1e99c9db6468b23b72ce36795577 Mon Sep 17 00:00:00 2001 From: Doron Cohen Date: Fri, 9 Oct 2020 22:00:45 +0300 Subject: [PATCH] feat: init cmd for initializing antidot --- cmd/init.go | 43 ++++++++++++++++++++++++++++++++++++++++++ internal/utils/env.go | 11 +++++++++++ internal/utils/text.go | 14 ++++++++++++++ 3 files changed, 68 insertions(+) create mode 100644 cmd/init.go create mode 100644 internal/utils/text.go diff --git a/cmd/init.go b/cmd/init.go new file mode 100644 index 0000000..444ebe0 --- /dev/null +++ b/cmd/init.go @@ -0,0 +1,43 @@ +package cmd + +import ( + "fmt" + "log" + + "github.com/spf13/cobra" + + "github.com/doron-cohen/antidot/internal/utils" +) + +func init() { + rootCmd.AddCommand(initCmd) +} + +var initCmd = &cobra.Command{ + Use: "init", + Short: "Initialize antidot for aliases and env vars to work", + Run: func(cmd *cobra.Command, args []string) { + // TODO: detect shell and generate appropriate script + envFilePath, err := utils.GetEnvFile() + if err != nil { + log.Fatalf("Failed to get env file path: %v", err) + } + + aliasFilePath, err := utils.GetAliasFile() + if err != nil { + log.Fatalf("Failed to get alias file path: %v", err) + } + + fmt.Printf(`if [[ "$ANTIDOT_INIT" != "1" ]]; then +%s + source %s + source %s + + export ANTIDOT_INIT=1 +fi`, + utils.IndentLines(utils.XdgVarsExport()), + envFilePath, + aliasFilePath, + ) + }, +} diff --git a/internal/utils/env.go b/internal/utils/env.go index bc33736..c7c113e 100644 --- a/internal/utils/env.go +++ b/internal/utils/env.go @@ -5,6 +5,7 @@ import ( "os" "os/user" + "github.com/adrg/xdg" "github.com/joho/godotenv" ) @@ -33,6 +34,16 @@ func WriteEnvToFile(envMap map[string]string, filePath string) error { return godotenv.Write(newMap, filePath) } +func XdgVarsExport() string { + return fmt.Sprintf(`export XDG_CONFIG_HOME="%s" +export XDG_CACHE_HOME="%s" +export XDG_DATA_HOME="%s"`, + xdg.ConfigHome, + xdg.CacheHome, + xdg.DataHome, + ) +} + func GetAliasFile() (string, error) { return AppDirs.GetDataFile("alias.sh") } diff --git a/internal/utils/text.go b/internal/utils/text.go new file mode 100644 index 0000000..99e8c42 --- /dev/null +++ b/internal/utils/text.go @@ -0,0 +1,14 @@ +package utils + +import ( + "fmt" + "strings" +) + +func IndentLines(lines string) string { + var builder strings.Builder + for _, line := range strings.Split(lines, "\n") { + builder.WriteString(fmt.Sprintf(" %s\n", line)) + } + return builder.String() +}