feat(cleanup): 添加启动时清理日志的功能和--cleanup标志支持

This commit is contained in:
freespace8
2025-12-07 12:28:06 +08:00
parent 1533e08425
commit 33149d9615
8 changed files with 1428 additions and 48 deletions

View File

@@ -41,6 +41,9 @@ var (
commandContext = exec.CommandContext
jsonMarshal = json.Marshal
forceKillDelay = 5 // seconds - made variable for testability
cleanupLogsFn = cleanupOldLogs
signalNotifyFn = signal.Notify
signalStopFn = signal.Stop
)
// Config holds CLI configuration
@@ -358,11 +361,27 @@ func main() {
os.Exit(exitCode)
}
func runStartupCleanup() {
if cleanupLogsFn == nil {
return
}
defer func() {
if r := recover(); r != nil {
logWarn(fmt.Sprintf("cleanupOldLogs panic: %v", r))
}
}()
if _, err := cleanupLogsFn(); err != nil {
logWarn(fmt.Sprintf("cleanupOldLogs error: %v", err))
}
}
// run is the main logic, returns exit code for testability
func run() (exitCode int) {
// Handle --version and --help first (no logger needed)
if len(os.Args) > 1 {
switch os.Args[1] {
case "--cleanup":
return runCleanupMode()
case "--version", "-v":
fmt.Printf("codex-wrapper version %s\n", version)
return 0
@@ -397,6 +416,8 @@ func run() (exitCode int) {
}()
defer runCleanupHook()
runStartupCleanup()
// Handle remaining commands
if len(os.Args) > 1 {
switch os.Args[1] {
@@ -557,6 +578,38 @@ func run() (exitCode int) {
return 0
}
func runCleanupMode() int {
if cleanupLogsFn == nil {
fmt.Fprintln(os.Stderr, "Cleanup failed: log cleanup function not configured")
return 1
}
stats, err := cleanupLogsFn()
if err != nil {
fmt.Fprintf(os.Stderr, "Cleanup failed: %v\n", err)
return 1
}
fmt.Println("Cleanup completed")
fmt.Printf("Files scanned: %d\n", stats.Scanned)
fmt.Printf("Files deleted: %d\n", stats.Deleted)
if len(stats.DeletedFiles) > 0 {
for _, f := range stats.DeletedFiles {
fmt.Printf(" - %s\n", f)
}
}
fmt.Printf("Files kept: %d\n", stats.Kept)
if len(stats.KeptFiles) > 0 {
for _, f := range stats.KeptFiles {
fmt.Printf(" - %s\n", f)
}
}
if stats.Errors > 0 {
fmt.Printf("Deletion errors: %d\n", stats.Errors)
}
return 0
}
func parseArgs() (*Config, error) {
args := os.Args[1:]
if len(args) == 0 {
@@ -925,10 +978,10 @@ func (b *tailBuffer) String() string {
func forwardSignals(ctx context.Context, cmd *exec.Cmd, logErrorFn func(string)) {
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
signalNotifyFn(sigCh, syscall.SIGINT, syscall.SIGTERM)
go func() {
defer signal.Stop(sigCh)
defer signalStopFn(sigCh)
select {
case sig := <-sigCh:
logErrorFn(fmt.Sprintf("Received signal: %v", sig))