make some correction

This commit is contained in:
bcharest 2023-11-29 12:57:49 -05:00
parent 70c9e72753
commit 8000ff69c9
11 changed files with 948 additions and 65 deletions

View File

@ -4,6 +4,7 @@ import (
"fmt" "fmt"
"kode-creator/config" "kode-creator/config"
"kode-creator/configFile" "kode-creator/configFile"
"os/exec"
"kode-creator/utils" "kode-creator/utils"
"os" "os"
@ -28,17 +29,8 @@ var EnvCmd = &cobra.Command{
Long: `A simple CLI option to manage environment variables`, Long: `A simple CLI option to manage environment variables`,
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
<<<<<<< HEAD
// Start Env command // Start Env command
startEnvVar(cmd, args) startEnvVar(cmd, args)
=======
config.SetInformations(cmd, args)
// if option --env or -e is set then print environment variables
if config.GetEnvVariablesFlag() {
printEnvVariables()
}
>>>>>>> b7ba427 (corr. envVar)
}, },
} }
@ -55,6 +47,7 @@ func startEnvVar(cmd *cobra.Command, args []string) {
CfgGlobal.DebugPrintConfig("Function StartEnvVar") CfgGlobal.DebugPrintConfig("Function StartEnvVar")
// check if env flag EnvVariablesListFlag is set
if CfgGlobal.GetEnvListFlag() { if CfgGlobal.GetEnvListFlag() {
if !CfgGlobal.GetJsonFlag() { if !CfgGlobal.GetJsonFlag() {
@ -74,6 +67,40 @@ func startEnvVar(cmd *cobra.Command, args []string) {
fmt.Println(json) 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() { } else if CfgGlobal.GetEnvYmlFileFlag() {
cfgYmlFile := configFile.LoadConfigFile(CfgGlobal) cfgYmlFile := configFile.LoadConfigFile(CfgGlobal)
@ -146,8 +173,9 @@ func startEnvVar(cmd *cobra.Command, args []string) {
} }
} else { } else {
utils.PrintHeader()
cmd.Help() cmd.Help()
fmt.Println(utils.CreateLine(8)) color.Yellow.Println(utils.CreateLine(15))
} }
} }
@ -307,8 +335,14 @@ func listEnvVariables() error {
} }
func printEnvVariables() { func printEnvVariables() {
fmt.Println("E n v i r o n m e n t v a r i a b l e s")
fmt.Println("-----------------------------------------") // 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 nb := 1
@ -320,13 +354,14 @@ func printEnvVariables() {
nb++ nb++
} }
fmt.Println("-----------------------------------------") color.Yellow.Println(utils.CreateLine(15))
} }
func printEnvVariablesFilter(filter string, showAll bool) { func printEnvVariablesFilter(filter string, showAll bool) {
fmt.Println("Filter Environment variables")
// fmt.Println("---------------------") utils.PrintHeader()
utils.CreateLine(5) 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 nb := 1
var str2, str3 string var str2, str3 string
@ -359,4 +394,81 @@ func printEnvVariablesFilter(filter string, showAll bool) {
nb++ 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
} }

View File

@ -7,6 +7,7 @@ import (
"kode-creator/utils" "kode-creator/utils"
"net/http" "net/http"
"github.com/gookit/color"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -55,10 +56,10 @@ func startList(cmd *cobra.Command, args []string) {
// if -o flag is set, list projects for that org // if -o flag is set, list projects for that org
if CfgGlobal.GetListOrganizationFlag() { if CfgGlobal.GetListOrganizationFlag() {
if !CfgGlobal.GetJsonFlag() { if !CfgGlobal.GetJsonFlag() {
fmt.Println("\n L I S T P R O J E C T S F O R O R G. ") color.Green.Println("\n L I S T P R O J E C T S F O R O R G. ")
fmt.Println(utils.CreateLine(8)) color.Yellow.Println(utils.CreateLine(15))
fmt.Println(" ==> " + CfgGlobal.GetListOrganization() + " <== ") color.Green.Println(" ==> " + CfgGlobal.GetListOrganization() + " <== ")
fmt.Println(utils.CreateLine(8)) color.Yellow.Println(utils.CreateLine(15))
} }
projects, err := ListGitTeaProjects(CfgGlobal.GetListOrganization()) projects, err := ListGitTeaProjects(CfgGlobal.GetListOrganization())
if err != nil { if err != nil {
@ -66,10 +67,9 @@ func startList(cmd *cobra.Command, args []string) {
return return
} }
for _, project := range projects { for _, project := range projects {
fmt.Println(project) fmt.Print(project)
// fmt.Print(project)
} }
fmt.Println(utils.CreateLine(8)) color.Yellow.Println(utils.CreateLine(15))
} else { } else {
orgs, err := ListGitTeaOrganization() orgs, err := ListGitTeaOrganization()
@ -78,14 +78,14 @@ func startList(cmd *cobra.Command, args []string) {
return return
} }
if !CfgGlobal.GetJsonFlag() { if !CfgGlobal.GetJsonFlag() {
fmt.Println("\n L I S T O R G A N I Z A T I O N S") color.Green.Println("\n L I S T O R G A N I Z A T I O N S")
fmt.Println(utils.CreateLine(8)) color.Yellow.Println(utils.CreateLine(15))
} }
for _, org := range orgs { for _, org := range orgs {
fmt.Print(org) fmt.Print(org)
} }
fmt.Println(utils.CreateLine(8)) color.Yellow.Println(utils.CreateLine(15))
} }
// if Github flag is set // if Github flag is set
@ -94,8 +94,8 @@ func startList(cmd *cobra.Command, args []string) {
// if user flag is set, list projects for that user // if user flag is set, list projects for that user
if CfgGlobal.GetListUserFlag() { if CfgGlobal.GetListUserFlag() {
fmt.Println("\n L I S T G I T H U B P R O J E C T S F O R : " + CfgGlobal.GetListUser()) color.Green.Println("\n L I S T G I T H U B P R O J E C T S F O R : " + CfgGlobal.GetListUser())
fmt.Println(utils.CreateLine(11)) color.Yellow.Println(utils.CreateLine(15))
repos, err := ListGitHubProjectsfromUser(CfgGlobal.GetListUser(), CfgGlobal.GetGithubTokenEnv()) repos, err := ListGitHubProjectsfromUser(CfgGlobal.GetListUser(), CfgGlobal.GetGithubTokenEnv())
if err != nil { if err != nil {
fmt.Println("Error:", err) fmt.Println("Error:", err)
@ -108,8 +108,8 @@ func startList(cmd *cobra.Command, args []string) {
} }
} else if CfgGlobal.GetGitHubSearchFlag() { } else if CfgGlobal.GetGitHubSearchFlag() {
fmt.Println("\n L I S T G I T H U B P R O J E C T S F R O M S E A R C H : " + CfgGlobal.GetListCmd().GitHubSearch) color.Green.Println("\n L I S T G I T H U B P R O J E C T S F R O M S E A R C H : " + CfgGlobal.GetListCmd().GitHubSearch)
fmt.Println(utils.CreateLine(11)) color.Yellow.Println(utils.CreateLine(15))
repos, err := SearchGitHubProjectsfromSearch(CfgGlobal.GetListCmd().GitHubSearch, CfgGlobal.GetGithubTokenEnv()) repos, err := SearchGitHubProjectsfromSearch(CfgGlobal.GetListCmd().GitHubSearch, CfgGlobal.GetGithubTokenEnv())
if err != nil { if err != nil {
fmt.Println("Error:", err) fmt.Println("Error:", err)
@ -128,7 +128,7 @@ func startList(cmd *cobra.Command, args []string) {
// print help if no flag is set // print help if no flag is set
cmd.Help() cmd.Help()
fmt.Println(utils.CreateLine(11)) color.Yellow.Println(utils.CreateLine(15))
} }

View File

@ -68,6 +68,9 @@ type EnvCmdConfig struct {
EnvVariablesCategory string EnvVariablesCategory string
EnvVariablesSetFlag bool EnvVariablesSetFlag bool
EnvVariablesShowAllFlag bool EnvVariablesShowAllFlag bool
EnvVariablesKey string
EnvVariablesValue string
EnvVariablesDeleteFlag bool
} }
// * * * * * * * * * * * * * * * * * * * * * * * * // // * * * * * * * * * * * * * * * * * * * * * * * * //
@ -104,24 +107,9 @@ func (c *Config) SetAuthor(value string) {
c.author = value c.author = value
} }
<<<<<<< HEAD
// Getter for modifDate field // Getter for modifDate field
func (c *Config) GetModifDate() string { func (c *Config) GetModifDate() string {
return c.ModifDate return c.ModifDate
=======
func GetEnvVariablesFlag() bool {
return envVariablesFlag
}
func SetEnvVariablesFlag(flag bool) {
envVariablesFlag = flag
}
// functions for list command
// --------------------------
func SetListOrganisation(name string) {
listOrganization = name
>>>>>>> b7ba427 (corr. envVar)
} }
// Setter for modifDate field // Setter for modifDate field
@ -561,6 +549,36 @@ func (c *Config) SetEnvShowAllFlag(value bool) {
c.EnvCmd.EnvVariablesShowAllFlag = value c.EnvCmd.EnvVariablesShowAllFlag = value
} }
// Getter for env Key
func (c *Config) GetEnvKey() string {
return c.EnvCmd.EnvVariablesKey
}
// Setter for env Key
func (c *Config) SetEnvKey(value string) {
c.EnvCmd.EnvVariablesKey = value
}
// Getter for env Value
func (c *Config) GetEnvValue() string {
return c.EnvCmd.EnvVariablesValue
}
// Setter for env Value
func (c *Config) SetEnvValue(value string) {
c.EnvCmd.EnvVariablesValue = value
}
// Getter for env Delete flag
func (c *Config) GetEnvDeleteFlag() bool {
return c.EnvCmd.EnvVariablesDeleteFlag
}
// Setter for env Delete flag
func (c *Config) SetEnvDeleteFlag(value bool) {
c.EnvCmd.EnvVariablesDeleteFlag = value
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * // // * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// initialize basic configuration // initialize basic configuration
// * * * * * * * * * * * * * * * * * * * * * * * * * * * // // * * * * * * * * * * * * * * * * * * * * * * * * * * * //
@ -580,11 +598,11 @@ func (c *Config) Init() {
c.SetConfigFileYmlName(configFileYmlName) c.SetConfigFileYmlName(configFileYmlName)
// set Github token from environment variable // set Github token from environment variable
var githubTokenEnv string = utils.GetEnvVarValueFromOsEnv("GITHUB_TOKEN") var githubTokenEnv string = utils.GetGitTokenFromOsEnv()
c.SetGithubTokenEnv(githubTokenEnv) c.SetGithubTokenEnv(githubTokenEnv)
// set Gitea token from environment variable // set Gitea token from environment variable
var giteaTokenEnv string = utils.GetEnvVarValueFromOsEnv("GITEA_TOKEN") var giteaTokenEnv string = utils.GetGitTeaTokenFromOsEnv()
c.SetGitTeaTokenEnv(giteaTokenEnv) c.SetGitTeaTokenEnv(giteaTokenEnv)
// set verbose flag // set verbose flag
@ -599,6 +617,9 @@ func (c *Config) Init() {
// set help flag // set help flag
c.SetHelpFlag(false) c.SetHelpFlag(false)
// set delete flag
c.SetEnvDeleteFlag(false)
// set url base // set url base
var urlBase string = "https://git.bcmaison.cf" var urlBase string = "https://git.bcmaison.cf"
c.SetUrlBase(urlBase) c.SetUrlBase(urlBase)
@ -829,7 +850,7 @@ func (c *Config) DebugPrintString(str string) {
func (c *Config) printAllConfiguration() { func (c *Config) printAllConfiguration() {
fmt.Println("General Configuration:") fmt.Println("General Configuration:")
fmt.Println("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -") fmt.Println("- - - - - - - - - - - - - - - GIT_TOKEN- - - - - - - - - - - - - - -")
fmt.Println("Config: DebugMode: ", c.GetDebugMode()) fmt.Println("Config: DebugMode: ", c.GetDebugMode())
fmt.Println("Config: LogLevel: ", c.GetLogLevel()) fmt.Println("Config: LogLevel: ", c.GetLogLevel())
fmt.Println("config: Author: ", c.GetAuthor()) fmt.Println("config: Author: ", c.GetAuthor())
@ -874,6 +895,10 @@ func (c *Config) printAllConfiguration() {
fmt.Println("config: EnvVariablesCategoryFlag: ", c.GetEnvCategoryFlag()) fmt.Println("config: EnvVariablesCategoryFlag: ", c.GetEnvCategoryFlag())
fmt.Println("config: EnvVariablesCategory: ", c.GetEnvCategoryInfo()) fmt.Println("config: EnvVariablesCategory: ", c.GetEnvCategoryInfo())
fmt.Println("config: EnvVariablesSetFlag: ", c.GetEnvSetFlag()) fmt.Println("config: EnvVariablesSetFlag: ", c.GetEnvSetFlag())
fmt.Println("config: EnvVariablesShowAllFlag: ", c.GetEnvShowAllFlag())
fmt.Println("config: EnvVariablesKey: ", c.GetEnvKey())
fmt.Println("config: EnvVariablesValue: ", c.GetEnvValue())
fmt.Println("config: EnvVariablesDeleteFlag: ", c.GetEnvDeleteFlag())
fmt.Println("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -") fmt.Println("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -")
} }

4
go.mod
View File

@ -4,7 +4,7 @@ go 1.19
require ( require (
github.com/google/go-github v17.0.0+incompatible github.com/google/go-github v17.0.0+incompatible
github.com/gookit/color v1.5.3 github.com/gookit/color v1.5.4
github.com/joho/godotenv v1.5.1 github.com/joho/godotenv v1.5.1
github.com/spf13/cobra v1.7.0 github.com/spf13/cobra v1.7.0
golang.org/x/oauth2 v0.9.0 golang.org/x/oauth2 v0.9.0
@ -18,7 +18,7 @@ require (
github.com/spf13/pflag v1.0.5 // indirect github.com/spf13/pflag v1.0.5 // indirect
github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778 // indirect github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778 // indirect
golang.org/x/net v0.11.0 // indirect golang.org/x/net v0.11.0 // indirect
golang.org/x/sys v0.9.0 // indirect golang.org/x/sys v0.10.0 // indirect
google.golang.org/appengine v1.6.7 // indirect google.golang.org/appengine v1.6.7 // indirect
google.golang.org/protobuf v1.28.0 // indirect google.golang.org/protobuf v1.28.0 // indirect
) )

5
go.sum
View File

@ -13,6 +13,8 @@ github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD
github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU= github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU=
github.com/gookit/color v1.5.3 h1:twfIhZs4QLCtimkP7MOxlF3A0U/5cDPseRT9M/+2SCE= github.com/gookit/color v1.5.3 h1:twfIhZs4QLCtimkP7MOxlF3A0U/5cDPseRT9M/+2SCE=
github.com/gookit/color v1.5.3/go.mod h1:NUzwzeehUfl7GIb36pqId+UGmRfQcU/WiiyTTeNjHtE= github.com/gookit/color v1.5.3/go.mod h1:NUzwzeehUfl7GIb36pqId+UGmRfQcU/WiiyTTeNjHtE=
github.com/gookit/color v1.5.4 h1:FZmqs7XOyGgCAxmWyPslpiok1k05wmY3SJTytgvYFs0=
github.com/gookit/color v1.5.4/go.mod h1:pZJOeOS8DM43rXbp4AZo1n9zCU2qjpcRko0b6/QJi9w=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
@ -24,6 +26,7 @@ github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRM
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk= github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778 h1:QldyIu/L63oPpyvQmHgvgickp1Yw510KJOqX7H24mg8= github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778 h1:QldyIu/L63oPpyvQmHgvgickp1Yw510KJOqX7H24mg8=
github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778/go.mod h1:2MuV+tbUrU1zIOPMxZ5EncGwgmMJsa+9ucAQZXxsObs= github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778/go.mod h1:2MuV+tbUrU1zIOPMxZ5EncGwgmMJsa+9ucAQZXxsObs=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
@ -35,6 +38,8 @@ golang.org/x/oauth2 v0.9.0/go.mod h1:qYgFZaFiu6Wg24azG8bdV52QJXJGbZzIIsRCdVKzbLw
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.9.0 h1:KS/R3tvhPqvJvwcKfnBHJwwthS11LRhmM5D59eEXa0s= golang.org/x/sys v0.9.0 h1:KS/R3tvhPqvJvwcKfnBHJwwthS11LRhmM5D59eEXa0s=
golang.org/x/sys v0.9.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.9.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.10.0 h1:SqMFp9UcQJZa+pmYuAKjd9xq1f0j5rLcDIk0mj4qAsA=
golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=

0
install/install.ps1 Normal file
View File

View File

@ -0,0 +1,697 @@
# Issue Tracker: https://github.com/ScoopInstaller/Install/issues
# Unlicense License:
#
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as a compiled
# binary, for any purpose, commercial or non-commercial, and by any
# means.
#
# In jurisdictions that recognize copyright laws, the author or authors
# of this software dedicate any and all copyright interest in the
# software to the public domain. We make this dedication for the benefit
# of the public at large and to the detriment of our heirs and
# successors. We intend this dedication to be an overt act of
# relinquishment in perpetuity of all present and future rights to this
# software under copyright law.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# For more information, please refer to <http://unlicense.org/>
<#
.SYNOPSIS
Scoop installer.
.DESCRIPTION
The installer of Scoop. For details please check the website and wiki.
.PARAMETER ScoopDir
Specifies Scoop root path.
If not specified, Scoop will be installed to '$env:USERPROFILE\scoop'.
.PARAMETER ScoopGlobalDir
Specifies directory to store global apps.
If not specified, global apps will be installed to '$env:ProgramData\scoop'.
.PARAMETER ScoopCacheDir
Specifies cache directory.
If not specified, caches will be downloaded to '$ScoopDir\cache'.
.PARAMETER NoProxy
Bypass system proxy during the installation.
.PARAMETER Proxy
Specifies proxy to use during the installation.
.PARAMETER ProxyCredential
Specifies credential for the given proxy.
.PARAMETER ProxyUseDefaultCredentials
Use the credentials of the current user for the proxy server that is specified by the -Proxy parameter.
.PARAMETER RunAsAdmin
Force to run the installer as administrator.
.LINK
https://scoop.sh
.LINK
https://github.com/ScoopInstaller/Scoop/wiki
#>
param(
[String] $ScoopDir,
[String] $ScoopGlobalDir,
[String] $ScoopCacheDir,
[Switch] $NoProxy,
[Uri] $Proxy,
[System.Management.Automation.PSCredential] $ProxyCredential,
[Switch] $ProxyUseDefaultCredentials,
[Switch] $RunAsAdmin
)
# Disable StrictMode in this script
Set-StrictMode -Off
function Write-InstallInfo {
param(
[Parameter(Mandatory = $True, Position = 0)]
[String] $String,
[Parameter(Mandatory = $False, Position = 1)]
[System.ConsoleColor] $ForegroundColor = $host.UI.RawUI.ForegroundColor
)
$backup = $host.UI.RawUI.ForegroundColor
if ($ForegroundColor -ne $host.UI.RawUI.ForegroundColor) {
$host.UI.RawUI.ForegroundColor = $ForegroundColor
}
Write-Output "$String"
$host.UI.RawUI.ForegroundColor = $backup
}
function Deny-Install {
param(
[String] $message,
[Int] $errorCode = 1
)
Write-InstallInfo -String $message -ForegroundColor DarkRed
Write-InstallInfo "Abort."
# Don't abort if invoked with iex that would close the PS session
if ($IS_EXECUTED_FROM_IEX) {
break
} else {
exit $errorCode
}
}
function Test-ValidateParameter {
if ($null -eq $Proxy -and ($null -ne $ProxyCredential -or $ProxyUseDefaultCredentials)) {
Deny-Install "Provide a valid proxy URI for the -Proxy parameter when using the -ProxyCredential or -ProxyUseDefaultCredentials."
}
if ($ProxyUseDefaultCredentials -and $null -ne $ProxyCredential) {
Deny-Install "ProxyUseDefaultCredentials is conflict with ProxyCredential. Don't use the -ProxyCredential and -ProxyUseDefaultCredentials together."
}
}
function Test-IsAdministrator {
return ([Security.Principal.WindowsPrincipal]`
[Security.Principal.WindowsIdentity]::GetCurrent()`
).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) -and $env:USERNAME -ne 'WDAGUtilityAccount'
}
function Test-Prerequisite {
# Scoop requires PowerShell 5 at least
if (($PSVersionTable.PSVersion.Major) -lt 5) {
Deny-Install "PowerShell 5 or later is required to run Scoop. Go to https://microsoft.com/powershell to get the latest version of PowerShell."
}
# Scoop requires TLS 1.2 SecurityProtocol, which exists in .NET Framework 4.5+
if ([System.Enum]::GetNames([System.Net.SecurityProtocolType]) -notcontains 'Tls12') {
Deny-Install "Scoop requires .NET Framework 4.5+ to work. Go to https://microsoft.com/net/download to get the latest version of .NET Framework."
}
# Ensure Robocopy.exe is accessible
if (!(Test-CommandAvailable('robocopy'))) {
Deny-Install "Scoop requires 'C:\Windows\System32\Robocopy.exe' to work. Please make sure 'C:\Windows\System32' is in your PATH."
}
# Detect if RunAsAdministrator, there is no need to run as administrator when installing Scoop.
if (!$RunAsAdmin -and (Test-IsAdministrator)) {
Deny-Install "Running the installer as administrator is disabled by default, see https://github.com/ScoopInstaller/Install#for-admin for details."
}
# Show notification to change execution policy
$allowedExecutionPolicy = @('Unrestricted', 'RemoteSigned', 'ByPass')
if ((Get-ExecutionPolicy).ToString() -notin $allowedExecutionPolicy) {
Deny-Install "PowerShell requires an execution policy in [$($allowedExecutionPolicy -join ", ")] to run Scoop. For example, to set the execution policy to 'RemoteSigned' please run 'Set-ExecutionPolicy RemoteSigned -Scope CurrentUser'."
}
# Test if scoop is installed, by checking if scoop command exists.
if (Test-CommandAvailable('scoop')) {
Deny-Install "Scoop is already installed. Run 'scoop update' to get the latest version."
}
}
function Optimize-SecurityProtocol {
# .NET Framework 4.7+ has a default security protocol called 'SystemDefault',
# which allows the operating system to choose the best protocol to use.
# If SecurityProtocolType contains 'SystemDefault' (means .NET4.7+ detected)
# and the value of SecurityProtocol is 'SystemDefault', just do nothing on SecurityProtocol,
# 'SystemDefault' will use TLS 1.2 if the webrequest requires.
$isNewerNetFramework = ([System.Enum]::GetNames([System.Net.SecurityProtocolType]) -contains 'SystemDefault')
$isSystemDefault = ([System.Net.ServicePointManager]::SecurityProtocol.Equals([System.Net.SecurityProtocolType]::SystemDefault))
# If not, change it to support TLS 1.2
if (!($isNewerNetFramework -and $isSystemDefault)) {
# Set to TLS 1.2 (3072), then TLS 1.1 (768), and TLS 1.0 (192). Ssl3 has been superseded,
# https://docs.microsoft.com/en-us/dotnet/api/system.net.securityprotocoltype?view=netframework-4.5
[System.Net.ServicePointManager]::SecurityProtocol = 3072 -bor 768 -bor 192
Write-Verbose "SecurityProtocol has been updated to support TLS 1.2"
}
}
function Get-Downloader {
$downloadSession = New-Object System.Net.WebClient
# Set proxy to null if NoProxy is specificed
if ($NoProxy) {
$downloadSession.Proxy = $null
} elseif ($Proxy) {
# Prepend protocol if not provided
if (!$Proxy.IsAbsoluteUri) {
$Proxy = New-Object System.Uri("http://" + $Proxy.OriginalString)
}
$Proxy = New-Object System.Net.WebProxy($Proxy)
if ($null -ne $ProxyCredential) {
$Proxy.Credentials = $ProxyCredential.GetNetworkCredential()
} elseif ($ProxyUseDefaultCredentials) {
$Proxy.UseDefaultCredentials = $true
}
$downloadSession.Proxy = $Proxy
}
return $downloadSession
}
function Test-isFileLocked {
param(
[String] $path
)
$file = New-Object System.IO.FileInfo $path
if (!(Test-Path $path)) {
return $false
}
try {
$stream = $file.Open(
[System.IO.FileMode]::Open,
[System.IO.FileAccess]::ReadWrite,
[System.IO.FileShare]::None
)
if ($stream) {
$stream.Close()
}
return $false
} catch {
# The file is locked by a process.
return $true
}
}
function Expand-ZipArchive {
param(
[String] $path,
[String] $to
)
if (!(Test-Path $path)) {
Deny-Install "Unzip failed: can't find $path to unzip."
}
# Check if the zip file is locked, by antivirus software for example
$retries = 0
while ($retries -le 10) {
if ($retries -eq 10) {
Deny-Install "Unzip failed: can't unzip because a process is locking the file."
}
if (Test-isFileLocked $path) {
Write-InstallInfo "Waiting for $path to be unlocked by another process... ($retries/10)"
$retries++
Start-Sleep -Seconds 2
} else {
break
}
}
# Workaround to suspend Expand-Archive verbose output,
# upstream issue: https://github.com/PowerShell/Microsoft.PowerShell.Archive/issues/98
$oldVerbosePreference = $VerbosePreference
$global:VerbosePreference = 'SilentlyContinue'
# Disable progress bar to gain performance
$oldProgressPreference = $ProgressPreference
$global:ProgressPreference = 'SilentlyContinue'
# PowerShell 5+: use Expand-Archive to extract zip files
Microsoft.PowerShell.Archive\Expand-Archive -Path $path -DestinationPath $to -Force
$global:VerbosePreference = $oldVerbosePreference
$global:ProgressPreference = $oldProgressPreference
}
function Out-UTF8File {
param(
[Parameter(Mandatory = $True, Position = 0)]
[Alias("Path")]
[String] $FilePath,
[Switch] $Append,
[Switch] $NoNewLine,
[Parameter(ValueFromPipeline = $True)]
[PSObject] $InputObject
)
process {
if ($Append) {
[System.IO.File]::AppendAllText($FilePath, $InputObject)
} else {
if (!$NoNewLine) {
# Ref: https://stackoverflow.com/questions/5596982
# Performance Note: `WriteAllLines` throttles memory usage while
# `WriteAllText` needs to keep the complete string in memory.
[System.IO.File]::WriteAllLines($FilePath, $InputObject)
} else {
# However `WriteAllText` does not add ending newline.
[System.IO.File]::WriteAllText($FilePath, $InputObject)
}
}
}
}
function Import-ScoopShim {
Write-InstallInfo "Creating shim..."
# The scoop executable
$path = "$SCOOP_APP_DIR\bin\scoop.ps1"
if (!(Test-Path $SCOOP_SHIMS_DIR)) {
New-Item -Type Directory $SCOOP_SHIMS_DIR | Out-Null
}
# The scoop shim
$shim = "$SCOOP_SHIMS_DIR\scoop"
# Convert to relative path
Push-Location $SCOOP_SHIMS_DIR
$relativePath = Resolve-Path -Relative $path
Pop-Location
$absolutePath = Resolve-Path $path
# if $path points to another drive resolve-path prepends .\ which could break shims
$ps1text = if ($relativePath -match '^(\.\\)?\w:.*$') {
@(
"# $absolutePath",
"`$path = `"$path`"",
"if (`$MyInvocation.ExpectingInput) { `$input | & `$path $arg @args } else { & `$path $arg @args }",
"exit `$LASTEXITCODE"
)
} else {
@(
"# $absolutePath",
"`$path = Join-Path `$PSScriptRoot `"$relativePath`"",
"if (`$MyInvocation.ExpectingInput) { `$input | & `$path $arg @args } else { & `$path $arg @args }",
"exit `$LASTEXITCODE"
)
}
$ps1text -join "`r`n" | Out-UTF8File "$shim.ps1"
# make ps1 accessible from cmd.exe
@(
"@rem $absolutePath",
"@echo off",
"setlocal enabledelayedexpansion",
"set args=%*",
":: replace problem characters in arguments",
"set args=%args:`"='%",
"set args=%args:(=``(%",
"set args=%args:)=``)%",
"set invalid=`"='",
"if !args! == !invalid! ( set args= )",
"where /q pwsh.exe",
"if %errorlevel% equ 0 (",
" pwsh -noprofile -ex unrestricted -file `"$absolutePath`" $arg %args%",
") else (",
" powershell -noprofile -ex unrestricted -file `"$absolutePath`" $arg %args%",
")"
) -join "`r`n" | Out-UTF8File "$shim.cmd"
@(
"#!/bin/sh",
"# $absolutePath",
"if command -v pwsh.exe > /dev/null 2>&1; then",
" pwsh.exe -noprofile -ex unrestricted -file `"$absolutePath`" $arg `"$@`"",
"else",
" powershell.exe -noprofile -ex unrestricted -file `"$absolutePath`" $arg `"$@`"",
"fi"
) -join "`n" | Out-UTF8File $shim -NoNewLine
}
function Get-Env {
param(
[String] $name,
[Switch] $global
)
$RegisterKey = if ($global) {
Get-Item -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager'
} else {
Get-Item -Path 'HKCU:'
}
$EnvRegisterKey = $RegisterKey.OpenSubKey('Environment')
$RegistryValueOption = [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames
$EnvRegisterKey.GetValue($name, $null, $RegistryValueOption)
}
function Publish-Env {
if (-not ("Win32.NativeMethods" -as [Type])) {
Add-Type -Namespace Win32 -Name NativeMethods -MemberDefinition @"
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern IntPtr SendMessageTimeout(
IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam,
uint fuFlags, uint uTimeout, out UIntPtr lpdwResult);
"@
}
$HWND_BROADCAST = [IntPtr] 0xffff
$WM_SETTINGCHANGE = 0x1a
$result = [UIntPtr]::Zero
[Win32.Nativemethods]::SendMessageTimeout($HWND_BROADCAST,
$WM_SETTINGCHANGE,
[UIntPtr]::Zero,
"Environment",
2,
5000,
[ref] $result
) | Out-Null
}
function Write-Env {
param(
[String] $name,
[String] $val,
[Switch] $global
)
$RegisterKey = if ($global) {
Get-Item -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager'
} else {
Get-Item -Path 'HKCU:'
}
$EnvRegisterKey = $RegisterKey.OpenSubKey('Environment', $true)
if ($val -eq $null) {
$EnvRegisterKey.DeleteValue($name)
} else {
$RegistryValueKind = if ($val.Contains('%')) {
[Microsoft.Win32.RegistryValueKind]::ExpandString
} elseif ($EnvRegisterKey.GetValue($name)) {
$EnvRegisterKey.GetValueKind($name)
} else {
[Microsoft.Win32.RegistryValueKind]::String
}
$EnvRegisterKey.SetValue($name, $val, $RegistryValueKind)
}
Publish-Env
}
function Add-ShimsDirToPath {
# Get $env:PATH of current user
$userEnvPath = Get-Env 'PATH'
if ($userEnvPath -notmatch [Regex]::Escape($SCOOP_SHIMS_DIR)) {
$h = (Get-PSProvider 'FileSystem').Home
if (!$h.EndsWith('\')) {
$h += '\'
}
if (!($h -eq '\')) {
$friendlyPath = "$SCOOP_SHIMS_DIR" -Replace ([Regex]::Escape($h)), "~\"
Write-InstallInfo "Adding $friendlyPath to your path."
} else {
Write-InstallInfo "Adding $SCOOP_SHIMS_DIR to your path."
}
# For future sessions
Write-Env 'PATH' "$SCOOP_SHIMS_DIR;$userEnvPath"
# For current session
$env:PATH = "$SCOOP_SHIMS_DIR;$env:PATH"
}
}
function Use-Config {
if (!(Test-Path $SCOOP_CONFIG_FILE)) {
return $null
}
try {
return (Get-Content $SCOOP_CONFIG_FILE -Raw | ConvertFrom-Json -ErrorAction Stop)
} catch {
Deny-Install "ERROR loading $SCOOP_CONFIG_FILE`: $($_.Exception.Message)"
}
}
function Add-Config {
param (
[Parameter(Mandatory = $True, Position = 0)]
[String] $Name,
[Parameter(Mandatory = $True, Position = 1)]
[String] $Value
)
$scoopConfig = Use-Config
if ($scoopConfig -is [System.Management.Automation.PSObject]) {
if ($Value -eq [bool]::TrueString -or $Value -eq [bool]::FalseString) {
$Value = [System.Convert]::ToBoolean($Value)
}
if ($null -eq $scoopConfig.$Name) {
$scoopConfig | Add-Member -MemberType NoteProperty -Name $Name -Value $Value
} else {
$scoopConfig.$Name = $Value
}
} else {
$baseDir = Split-Path -Path $SCOOP_CONFIG_FILE
if (!(Test-Path $baseDir)) {
New-Item -Type Directory $baseDir | Out-Null
}
$scoopConfig = New-Object PSObject
$scoopConfig | Add-Member -MemberType NoteProperty -Name $Name -Value $Value
}
if ($null -eq $Value) {
$scoopConfig.PSObject.Properties.Remove($Name)
}
ConvertTo-Json $scoopConfig | Set-Content $SCOOP_CONFIG_FILE -Encoding ASCII
return $scoopConfig
}
function Add-DefaultConfig {
# If user-level SCOOP env not defined, save to root_path
if (!(Get-Env 'SCOOP')) {
if ($SCOOP_DIR -ne "$env:USERPROFILE\scoop") {
Write-Verbose "Adding config root_path: $SCOOP_DIR"
Add-Config -Name 'root_path' -Value $SCOOP_DIR | Out-Null
}
}
# Use system SCOOP_GLOBAL, or set system SCOOP_GLOBAL
# with $env:SCOOP_GLOBAL if RunAsAdmin, otherwise save to global_path
if (!(Get-Env 'SCOOP_GLOBAL' -global)) {
if ((Test-IsAdministrator) -and $env:SCOOP_GLOBAL) {
Write-Verbose "Setting System Environment Variable SCOOP_GLOBAL: $env:SCOOP_GLOBAL"
[Environment]::SetEnvironmentVariable('SCOOP_GLOBAL', $env:SCOOP_GLOBAL, 'Machine')
} else {
if ($SCOOP_GLOBAL_DIR -ne "$env:ProgramData\scoop") {
Write-Verbose "Adding config global_path: $SCOOP_GLOBAL_DIR"
Add-Config -Name 'global_path' -Value $SCOOP_GLOBAL_DIR | Out-Null
}
}
}
# Use system SCOOP_CACHE, or set system SCOOP_CACHE
# with $env:SCOOP_CACHE if RunAsAdmin, otherwise save to cache_path
if (!(Get-Env 'SCOOP_CACHE' -global)) {
if ((Test-IsAdministrator) -and $env:SCOOP_CACHE) {
Write-Verbose "Setting System Environment Variable SCOOP_CACHE: $env:SCOOP_CACHE"
[Environment]::SetEnvironmentVariable('SCOOP_CACHE', $env:SCOOP_CACHE, 'Machine')
} else {
if ($SCOOP_CACHE_DIR -ne "$SCOOP_DIR\cache") {
Write-Verbose "Adding config cache_path: $SCOOP_CACHE_DIR"
Add-Config -Name 'cache_path' -Value $SCOOP_CACHE_DIR | Out-Null
}
}
}
# save current datatime to last_update
Add-Config -Name 'last_update' -Value ([System.DateTime]::Now.ToString('o')) | Out-Null
}
function Test-CommandAvailable {
param (
[Parameter(Mandatory = $True, Position = 0)]
[String] $Command
)
return [Boolean](Get-Command $Command -ErrorAction SilentlyContinue)
}
function Install-Scoop {
Write-InstallInfo "Initializing..."
# Validate install parameters
Test-ValidateParameter
# Check prerequisites
Test-Prerequisite
# Enable TLS 1.2
Optimize-SecurityProtocol
# Download scoop from GitHub
Write-InstallInfo "Downloading ..."
$downloader = Get-Downloader
[bool]$downloadZipsRequired = $True
if (Test-CommandAvailable('git')) {
$old_https = $env:HTTPS_PROXY
$old_http = $env:HTTP_PROXY
try {
if ($downloader.Proxy) {
#define env vars for git when behind a proxy
$Env:HTTP_PROXY = $downloader.Proxy.Address
$Env:HTTPS_PROXY = $downloader.Proxy.Address
}
Write-Verbose "Cloning $SCOOP_PACKAGE_GIT_REPO to $SCOOP_APP_DIR"
git clone -q $SCOOP_PACKAGE_GIT_REPO $SCOOP_APP_DIR
if (-Not $?) {
throw "Cloning failed. Falling back to downloading zip files."
}
Write-Verbose "Cloning $SCOOP_MAIN_BUCKET_GIT_REPO to $SCOOP_MAIN_BUCKET_DIR"
git clone -q $SCOOP_MAIN_BUCKET_GIT_REPO $SCOOP_MAIN_BUCKET_DIR
if (-Not $?) {
throw "Cloning failed. Falling back to downloading zip files."
}
$downloadZipsRequired = $False
} catch {
Write-Warning "$($_.Exception.Message)"
$Global:LastExitCode = 0
} finally {
$env:HTTPS_PROXY = $old_https
$env:HTTP_PROXY = $old_http
}
}
if ($downloadZipsRequired) {
# 1. download scoop
$scoopZipfile = "$SCOOP_APP_DIR\scoop.zip"
if (!(Test-Path $SCOOP_APP_DIR)) {
New-Item -Type Directory $SCOOP_APP_DIR | Out-Null
}
Write-Verbose "Downloading $SCOOP_PACKAGE_REPO to $scoopZipfile"
$downloader.downloadFile($SCOOP_PACKAGE_REPO, $scoopZipfile)
# 2. download scoop main bucket
$scoopMainZipfile = "$SCOOP_MAIN_BUCKET_DIR\scoop-main.zip"
if (!(Test-Path $SCOOP_MAIN_BUCKET_DIR)) {
New-Item -Type Directory $SCOOP_MAIN_BUCKET_DIR | Out-Null
}
Write-Verbose "Downloading $SCOOP_MAIN_BUCKET_REPO to $scoopMainZipfile"
$downloader.downloadFile($SCOOP_MAIN_BUCKET_REPO, $scoopMainZipfile)
# Extract files from downloaded zip
Write-InstallInfo "Extracting..."
# 1. extract scoop
$scoopUnzipTempDir = "$SCOOP_APP_DIR\_tmp"
Write-Verbose "Extracting $scoopZipfile to $scoopUnzipTempDir"
Expand-ZipArchive $scoopZipfile $scoopUnzipTempDir
Copy-Item "$scoopUnzipTempDir\scoop-*\*" $SCOOP_APP_DIR -Recurse -Force
# 2. extract scoop main bucket
$scoopMainUnzipTempDir = "$SCOOP_MAIN_BUCKET_DIR\_tmp"
Write-Verbose "Extracting $scoopMainZipfile to $scoopMainUnzipTempDir"
Expand-ZipArchive $scoopMainZipfile $scoopMainUnzipTempDir
Copy-Item "$scoopMainUnzipTempDir\Main-*\*" $SCOOP_MAIN_BUCKET_DIR -Recurse -Force
# Cleanup
Remove-Item $scoopUnzipTempDir -Recurse -Force
Remove-Item $scoopZipfile
Remove-Item $scoopMainUnzipTempDir -Recurse -Force
Remove-Item $scoopMainZipfile
}
# Create the scoop shim
Import-ScoopShim
# Finially ensure scoop shims is in the PATH
Add-ShimsDirToPath
# Setup initial configuration of Scoop
Add-DefaultConfig
Write-InstallInfo "Scoop was installed successfully!" -ForegroundColor DarkGreen
Write-InstallInfo "Type 'scoop help' for instructions."
}
function Write-DebugInfo {
param($BoundArgs)
Write-Verbose "-------- PSBoundParameters --------"
$BoundArgs.GetEnumerator() | ForEach-Object { Write-Verbose $_ }
Write-Verbose "-------- Environment Variables --------"
Write-Verbose "`$env:USERPROFILE: $env:USERPROFILE"
Write-Verbose "`$env:ProgramData: $env:ProgramData"
Write-Verbose "`$env:SCOOP: $env:SCOOP"
Write-Verbose "`$env:SCOOP_CACHE: $SCOOP_CACHE"
Write-Verbose "`$env:SCOOP_GLOBAL: $env:SCOOP_GLOBAL"
Write-Verbose "-------- Selected Variables --------"
Write-Verbose "SCOOP_DIR: $SCOOP_DIR"
Write-Verbose "SCOOP_CACHE_DIR: $SCOOP_CACHE_DIR"
Write-Verbose "SCOOP_GLOBAL_DIR: $SCOOP_GLOBAL_DIR"
Write-Verbose "SCOOP_CONFIG_HOME: $SCOOP_CONFIG_HOME"
}
# Prepare variables
$IS_EXECUTED_FROM_IEX = ($null -eq $MyInvocation.MyCommand.Path)
# Scoop root directory
$SCOOP_DIR = $ScoopDir, $env:SCOOP, "$env:USERPROFILE\scoop" | Where-Object { -not [String]::IsNullOrEmpty($_) } | Select-Object -First 1
# Scoop global apps directory
$SCOOP_GLOBAL_DIR = $ScoopGlobalDir, $env:SCOOP_GLOBAL, "$env:ProgramData\scoop" | Where-Object { -not [String]::IsNullOrEmpty($_) } | Select-Object -First 1
# Scoop cache directory
$SCOOP_CACHE_DIR = $ScoopCacheDir, $env:SCOOP_CACHE, "$SCOOP_DIR\cache" | Where-Object { -not [String]::IsNullOrEmpty($_) } | Select-Object -First 1
# Scoop shims directory
$SCOOP_SHIMS_DIR = "$SCOOP_DIR\shims"
# Scoop itself directory
$SCOOP_APP_DIR = "$SCOOP_DIR\apps\scoop\current"
# Scoop main bucket directory
$SCOOP_MAIN_BUCKET_DIR = "$SCOOP_DIR\buckets\main"
# Scoop config file location
$SCOOP_CONFIG_HOME = $env:XDG_CONFIG_HOME, "$env:USERPROFILE\.config" | Select-Object -First 1
$SCOOP_CONFIG_FILE = "$SCOOP_CONFIG_HOME\scoop\config.json"
# TODO: Use a specific version of Scoop and the main bucket
$SCOOP_PACKAGE_REPO = "https://github.com/ScoopInstaller/Scoop/archive/master.zip"
$SCOOP_MAIN_BUCKET_REPO = "https://github.com/ScoopInstaller/Main/archive/master.zip"
$SCOOP_PACKAGE_GIT_REPO = "https://github.com/ScoopInstaller/Scoop.git"
$SCOOP_MAIN_BUCKET_GIT_REPO = "https://github.com/ScoopInstaller/Main.git"
# Quit if anything goes wrong
$oldErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = 'Stop'
# Logging debug info
Write-DebugInfo $PSBoundParameters
# Bootstrap function
Install-Scoop
# Reset $ErrorActionPreference to original value
$ErrorActionPreference = $oldErrorActionPreference

View File

@ -17,8 +17,8 @@ var CfgGlobal = &config.Config{}
// rootCmd represents the base command when called without any subcommands // rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{ var rootCmd = &cobra.Command{
Use: "kode-creator.exe", Use: "kode-creator.exe",
Short: "Simple cli app create startup project", Short: "Simple cli to manage projects development, environment variables develepment tools and more.",
Long: `A simple CLI app to work with Github, Gitea`, Long: `Simple cli to manage projects development, environment variables develepment tools and more.`,
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
mainProgram(cmd, args) mainProgram(cmd, args)
@ -31,14 +31,17 @@ func init() {
CfgGlobal.Init() CfgGlobal.Init()
// root menu section // root menu section
// option : debug(d), version(V), help(h)
// - - - - - - - - - - - // - - - - - - - - - - -
rootCmd.PersistentFlags().BoolVarP(&CfgGlobal.JsonFlag, "json", "j", false, "JSON output format") rootCmd.PersistentFlags().BoolVarP(&CfgGlobal.JsonFlag, "json", "j", false, "JSON output format")
rootCmd.PersistentFlags().BoolVarP(&CfgGlobal.VerboseFlag, "verbose", "v", false, "VERBOSE mode output") rootCmd.PersistentFlags().BoolVarP(&CfgGlobal.VerboseFlag, "debug", "d", false, "Debug mode output")
rootCmd.Flags().BoolVarP(&CfgGlobal.VersionFlag, "version", "V", false, "Show VERSION of "+CfgGlobal.GetApplicationName()) rootCmd.Flags().BoolVarP(&CfgGlobal.VersionFlag, "version", "V", false, "Show VERSION of "+CfgGlobal.GetApplicationName())
rootCmd.Flags().BoolP("help", "h", false, "Show help for "+CfgGlobal.GetApplicationName()) rootCmd.Flags().BoolP("help", "h", false, "Show help for "+CfgGlobal.GetApplicationName())
rootCmd.CompletionOptions.DisableDefaultCmd = true rootCmd.CompletionOptions.DisableDefaultCmd = true
rootCmd.Flags().SortFlags = false rootCmd.Flags().SortFlags = false
// List menu section // List menu section
// option : git(g), tea(a), search(s), user(u), org(o)
// - - - - - - - - - - - // - - - - - - - - - - -
cmdLists.ListCmd.Flags().StringVarP(&CfgGlobal.TokenEnv, "token", "t", "", "TOKEN for Gitea or Github") cmdLists.ListCmd.Flags().StringVarP(&CfgGlobal.TokenEnv, "token", "t", "", "TOKEN for Gitea or Github")
cmdLists.ListCmd.Flags().BoolVarP(&CfgGlobal.ListCmd.GitFlag, "git", "g", false, "List all repositories from GITHUB") cmdLists.ListCmd.Flags().BoolVarP(&CfgGlobal.ListCmd.GitFlag, "git", "g", false, "List all repositories from GITHUB")
@ -49,6 +52,7 @@ func init() {
cmdLists.ListCmd.Flags().SortFlags = false cmdLists.ListCmd.Flags().SortFlags = false
// Create menu section (create project directories structure, init git, Github or Gitea repository, create README.md template ) // Create menu section (create project directories structure, init git, Github or Gitea repository, create README.md template )
// option : name(n), desc(d), struc(s), control(c), readme(r), token(t), org(o), private(p)
// - - - - - - - - - - - - - - - - - - - // - - - - - - - - - - - - - - - - - - -
// project informations // project informations
cmdCreate.CreateCmd.Flags().StringVarP(&CfgGlobal.CreateCmd.Name, "name", "n", "", "NAME of the Project") cmdCreate.CreateCmd.Flags().StringVarP(&CfgGlobal.CreateCmd.Name, "name", "n", "", "NAME of the Project")
@ -66,14 +70,20 @@ func init() {
cmdCreate.CreateCmd.Flags().SortFlags = false cmdCreate.CreateCmd.Flags().SortFlags = false
// Env menu section // Env menu section
// option : group(g), list(l), filter(f), yml(y), cat(c), set(s), key(k), value(v), all(a)
// - - - - - - - - - - - // - - - - - - - - - - -
cmdEnv.EnvCmd.Flags().BoolVarP(&CfgGlobal.EnvCmd.EnvVariablesFlag, "group", "g", false, "GROUP environnement variables by categories")
cmdEnv.EnvCmd.Flags().BoolVarP(&CfgGlobal.EnvCmd.EnvVariablesListFlag, "list", "l", false, "LIST environnement variables") cmdEnv.EnvCmd.Flags().BoolVarP(&CfgGlobal.EnvCmd.EnvVariablesListFlag, "list", "l", false, "==> LIST environnement variables")
cmdEnv.EnvCmd.Flags().StringVarP(&CfgGlobal.EnvCmd.EnvVariablesFilter, "filter", "f", "", "HIGHLIGHT a specific word in environnement variables") cmdEnv.EnvCmd.Flags().StringVarP(&CfgGlobal.EnvCmd.EnvVariablesFilter, "filter", "f", "", "(LIST) HIGHLIGHT a specific word in environnement variables")
cmdEnv.EnvCmd.Flags().BoolVarP(&CfgGlobal.EnvCmd.EnvVariablesYmlFlag, "yml", "y", false, "YAML List environnement variables from config.yml") cmdEnv.EnvCmd.Flags().BoolVarP(&CfgGlobal.EnvCmd.EnvVariablesSetFlag, "set", "s", false, "CREATE or modified environnement variable available from config.yml")
cmdEnv.EnvCmd.Flags().StringVarP(&CfgGlobal.EnvCmd.EnvVariablesCategory, "cat", "c", "", "FILTER for a specific category") // delete environnement variable flag
cmdEnv.EnvCmd.Flags().BoolVarP(&CfgGlobal.EnvCmd.EnvVariablesSetFlag, "set", "s", false, "Set environnement variable available from config.yml") cmdEnv.EnvCmd.Flags().BoolVarP(&CfgGlobal.EnvCmd.EnvVariablesDeleteFlag, "DEL", "D", false, "DELETE environnement variable from config.yml")
cmdEnv.EnvCmd.Flags().BoolVarP(&CfgGlobal.EnvCmd.EnvVariablesShowAllFlag, "all", "a", false, "Show all environnement variables") cmdEnv.EnvCmd.Flags().StringVarP(&CfgGlobal.EnvCmd.EnvVariablesKey, "key", "k", "", "(MODIF) create a KEY for environnement variable")
cmdEnv.EnvCmd.Flags().StringVarP(&CfgGlobal.EnvCmd.EnvVariablesValue, "value", "v", "", "(MODIF) create a VALUE for environnement variable")
cmdEnv.EnvCmd.Flags().BoolVarP(&CfgGlobal.EnvCmd.EnvVariablesYmlFlag, "yml", "y", false, "==> YAML List environnement variables from config.yml")
cmdEnv.EnvCmd.Flags().BoolVarP(&CfgGlobal.EnvCmd.EnvVariablesFlag, "group", "g", false, "(YAML) GROUP environnement variables by categories")
cmdEnv.EnvCmd.Flags().StringVarP(&CfgGlobal.EnvCmd.EnvVariablesCategory, "cat", "c", "", "(YAML) FILTER for a specific category")
// cmdEnv.EnvCmd.Flags().BoolVarP(&CfgGlobal.EnvCmd.EnvVariablesShowAllFlag, "all", "a", false, "Show all environnement variables")
cmdEnv.EnvCmd.Flags().SortFlags = false cmdEnv.EnvCmd.Flags().SortFlags = false
// Add subcommands // Add subcommands
@ -116,7 +126,8 @@ func main() {
cmdEnv.InitConfig(CfgGlobal) cmdEnv.InitConfig(CfgGlobal)
// set debug mode // set debug mode
CfgGlobal.SetDebugMode(true) // CfgGlobal.SetDebugMode(true)
CfgGlobal.SetDebugMode(false)
CfgGlobal.DebugPrintConfig("Function main") CfgGlobal.DebugPrintConfig("Function main")
// execute root command // execute root command

View File

@ -73,6 +73,24 @@ You can set the following environment variables:
(Github Token from Github)[ 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 ] (Github Token from Github)[ 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 ]
## TODO ## TODO
### create github project
- [ ] Create a Github project
### Manage environment variables
- [x] Commanand to list and filter environment variables
- [x] ex: .\kode-creator.exe env -l
- [x] ex: .\kode-creator.exe env -l -f "jdk"
### LIST Github, Gitea orgs, project
- [x] Command to list Github orgs and repos
- [x] ex: .\kode-creator.exe list -t <github_token> -o <org_name>
- [ ] Command to list Gitea orgs and repos
- [ ] ex: .\kode-creator.exe list -t <gitea_token> -o <org_name>
- [ ] Command to list Github orgs and repos
- [ ] ex: .\kode-creator.exe list -t <github_token> -o <org_name>
- add fonctionnalities to .bachrc file - add fonctionnalities to .bachrc file
- show .bashrc file - show .bashrc file
- add export variables configure in your yaml config - add export variables configure in your yaml config

View File

@ -60,7 +60,12 @@ func GetEnvVarValueFromOsEnv(key string) string {
} }
func GetGitTokenFromOsEnv() string { func GetGitTokenFromOsEnv() string {
token := os.Getenv("GIT_TOKEN") token := os.Getenv("GITHUB_TOKEN")
return token
}
func GetGitTeaTokenFromOsEnv() string {
token := os.Getenv("GITEA_TOKEN")
return token return token
} }
@ -171,3 +176,13 @@ func GetProgramDir() string {
return exPath return exPath
} }
// function check if OS = Windows
func IsWindows() bool {
return os.PathSeparator == '\\' && os.PathListSeparator == ';'
}
// function check if OS = Linux
func IsLinux() bool {
return os.PathSeparator == '/' && os.PathListSeparator == ':'
}

View File

@ -15,7 +15,7 @@ type Version struct {
// version variable that will be set at build time by versionManager.exe // version variable that will be set at build time by versionManager.exe
// *** DO NOT EDIT *** // *** DO NOT EDIT ***
var versionNumber Version = Version{0, 0, 0, 42} var versionNumber Version = Version{0, 0, 0, 44}
// GetFullVersion returns the full version number as a string // GetFullVersion returns the full version number as a string
func GetFullVersion() string { func GetFullVersion() string {