fix: moved logging functions to its own package

This commit is contained in:
Simon Cornet 2025-03-06 08:47:02 +01:00
commit 13602ae71c
6 changed files with 64 additions and 55 deletions

View file

@ -2,6 +2,7 @@ package main
import ( import (
"fmt" "fmt"
"gogitlabber/cmd/gogitlabber/logging"
"os/exec" "os/exec"
"strings" "strings"
"sync" "sync"
@ -37,7 +38,7 @@ func checkoutRepositories(repositories []Repository, concurrency int) {
repoDestination := repoDestinationPre + repoName repoDestination := repoDestinationPre + repoName
// log activity // log activity
logPrint("Starting on repository: "+repoName, nil) logging.LogPrint(debug, "Starting on repository: "+repoName, nil)
// make gitlab url // make gitlab url
url := fmt.Sprintf("https://gitlab-token:%s@%s/%s.git", gitlabToken, gitlabHost, repoName) url := fmt.Sprintf("https://gitlab-token:%s@%s/%s.git", gitlabToken, gitlabHost, repoName)
@ -46,7 +47,7 @@ func checkoutRepositories(repositories []Repository, concurrency int) {
checkRepo := func(repoDestination string) string { checkRepo := func(repoDestination string) string {
checkCmd := exec.Command("git", "-C", repoDestination, "remote", "-v") checkCmd := exec.Command("git", "-C", repoDestination, "remote", "-v")
checkOutput, _ := checkCmd.CombinedOutput() checkOutput, _ := checkCmd.CombinedOutput()
logPrint("Checking status for repository: "+repoName, nil) logging.LogPrint(debug, "Checking status for repository: "+repoName, nil)
return string(checkOutput) return string(checkOutput)
} }
@ -58,19 +59,19 @@ func checkoutRepositories(repositories []Repository, concurrency int) {
case strings.Contains(string(repoStatus), "No such file or directory"): case strings.Contains(string(repoStatus), "No such file or directory"):
// log activity // log activity
logPrint("Decided to clone repository: "+repoName, nil) logging.LogPrint(debug, "Decided to clone repository: "+repoName, nil)
// clone the repo // clone the repo
cloneRepository := func(repoDestination string, url string) (string, error) { cloneRepository := func(repoDestination string, url string) (string, error) {
cloneCmd := exec.Command("git", "clone", url, repoDestination) cloneCmd := exec.Command("git", "clone", url, repoDestination)
cloneOutput, err := cloneCmd.CombinedOutput() cloneOutput, err := cloneCmd.CombinedOutput()
logPrint("Cloning repository: "+repoName+" to "+repoDestination, nil) logging.LogPrint(debug, "Cloning repository: "+repoName+" to "+repoDestination, nil)
return string(cloneOutput), err return string(cloneOutput), err
} }
_, err := cloneRepository(repoDestination, url) _, err := cloneRepository(repoDestination, url)
if err != nil { if err != nil {
logPrint("ERROR: %v\n", err) logging.LogPrint(debug, "ERROR: %v\n", err)
} }
// set a lock, increment counters, update progressbar and unlock // set a lock, increment counters, update progressbar and unlock
@ -87,7 +88,7 @@ func checkoutRepositories(repositories []Repository, concurrency int) {
// pull the latest // pull the latest
case strings.Contains(string(repoStatus), url): case strings.Contains(string(repoStatus), url):
logPrint("Decided to pull repository: "+repoName, nil) logging.LogPrint(debug, "Decided to pull repository: "+repoName, nil)
pullRepository(repoName, repoDestination) pullRepository(repoName, repoDestination)
if !debug { if !debug {
descriptionPrefixPre := "Pulling repository " descriptionPrefixPre := "Pulling repository "
@ -97,8 +98,8 @@ func checkoutRepositories(repositories []Repository, concurrency int) {
} }
default: default:
logPrint("ERROR: decided not to clone or pull repository: "+repoName, nil) logging.LogPrint(debug, "ERROR: decided not to clone or pull repository: "+repoName, nil)
logPrint("ERROR: this is why: "+repoStatus, nil) logging.LogPrint(debug, "ERROR: this is why: "+repoStatus, nil)
// set a lock, increment counters and unlock // set a lock, increment counters and unlock
mu.Lock() mu.Lock()
@ -118,7 +119,7 @@ func checkoutRepositories(repositories []Repository, concurrency int) {
func pullRepository(repoName string, repoDestination string) { func pullRepository(repoName string, repoDestination string) {
// log activity // log activity
logPrint("Pulling repository: "+repoName+" at "+repoDestination, nil) logging.LogPrint(debug, "Pulling repository: "+repoName+" at "+repoDestination, nil)
// find remote // find remote
findRemote := func(repoDestination string) (string, error) { findRemote := func(repoDestination string) (string, error) {
@ -128,9 +129,9 @@ func pullRepository(repoName string, repoDestination string) {
return "", fmt.Errorf("finding remote: %v\n", err) return "", fmt.Errorf("finding remote: %v\n", err)
} }
logPrint("Finding remote for repository: "+repoName+" at "+repoDestination, nil) logging.LogPrint(debug, "Finding remote for repository: "+repoName+" at "+repoDestination, nil)
remote := strings.Split(strings.TrimSpace(string(remoteOutput)), "\n")[0] remote := strings.Split(strings.TrimSpace(string(remoteOutput)), "\n")[0]
logPrint("Found remote; "+remote+" for repository: "+repoName+" at "+repoDestination, nil) logging.LogPrint(debug, "Found remote; "+remote+" for repository: "+repoName+" at "+repoDestination, nil)
return remote, nil return remote, nil
} }
remote, _ := findRemote(repoDestination) remote, _ := findRemote(repoDestination)
@ -155,13 +156,13 @@ func pullRepository(repoName string, repoDestination string) {
switch { switch {
case strings.Contains(string(pullOutput), "You have unstaged changes"): case strings.Contains(string(pullOutput), "You have unstaged changes"):
pullErrorMsg = append(pullErrorMsg, repoDestination) pullErrorMsg = append(pullErrorMsg, repoDestination)
logPrint("Found unstaged changes for repository: "+repoName+" at "+repoDestination, nil) logging.LogPrint(debug, "Found unstaged changes for repository: "+repoName+" at "+repoDestination, nil)
default: default:
logPrint("ERROR: pulling "+repoName, nil) logging.LogPrint(debug, "ERROR: pulling "+repoName, nil)
} }
} }
// log activity // log activity
logPrint("Pulled repository: "+repoName+" at "+repoDestination, nil) logging.LogPrint(debug, "Pulled repository: "+repoName+" at "+repoDestination, nil)
} }

View file

@ -3,6 +3,7 @@ package main
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"gogitlabber/cmd/gogitlabber/logging"
"net/http" "net/http"
) )
@ -27,16 +28,16 @@ func fetchRepositoriesGitlab() ([]Repository, error) {
url := fmt.Sprintf("https://%s/api/v4/projects?%s&%s&%s%s", url := fmt.Sprintf("https://%s/api/v4/projects?%s&%s&%s%s",
gitlabHost, membership, order, perpage, archived) gitlabHost, membership, order, perpage, archived)
logPrint("HTTP: Creating API request", nil) logging.LogPrint(debug, "HTTP: Creating API request", nil)
req, err := http.NewRequest("GET", url, nil) req, err := http.NewRequest("GET", url, nil)
if err != nil { if err != nil {
return nil, fmt.Errorf("ERROR: creating request: %v\n", err) return nil, fmt.Errorf("ERROR: creating request: %v\n", err)
} }
logPrint("HTTP: Adding PRIVATE-TOKEN header to API request", nil) logging.LogPrint(debug, "HTTP: Adding PRIVATE-TOKEN header to API request", nil)
req.Header.Set("PRIVATE-TOKEN", gitlabToken) req.Header.Set("PRIVATE-TOKEN", gitlabToken)
logPrint("HTTP: Making request", nil) logging.LogPrint(debug, "HTTP: Making request", nil)
client := &http.Client{} client := &http.Client{}
resp, err := client.Do(req) resp, err := client.Do(req)
if err != nil { if err != nil {
@ -48,7 +49,7 @@ func fetchRepositoriesGitlab() ([]Repository, error) {
return nil, fmt.Errorf("ERROR: API request failed with status: %d\n", resp.StatusCode) return nil, fmt.Errorf("ERROR: API request failed with status: %d\n", resp.StatusCode)
} }
logPrint("HTTP: Decoding JSON response", nil) logging.LogPrint(debug, "HTTP: Decoding JSON response", nil)
var repositories []Repository var repositories []Repository
if err := json.NewDecoder(resp.Body).Decode(&repositories); err != nil { if err := json.NewDecoder(resp.Body).Decode(&repositories); err != nil {
return nil, fmt.Errorf("ERROR: decoding response: %v\n", err) return nil, fmt.Errorf("ERROR: decoding response: %v\n", err)
@ -61,10 +62,10 @@ func fetchRepositoriesGitlab() ([]Repository, error) {
repoCount := len(repositories) repoCount := len(repositories)
err = bar.Set(0) err = bar.Set(0)
if err != nil { if err != nil {
logFatal("Could not reset the progressbar", err) logging.LogFatal("Could not reset the progressbar", err)
} }
bar.ChangeMax(repoCount) bar.ChangeMax(repoCount)
logPrint("HTTP: Returning repositories found", nil) logging.LogPrint(debug, "HTTP: Returning repositories found", nil)
return repositories, nil return repositories, nil
} }

View file

@ -2,6 +2,7 @@ package main
import ( import (
"flag" "flag"
"gogitlabber/cmd/gogitlabber/logging"
"os" "os"
"strconv" "strconv"
"strings" "strings"
@ -23,7 +24,7 @@ func setDefaultsFromEnv() {
if debugVal, err := strconv.ParseBool(envDebug); err == nil { if debugVal, err := strconv.ParseBool(envDebug); err == nil {
debug = debugVal debug = debugVal
} else { } else {
logPrint("Warning: Invalid debug value in environment, using default", nil) logging.LogPrint(debug, "Warning: Invalid debug value in environment, using default", nil)
} }
} }
@ -43,7 +44,7 @@ func setDefaultsFromEnv() {
if concurrencyVal, err := strconv.Atoi(envConcurrency); err == nil { if concurrencyVal, err := strconv.Atoi(envConcurrency); err == nil {
concurrency = concurrencyVal concurrency = concurrencyVal
} else { } else {
logPrint("Warning: Invalid concurrency value in environment, using default", nil) logging.LogPrint(debug, "Warning: Invalid concurrency value in environment, using default", nil)
} }
} }
@ -52,7 +53,7 @@ func setDefaultsFromEnv() {
case "any", "exclusive", "excluded": case "any", "exclusive", "excluded":
includeArchived = envArchived includeArchived = envArchived
default: default:
logPrint("Warning: Invalid archived value in environment, using default", nil) logging.LogPrint(debug, "Warning: Invalid archived value in environment, using default", nil)
} }
} }
} }
@ -111,7 +112,7 @@ func manageArguments() {
// validate required parameters // validate required parameters
if gitlabToken == "" { if gitlabToken == "" {
flag.Usage() flag.Usage()
logFatal("Configuration: Gitlab API Token not found", nil) logging.LogFatal("Configuration: Gitlab API Token not found", nil)
} }
// validate archived option // validate archived option
@ -119,15 +120,15 @@ func manageArguments() {
case "any", "exclusive", "excluded": case "any", "exclusive", "excluded":
default: default:
flag.Usage() flag.Usage()
logFatal("Configuration: Invalid archive option: "+includeArchived, nil) logging.LogFatal("Configuration: Invalid archive option: "+includeArchived, nil)
} }
// log configuration // log configuration
logPrint("Configuration: Using GitLab host: "+gitlabHost, nil) logging.LogPrint(debug, "Configuration: Using GitLab host: "+gitlabHost, nil)
logPrint("Configuration: Using destination: "+repoDestinationPre, nil) logging.LogPrint(debug, "Configuration: Using destination: "+repoDestinationPre, nil)
logPrint("Configuration: Using concurrency: "+strconv.Itoa(concurrency), nil) logging.LogPrint(debug, "Configuration: Using concurrency: "+strconv.Itoa(concurrency), nil)
logPrint("Configuration: Using archived option: "+includeArchived, nil) logging.LogPrint(debug, "Configuration: Using archived option: "+includeArchived, nil)
if debug { if debug {
logPrint("Configuration: Debug mode enabled", nil) logging.LogPrint(debug, "Configuration: Debug mode enabled", nil)
} }
} }

