package cmdEnv import ( "fmt" "kode-creator/config" "kode-creator/configFile" "os/exec" "kode-creator/utils" "os" "strconv" "strings" "github.com/gookit/color" "github.com/spf13/cobra" ) // initailize global config var CfgGlobal *config.Config // Declare a global variable for config // init configuration for this package func InitConfig(config *config.Config) { CfgGlobal = config // Assign the passed config to the global variable } var EnvCmd = &cobra.Command{ Use: "env", Short: "Manage ENVIRONMENT variables", Long: `A simple CLI option to manage environment variables`, Run: func(cmd *cobra.Command, args []string) { // Start Env command startEnvVar(cmd, args) }, } func startEnvVar(cmd *cobra.Command, args []string) { CfgGlobal.DebugPrintConfig("Function StartEnvVar") // declare map listPaths var ListPaths map[string]string // initialize command environment CfgGlobal.InitCmdEnv(cmd, args) CfgGlobal.DebugPrintConfig("Function StartEnvVar") // check if env flag EnvVariablesListFlag is set if CfgGlobal.GetEnvListFlag() { if !CfgGlobal.GetJsonFlag() { if CfgGlobal.GetEnvFilterFlag() { fmt.Println("with filter") printEnvVariablesFilter(CfgGlobal.GetEnvFilter(), CfgGlobal.GetEnvShowAllFlag()) } else { printEnvVariables() } } else { json, err := createJsonAllEnvVar(CfgGlobal.GetEnvFilter(), CfgGlobal.GetEnvShowAllFlag()) if err != nil { fmt.Println("Error:", err) return } fmt.Println(json) } // check if env flag EnvVariablesSetFlag is set } else if CfgGlobal.GetEnvSetFlag() { // if key and value are not empty if CfgGlobal.GetEnvKey() != "" && CfgGlobal.GetEnvValue() != "" { // set environment variable with key and value permanently if utils.IsWindows() { createEnvVariableWindows(CfgGlobal.GetEnvKey(), CfgGlobal.GetEnvValue()) } else { createEnvVariableLinux(CfgGlobal.GetEnvKey(), CfgGlobal.GetEnvValue()) } utils.PrintHeader() color.Green.Println("\n S E T E N V I R O N M E N T V A R I A B L E ") color.Yellow.Println(utils.CreateLine(15)) color.Green.Println("Key: " + CfgGlobal.GetEnvKey()) color.Green.Println("Value: " + CfgGlobal.GetEnvValue()) // get all environment variables printEnvVariables() color.Yellow.Println(utils.CreateLine(15)) } else { utils.PrintHeader() color.Green.Println("\n S E T E N V I R O N M E N T V A R I A B L E ") color.Yellow.Println(utils.CreateLine(15)) color.Red.Println("Error: key and value are required") fmt.Println("\nExample: kode-creator env -s -k KEY -v VALUE") color.Yellow.Println(utils.CreateLine(15)) return } // check if env flag EnvVariablesYmlFlag is set } else if CfgGlobal.GetEnvYmlFileFlag() { cfgYmlFile := configFile.LoadConfigFile(CfgGlobal) ListCategories, err := cfgYmlFile.GetListCategory() if err != nil { fmt.Println("Error:", err) return } if !CfgGlobal.GetJsonFlag() { utils.PrintHeader() fmt.Println("\n L I S T E N V V A R S F R O M Y M L F I L E ") fmt.Println(utils.CreateLine(11)) for _, category := range ListCategories { // fmt.Println("Category: " + category) ListPaths, err = cfgYmlFile.GetAllEnvironmentVariables(category) if err != nil { fmt.Println("Error:", err) return } // if category flag is set if CfgGlobal.GetEnvCategoryFlag() { if CfgGlobal.GetEnvCategoryInfo() == category { // if ListPaths is no empty if len(ListPaths) > 0 { fmt.Println(color.FgLightGreen.Render("\nCategory: " + category)) fmt.Println(utils.CreateLine(3)) // print path and value nb := 1 for path, value := range ListPaths { utils.PrintTreeElement(nb, path, value) nb++ } } } } else { // if ListPaths is no empty if len(ListPaths) > 0 { fmt.Println(color.FgLightGreen.Render("\nCategory: " + category)) fmt.Println(utils.CreateLine(3)) // print path and value nb := 1 for path, value := range ListPaths { utils.PrintTreeElement(nb, path, value) nb++ } } } } fmt.Println(utils.CreateLine(3)) } else { // Execute function createJsonAllEnvVarYml : create json output for all environment variables with category jsonOutput, err := createJsonAllEnvVarYml(cfgYmlFile, CfgGlobal.GetEnvCategoryInfo()) if err != nil { fmt.Println("Error:", err) return } fmt.Println(jsonOutput) } } else { utils.PrintHeader() cmd.Help() color.Yellow.Println(utils.CreateLine(15)) } } func createJsonAllEnvVar(filter string, showAll bool) (string, error) { //var jsonOutput string jsonOutput := "" // var map listPaths ListPaths := make(map[string]string) // var pair []string for _, e := range os.Environ() { // split key and value pair := strings.Split(e, "=") // fmt.Println(pair[1]) if showAll { ListPaths[string(pair[0])] = string(pair[1]) } else { if (strings.Contains(pair[0], filter)) || (strings.Contains(pair[1], filter)) { ListPaths[string(pair[0])] = string(pair[1]) } } } // loop over all environment variables to create json output jsonOutput += "{\n" for path, value := range ListPaths { jsonOutput += " \"" + path + "\": \"" + value + "\",\n" } jsonOutput = strings.TrimSuffix(jsonOutput, ",\n") jsonOutput += "\n}\n" return utils.DoubleBackSlash(jsonOutput), nil } // The function `createJsonAllEnvVar` creates a JSON string containing all environment variables from a // given configuration YAML file. func createJsonAllEnvVarYml(cfgYmlFile *configFile.ConfigYml, categoryInfo string) (string, error) { //var jsonOutput string jsonOutput := "" ListCategories, err := cfgYmlFile.GetListCategory() if err != nil { fmt.Println("Error:", err) return "", err } var isCategoryInfoPresent bool = false // check if categoryInfo includes in ListCategories for _, category := range ListCategories { if category == categoryInfo { isCategoryInfoPresent = true break } } if categoryInfo == "" { // loop over all categories jsonOutput += "{\n" for _, category := range ListCategories { ListPaths, err := cfgYmlFile.GetAllEnvironmentVariables(category) if err != nil { fmt.Println("Error:", err) return "", err } // if ListPaths is no empty if len(ListPaths) > 0 { // add category as array and list of environment variables to jsonOutput jsonOutput += " \"" + category + "\": [\n" // loop over all environment variables for path, value := range ListPaths { jsonOutput += " {\n" jsonOutput += " \"" + path + "\": \"" + value + "\"\n" jsonOutput += " },\n" } // remove last comma jsonOutput = strings.TrimSuffix(jsonOutput, ",\n") jsonOutput += "\n ],\n" } } jsonOutput = strings.TrimSuffix(jsonOutput, ",\n") jsonOutput += "\n}\n" } else { // loop over all categories if isCategoryInfoPresent { jsonOutput += "{\n" for _, category := range ListCategories { ListPaths, err := cfgYmlFile.GetAllEnvironmentVariables(category) if err != nil { fmt.Println("Error:", err) return "", err } if category == categoryInfo { // if ListPaths is no empty if len(ListPaths) > 0 { // add category as array and list of environment variables to jsonOutput jsonOutput += " \"" + category + "\": [\n" // loop over all environment variables for path, value := range ListPaths { jsonOutput += " {\n" jsonOutput += " \"" + path + "\": \"" + value + "\"\n" jsonOutput += " },\n" } // remove last comma jsonOutput = strings.TrimSuffix(jsonOutput, ",\n") jsonOutput += "\n ],\n" } } } jsonOutput = strings.TrimSuffix(jsonOutput, ",\n") jsonOutput += "\n}\n" } } return utils.DoubleBackSlash(jsonOutput), nil } func listEnvVariables() error { if CfgGlobal.GetEnvCmd().EnvVariablesFilterFlag { fmt.Println("GetEnvVariablesListFlag: " + strconv.FormatBool(CfgGlobal.GetEnvCmd().EnvVariablesListFlag)) printEnvVariables() } return nil } func printEnvVariables() { // print header if json flag is not set if !CfgGlobal.GetJsonFlag() { utils.PrintHeader() } color.Green.Println("E n v i r o n m e n t v a r i a b l e s") color.Yellow.Println(utils.CreateLine(15)) nb := 1 // loop over all environment variables for _, e := range os.Environ() { // split key and value pair := strings.Split(e, "=") utils.PrintTreeElement(nb, pair[0], pair[1]) nb++ } color.Yellow.Println(utils.CreateLine(15)) } func printEnvVariablesFilter(filter string, showAll bool) { utils.PrintHeader() color.Green.Println("F i l t e r E n v i r o n m e n t v a r i a b l e s") color.Yellow.Println(utils.CreateLine(15)) nb := 1 var str2, str3 string var addToPrint bool = false // loop over all environment variables for _, e := range os.Environ() { // split key and value pair := strings.Split(e, "=") if strings.Contains(pair[0], filter) { str2 = utils.ColorizeSubStrRed(pair[0], filter) str3 = color.Green.Sprint(pair[1]) addToPrint = true } else if strings.Contains(pair[1], filter) { str2 = color.Green.Sprint(pair[0]) str3 = utils.ColorizeSubStrRed(pair[1], filter) addToPrint = true } else { if showAll { str2 = utils.ColorizeString(pair[0], color.Green) str3 = utils.ColorizeString(pair[1], color.LightWhite) addToPrint = true } } if addToPrint { utils.PrintTreeElement(nb, str2, str3) } addToPrint = false nb++ } color.Yellow.Println(utils.CreateLine(15)) } // create a permanent environment variable on Windows with key and value func createEnvVariableWindows(key string, value string) error { // detect if OS is Windows if utils.IsWindows() { // set environment variable with key and value permanently // setx Key "Value" cmd := exec.Command("cmd", "/C", "setx", key, value) err := cmd.Run() if err != nil { color.Red.Println("Error:", err) } } return nil } // create a permanent environment variable on Linux with key and value func createEnvVariableLinux(key string, value string) error { // detect if OS is Linux if !utils.IsWindows() { // set environment variable with key and value permanently // setx Key "Value" cmd := exec.Command("export", key+"="+value) err := cmd.Run() if err != nil { color.Red.Println("Error:", err) } } return nil } // delete a permanent environment variable on Windows with key func deleteEnvVariableWindows(key string) error { // detect if OS is Windows if utils.IsWindows() { // set environment variable with key and value permanently // setx Key "Value" cmd := exec.Command("cmd", "/C", "setx", key, "") err := cmd.Run() if err != nil { color.Red.Println("Error:", err) } } return nil } // delete a permanent environment variable on Linux with key func deleteEnvVariableLinux(key string) error { // detect if OS is Linux if !utils.IsWindows() { // set environment variable with key and value permanently // setx Key "Value" cmd := exec.Command("unset", key) err := cmd.Run() if err != nil { color.Red.Println("Error:", err) } } return nil }