Implement a more better logging solution

This commit is contained in:
2025-03-27 17:47:39 +01:00
parent 81d8259dfc
commit 9cea103042
7 changed files with 579 additions and 78 deletions

89
main.go
View File

@@ -13,6 +13,7 @@ import (
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing/object"
"modify/logger"
"modify/processor"
)
@@ -24,20 +25,22 @@ type GlobalStats struct {
}
var stats GlobalStats
var logger *log.Logger
var stdLogger *log.Logger // Legacy logger for compatibility
var (
jsonFlag = flag.Bool("json", false, "Process JSON files")
xmlFlag = flag.Bool("xml", false, "Process XML files")
gitFlag = flag.Bool("git", false, "Use git to manage files")
resetFlag = flag.Bool("reset", false, "Reset files to their original state")
logLevel = flag.String("loglevel", "INFO", "Set log level: ERROR, WARNING, INFO, DEBUG, TRACE")
repo *git.Repository
worktree *git.Worktree
)
func init() {
// Keep standard logger setup for compatibility with legacy code
log.SetFlags(log.Lmicroseconds | log.Lshortfile)
logger = log.New(os.Stdout, "", log.Lmicroseconds|log.Lshortfile)
stdLogger = log.New(os.Stdout, "", log.Lmicroseconds|log.Lshortfile)
stats = GlobalStats{}
}
@@ -66,6 +69,8 @@ func main() {
fmt.Fprintf(os.Stderr, " Use git to manage files\n")
fmt.Fprintf(os.Stderr, " -reset\n")
fmt.Fprintf(os.Stderr, " Reset files to their original state\n")
fmt.Fprintf(os.Stderr, " -loglevel string\n")
fmt.Fprintf(os.Stderr, " Set logging level: ERROR, WARNING, INFO, DEBUG, TRACE (default \"INFO\")\n")
fmt.Fprintf(os.Stderr, " -mode string\n")
fmt.Fprintf(os.Stderr, " Processing mode: regex, xml, json (default \"regex\")\n")
fmt.Fprintf(os.Stderr, "\nExamples:\n")
@@ -86,13 +91,19 @@ func main() {
}
flag.Parse()
// Initialize logger with the specified log level
level := logger.ParseLevel(*logLevel)
logger.Init(level)
logger.Info("Initializing with log level: %s", level.String())
args := flag.Args()
if *resetFlag {
*gitFlag = true
}
if len(args) < 3 {
log.Printf("At least %d arguments are required", 3)
logger.Error("At least %d arguments are required", 3)
flag.Usage()
return
}
@@ -109,37 +120,45 @@ func main() {
originalLuaExpr := luaExpr
luaExpr = processor.BuildLuaScript(luaExpr)
if originalLuaExpr != luaExpr {
logger.Printf("Transformed Lua expression from %q to %q", originalLuaExpr, luaExpr)
logger.Debug("Transformed Lua expression from %q to %q", originalLuaExpr, luaExpr)
}
if *gitFlag {
logger.Info("Git integration enabled, setting up git repository")
err := setupGit()
if err != nil {
logger.Error("Failed to setup git: %v", err)
fmt.Fprintf(os.Stderr, "Error setting up git: %v\n", err)
return
}
}
// Expand file patterns with glob support
logger.Debug("Expanding file patterns: %v", filePatterns)
files, err := expandFilePatterns(filePatterns)
if err != nil {
logger.Error("Failed to expand file patterns: %v", err)
fmt.Fprintf(os.Stderr, "Error expanding file patterns: %v\n", err)
return
}
if len(files) == 0 {
logger.Warning("No files found matching the specified patterns")
fmt.Fprintf(os.Stderr, "No files found matching the specified patterns\n")
return
}
if *gitFlag {
logger.Info("Cleaning up git files before processing")
err := cleanupGitFiles(files)
if err != nil {
logger.Error("Failed to cleanup git files: %v", err)
fmt.Fprintf(os.Stderr, "Error cleaning up git files: %v\n", err)
return
}
}
if *resetFlag {
logger.Info("Files reset to their original state, nothing more to do")
log.Printf("Files reset to their original state, nothing more to do")
return
}
@@ -149,15 +168,15 @@ func main() {
switch {
case *xmlFlag:
proc = &processor.XMLProcessor{}
logger.Printf("Starting XML modifier with XPath %q, expression %q on %d files",
logger.Info("Starting XML modifier with XPath %q, expression %q on %d files",
pattern, luaExpr, len(files))
case *jsonFlag:
proc = &processor.JSONProcessor{}
logger.Printf("Starting JSON modifier with JSONPath %q, expression %q on %d files",
logger.Info("Starting JSON modifier with JSONPath %q, expression %q on %d files",
pattern, luaExpr, len(files))
default:
proc = &processor.RegexProcessor{}
logger.Printf("Starting regex modifier with pattern %q, expression %q on %d files",
logger.Info("Starting regex modifier with pattern %q, expression %q on %d files",
pattern, luaExpr, len(files))
}
@@ -167,15 +186,24 @@ func main() {
wg.Add(1)
go func(file string) {
defer wg.Done()
logger.Printf("Processing file: %s", file)
logger.Debug("Processing file: %s", file)
// It's a bit fucked, maybe I could do better to call it from proc... But it'll do for now
modCount, matchCount, err := processor.Process(proc, file, pattern, luaExpr)
if err != nil {
logger.Error("Failed to process file %s: %v", file, err)
fmt.Fprintf(os.Stderr, "Failed to process file %s: %v\n", file, err)
stats.FailedFiles++
} else {
logger.Printf("Successfully processed file: %s", file)
if modCount > 0 {
logger.Info("Successfully processed file %s: %d modifications from %d matches",
file, modCount, matchCount)
} else if matchCount > 0 {
logger.Info("Found %d matches in file %s but made no modifications",
matchCount, file)
} else {
logger.Debug("No matches found in file: %s", file)
}
stats.ProcessedFiles++
stats.TotalMatches += matchCount
stats.TotalModifications += modCount
@@ -186,8 +214,11 @@ func main() {
// Print summary
if stats.TotalModifications == 0 {
logger.Warning("No modifications were made in any files")
fmt.Fprintf(os.Stderr, "No modifications were made in any files\n")
} else {
logger.Info("Operation complete! Modified %d values in %d/%d files",
stats.TotalModifications, stats.ProcessedFiles, stats.ProcessedFiles+stats.FailedFiles)
fmt.Printf("Operation complete! Modified %d values in %d/%d files\n",
stats.TotalModifications, stats.ProcessedFiles, stats.ProcessedFiles+stats.FailedFiles)
}
@@ -198,27 +229,27 @@ func setupGit() error {
if err != nil {
return fmt.Errorf("failed to get current working directory: %w", err)
}
logger.Printf("Current working directory obtained: %s", cwd)
logger.Debug("Current working directory obtained: %s", cwd)
logger.Printf("Attempting to open git repository at %s", cwd)
logger.Debug("Attempting to open git repository at %s", cwd)
repo, err = git.PlainOpen(cwd)
if err != nil {
logger.Printf("No existing git repository found at %s, attempting to initialize a new git repository.", cwd)
logger.Debug("No existing git repository found at %s, attempting to initialize a new git repository.", cwd)
repo, err = git.PlainInit(cwd, false)
if err != nil {
return fmt.Errorf("failed to initialize a new git repository at %s: %w", cwd, err)
}
logger.Printf("Successfully initialized a new git repository at %s", cwd)
logger.Info("Successfully initialized a new git repository at %s", cwd)
} else {
logger.Printf("Successfully opened existing git repository at %s", cwd)
logger.Info("Successfully opened existing git repository at %s", cwd)
}
logger.Printf("Attempting to obtain worktree for repository at %s", cwd)
logger.Debug("Attempting to obtain worktree for repository at %s", cwd)
worktree, err = repo.Worktree()
if err != nil {
return fmt.Errorf("failed to obtain worktree for repository at %s: %w", cwd, err)
}
logger.Printf("Successfully obtained worktree for repository at %s", cwd)
logger.Debug("Successfully obtained worktree for repository at %s", cwd)
return nil
}
@@ -230,45 +261,51 @@ func expandFilePatterns(patterns []string) ([]string, error) {
if err != nil {
return nil, fmt.Errorf("failed to get current working directory: %w", err)
}
logger.Debug("Expanding patterns from directory: %s", cwd)
for _, pattern := range patterns {
logger.Trace("Processing pattern: %s", pattern)
matches, _ := doublestar.Glob(os.DirFS(cwd), pattern)
log.Printf("Found %d matches for pattern %s", len(matches), pattern)
logger.Debug("Found %d matches for pattern %s", len(matches), pattern)
for _, m := range matches {
info, err := os.Stat(m)
if err != nil {
logger.Printf("Error getting file info for %s: %v", m, err)
logger.Warning("Error getting file info for %s: %v", m, err)
continue
}
if !info.IsDir() && !filesMap[m] {
logger.Trace("Adding file to process list: %s", m)
filesMap[m], files = true, append(files, m)
}
}
}
if len(files) > 0 {
logger.Printf("Found %d files to process", len(files))
logger.Debug("Found %d files to process: %v", len(files), files)
}
return files, nil
}
func cleanupGitFiles(files []string) error {
for _, file := range files {
logger.Printf("Checking file: %s", file)
logger.Debug("Checking git status for file: %s", file)
status, err := worktree.Status()
if err != nil {
logger.Error("Error getting worktree status: %v", err)
fmt.Fprintf(os.Stderr, "Error getting worktree status: %v\n", err)
return fmt.Errorf("error getting worktree status: %w", err)
}
if status.IsUntracked(file) {
logger.Printf("Detected untracked file: %s. Attempting to add it to the git index.", file)
logger.Info("Detected untracked file: %s. Adding to git index.", file)
_, err = worktree.Add(file)
if err != nil {
logger.Error("Error adding file to git: %v", err)
fmt.Fprintf(os.Stderr, "Error adding file to git: %v\n", err)
return fmt.Errorf("error adding file to git: %w", err)
}
filename := filepath.Base(file)
logger.Printf("File %s added successfully. Now committing it with message: 'Track %s'", filename, filename)
logger.Info("File %s added successfully. Committing with message: 'Track %s'", filename, filename)
_, err = worktree.Commit("Track "+filename, &git.CommitOptions{
Author: &object.Signature{
Name: "Big Chef",
@@ -277,22 +314,24 @@ func cleanupGitFiles(files []string) error {
},
})
if err != nil {
logger.Error("Error committing file: %v", err)
fmt.Fprintf(os.Stderr, "Error committing file: %v\n", err)
return fmt.Errorf("error committing file: %w", err)
}
logger.Printf("Successfully committed file: %s with message: 'Track %s'", filename, filename)
logger.Info("Successfully committed file: %s", filename)
} else {
logger.Printf("File %s is already tracked. Restoring it to the working tree.", file)
logger.Info("File %s is already tracked. Restoring it to the working tree.", file)
err := worktree.Restore(&git.RestoreOptions{
Files: []string{file},
Staged: true,
Worktree: true,
})
if err != nil {
logger.Error("Error restoring file: %v", err)
fmt.Fprintf(os.Stderr, "Error restoring file: %v\n", err)
return fmt.Errorf("error restoring file: %w", err)
}
logger.Printf("File %s restored successfully.", file)
logger.Info("File %s restored successfully", file)
}
}
return nil