View file

@ -0,0 +1,23 @@
package logging
import (
"log"
)
func LogPrint(debug bool, message string, err error) {
if debug {
if err != nil {
log.Printf("gogitlabber | DEBUG: %v error: %v\n", message, err)
}
if err == nil {
log.Printf("gogitlabber | DEBUG: %v\n", message)
}
}
}
func LogFatal(message string, err error) {
if err != nil {
log.Fatalf("gogitlabber | FATAL: %v error: %v\n", message, err)
}
log.Fatalf("gogitlabber | FATAL: %v\n", message)
}

View file

@ -1,6 +1,7 @@
package main package main
import ( import (
"gogitlabber/cmd/gogitlabber/logging"
"io" "io"
"log" "log"
) )
@ -33,9 +34,9 @@ func main() {
// check for git // check for git
err := verifyGitAvailable() err := verifyGitAvailable()
if err != nil { if err != nil {
logFatal("git not found in path: %v", err) logging.LogFatal("git not found in path: %v", err)
} }
logPrint("VALIDATION: git found in path", nil) logging.LogPrint(debug, "VALIDATION: git found in path", nil)
// make initial progressbar // make initial progressbar
if !debug { if !debug {
@ -46,7 +47,7 @@ func main() {
// fetch repository information from gitlab // fetch repository information from gitlab
repositories, err := fetchRepositoriesGitlab() repositories, err := fetchRepositoriesGitlab()
if err != nil { if err != nil {
logFatal("FATAL: %v", err) logging.LogFatal("FATAL: %v", err)
} }
// manage found repositories // manage found repositories

View file

@ -2,7 +2,7 @@ package main
import ( import (
"fmt" "fmt"
"log" "gogitlabber/cmd/gogitlabber/logging"
"github.com/k0kubun/go-ansi" "github.com/k0kubun/go-ansi"
"github.com/schollz/progressbar/v3" "github.com/schollz/progressbar/v3"
@ -32,17 +32,17 @@ func progressBar() {
) )
// initialize progressbar // initialize progressbar
logPrint("Initialize progressbar", nil) logging.LogPrint(debug, "Initialize progressbar", nil)
err := bar.RenderBlank() err := bar.RenderBlank()
progressBarAdd(1) progressBarAdd(1)
if err != nil { if err != nil {
logFatal("Initialization of the progressbar failed", err) logging.LogFatal("Initialization of the progressbar failed", err)
} }
} }
func progressBarAdd(amount int) { func progressBarAdd(amount int) {
if err := bar.Add(amount); err != nil { if err := bar.Add(amount); err != nil {
logPrint("ERROR: Progress bar update error: %v\n", err) logging.LogPrint(debug, "ERROR: Progress bar update error: %v\n", err)
} }
} }
@ -67,21 +67,3 @@ func printPullError(pullErrorMsg []string) {
} }
} }
} }
func logPrint(message string, err error) {
if debug {
if err != nil {
log.Printf("gogitlabber | DEBUG: %v error: %v\n", message, err)
}
if err == nil {
log.Printf("gogitlabber | DEBUG: %v\n", message)
}
}
}
func logFatal(message string, err error) {
if err != nil {
log.Fatalf("gogitlabber | FATAL: %v error: %v\n", message, err)
}
log.Fatalf("gogitlabber | FATAL: %v\n", message)
}