mirror of
https://github.com/Belphemur/CBZOptimizer.git
synced 2025-10-14 12:38:50 +02:00
feat: enhance optimization logic for CBR/CBZ file handling and add tests
This commit is contained in:
@@ -3,11 +3,14 @@ package utils
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/belphemur/CBZOptimizer/v2/internal/cbz"
|
||||
"github.com/belphemur/CBZOptimizer/v2/pkg/converter"
|
||||
errors2 "github.com/belphemur/CBZOptimizer/v2/pkg/converter/errors"
|
||||
"log"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type OptimizeOptions struct {
|
||||
@@ -51,9 +54,21 @@ func Optimize(options *OptimizeOptions) error {
|
||||
|
||||
convertedChapter.SetConverted()
|
||||
|
||||
// Write the converted chapter back to a CBZ file
|
||||
// Determine output path and handle CBR override logic
|
||||
outputPath := options.Path
|
||||
if !options.Override {
|
||||
originalPath := options.Path
|
||||
isCbrOverride := false
|
||||
|
||||
if options.Override {
|
||||
// For override mode, check if it's a CBR file that needs to be converted to CBZ
|
||||
pathLower := strings.ToLower(options.Path)
|
||||
if strings.HasSuffix(pathLower, ".cbr") {
|
||||
// Convert CBR to CBZ: change extension and mark for deletion
|
||||
outputPath = strings.TrimSuffix(options.Path, filepath.Ext(options.Path)) + ".cbz"
|
||||
isCbrOverride = true
|
||||
}
|
||||
// For CBZ files, outputPath remains the same (overwrite)
|
||||
} else {
|
||||
// Handle both .cbz and .cbr files - strip the extension and add _converted.cbz
|
||||
pathLower := strings.ToLower(options.Path)
|
||||
if strings.HasSuffix(pathLower, ".cbz") {
|
||||
@@ -65,11 +80,24 @@ func Optimize(options *OptimizeOptions) error {
|
||||
outputPath = options.Path + "_converted.cbz"
|
||||
}
|
||||
}
|
||||
|
||||
// Write the converted chapter to CBZ file
|
||||
err = cbz.WriteChapterToCBZ(convertedChapter, outputPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to write converted chapter: %v", err)
|
||||
}
|
||||
|
||||
// If we're overriding a CBR file, delete the original CBR after successful write
|
||||
if isCbrOverride {
|
||||
err = os.Remove(originalPath)
|
||||
if err != nil {
|
||||
// Log the error but don't fail the operation since conversion succeeded
|
||||
log.Printf("Warning: failed to delete original CBR file %s: %v", originalPath, err)
|
||||
} else {
|
||||
log.Printf("Deleted original CBR file: %s", originalPath)
|
||||
}
|
||||
}
|
||||
|
||||
log.Printf("Converted file written to: %s\n", outputPath)
|
||||
return nil
|
||||
|
||||
|
Reference in New Issue
Block a user