build 0.0.0.25

This commit is contained in:
bruno 2023-06-30 10:09:01 -04:00
parent 3be0c4d9f6
commit 97466a8f71
15 changed files with 1186 additions and 443 deletions

View File

@ -10,9 +10,11 @@ vars:
GORUN: "{{.GOCMD}} run"
GOTEST: "{{.GOCMD}} test -v"
GOCOVER: "{{.GOCMD}} test -v --cover"
VERSION:
sh: cd version/ && versionManager go version
WINDOWS_BINARY_NAME: ./release/windows/kode-starter.exe
LINUX_BINARY_NAME: ./release/linux/kode-starter
WINDOWS_BINARY_NAME: ./release/windows/{{.VERSION}}/kode-starter.exe
LINUX_BINARY_NAME: ./release/linux/{{.VERSION}}/kode-starter
# env:
GOOS: Linux

View File

@ -18,15 +18,20 @@ import (
var token, org, name, private, description string
// initailize global config
var CfgGlobal *config.Config // Declare a global variable for config
func InitConfig(config *config.Config) {
CfgGlobal = config // Assign the passed config to the global variable
}
var CreateCmd = &cobra.Command{
Use: "create",
Short: "Create Github project",
Long: `A simple CLI app to create a startup project on Github`,
Run: func(cmd *cobra.Command, args []string) {
config.SetInformations(cmd, args)
err := CreateProject()
err := CreateProject(cmd, args)
if err != nil {
fmt.Println("Error:", err)
return
@ -34,15 +39,19 @@ var CreateCmd = &cobra.Command{
},
}
func CreateProject() error {
func CreateProject(cmd *cobra.Command, args []string) error {
godotenv.Load()
fmt.Printf("Token: %s\n", config.GetToken())
fmt.Printf("Name: %s\n", config.GetCreateName())
fmt.Printf("Description: %s\n", config.GetCreateDescription())
fmt.Printf("Private: %s\n", config.GetCreatePrivate())
fmt.Printf("Org: %s\n", config.GetCreateOrganisation())
CfgGlobal.DebugPrintConfig("Function CreateProject")
// initialize global config for command list
CfgGlobal.InitCmdCreate(cmd, args)
// print header if json flag is not set
if !CfgGlobal.GetJsonFlag() {
utils.PrintHeader()
}
// Construct POST data
data := structures.Project{
@ -51,8 +60,8 @@ func CreateProject() error {
Private: private == "true",
}
data.Name = config.GetCreateName()
data.Description = config.GetCreateDescription()
data.Name = CfgGlobal.GetCreateName()
data.Description = CfgGlobal.GetCreateDescription()
fmt.Println("Structure Name:" + data.Name)
@ -60,9 +69,9 @@ func CreateProject() error {
jsonData, _ := json.Marshal(data)
req, err := http.NewRequest("POST",
fmt.Sprintf("%s/%s/repos", config.GetUrlApiOrgs(), config.GetCreateOrganisation()),
fmt.Sprintf("%s/%s/repos", CfgGlobal.GetUrlApiOrgs(), CfgGlobal.GetCreateCmd().Organisation),
bytes.NewBuffer(jsonData))
req.Header.Set("Authorization", "token "+config.GetToken())
req.Header.Set("Authorization", "token "+CfgGlobal.GetTokenEnv())
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
res, err := client.Do(req)

View File

@ -3,6 +3,8 @@ package cmdEnv
import (
"fmt"
"kode-starter/config"
"kode-starter/configFile"
"kode-starter/utils"
"os"
"strconv"
@ -12,56 +14,282 @@ import (
"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) {
config.SetInformations(cmd, args)
// Start Env command
startEnvVar(cmd, args)
// listFlag := config.GetEnvVariablesListFlag()
// fmt.Println("listFlag: " + strconv.FormatBool(listFlag))
// fmt.Println("GetEnvVariablesListFlag: " + strconv.FormatBool(config.GetEnvVariablesListFlag()))
// if listFlag {
// printEnvVariables()
// }
// err := listEnvVariables()
// if err != nil {
// fmt.Println("Error:", err)
// return
// }
// if config.GetEnvVariablesFilterFlag() {
// printEnvVariablesFilter(config.GetEnvVariablesFilter())
// } else if config.GetEnvVariablesListFlag() {
// printEnvVariables()
// }
},
}
func startEnvVar(cmd *cobra.Command, args []string) {
config.SetInformations(cmd, args)
flag := config.EnvVariablesFlag
CfgGlobal.DebugPrintConfig("Function StartEnvVar")
// if list flag is set to true list all environment variables
fmt.Println("GetEnvVariablesListFlag: " + strconv.FormatBool(config.GetEnvVariablesListFlag()))
if flag {
// declare map listPaths
var ListPaths map[string]string
// initialize command environment
CfgGlobal.InitCmdEnv(cmd, args)
CfgGlobal.DebugPrintConfig("Function StartEnvVar")
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)
}
} 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 {
cmd.Help()
fmt.Println(utils.CreateLine(8))
}
}
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 config.GetEnvVariablesListFlag() {
fmt.Println("GetEnvVariablesListFlag: " + strconv.FormatBool(config.GetEnvVariablesListFlag()))
if CfgGlobal.GetEnvCmd().EnvVariablesFilterFlag {
fmt.Println("GetEnvVariablesListFlag: " + strconv.FormatBool(CfgGlobal.GetEnvCmd().EnvVariablesListFlag))
printEnvVariables()
}
@ -71,32 +299,55 @@ func listEnvVariables() error {
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("---------------------")
fmt.Println("-----------------------------------------")
nb := 1
// loop over all environment variables
for _, e := range os.Environ() {
// split key and value
pair := strings.Split(e, "=")
fmt.Printf("%s=%s\n", pair[0], pair[1])
}
utils.PrintTreeElement(nb, pair[0], pair[1])
nb++
}
func printEnvVariablesFilter(filter string) {
fmt.Println("Environment variables")
fmt.Println("-----------------------------------------")
}
func printEnvVariablesFilter(filter string, showAll bool) {
fmt.Println("Filter Environment variables")
// fmt.Println("---------------------")
utils.CreateLine(5)
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) {
fmt.Printf("%s=%s\n", utils.ColorizeSubStrRed(pair[0], filter), color.Green.Sprint(pair[1]))
str2 = utils.ColorizeSubStrRed(pair[0], filter)
str3 = color.Green.Sprint(pair[1])
addToPrint = true
} else if strings.Contains(pair[1], filter) {
fmt.Printf("%s=%s\n", color.Green.Sprint(pair[0]), utils.ColorizeSubStrRed(pair[1], filter))
str2 = color.Green.Sprint(pair[0])
str3 = utils.ColorizeSubStrRed(pair[1], filter)
addToPrint = true
} else {
fmt.Printf("%s=%s\n", pair[0], pair[1])
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++
}
}

42
cmdLists/gitHub.go Normal file
View File

@ -0,0 +1,42 @@
package cmdLists
import (
"context"
"fmt"
"github.com/google/go-github/github"
"golang.org/x/oauth2"
)
func ListGitHubOrganization() ([]string, error) {
var orgs []string
return orgs, nil
}
func ListGitHubProjectsfromUser(username string) ([]*github.Repository, error) {
// Replace with your access token
token := "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"
// Create an oauth2 token source with the access token
tokenSource := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: token},
)
// Create an oauth2 http client with the token source
oauth2Client := oauth2.NewClient(context.Background(), tokenSource)
// Create a new github client with the oauth2 http client
client := github.NewClient(oauth2Client)
// List the repositories of the user
repos, _, err := client.Repositories.List(context.Background(), username, nil)
if err != nil {
fmt.Println(err)
return nil, err
}
return repos, nil
}

72
cmdLists/gitTea.go Normal file
View File

@ -0,0 +1,72 @@
package cmdLists
import (
"encoding/json"
"fmt"
"kode-starter/utils"
"github.com/joho/godotenv"
)
// The ListOrganization function retrieves a list of organizations from a specified URL and returns
// their names and URLs.
func ListGitTeaOrganization() ([]string, error) {
godotenv.Load()
body := UrlGetBody(CfgGlobal.GetUrlApiOrgs())
if CfgGlobal.GetJsonFlag() {
return utils.BytesToStrings(body), nil
} else {
var orgs []map[string]interface{}
err := json.Unmarshal(body, &orgs)
if err != nil {
return nil, err
} else {
var orgNames []string
for i, org := range orgs {
// nb := "[ " + strconv.FormatInt(int64(i+1), 10) + " ] "
nb := fmt.Sprintf("[ %02d ] ", int64(i+1))
orgName := fmt.Sprintf("%s", org["username"])
orgUrl := fmt.Sprintf("[ %s/%s ]\n", CfgGlobal.GetUrlBase(), org["username"])
orgNames = append(
orgNames,
utils.PadString(nb, 4),
utils.PadDotString(orgName, 30),
orgUrl)
}
return orgNames, nil
}
}
}
// This function lists the projects of a given organization and returns their names and clone URLs.
func ListGitTeaProjects(org string) ([]string, error) {
godotenv.Load()
body := UrlGetBody(CfgGlobal.GetUrlApiOrgs() + "/" + org + "/repos")
if CfgGlobal.GetJsonFlag() {
return utils.BytesToStrings(body), nil
} else {
var prjs []map[string]interface{}
err := json.Unmarshal(body, &prjs)
if err != nil {
return nil, err
} else {
var orgNames []string
for i, prj := range prjs {
nb := fmt.Sprintf("[ %02d ] ", int64(i+1))
projectName := fmt.Sprintf("%s", prj["name"])
cloneUrl := fmt.Sprintf("[ %s ]\n", prj["clone_url"])
orgNames = append(
orgNames,
utils.PadString(nb, 4),
utils.PadString(projectName, 40),
cloneUrl,
)
}
return orgNames, nil
}
}
}

View File

@ -1,18 +1,23 @@
package cmdLists
import (
"encoding/json"
"fmt"
"io"
"kode-starter/config"
"kode-starter/utils"
"net/http"
"strconv"
"github.com/joho/godotenv"
"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
}
// This is a variable declaration that creates a new Cobra command called `ListCmd`. The command has a
// `Use` field that specifies the name of the command, a `Short` field that provides a brief
// description of the command, and a `Long` field that provides a more detailed description of the
@ -25,112 +30,84 @@ var ListCmd = &cobra.Command{
Long: `A simple CLI app to list Github, Gitea orgs, project`,
Run: func(cmd *cobra.Command, args []string) {
config.SetInformations(cmd, args)
// Start list command
startList(cmd, args)
},
}
// The startList function sets some configuration information based on the command line arguments.
func startList(cmd *cobra.Command, args []string) {
CfgGlobal.DebugPrintConfig("Function startList")
// initialize global config for command list
CfgGlobal.InitCmdList(cmd, args)
// print header if json flag is not set
if !CfgGlobal.GetJsonFlag() {
utils.PrintHeader()
}
if CfgGlobal.GetTeaFlag() {
// if -o flag is set, list projects for that org
if config.GetListOrganisationFlag() {
if !config.GetJsonFlag() {
// utils.PrintHeader()
fmt.Println("\nList projects for org: " + config.GetListOrganisation() + "\n")
fmt.Println(utils.CreateLine(6))
if CfgGlobal.GetListOrganizationFlag() {
if !CfgGlobal.GetJsonFlag() {
fmt.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))
fmt.Println(" ==> " + CfgGlobal.GetListOrganization() + " <== ")
fmt.Println(utils.CreateLine(8))
}
projects, err := ListProjects(config.GetListOrganisation())
projects, err := ListGitTeaProjects(CfgGlobal.GetListOrganization())
if err != nil {
fmt.Println("Error:", err)
return
}
for _, project := range projects {
fmt.Print(project)
fmt.Println(project)
// fmt.Print(project)
}
fmt.Println(utils.CreateLine(8))
} else {
orgs, err := ListOrganization()
orgs, err := ListGitTeaOrganization()
if err != nil {
fmt.Println("Error:", err)
return
}
if !config.GetJsonFlag() {
fmt.Println("\nList of Organizations :")
fmt.Println(utils.CreateLine(4))
if !CfgGlobal.GetJsonFlag() {
fmt.Println("\n L I S T O R G A N I Z A T I O N S")
fmt.Println(utils.CreateLine(8))
}
for _, org := range orgs {
fmt.Print(org)
}
fmt.Println(utils.CreateLine(8))
}
},
}
// The ListOrganization function retrieves a list of organizations from a specified URL and returns
// their names and URLs.
func ListOrganization() ([]string, error) {
godotenv.Load()
if config.GetVerboseFlag() {
fmt.Println("execute ListOrganization ...")
fmt.Println("URL: " + config.GetUrlApiOrgs())
fmt.Println("Token: " + config.GetToken())
}
body := UrlGetBody(config.GetUrlApiOrgs())
if config.GetJsonFlag() {
return utils.BytesToStrings(body), nil
} else {
var orgs []map[string]interface{}
err := json.Unmarshal(body, &orgs)
} else if CfgGlobal.GetGitFlag() {
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())
fmt.Println(utils.CreateLine(11))
repos, err := ListGitHubProjectsfromUser(CfgGlobal.GetListUser())
if err != nil {
return nil, err
fmt.Println("Error:", err)
return
}
nb := 1
for _, repo := range repos {
utils.PrintTreeElement(nb, *repo.Name, *repo.HTMLURL)
nb++
}
fmt.Println(utils.CreateLine(11))
} else {
var orgNames []string
for i, org := range orgs {
nb := strconv.FormatInt(int64(i+1), 10)
orgName := fmt.Sprintf("%s", org["username"])
orgUrl := fmt.Sprintf("[ %s/%s ]\n", config.GetUrlBase(), org["username"])
orgNames = append(
orgNames,
utils.PadString(nb, 4),
utils.PadString(orgName, 30),
orgUrl)
}
return orgNames, nil
}
}
// print help if no flag is set
cmd.Help()
}
// This function lists the projects of a given organization and returns their names and clone URLs.
func ListProjects(org string) ([]string, error) {
godotenv.Load()
if config.GetVerboseFlag() {
fmt.Println("execute ListProjects ...")
fmt.Println("URL: " + config.GetUrlApiOrgs())
fmt.Println("Token: " + config.GetToken())
}
body := UrlGetBody(config.GetUrlApiOrgs() + "/" + org + "/repos")
if config.GetJsonFlag() {
return utils.BytesToStrings(body), nil
} else {
var prjs []map[string]interface{}
err := json.Unmarshal(body, &prjs)
if err != nil {
return nil, err
} else {
var orgNames []string
for i, prj := range prjs {
nb := strconv.FormatInt(int64(i+1), 10)
projectName := fmt.Sprintf("%s", prj["name"])
cloneUrl := fmt.Sprintf("[ %s ]\n", prj["clone_url"])
orgNames = append(
orgNames,
utils.PadString(nb, 4),
utils.PadString(projectName, 40),
cloneUrl,
)
}
return orgNames, nil
}
}
}
// This function sends a GET request to a specified URL with authorization and content-type headers,
@ -142,7 +119,7 @@ func UrlGetBody(url string) []byte {
fmt.Println("Error creating request:", err)
}
req.Header.Set("Authorization", "token "+config.GetToken())
req.Header.Set("Authorization", "token "+CfgGlobal.GetTokenEnv())
req.Header.Set("Content-Type", "application/json")
// fmt.Println(req.Header.Get("Authorization"))
resp, err := http.DefaultClient.Do(req)

View File

@ -3,6 +3,7 @@ package config
import (
"fmt"
"kode-starter/utils"
"time"
"github.com/spf13/cobra"
)
@ -10,369 +11,693 @@ import (
type Config struct {
DebugMode bool
LogLevel string
author string
ModifDate string
ConfigFileYmlName string
TokenEnv string
VerboseFlag bool
JsonFlag bool
VersionFlag bool
HelpFlag bool
Url URLConfig
ListCmd ListCmdConfig
CreateCmd CreateCmdConfig
EnvCmd EnvCmdConfig
applicationName string
}
type URLConfig struct {
Base string
ApiBase string
ApiOrgs string
}
type ListCmdConfig struct {
Organization string
GitFlag bool
TeaFlag bool
User string
listOrganizationFlag bool
}
type CreateCmdConfig struct {
Name string
Organisation string
Description string
Private bool
}
type EnvCmdConfig struct {
EnvVariablesFlag bool
EnvVariablesListFlag bool
EnvVariablesFilterFlag bool
EnvVariablesFilter string
EnvVariablesYmlFlag bool
EnvVariablesCategoryFlag bool
EnvVariablesCategory string
EnvVariablesSetFlag bool
EnvVariablesShowAllFlag bool
}
// * * * * * * * * * * * * * * * * * * * * * * * * //
// **** G E N E R A L GETTER - SETTER ****
// * * * * * * * * * * * * * * * * * * * * * * * * //
// Getter for DebugMode field
func (c *Config) GetDebugMode() bool {
return c.DebugMode
}
// Setter for DebugMode field
func (c *Config) SetDebugMode(value bool) {
c.DebugMode = value
}
// Getter for LogLevel field
func (c *Config) GetLogLevel() string {
return c.LogLevel
}
// Setter for LogLevel field
func (c *Config) SetLogLevel(value string) {
c.LogLevel = value
}
// Getter for author field
func (c *Config) GetAuthor() string {
return c.author
}
// Setter for author field
func (c *Config) SetAuthor(value string) {
c.author = value
}
// Getter for modifDate field
func (c *Config) GetModifDate() string {
return c.ModifDate
}
// Setter for modifDate field
func (c *Config) SetModifDate(value string) {
c.ModifDate = value
}
// Getter for ConfigFileYmlName field
func (c *Config) GetConfigFileYmlName() string {
return c.ConfigFileYmlName
}
// Setter for ConfigFileYmlName field
func (c *Config) SetConfigFileYmlName(value string) {
c.ConfigFileYmlName = value
}
// Getter for tokenEnv field
func (c *Config) GetTokenEnv() string {
return c.TokenEnv
}
// Setter for tokenEnv field
func (c *Config) SetTokenEnv(value string) {
c.TokenEnv = value
}
// Getter for verboseFlag field
func (c *Config) GetVerboseFlag() bool {
return c.VerboseFlag
}
// Setter for verboseFlag field
func (c *Config) SetVerboseFlag(value bool) {
c.VerboseFlag = value
}
// Getter for jsonFlag field
func (c *Config) GetJsonFlag() bool {
return c.JsonFlag
}
// Setter for jsonFlag field
func (c *Config) SetJsonFlag(value bool) {
c.JsonFlag = value
}
// Getter for versionFlag field
func (c *Config) GetVersionFlag() bool {
return c.VersionFlag
}
// Setter for versionFlag field
func (c *Config) SetVersionFlag(value bool) {
c.VersionFlag = value
}
// Getter for helpFlag field
func (c *Config) GetHelpFlag() bool {
return c.HelpFlag
}
// Setter for helpFlag field
func (c *Config) SetHelpFlag(value bool) {
c.HelpFlag = value
}
// Getter for url field
func (c *Config) GetUrl() URLConfig {
return c.Url
}
// Setter for url field
func (c *Config) SetUrl(value URLConfig) {
c.Url = value
}
// Getter urlBase field
func (c *Config) GetUrlBase() string {
return c.Url.Base
}
// Setter urlBase field
func (c *Config) SetUrlBase(value string) {
c.Url.Base = value
}
// Getter urlApiBase field
func (c *Config) GetUrlApiBase() string {
return c.Url.ApiBase
}
// Setter urlApiBase field
func (c *Config) SetUrlApiBase(value string) {
c.Url.ApiBase = value
}
// Getter urlApiOrgs field
func (c *Config) GetUrlApiOrgs() string {
return c.Url.ApiOrgs
}
// Setter urlApiOrgs field
func (c *Config) SetUrlApiOrgs(value string) {
c.Url.ApiOrgs = value
}
// Getter for applicationName field
func (c *Config) GetApplicationName() string {
return c.applicationName
}
// Setter for applicationName field
func (c *Config) SetApplicationName(value string) {
c.applicationName = value
}
// * * * * * * * * * * * * * * * * * * * * * * * * //
// * * * * L I S T C M D GETTER - SETTER * * * *
// * * * * * * * * * * * * * * * * * * * * * * * * //
// Getter for listCmd field
func (c *Config) GetListCmd() ListCmdConfig {
return c.ListCmd
}
// Setter for listCmd field
func (c *Config) SetListCmd(value ListCmdConfig) {
c.ListCmd = value
}
// Getter for listOrganizationFlag field
func (c *Config) GetListOrganizationFlag() bool {
return c.ListCmd.listOrganizationFlag
}
// Setter for listOrganizationFlag field
func (c *Config) SetListOrganizationFlag(value bool) {
c.ListCmd.listOrganizationFlag = value
}
// Getter for listOrganization field
func (c *Config) GetListOrganization() string {
return c.ListCmd.Organization
}
// Setter for listOrganization field
func (c *Config) SetListOrganization(value string) {
c.ListCmd.Organization = value
}
// getter for Git flag
func (c *Config) GetGitFlag() bool {
return c.ListCmd.GitFlag
}
// setter for Git flag
func (c *Config) SetGitFlag(value bool) {
c.ListCmd.GitFlag = value
}
// getter for Tea flag
func (c *Config) GetTeaFlag() bool {
return c.ListCmd.TeaFlag
}
// setter for Tea flag
func (c *Config) SetTeaFlag(value bool) {
c.ListCmd.TeaFlag = value
}
// getter for User
func (c *Config) GetListUser() string {
return c.ListCmd.User
}
// setter for User
func (c *Config) SetListUser(value string) {
c.ListCmd.User = value
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// * * * * C R E A T E C M D GETTER - SETTER * * * *
// * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// Getter for createCmd field
func (c *Config) GetCreateCmd() CreateCmdConfig {
return c.CreateCmd
}
// Setter for createCmd field
func (c *Config) SetCreateCmd(value CreateCmdConfig) {
c.CreateCmd = value
}
// Getter for createName field
func (c *Config) GetCreateName() string {
return c.CreateCmd.Name
}
// Setter for createName field
func (c *Config) SetCreateName(value string) {
c.CreateCmd.Name = value
}
// Getter for createDescription field
func (c *Config) GetCreateDescription() string {
return c.CreateCmd.Description
}
// Setter for createDescription field
func (c *Config) SetCreateDescription(value string) {
c.CreateCmd.Description = value
}
// Getter for createPrivate field
func (c *Config) GetCreatePrivate() bool {
return c.CreateCmd.Private
}
// Setter for createPrivate field
func (c *Config) SetCreatePrivate(value bool) {
c.CreateCmd.Private = value
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// * * * * E N V C M D GETTER - SETTER * * * *
// * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// Getter for envCmd field
func (c *Config) GetEnvCmd() EnvCmdConfig {
return c.EnvCmd
}
// Setter for envCmd field
func (c *Config) SetEnvCmd(value EnvCmdConfig) {
c.EnvCmd = value
}
// Getter for envVariblesFlag flag
func (c *Config) GetEnvVariblesFlag() bool {
return c.EnvCmd.EnvVariablesFlag
}
// Setter for envVariblesFlag flag
func (c *Config) SetEnvVariblesFlag(value bool) {
c.EnvCmd.EnvVariablesFlag = value
}
// Getter for env list flag
func (c *Config) GetEnvListFlag() bool {
return c.EnvCmd.EnvVariablesListFlag
}
// Setter for env list flag
func (c *Config) SetEnvListFlag(value bool) {
c.EnvCmd.EnvVariablesListFlag = value
}
// Getter for env filter flag
func (c *Config) GetEnvFilterFlag() bool {
return c.EnvCmd.EnvVariablesFilterFlag
}
// Setter for env filter flag
func (c *Config) SetEnvFilterFlag(value bool) {
c.EnvCmd.EnvVariablesFilterFlag = value
}
// Getter for env filter
func (c *Config) GetEnvFilter() string {
return c.EnvCmd.EnvVariablesFilter
}
// Setter for env filter
func (c *Config) SetEnvFilterInfo(value string) {
c.EnvCmd.EnvVariablesFilter = value
}
// Getter for env yml file flag
func (c *Config) GetEnvYmlFileFlag() bool {
return c.EnvCmd.EnvVariablesYmlFlag
}
// Setter for env yml file flag
func (c *Config) SetEnvYmlFileFlag(value bool) {
c.EnvCmd.EnvVariablesYmlFlag = value
}
// Getter for env category flag
func (c *Config) GetEnvCategoryFlag() bool {
return c.EnvCmd.EnvVariablesCategoryFlag
}
// Setter for env category flag
func (c *Config) SetEnvCategoryFlag(value bool) {
c.EnvCmd.EnvVariablesCategoryFlag = value
}
// Getter for env category Info
func (c *Config) GetEnvCategoryInfo() string {
return c.EnvCmd.EnvVariablesCategory
}
// Setter for env category Info
func (c *Config) SetEnvCategoryInfo(value string) {
c.EnvCmd.EnvVariablesCategory = value
}
// Getter for env Set flag
func (c *Config) GetEnvSetFlag() bool {
return c.EnvCmd.EnvVariablesSetFlag
}
// Setter for env Set flag
func (c *Config) SetEnvSetFlag(value bool) {
c.EnvCmd.EnvVariablesSetFlag = value
}
// Getter for env Show All flag
func (c *Config) GetEnvShowAllFlag() bool {
return c.EnvCmd.EnvVariablesShowAllFlag
}
// Setter for env Show All flag
func (c *Config) SetEnvShowAllFlag(value bool) {
c.EnvCmd.EnvVariablesShowAllFlag = value
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// initialize basic configuration
// * * * * * * * * * * * * * * * * * * * * * * * * * * * //
func (c *Config) Init() {
// autor
var author string = "Bruno Charest"
// Cfg.SetAuthor(author)
c.SetAuthor(author)
var modifDate string = "2023-06-12"
// set modification date to current date
var modifDate string = time.Now().Format("2006-01-02")
c.SetModifDate(modifDate)
var ConfigFileYmlName string = "config.yml"
// set config file name
var configFileYmlName string = "config.yml"
c.SetConfigFileYmlName(configFileYmlName)
var tokenEnv string = utils.GetGitToken()
// set token from environment variable
var tokenEnv string = utils.GetGitTokenFromOsEnv()
c.SetTokenEnv(tokenEnv)
var verboseFlag bool = false
// set verbose flag
c.SetVerboseFlag(false)
var jsonFlag bool = false
// set json flag
c.SetJsonFlag(false)
var versionFlag bool = false
// set version flag
c.SetVersionFlag(false)
var helpFlag bool = false
// set help flag
c.SetHelpFlag(false)
// variables for URL
// -----------------
// set url base
var urlBase string = "https://git.bcmaison.cf"
c.SetUrlBase(urlBase)
// set url api base
var urlApiBase string = urlBase + "/api/v1"
c.SetUrlApiBase(urlApiBase)
// set url api orgs
var urlApiOrgs string = urlApiBase + "/orgs"
c.SetUrlApiOrgs(urlApiOrgs)
// variables for list command
// --------------------------
var listOrganization string
//set application name
var appName string = "Kode-Creator"
c.SetApplicationName(appName)
var listOrganizationFlag bool = false
// variables for create command
// ----------------------------
var createName string
var createOrganisation string
var createDescription string
var createPrivatge string
// variables for env command
// -------------------------
var EnvVariablesFlag bool = false
var envVariablesFilterFlag bool = false
var ennVariablesListFlag bool = false
var envVariablesFilter string
var envVariablesYmlFlag bool = false
var envVariablesCategoryFlag bool = false
var envVariablesCategory string
var envVariablesSetFlag bool = false
// general functions
// -----------------
func GetAuthor() string {
return author
}
func GetBuildDate() string {
return modifDate
}
func GetConfigFileName() string {
return ConfigFileYmlName
}
func GetToken() string {
return tokenEnv
}
func SetToken(token string) {
tokenEnv = token
}
func GetJsonFlag() bool {
return jsonFlag
}
func SetJsonFlag(flag bool) {
jsonFlag = flag
}
func GetUrlBase() string {
return urlBase
}
func GetUrlApiBase() string {
return urlApiBase
}
func GetUrlApiOrgs() string {
return urlApiOrgs
}
func GetVerboseFlag() bool {
return verboseFlag
}
func SetVerboseFlag(flag bool) {
verboseFlag = flag
}
func SetVersionFlag(flag bool) {
versionFlag = flag
}
func GetVersionFlag() bool {
return versionFlag
}
func SetHelpFlag(flag bool) {
helpFlag = flag
}
func GetHelpFlag() bool {
return helpFlag
}
// functions for list command
// --------------------------
func SetListOrganisation(name string) {
listOrganization = name
}
func GetListOrganisation() string {
return listOrganization
}
func SetListOrganisationFlag(flag bool) {
listOrganizationFlag = flag
}
func GetListOrganisationFlag() bool {
return listOrganizationFlag
}
// functions for create command
// ----------------------------
func GetCreateName() string {
return createName
}
func SetCreateName(name string) {
createName = name
}
func GetCreateOrganisation() string {
return createOrganisation
}
func SetCeateOrganisation(organisation string) {
createOrganisation = organisation
}
func GetCreateDescription() string {
return createDescription
}
func SetCeateDescription(description string) {
createDescription = description
}
func GetCreatePrivate() string {
return createPrivatge
}
func SetCreatePrivate(private string) {
createPrivatge = private
}
// function for env command
// ------------------------
func GetEnvVariablesFlag() bool {
return EnvVariablesFlag
}
func SetEnvVariablesFlag(flag bool) {
EnvVariablesFlag = flag
}
func GetEnvVariablesFilterFlag() bool {
return envVariablesFilterFlag
}
func SetEnvVariablesFilterFlag(flag bool) {
envVariablesFilterFlag = flag
}
func GetEnvVariablesFilter() string {
return envVariablesFilter
}
func SetEnvVariablesFilter(filter string) {
envVariablesFilter = filter
}
func GetEnvVariablesListFlag() bool {
return ennVariablesListFlag
}
func SetEnvVariablesListFlag(flag bool) {
ennVariablesListFlag = flag
}
func GetEnvVariablesYmlFlag() bool {
return envVariablesYmlFlag
}
func SetEnvVariablesYmlFlag(flag bool) {
envVariablesYmlFlag = flag
}
func GetEnvVariablesCategoryFlag() bool {
return envVariablesCategoryFlag
}
func SetEnvVariablesCategoryFlag(flag bool) {
envVariablesCategoryFlag = flag
}
func GetEnvVariablesCategory() string {
return envVariablesCategory
}
func SetEnvVariablesCategory(category string) {
envVariablesCategory = category
}
func GetEnvVariablesSetFlag() bool {
return envVariablesSetFlag
}
func SetEnvVariablesSetFlag(flag bool) {
envVariablesSetFlag = flag
}
// SetInformations - set informations from command line
func SetInformations(cmd *cobra.Command, args []string) {
// * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// initialize configuration for commands and flags
// for root command
// * * * * * * * * * * * * * * * * * * * * * * * * * * * //
func (c *Config) InitCmdRoot(cmd *cobra.Command, args []string) {
// Check if the version flag is set
if cmd.Flags().Changed("version") || cmd.Flags().Changed("V") {
SetVersionFlag(true)
c.SetVersionFlag(true)
}
// Check if the verbose flag is set
if cmd.Flags().Changed("verbose") || cmd.Flags().Changed("v") {
SetVerboseFlag(true)
c.SetVerboseFlag(true)
} else {
SetVerboseFlag(false)
c.SetVerboseFlag(false)
}
// Check if the json flag is set
if cmd.Flags().Changed("json") || cmd.Flags().Changed("j") {
SetJsonFlag(true)
c.SetJsonFlag(true)
} else {
SetJsonFlag(false)
c.SetJsonFlag(false)
}
// check if the help flag is set
if cmd.Flags().Changed("help") || cmd.Flags().Changed("h") {
SetHelpFlag(true)
c.SetHelpFlag(true)
}
if cmd.Flags().Changed("name") || cmd.Flags().Changed("n") {
SetCreateName(cmd.Flag("name").Value.String())
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// initialize configuration command and flags
// for list command
// * * * * * * * * * * * * * * * * * * * * * * * * * * * //
func (c *Config) InitCmdList(cmd *cobra.Command, args []string) {
if cmd.Flags().Changed("org") || cmd.Flags().Changed("o") {
if cmd.Name() == "list" {
SetListOrganisation(cmd.Flag("org").Value.String())
SetListOrganisationFlag(true)
c.SetListOrganization(cmd.Flag("org").Value.String())
c.SetListOrganizationFlag(true)
} else {
SetCeateOrganisation(cmd.Flag("org").Value.String())
c.SetListOrganization(cmd.Flag("org").Value.String())
}
}
if cmd.Flags().Changed("user") || cmd.Flags().Changed("u") {
c.SetListUser(cmd.Flag("user").Value.String())
}
if cmd.Flags().Changed("git") || cmd.Flags().Changed("g") {
c.SetGitFlag(true)
}
if cmd.Flags().Changed("tea") || cmd.Flags().Changed("a") {
c.SetTeaFlag(true)
}
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// initialize configuration for commands and flags
// for create command
// * * * * * * * * * * * * * * * * * * * * * * * * * * * //
func (c *Config) InitCmdCreate(cmd *cobra.Command, args []string) {
// initialize configuration for root command
// c.InitCmdRoot(cmd, args)
// validate flag on create command
if cmd.Name() == "create" {
// set organization flag if set
if cmd.Flags().Changed("org") || cmd.Flags().Changed("o") {
c.SetListOrganization(cmd.Flag("org").Value.String())
c.SetListOrganizationFlag(true)
}
// set name flag if set
if cmd.Flags().Changed("name") || cmd.Flags().Changed("n") {
c.SetCreateName(cmd.Flag("name").Value.String())
}
// set description flag if set
if cmd.Flags().Changed("desc") || cmd.Flags().Changed("d") {
SetCeateDescription(cmd.Flag("desc").Value.String())
c.SetCreateDescription(cmd.Flag("desc").Value.String())
}
// set private flag if set
if cmd.Flags().Changed("private") || cmd.Flags().Changed("p") {
SetCreatePrivate(cmd.Flag("private").Value.String())
if cmd.Flag("private").Value.String() == "true" {
c.SetCreatePrivate(true)
} else if cmd.Flag("private").Value.String() == "false" {
c.SetCreatePrivate(false)
} else {
c.SetCreatePrivate(false)
}
}
}
}
// set env variables flag if set
if cmd.Flags().Changed("env") || cmd.Flags().Changed("e") {
SetEnvVariablesFlag(true)
// * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// initialize configuration commands and flags
// for env command
// * * * * * * * * * * * * * * * * * * * * * * * * * * * //
func (c *Config) InitCmdEnv(cmd *cobra.Command, args []string) {
// initialize configuration for root command
c.InitCmdRoot(cmd, args)
// validate flag on env command
if cmd.Name() == "env" {
// if flag list is set, set filter flag
if cmd.Flags().Changed("list") || cmd.Flags().Changed("l") {
SetEnvVariablesListFlag(true)
c.SetEnvListFlag(true)
// // set env variables filter flag if set
// if cmd.Flags().Changed("filter") || cmd.Flags().Changed("f") {
// c.SetEnvFilterInfo(cmd.Flag("filter").Value.String())
// c.SetEnvFilterFlag(true)
// }
}
// set env variables filter flag if set
if cmd.Flags().Changed("filter") || cmd.Flags().Changed("f") {
SetEnvVariablesFilter(cmd.Flag("filter").Value.String())
c.SetEnvFilterInfo(cmd.Flag("filter").Value.String())
c.SetEnvFilterFlag(true)
}
} else if cmd.Flags().Changed("yml") || cmd.Flags().Changed("y") {
SetEnvVariablesYmlFlag(true)
if cmd.Flags().Changed("yml") || cmd.Flags().Changed("y") {
c.SetEnvYmlFileFlag(true)
}
if cmd.Flags().Changed("set") || cmd.Flags().Changed("s") {
c.SetEnvSetFlag(true)
}
// set env variables category flag if set
if cmd.Flags().Changed("category") || cmd.Flags().Changed("c") {
SetEnvVariablesCategoryFlag(true)
SetEnvVariablesCategory(cmd.Flag("category").Value.String())
if cmd.Flags().Changed("cat") || cmd.Flags().Changed("c") {
fmt.Println("cat flag set")
c.SetEnvCategoryFlag(true)
c.SetEnvCategoryInfo(cmd.Flag("cat").Value.String())
}
} else if cmd.Flags().Changed("set") || cmd.Flags().Changed("s") {
SetEnvVariablesSetFlag(true)
// set env variables show all flag if set
if cmd.Flags().Changed("all") || cmd.Flags().Changed("a") {
c.SetEnvShowAllFlag(true)
}
}
}
// If verbose flag is set, print informations
if GetVerboseFlag() {
if cmd.Name() == "list" {
fmt.Println("SetInformations - progress list option:")
fmt.Println("SetInformations - org:" + cmd.Flag("org").Value.String())
fmt.Println("SetInformations - cmd Usertoken:" + cmd.Flag("token").Value.String())
}
if cmd.Name() == "create" {
fmt.Println("SetInformations - progress create option:")
fmt.Println("SetInformations - name:" + cmd.Flag("name").Value.String())
fmt.Println("SetInformations - description:" + cmd.Flag("desc").Value.String())
fmt.Println("SetInformations - private:" + cmd.Flag("private").Value.String())
fmt.Println("SetInformations - cmd Usertoken:" + cmd.Flag("token").Value.String())
fmt.Println("SetInformations - org:" + cmd.Flag("org").Value.String())
}
if cmd.Name() == "env" {
fmt.Println("SetInformations - progress env option:")
// fmt.Println("SetInformations - cmd Usertoken:" + cmd.Flag("token").Value.String())
fmt.Println("SetInformations - env:" + cmd.Flag("env").Value.String())
fmt.Println("SetInformations - filter:" + cmd.Flag("filter").Value.String())
fmt.Println("SetInformations - list:" + cmd.Flag("list").Value.String())
fmt.Println("SetInformations - yml:" + cmd.Flag("yml").Value.String())
if GetEnvVariablesListFlag() {
fmt.Println("SetInformations - category:" + cmd.Flag("category").Value.String())
}
fmt.Println("SetInformations - set:" + cmd.Flag("set").Value.String())
// function that print all configuration if DebugMode is true
func (c *Config) DebugPrintConfig(section string) {
if c.GetDebugMode() {
fmt.Println("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -")
fmt.Println("| Section: " + section)
fmt.Println("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -")
c.printAllConfiguration()
}
}
// Check if token come from flag or env
if cmd.Flags().Changed("token") || cmd.Flags().Changed("t") {
if utils.IsValidToken(cmd.Flag("token").Value.String()) {
SetToken(cmd.Flag("token").Value.String())
} else {
utils.ExitWithError(10, "Invalid token, format must be 40 characters UUID.")
// function that print string if DebugMode is true
func (c *Config) DebugPrintString(str string) {
if c.GetDebugMode() {
fmt.Println(str)
}
}
} else {
if utils.IsValidToken(utils.GetGitToken()) {
SetToken(utils.GetGitToken())
} else {
utils.ExitWithError(10, "Invalid token, format must be 40 characters UUID.")
}
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// function to print all configuration
// for information and flags
// * * * * * * * * * * * * * * * * * * * * * * * * * * * //
func (c *Config) printAllConfiguration() {
fmt.Println("General Configuration:")
fmt.Println("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -")
fmt.Println("Config: DebugMode: ", c.GetDebugMode())
fmt.Println("Config: LogLevel: ", c.GetLogLevel())
fmt.Println("config: Author: ", c.GetAuthor())
fmt.Println("config: ModifDate: ", c.GetModifDate())
fmt.Println("config: ConfigFileYmlName: ", c.GetConfigFileYmlName())
fmt.Println("config: TokenEnv: ", c.GetTokenEnv())
fmt.Println("config: VerboseFlag: ", c.GetVerboseFlag())
fmt.Println("config: JsonFlag: ", c.GetJsonFlag())
fmt.Println("config: VersionFlag: ", c.GetVersionFlag())
fmt.Println("config: HelpFlag: ", c.GetHelpFlag())
fmt.Println("config: UrlBase: ", c.GetUrlBase())
fmt.Println("config: UrlApiBase: ", c.GetUrlApiBase())
fmt.Println("config: UrlApiOrgs: ", c.GetUrlApiOrgs())
fmt.Println("List Commands Configuration:")
fmt.Println("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -")
fmt.Println("config: ListOrganization: ", c.GetListOrganization())
fmt.Println("config: ListOrganizationFlag: ", c.GetListOrganizationFlag())
fmt.Println("Create commands Configuration:")
fmt.Println("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -")
fmt.Println("config: CreateName: ", c.GetCreateCmd().Name)
fmt.Println("config: Organization: ", c.GetCreateCmd().Organisation)
fmt.Println("config: CreateDescription: ", c.GetCreateCmd().Description)
fmt.Println("config: CreatePrivate: ", c.GetCreatePrivate())
fmt.Println("config: CreateCmd: ", c.GetCreateCmd())
fmt.Println("Environment Variables Configuration:")
fmt.Println("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -")
fmt.Println("config: EnvCmd: ", c.GetEnvCmd())
fmt.Println("config: EnvVariablesFlag: ", c.GetEnvVariblesFlag())
fmt.Println("config: EnvListFlag: ", c.GetEnvListFlag())
fmt.Println("config: EnvFilterFlag: ", c.GetEnvFilterFlag())
fmt.Println("config: EnvVariablesFilter: ", c.GetEnvFilter())
fmt.Println("config: EnvVariablesYmlFlag: ", c.GetEnvYmlFileFlag())
fmt.Println("config: EnvVariablesCategoryFlag: ", c.GetEnvCategoryFlag())
fmt.Println("config: EnvVariablesCategory: ", c.GetEnvCategoryInfo())
fmt.Println("config: EnvVariablesSetFlag: ", c.GetEnvSetFlag())
fmt.Println("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -")
}

View File

@ -7,22 +7,21 @@ import (
"os"
)
func loadConfigFile() *Config {
func LoadConfigFile(c *config.Config) *ConfigYml {
filename := config.GetConfigFileName()
cfg, err := LoadConfig(filename)
filename := c.GetConfigFileYmlName()
cfgfile, err := LoadConfig(filename)
if err != nil {
log.Fatalf("error loading config file: %v", err)
os.Exit(1)
}
return cfg
return cfgfile
}
func Listcategory() {
func Listcategory(c *config.Config) {
cfg := loadConfigFile()
cfg := LoadConfigFile(c)
// list all categories
ListCategories, err := cfg.GetListCategory()

View File

@ -7,11 +7,7 @@ import (
"gopkg.in/yaml.v2"
)
// The above code defines a configuration struct for software projects with sections for software,
// environment variables, directories, and pipeline configurations.
// @property Sections - A map of SectionConfig objects, where each key is a string representing the
// name of the section.
type Config struct {
type ConfigYml struct {
Sections map[string]SectionConfig `yaml:"category"`
}
@ -46,14 +42,27 @@ type PipelineConfig struct {
Build string `yaml:"build"`
Test string `yaml:"test"`
Lint string `yaml:"lint"`
// Compile string `yaml:"compile"`
// Package string `yaml:"package"`
}
// function GetPathsFromCategory
func (c *ConfigYml) GetPathsFromCategory(sectionName string) ([]string, error) {
section, ok := c.Sections[sectionName]
if !ok {
return nil, fmt.Errorf("section '%s' not found", sectionName)
}
var paths []string
for _, EnvVar := range section.EnvironmentsVariables {
paths = append(paths, EnvVar)
}
return paths, nil
}
// The function loads a configuration file in YAML format and returns a pointer to a Config struct or
// an error.
func LoadConfig(filename string) (*Config, error) {
var config Config
func LoadConfig(filename string) (*ConfigYml, error) {
var config ConfigYml
source, err := ioutil.ReadFile(filename)
if err != nil {
@ -72,7 +81,7 @@ func LoadConfig(filename string) (*Config, error) {
}
// function GetListCategory return list category from config file
func (c *Config) GetListCategory() ([]string, error) {
func (c *ConfigYml) GetListCategory() ([]string, error) {
var categories []string
for categoryName := range c.Sections {
categories = append(categories, categoryName)
@ -84,7 +93,7 @@ func (c *Config) GetListCategory() ([]string, error) {
// This is a method defined on the `Config` struct that returns a list of software names for a given
// section. It takes in a `sectionName` string as a parameter and returns a slice of strings and an
// error.
func (c *Config) GetListSoftware(sectionName string) ([]string, error) {
func (c *ConfigYml) GetListSoftware(sectionName string) ([]string, error) {
section, ok := c.Sections[sectionName]
if !ok {
return nil, fmt.Errorf("section '%s' not found", sectionName)
@ -100,7 +109,7 @@ func (c *Config) GetListSoftware(sectionName string) ([]string, error) {
// This is a method defined on the `Config` struct that takes in two string parameters `sectionName`
// and `SoftwareName`. It returns a pointer to a `SoftwareConfig` struct and an error.
func (c *Config) GetSoftware(sectionName, SoftwareName string) (*SoftwareConfig, error) {
func (c *ConfigYml) GetSoftware(sectionName, SoftwareName string) (*SoftwareConfig, error) {
section, ok := c.Sections[sectionName]
if !ok {
return nil, fmt.Errorf("section '%s' not found", sectionName)
@ -115,7 +124,7 @@ func (c *Config) GetSoftware(sectionName, SoftwareName string) (*SoftwareConfig,
}
// get list environment variables
func (c *Config) GetListEnvironmentVariables(sectionName string) ([]string, error) {
func (c *ConfigYml) GetListEnvironmentVariables(sectionName string) ([]string, error) {
section, ok := c.Sections[sectionName]
if !ok {
return nil, fmt.Errorf("section '%s' not found", sectionName)
@ -134,7 +143,7 @@ func (c *Config) GetListEnvironmentVariables(sectionName string) ([]string, erro
// section in the configuration and then looks for the specified environment variable within that
// section. If the section or variable is not found, an error is returned. If the variable is found,
// its value is returned.
func (c *Config) GetEnvironmentVariables(sectionName, variableName string) (string, error) {
func (c *ConfigYml) GetEnvironmentVariables(sectionName, variableName string) (string, error) {
section, ok := c.Sections[sectionName]
if !ok {
return "", fmt.Errorf("section '%s' not found", sectionName)
@ -148,12 +157,22 @@ func (c *Config) GetEnvironmentVariables(sectionName, variableName string) (stri
return variable, nil
}
// get all environment variables names and values
func (c *ConfigYml) GetAllEnvironmentVariables(sectionName string) (map[string]string, error) {
section, ok := c.Sections[sectionName]
if !ok {
return nil, fmt.Errorf("section '%s' not found", sectionName)
}
return section.EnvironmentsVariables, nil
}
// This is a method defined on the `Config` struct that takes in two string parameters `sectionName`
// and `directoryName`. It returns a pointer to a `DirectoryConfig` struct and an error. The method
// looks for the specified section in the configuration and then looks for the specified directory
// within that section. If the section or directory is not found, an error is returned. If the
// directory is found, its configuration is returned.
func (c *Config) GetDirectory(sectionName, directoryName string) (*DirectoryConfig, error) {
func (c *ConfigYml) GetDirectory(sectionName, directoryName string) (*DirectoryConfig, error) {
section, ok := c.Sections[sectionName]
if !ok {
return nil, fmt.Errorf("section '%s' not found", sectionName)
@ -173,7 +192,7 @@ func (c *Config) GetDirectory(sectionName, directoryName string) (*DirectoryConf
// for the specified section in the configuration and then looks for the specified pipeline within that
// section. If the section or pipeline is not found, an error is returned. If the pipeline is found,
// its configuration is returned.
func (c *Config) GetPipeline(sectionName, pipelineName string) (*PipelineConfig, error) {
func (c *ConfigYml) GetPipeline(sectionName, pipelineName string) (*PipelineConfig, error) {
section, ok := c.Sections[sectionName]
if !ok {
return nil, fmt.Errorf("section '%s' not found", sectionName)

12
go.mod
View File

@ -9,9 +9,19 @@ require (
)
require (
github.com/golang/protobuf v1.5.2 // indirect
github.com/google/go-querystring v1.1.0 // indirect
golang.org/x/net v0.11.0 // indirect
google.golang.org/appengine v1.6.7 // indirect
google.golang.org/protobuf v1.28.0 // indirect
)
require (
github.com/google/go-github v17.0.0+incompatible
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778 // indirect
golang.org/x/sys v0.6.0 // indirect
golang.org/x/oauth2 v0.9.0
golang.org/x/sys v0.9.0 // indirect
gopkg.in/yaml.v2 v2.4.0
)

28
go.sum
View File

@ -1,5 +1,15 @@
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw=
github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-github v17.0.0+incompatible h1:N0LgJ1j65A7kfXrZnUDaYCs/Sf4rEjNlfyDHW9dolSY=
github.com/google/go-github v17.0.0+incompatible/go.mod h1:zLgOLi98H3fifZn+44m+umXrS52loVEgC2AApnigrVQ=
github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8=
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/go.mod h1:NUzwzeehUfl7GIb36pqId+UGmRfQcU/WiiyTTeNjHtE=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
@ -15,8 +25,26 @@ github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An
github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk=
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=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
golang.org/x/net v0.11.0 h1:Gi2tvZIJyBtO9SDr1q9h5hEQCp/4L2RQ+ar0qjx2oNU=
golang.org/x/net v0.11.0/go.mod h1:2L/ixqYpgIVXmeoSA/4Lu7BzTG4KIyPIryS4IsOd1oQ=
golang.org/x/oauth2 v0.9.0 h1:BPpt2kU7oMRq3kCHAA1tbSEshXRw1LpG2ztgDwrzuAs=
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.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.9.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.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/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c=
google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
google.golang.org/protobuf v1.28.0 h1:w43yiav+6bVFTBQFZX0r7ipe9JQ1QsbMgHwbBziscLw=
google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=

View File

@ -11,50 +11,54 @@ import (
"github.com/spf13/cobra"
)
// initailize global config
var CfgGlobal = &config.Config{}
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "kode-creator.exe",
Short: "Simple cli app create startup project",
Long: `A simple CLI app to work with Github, Gitea`,
Run: func(cmd *cobra.Command, args []string) {
config.SetInformations(cmd, args)
mainProgram(cmd, args)
},
}
var token, org, name, private, description, envGroup, envCategory string
var verbose, createFlag, versionFlag bool
var listEnvFlag, listEnvCfgFlag, setEnvFlag, envVariablesFlag, envGroupFlag bool
// init function that will be executed before the main function
func init() {
// var config = &config.Config{}
CfgGlobal.Init()
// root menu section
rootCmd.Flags().BoolP("help", "h", false, "Show help for create command")
rootCmd.Flags().BoolVarP(&versionFlag, "version", "V", false, "Show version")
rootCmd.Flags().BoolP("help", "h", false, "Show help for "+CfgGlobal.GetApplicationName())
rootCmd.Flags().BoolVarP(&CfgGlobal.VersionFlag, "version", "V", false, "Show VERSION of "+CfgGlobal.GetApplicationName())
rootCmd.CompletionOptions.DisableDefaultCmd = true
rootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "mode verbose")
rootCmd.PersistentFlags().BoolVarP(&createFlag, "json", "j", false, "Print output as json format")
rootCmd.PersistentFlags().BoolVarP(&CfgGlobal.VerboseFlag, "verbose", "v", false, "VERBOSE mode output")
rootCmd.PersistentFlags().BoolVarP(&CfgGlobal.JsonFlag, "json", "j", false, "JSON output format")
// List menu section
cmdLists.ListCmd.Flags().StringVarP(&token, "token", "t", "", "Github token")
cmdLists.ListCmd.Flags().StringVarP(&org, "org", "o", "", "Github organization")
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.TeaFlag, "tea", "a", false, "List all repositories from GITEA")
cmdLists.ListCmd.Flags().StringVarP(&CfgGlobal.ListCmd.User, "user", "u", "", "user for request on GITHUB or GITEA")
cmdLists.ListCmd.Flags().StringVarP(&CfgGlobal.ListCmd.Organization, "org", "o", "", "List projects from an ORGANIZATION")
// Create menu section
cmdCreate.CreateCmd.Flags().StringVarP(&token, "token", "t", "", "Github token")
cmdCreate.CreateCmd.Flags().StringVarP(&org, "org", "o", "", "Github organization")
cmdCreate.CreateCmd.Flags().StringVarP(&name, "name", "n", "", "Project name")
cmdCreate.CreateCmd.Flags().StringVarP(&description, "desc", "d", "", "Description")
cmdCreate.CreateCmd.Flags().StringVarP(&private, "private", "p", "", "true/false")
cmdCreate.CreateCmd.Flags().StringVarP(&CfgGlobal.TokenEnv, "token", "t", "", "TOKEN for Gitea or Github")
cmdCreate.CreateCmd.Flags().StringVarP(&CfgGlobal.CreateCmd.Organisation, "org", "o", "", "ORGANIZATION for this project")
cmdCreate.CreateCmd.Flags().StringVarP(&CfgGlobal.CreateCmd.Name, "name", "n", "", "NAME of the Project")
cmdCreate.CreateCmd.Flags().StringVarP(&CfgGlobal.CreateCmd.Description, "desc", "d", "", "DESCRIPTION of the project")
cmdCreate.CreateCmd.Flags().BoolVarP(&CfgGlobal.CreateCmd.Private, "private", "p", false, "PRIVATE with this switch")
// Env menu section
cmdEnv.EnvCmd.Flags().BoolVarP(&envVariablesFlag, "env", "e", false, "environnement variables management")
cmdEnv.EnvCmd.Flags().BoolVarP(&listEnvFlag, "list", "l", false, "List environnement variables")
cmdEnv.EnvCmd.Flags().StringVarP(&envGroup, "filter", "f", "", "Highlight a specific word in environnement variables")
cmdEnv.EnvCmd.Flags().BoolVarP(&listEnvCfgFlag, "yml", "y", false, "List environnement variables from config.yml")
cmdEnv.EnvCmd.Flags().StringVarP(&envCategory, "cat", "c", "", "filter for a specific category")
cmdEnv.EnvCmd.Flags().BoolVarP(&setEnvFlag, "set", "s", false, "set environnement variable available from config.yml")
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().StringVarP(&CfgGlobal.EnvCmd.EnvVariablesFilter, "filter", "f", "", "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().StringVarP(&CfgGlobal.EnvCmd.EnvVariablesCategory, "cat", "c", "", "FILTER for a specific category")
cmdEnv.EnvCmd.Flags().BoolVarP(&CfgGlobal.EnvCmd.EnvVariablesSetFlag, "set", "s", false, "Set environnement variable available from config.yml")
cmdEnv.EnvCmd.Flags().BoolVarP(&CfgGlobal.EnvCmd.EnvVariablesShowAllFlag, "all", "a", false, "Show all environnement variables")
// Add subcommands
rootCmd.AddCommand(cmdLists.ListCmd)
@ -63,31 +67,35 @@ func init() {
}
// function to print help or version
func mainProgram(cmd *cobra.Command, args []string) {
config.SetInformations(cmd, args)
// if version flag is set, print version and exit
if config.GetVersionFlag() {
utils.PrintVersion(version.GetFullVersion(), config.GetAuthor(), config.GetBuildDate())
if CfgGlobal.GetVersionFlag() {
utils.PrintVersion(version.GetFullVersion(), CfgGlobal.GetAuthor(), CfgGlobal.GetModifDate())
return
// if no flag is set, print help and exit
} else {
//configFile.Listcategory()
utils.PrintHelpFormated(version.GetFullVersion(), config.GetAuthor(), config.GetBuildDate(), cmd)
utils.PrintHelpFormated(version.GetFullVersion(), CfgGlobal.GetAuthor(), CfgGlobal.GetModifDate(), cmd)
return
}
}
// main function
func main() {
// var config = &config.Config{}
//initialize config
CfgGlobal.Init()
cmdLists.InitConfig(CfgGlobal)
cmdCreate.InitConfig(CfgGlobal)
cmdEnv.InitConfig(CfgGlobal)
// print header
utils.PrintHeader()
// set debug mode
CfgGlobal.SetDebugMode(false)
CfgGlobal.DebugPrintConfig("Function main")
// execute root command
rootCmd.Execute()

View File

@ -68,7 +68,8 @@ You can set the following environment variables:
- `GIT_TOKEN` - Your Github personal access token. This will be used instead of passing the `-t` flag.
*Temporaire*
(Git Token for linux)[ af65e1b846d721e3465422c04997d69b0cfe7f18 ]
(Gitea Token for linux)[ af65e1b846d721e3465422c04997d69b0cfe7f18 ]
(Github Token from Github)[ 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 ]
##License

Binary file not shown.

View File

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