feat: use flag package even better

This commit is contained in:
Simon Cornet 2025-01-05 12:10:37 +01:00
commit f90a706967
2 changed files with 33 additions and 37 deletions

View file

@ -7,13 +7,6 @@ import (
"strings" "strings"
) )
func loadEnvironmentVariables() error {
gitlabHost = os.Getenv("GITLAB_HOSTNAME")
gitlabToken = os.Getenv("GITLAB_API_TOKEN")
repoDestinationPre = os.Getenv("GOGITLABBER_DESTINATION")
return nil
}
func manageArguments() { func manageArguments() {
var archivedFlag = flag.String("archived", "excluded", "to include archived repositories (any|excluded|exclusive)\nenv = GOGITLABBER_ARCHIVED\n") var archivedFlag = flag.String("archived", "excluded", "to include archived repositories (any|excluded|exclusive)\nenv = GOGITLABBER_ARCHIVED\n")
@ -29,17 +22,40 @@ func manageArguments() {
gitlabToken = *tokenFlag gitlabToken = *tokenFlag
gitlabHost = *hostFlag gitlabHost = *hostFlag
// fail if destination is unknown // use environment variable if set, otherwise use flag value
if repoDestinationPre == "" { if envHost := os.Getenv("GITLAB_HOSTNAME"); envHost != "" {
fmt.Println("Fatal: No destination found.") gitlabHost = envHost
}
if envToken := os.Getenv("GITLAB_API_TOKEN"); envToken != "" {
gitlabToken = envToken
}
if envRepoDest := os.Getenv("GOGITLABBER_DESTINATION"); envRepoDest != "" {
repoDestinationPre = envRepoDest
}
if envArchived := os.Getenv("GOGITLABBER_ARCHIVED"); envArchived != "" {
includeArchived = envArchived
}
// fail if no configuration found
if gitlabHost == "" {
fmt.Println("Fatal: No GitLab Host found.")
flag.PrintDefaults() flag.PrintDefaults()
fmt.Println("")
os.Exit(1) os.Exit(1)
} }
// add slash 🎩🎸 if not provided if gitlabToken == "" {
if !strings.HasSuffix(repoDestinationPre, "/") { fmt.Println("Fatal: No GitLab API Token found.")
repoDestinationPre += "/" flag.PrintDefaults()
os.Exit(1)
}
if repoDestinationPre == "" {
fmt.Println("Fatal: No destination found.")
flag.PrintDefaults()
os.Exit(1)
} }
// --archive options: // --archive options:
@ -58,24 +74,9 @@ func manageArguments() {
os.Exit(1) os.Exit(1)
} }
// use environment variable if set, otherwise use flag value // add slash 🎩🎸 if not provided
if envHost := os.Getenv("GITLAB_HOSTNAME"); envHost != "" { if !strings.HasSuffix(repoDestinationPre, "/") {
gitlabHost = envHost repoDestinationPre += "/"
} }
if envToken := os.Getenv("GITLAB_API_TOKEN"); envToken != "" {
gitlabToken = envToken
}
if gitlabHost == "" {
fmt.Println("Fatal: No GitLab Host found.")
flag.PrintDefaults()
os.Exit(1)
}
if gitlabToken == "" {
fmt.Println("Fatal: No GitLab API Token found.")
flag.PrintDefaults()
os.Exit(1)
}
} }

View file

@ -20,11 +20,6 @@ type Repository struct {
func main() { func main() {
// environment variables < arguments
if err := loadEnvironmentVariables(); err != nil {
log.Fatalf("Error loading environment variables: %v", err)
}
// manage all argument magic // manage all argument magic
manageArguments() manageArguments()