go-KodeStarter/cmdEnv/envVars.go

475 lines
11 KiB
Go
Raw Permalink Normal View History

2023-06-21 11:50:12 -04:00
package cmdEnv
import (
"fmt"
2023-06-30 15:25:39 -04:00
"kode-creator/config"
"kode-creator/configFile"
2023-11-29 12:57:49 -05:00
"os/exec"
2023-06-30 10:09:01 -04:00
2023-06-30 15:25:39 -04:00
"kode-creator/utils"
2023-06-21 11:50:12 -04:00
"os"
2023-06-25 12:54:50 -04:00
"strconv"
2023-06-21 11:50:12 -04:00
"strings"
2023-06-25 12:54:50 -04:00
"github.com/gookit/color"
2023-06-21 11:50:12 -04:00
"github.com/spf13/cobra"
)
2023-06-30 10:09:01 -04:00
// 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
}
2023-06-21 11:50:12 -04:00
var EnvCmd = &cobra.Command{
Use: "env",
2023-07-08 00:45:18 -04:00
Short: "Manage ENVIRONMENT variables",
2023-06-21 11:50:12 -04:00
Long: `A simple CLI option to manage environment variables`,
Run: func(cmd *cobra.Command, args []string) {
2023-06-30 10:09:01 -04:00
// Start Env command
2023-06-25 12:54:50 -04:00
startEnvVar(cmd, args)
2023-06-21 11:50:12 -04:00
2023-06-30 10:09:01 -04:00
},
}
2023-06-25 12:54:50 -04:00
2023-06-30 10:09:01 -04:00
func startEnvVar(cmd *cobra.Command, args []string) {
2023-06-25 12:54:50 -04:00
2023-06-30 10:09:01 -04:00
CfgGlobal.DebugPrintConfig("Function StartEnvVar")
2023-06-25 12:54:50 -04:00
2023-06-30 10:09:01 -04:00
// declare map listPaths
var ListPaths map[string]string
2023-06-21 11:50:12 -04:00
2023-06-30 10:09:01 -04:00
// initialize command environment
CfgGlobal.InitCmdEnv(cmd, args)
CfgGlobal.DebugPrintConfig("Function StartEnvVar")
2023-11-29 12:57:49 -05:00
// check if env flag EnvVariablesListFlag is set
2023-06-30 10:09:01 -04:00
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)
}
2023-11-29 12:57:49 -05:00
// 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
2023-06-30 10:09:01 -04:00
} 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 {
2023-11-29 12:57:49 -05:00
utils.PrintHeader()
2023-06-30 10:09:01 -04:00
cmd.Help()
2023-11-29 12:57:49 -05:00
color.Yellow.Println(utils.CreateLine(15))
2023-06-30 10:09:01 -04:00
}
2023-06-25 12:54:50 -04:00
2023-06-21 11:50:12 -04:00
}
2023-06-30 10:09:01 -04:00
func createJsonAllEnvVar(filter string, showAll bool) (string, error) {
2023-06-25 12:54:50 -04:00
2023-06-30 10:09:01 -04:00
//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])
}
}
2023-06-25 12:54:50 -04:00
}
2023-06-30 10:09:01 -04:00
// 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
2023-06-25 12:54:50 -04:00
}
func listEnvVariables() error {
2023-06-30 10:09:01 -04:00
if CfgGlobal.GetEnvCmd().EnvVariablesFilterFlag {
fmt.Println("GetEnvVariablesListFlag: " + strconv.FormatBool(CfgGlobal.GetEnvCmd().EnvVariablesListFlag))
2023-06-25 12:54:50 -04:00
printEnvVariables()
}
return nil
}
2023-06-21 11:50:12 -04:00
func printEnvVariables() {
2023-11-29 12:57:49 -05:00
// 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))
2023-06-30 10:09:01 -04:00
nb := 1
2023-06-21 11:50:12 -04:00
// loop over all environment variables
for _, e := range os.Environ() {
// split key and value
pair := strings.Split(e, "=")
2023-06-30 10:09:01 -04:00
utils.PrintTreeElement(nb, pair[0], pair[1])
nb++
2023-06-25 12:54:50 -04:00
}
2023-06-30 10:09:01 -04:00
2023-11-29 12:57:49 -05:00
color.Yellow.Println(utils.CreateLine(15))
2023-06-25 12:54:50 -04:00
}
2023-06-30 10:09:01 -04:00
func printEnvVariablesFilter(filter string, showAll bool) {
2023-11-29 12:57:49 -05:00
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))
2023-06-25 12:54:50 -04:00
2023-06-30 10:09:01 -04:00
nb := 1
var str2, str3 string
var addToPrint bool = false
2023-06-25 12:54:50 -04:00
// loop over all environment variables
for _, e := range os.Environ() {
// split key and value
pair := strings.Split(e, "=")
if strings.Contains(pair[0], filter) {
2023-06-30 10:09:01 -04:00
str2 = utils.ColorizeSubStrRed(pair[0], filter)
str3 = color.Green.Sprint(pair[1])
addToPrint = true
2023-06-25 12:54:50 -04:00
} else if strings.Contains(pair[1], filter) {
2023-06-30 10:09:01 -04:00
str2 = color.Green.Sprint(pair[0])
str3 = utils.ColorizeSubStrRed(pair[1], filter)
addToPrint = true
2023-06-25 12:54:50 -04:00
} else {
2023-06-30 10:09:01 -04:00
if showAll {
str2 = utils.ColorizeString(pair[0], color.Green)
str3 = utils.ColorizeString(pair[1], color.LightWhite)
addToPrint = true
}
2023-06-25 12:54:50 -04:00
}
2023-06-30 10:09:01 -04:00
if addToPrint {
utils.PrintTreeElement(nb, str2, str3)
}
addToPrint = false
nb++
2023-06-25 12:54:50 -04:00
2023-06-21 11:50:12 -04:00
}
2023-11-29 12:57:49 -05:00
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
2023-06-21 11:50:12 -04:00
}