feat: using github.com/scornet256/go-logger

This commit is contained in:
Simon Cornet 2025-03-06 12:03:41 +01:00
commit cf33cc31f4
10 changed files with 61 additions and 110 deletions

View file

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

View file

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

View file

@ -2,10 +2,11 @@ package main
import (
"flag"
"gogitlabber/cmd/gogitlabber/logging"
"os"
"strconv"
"strings"
"github.com/scornet256/go-logger"
)
// set default values and override values from environment variables
@ -24,7 +25,7 @@ func setDefaultsFromEnv() {
if debugVal, err := strconv.ParseBool(envDebug); err == nil {
debug = debugVal
} else {
logging.Print("Warning: Invalid debug value in environment, using default", nil)
logger.Print("Warning: Invalid debug value in environment, using default", nil)
}
}
@ -44,7 +45,7 @@ func setDefaultsFromEnv() {
if concurrencyVal, err := strconv.Atoi(envConcurrency); err == nil {
concurrency = concurrencyVal
} else {
logging.Print("Warning: Invalid concurrency value in environment, using default", nil)
logger.Print("Warning: Invalid concurrency value in environment, using default", nil)
}
}
@ -53,7 +54,7 @@ func setDefaultsFromEnv() {
case "any", "exclusive", "excluded":
includeArchived = envArchived
default:
logging.Print("Warning: Invalid archived value in environment, using default", nil)
logger.Print("Warning: Invalid archived value in environment, using default", nil)
}
}
}
@ -112,7 +113,7 @@ func manageArguments() {
// validate required parameters
if gitlabToken == "" {
flag.Usage()
logging.Fatal("Configuration: Gitlab API Token not found", nil)
logger.Fatal("Configuration: Gitlab API Token not found", nil)
}
// validate archived option
@ -120,15 +121,15 @@ func manageArguments() {
case "any", "exclusive", "excluded":
default:
flag.Usage()
logging.Fatal("Configuration: Invalid archive option: "+includeArchived, nil)
logger.Fatal("Configuration: Invalid archive option: "+includeArchived, nil)
}
// log configuration
logging.Print("Configuration: Using GitLab host: "+gitlabHost, nil)
logging.Print("Configuration: Using destination: "+repoDestinationPre, nil)
logging.Print("Configuration: Using concurrency: "+strconv.Itoa(concurrency), nil)
logging.Print("Configuration: Using archived option: "+includeArchived, nil)
logger.Print("Configuration: Using GitLab host: "+gitlabHost, nil)
logger.Print("Configuration: Using destination: "+repoDestinationPre, nil)
logger.Print("Configuration: Using concurrency: "+strconv.Itoa(concurrency), nil)
logger.Print("Configuration: Using archived option: "+includeArchived, nil)
if debug {
logging.Print("Configuration: Debug mode enabled", nil)
logger.Print("Configuration: Debug mode enabled", nil)
}
}

View file

@ -1,21 +0,0 @@
package logging
import (
"io"
"log"
)
var debug bool
// Enables debug logging if set to true. Default is false.
func SetDebug(debugSetting bool) {
debug = debugSetting
if !debug {
log.SetOutput(io.Discard)
}
}
// Returns the current debug value as a boolean.
func GetDebug() bool {
return debug
}

View file

@ -1,25 +0,0 @@
package logging
import (
"log"
)
// Prints the formatted log, taking both a message (string) and optionally
// an error as inputs.
func Print(message string, err error) {
if debug {
log.Printf(applicationName+" | LOG: %v\n", message)
if err != nil {
log.Printf(applicationName+" | ERROR: %v\n", err)
}
}
}
// Prints the fatal error and exits the application. Takes both the message and
// optionally an error as inputs.
func Fatal(message string, err error) {
log.Fatalf(applicationName+" | FATAL: %v\n", message)
if err != nil {
log.Fatalf(applicationName+" | ERROR: %v\n", err)
}
}

View file

@ -1,15 +0,0 @@
package logging
var applicationName = ""
// Sets the application name prefix used in the logoutput. Example:
// <applicationName> | ...
func SetAppName(name string) {
applicationName = name
}
// Returns the logging prefix name as string.
func GetAppName() string {
return applicationName
}

View file

@ -1,7 +1,7 @@
package main
import (
"gogitlabber/cmd/gogitlabber/logging"
"github.com/scornet256/go-logger"
)
// userdata
@ -26,21 +26,21 @@ type Repository struct {
func main() {
// set appname for logging
logging.SetAppName("gogitlabber")
// set appname for logger
logger.SetAppName("gogitlabber")
// manage all argument magic
manageArguments()
// set debugging
logging.SetDebug(debug)
logger.SetDebug(debug)
// check for git
err := verifyGitAvailable()
if err != nil {
logging.Fatal("VALIDATION: git not found in path", err)
logger.Fatal("VALIDATION: git not found in path", err)
}
logging.Print("VALIDATION: git found in path", nil)
logger.Print("VALIDATION: git found in path", nil)
// make initial progressbar
if !debug {
@ -50,7 +50,7 @@ func main() {
// fetch repository information from gitlab
repositories, err := fetchRepositoriesGitlab()
if err != nil {
logging.Fatal("Fetching repositories failed", err)
logger.Fatal("Fetching repositories failed", err)
}
// manage found repositories

View file

@ -2,10 +2,10 @@ package main
import (
"fmt"
"gogitlabber/cmd/gogitlabber/logging"
"github.com/k0kubun/go-ansi"
"github.com/schollz/progressbar/v3"
"github.com/scornet256/go-logger"
)
var bar *progressbar.ProgressBar
@ -32,18 +32,18 @@ func progressBar() {
)
// initialize progressbar
logging.Print("Initialize progressbar", nil)
logger.Print("Initialize progressbar", nil)
err := bar.RenderBlank()
progressBarAdd(1)
if err != nil {
logging.Fatal("Initialization of the progressbar failed", err)
logger.Fatal("Initialization of the progressbar failed", err)
}
}
func progressBarAdd(amount int) {
logging.Print("BAR: Progressing the bar", nil)
logger.Print("BAR: Progressing the bar", nil)
if err := bar.Add(amount); err != nil {
logging.Print("BAR: Could not update the bar", err)
logger.Print("BAR: Could not update the bar", err)
}
}