From c075a6a843045f143bd9202b3cc5ebc16cc3c2fe Mon Sep 17 00:00:00 2001 From: Linghua Zhang Date: Fri, 5 Jan 2024 19:08:53 +0900 Subject: [PATCH 1/4] refactor: migrate to new logger --- go.mod | 7 ++-- go.sum | 20 +++++++----- internal/cache/file_cache.go | 8 ++--- internal/cmd/create.go | 11 +++---- internal/cmd/preview.go | 6 ++-- internal/cmd/root.go | 12 +++++-- internal/cmd/version.go | 5 +-- internal/config/file_config.go | 4 +-- internal/export/default_context.go | 8 ++--- internal/export/export.go | 4 +-- internal/export/export_test.go | 4 +-- internal/images/image.go | 4 +-- internal/indexer/indexer.go | 6 ++-- internal/log/log.go | 51 ------------------------------ internal/utils/error.go | 7 ++-- 15 files changed, 56 insertions(+), 101 deletions(-) delete mode 100644 internal/log/log.go diff --git a/go.mod b/go.mod index cef2fa5..dda6f5f 100644 --- a/go.mod +++ b/go.mod @@ -5,9 +5,9 @@ go 1.18 require ( github.com/chelnak/ysmrr v0.3.0 github.com/disintegration/imaging v1.6.2 - github.com/gookit/color v1.5.4 github.com/mitchellh/mapstructure v1.5.0 github.com/otiai10/copy v1.14.0 + github.com/rs/zerolog v1.31.0 github.com/spf13/cobra v1.8.0 github.com/spf13/viper v1.18.2 github.com/stretchr/testify v1.8.4 @@ -34,12 +34,11 @@ require ( github.com/stretchr/objx v0.5.0 // indirect github.com/subosito/gotenv v1.6.0 // indirect github.com/tdewolff/parse/v2 v2.7.7 // indirect - github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect go.uber.org/multierr v1.11.0 // indirect golang.org/x/exp v0.0.0-20240103183307-be819d1f06fc // indirect golang.org/x/image v0.14.0 // indirect - golang.org/x/sync v0.5.0 // indirect - golang.org/x/sys v0.15.0 // indirect + golang.org/x/sync v0.6.0 // indirect + golang.org/x/sys v0.16.0 // indirect golang.org/x/text v0.14.0 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect diff --git a/go.sum b/go.sum index f5817fb..47a0059 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,6 @@ github.com/chelnak/ysmrr v0.3.0 h1:eBm6PvNnjAV920MOEwCzCG3gLn+EFGUf4Go+t+T2/Ps= github.com/chelnak/ysmrr v0.3.0/go.mod h1:HedVxtqeGSPnSS7qDRtq4vPVGoz8DXcCr9jvjF263rQ= +github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -12,9 +13,8 @@ github.com/fatih/color v1.16.0/go.mod h1:fL2Sau1YI5c0pdGEVCbKQbLXB6edEj1ZgiY4Nij github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= +github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= -github.com/gookit/color v1.5.4 h1:FZmqs7XOyGgCAxmWyPslpiok1k05wmY3SJTytgvYFs0= -github.com/gookit/color v1.5.4/go.mod h1:pZJOeOS8DM43rXbp4AZo1n9zCU2qjpcRko0b6/QJi9w= github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= @@ -26,6 +26,7 @@ github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3v github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= @@ -35,10 +36,14 @@ github.com/otiai10/copy v1.14.0/go.mod h1:ECfuL02W+/FkTWZWgQqXPWZgW9oeKCSQ5qVfSc github.com/otiai10/mint v1.5.1 h1:XaPLeE+9vGbuyEHem1JNk3bYc7KKqyI/na0/mLd/Kks= github.com/pelletier/go-toml/v2 v2.1.1 h1:LWAJwfNvjQZCFIDKWYQaM62NcYeYViCmWIwmOStowAI= github.com/pelletier/go-toml/v2 v2.1.1/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= +github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= +github.com/rs/zerolog v1.31.0 h1:FcTR3NnLWW+NnTwwhFWiJSZr4ECLpqCm6QsEnyvbV4A= +github.com/rs/zerolog v1.31.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6keLGt6kNQ= github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4= @@ -72,8 +77,6 @@ github.com/tdewolff/parse/v2 v2.7.7 h1:V+50eFDH7Piw4IBwH8D8FtYeYbZp3T4SCtIvmBSIM github.com/tdewolff/parse/v2 v2.7.7/go.mod h1:3FbJWZp3XT9OWVN3Hmfp0p/a08v4h8J9W1aghka0soA= github.com/tdewolff/test v1.0.11-0.20231101010635-f1265d231d52 h1:gAQliwn+zJrkjAHVcBEYW/RFvd2St4yYimisvozAYlA= github.com/tdewolff/test v1.0.11-0.20231101010635-f1265d231d52/go.mod h1:6DAvZliBAAnD7rhVgwaM7DE5/d9NMOAJ09SqYqeK4QE= -github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no= -github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= golang.org/x/exp v0.0.0-20240103183307-be819d1f06fc h1:ao2WRsKSzW6KuUY9IWPwWahcHCgR0s52IfwutMfEbdM= @@ -81,12 +84,13 @@ golang.org/x/exp v0.0.0-20240103183307-be819d1f06fc/go.mod h1:iRJReGqOEeBhDZGkGb golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= golang.org/x/image v0.14.0 h1:tNgSxAFe3jC4uYqvZdTr84SZoM1KfwdC9SKIFrLjFn4= golang.org/x/image v0.14.0/go.mod h1:HUYqC05R2ZcZ3ejNQsIHQDQiwWM4JBqmm6MKANTp4LE= -golang.org/x/sync v0.5.0 h1:60k92dhOjHxJkrqnwsfl8KuaHbn/5dl0lUPUklKo3qE= -golang.org/x/sync v0.5.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.6.0 h1:5BMeUDZ7vkXGfEr1x9B4bRcTH4lpkTkpdh0T/J+qjbQ= +golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc= -golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.16.0 h1:xWw16ngr6ZMtmxDyKyIgsE93KNKz5HKmMa3b8ALHidU= +golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= diff --git a/internal/cache/file_cache.go b/internal/cache/file_cache.go index 8e89e84..44e7ef7 100644 --- a/internal/cache/file_cache.go +++ b/internal/cache/file_cache.go @@ -6,8 +6,8 @@ import ( "sync" cp "github.com/otiai10/copy" + "github.com/rs/zerolog/log" "github.com/waynezhang/foto/internal/files" - "github.com/waynezhang/foto/internal/log" ) // Implenmentation @@ -36,7 +36,7 @@ func (cache folderCache) AddImage(src string, width int, file string) { } path := cache.imagePath(*checksum, width) - log.Debug("Add cache image %s for %s", path, src) + log.Debug().Msgf("Add cache image %s for %s", path, src) err = files.EnsureParentDirectory(path) if err != nil { return @@ -48,7 +48,7 @@ func (cache folderCache) AddImage(src string, width int, file string) { func (cache folderCache) CachedImage(src string, width int) *string { checksum, err := files.Checksum(src) if err != nil { - log.Fatal("Failed to generate file hash %s (%s).", src, err.Error()) + log.Warn().Msgf("Failed to generate file hash %s (%s).", src, err.Error()) return nil } @@ -63,7 +63,7 @@ func (cache folderCache) CachedImage(src string, width int) *string { func (cache folderCache) Clear() { dir := cache.directoryName if !files.IsExisting(dir) { - log.Fatal("Failed to find cache directory %s.", dir) + log.Warn().Msgf("Failed to find cache directory %s.", dir) } files.PruneDirectory(dir) } diff --git a/internal/cmd/create.go b/internal/cmd/create.go index 94c67c4..6552cdc 100644 --- a/internal/cmd/create.go +++ b/internal/cmd/create.go @@ -2,14 +2,13 @@ package cmd import ( "io/fs" - "os" "path/filepath" "strings" + "github.com/rs/zerolog/log" "github.com/spf13/cobra" staticFs "github.com/waynezhang/foto/fs" "github.com/waynezhang/foto/internal/files" - "github.com/waynezhang/foto/internal/log" "github.com/waynezhang/foto/internal/utils" ) @@ -25,17 +24,15 @@ var CreateCmd = func() *cobra.Command { func create(cmd *cobra.Command, args []string) { if len(args) != 1 { - log.Fatal("Directory argument not found") - os.Exit(1) + log.Fatal().Msg("Directory argument not found") } targetPath := args[0] if files.IsExisting(targetPath) { - log.Fatal("Directory " + targetPath + " already exists.") - os.Exit(1) + log.Fatal().Msg("Directory " + targetPath + " already exists.") } - log.Debug("Creating directory %s...", targetPath) + log.Debug().Msgf("Creating directory %s...", targetPath) err := files.EnsureDirectory(targetPath) utils.CheckFatalError(err, "Failed to create directory") diff --git a/internal/cmd/preview.go b/internal/cmd/preview.go index fffa003..3be7102 100644 --- a/internal/cmd/preview.go +++ b/internal/cmd/preview.go @@ -6,12 +6,12 @@ import ( "net/http" "strings" + "github.com/rs/zerolog/log" "github.com/spf13/cobra" "github.com/waynezhang/foto/internal/config" "github.com/waynezhang/foto/internal/constants" "github.com/waynezhang/foto/internal/images" "github.com/waynezhang/foto/internal/indexer" - "github.com/waynezhang/foto/internal/log" "github.com/waynezhang/foto/internal/utils" ) @@ -29,7 +29,7 @@ var PreviewCmd = func() *cobra.Command { }() func preview(cmd *cobra.Command, args []string) { - log.Debug("Creating Preview...") + log.Debug().Msg("Creating Preview...") config := config.Shared() index, err := indexer.Build(config.GetSectionMetadata(), config.GetExtractOption()) @@ -61,7 +61,7 @@ func preview(cmd *cobra.Command, args []string) { http.Handle(path, http.StripPrefix(path, dir)) } - log.Info("Server started -> http://localhost:%d", port) + log.Info().Msgf("Server started -> http://localhost:%d", port) err = http.ListenAndServe(fmt.Sprintf(":%d", port), nil) utils.CheckFatalError(err, "Failed to listen the port") } diff --git a/internal/cmd/root.go b/internal/cmd/root.go index 19335a9..6ca1dcf 100644 --- a/internal/cmd/root.go +++ b/internal/cmd/root.go @@ -1,8 +1,11 @@ package cmd import ( + "os" + + "github.com/rs/zerolog" + "github.com/rs/zerolog/log" "github.com/spf13/cobra" - "github.com/waynezhang/foto/internal/log" "github.com/waynezhang/foto/internal/utils" ) @@ -15,7 +18,12 @@ func Execute() { _ = cmd.Help() }, PersistentPreRun: func(cmd *cobra.Command, args []string) { - log.SetVerbose(verbose) + log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}) + if verbose { + zerolog.SetGlobalLevel(zerolog.DebugLevel) + } else { + zerolog.SetGlobalLevel(zerolog.InfoLevel) + } }, } diff --git a/internal/cmd/version.go b/internal/cmd/version.go index df748bd..a9e8ead 100644 --- a/internal/cmd/version.go +++ b/internal/cmd/version.go @@ -1,8 +1,9 @@ package cmd import ( + "fmt" + "github.com/spf13/cobra" - "github.com/waynezhang/foto/internal/log" ) var Version = "" @@ -12,6 +13,6 @@ var VersionCmd = &cobra.Command{ Use: "version", Short: "Print the version", Run: func(cmd *cobra.Command, args []string) { - log.Println("foto v%s+%s", Version, Revision) + fmt.Printf("foto v%s+%s\n", Version, Revision) }, } diff --git a/internal/config/file_config.go b/internal/config/file_config.go index 28c9be6..ab61f65 100644 --- a/internal/config/file_config.go +++ b/internal/config/file_config.go @@ -1,9 +1,9 @@ package config import ( + "github.com/rs/zerolog/log" "github.com/spf13/viper" "github.com/waynezhang/foto/internal/constants" - "github.com/waynezhang/foto/internal/log" "github.com/waynezhang/foto/internal/utils" ) @@ -30,7 +30,7 @@ func NewFileConfig(file string) Config { v.UnmarshalKey("image", &config.option) v.UnmarshalKey("others.folders", &config.otherFolders) - log.Debug("Config parsed: %v", config) + log.Debug().Msgf("Config parsed: %v", config) return config } diff --git a/internal/export/default_context.go b/internal/export/default_context.go index 9236738..66dc440 100644 --- a/internal/export/default_context.go +++ b/internal/export/default_context.go @@ -8,12 +8,12 @@ import ( "sync" cp "github.com/otiai10/copy" + "github.com/rs/zerolog/log" "github.com/waynezhang/foto/internal/cache" "github.com/waynezhang/foto/internal/config" "github.com/waynezhang/foto/internal/files" "github.com/waynezhang/foto/internal/images" "github.com/waynezhang/foto/internal/indexer" - "github.com/waynezhang/foto/internal/log" mm "github.com/waynezhang/foto/internal/minimize" "github.com/waynezhang/foto/internal/utils" ) @@ -61,7 +61,7 @@ func (ctx defaultExportContext) exportPhotos( err = resizeImageAndCache(srcPath, originalPath, originalWidth, cache) utils.CheckFatalError(err, "Failed to generate original image") - log.Debug("Processing image %s", srcPath) + log.Debug().Msgf("Processing image %s", srcPath) if postProgressFn != nil { postProgressFn(srcPath) } @@ -98,7 +98,7 @@ func (ctx defaultExportContext) processOtherFolders(folders []string, outputPath } if err := cp.Copy(folder, targetFolder); err != nil { - log.Fatal("Failed to copy folder %s to %s (%s).", folder, targetFolder, err) + log.Error().Msgf("Failed to copy folder %s to %s (%s).", folder, targetFolder, err) } _ = filepath.WalkDir(targetFolder, func(path string, d fs.DirEntry, err error) error { if minimizer.Minimizable(path) { @@ -112,7 +112,7 @@ func (ctx defaultExportContext) processOtherFolders(folders []string, outputPath func resizeImageAndCache(src string, to string, width int, cache cache.Cache) error { cached := cache.CachedImage(src, width) if cached != nil { - log.Debug("Found cached image for %s", src) + log.Debug().Msgf("Found cached image for %s", src) err := cp.Copy(*cached, to) if err == nil { return nil diff --git a/internal/export/export.go b/internal/export/export.go index 40db09b..3947c67 100644 --- a/internal/export/export.go +++ b/internal/export/export.go @@ -5,12 +5,12 @@ import ( "github.com/chelnak/ysmrr" "github.com/chelnak/ysmrr/pkg/animations" + "github.com/rs/zerolog/log" "github.com/waynezhang/foto/internal/cache" "github.com/waynezhang/foto/internal/config" "github.com/waynezhang/foto/internal/constants" "github.com/waynezhang/foto/internal/files" "github.com/waynezhang/foto/internal/indexer" - "github.com/waynezhang/foto/internal/log" mm "github.com/waynezhang/foto/internal/minimize" "github.com/waynezhang/foto/internal/utils" ) @@ -88,7 +88,7 @@ func export( }) indexPath := files.OutputIndexFilePath(outputPath) - log.Debug("Exporting photos to %s", indexPath) + log.Debug().Msgf("Exporting photos to %s", indexPath) ctx.generateIndexHtml(cfg, constants.TemplateFilePath, section, indexPath, minimizer) ctx.processOtherFolders(cfg.GetOtherFolders(), outputPath, minimizer, func(src string, dst string) { diff --git a/internal/export/export_test.go b/internal/export/export_test.go index bda280d..7209550 100644 --- a/internal/export/export_test.go +++ b/internal/export/export_test.go @@ -244,8 +244,8 @@ func TestProcessOtherFolders(t *testing.T) { file1 := filepath.Join(tmp, collection1Folder, testdata.Collection1FileName1) file2 := filepath.Join(tmp, collection2Folder, testdata.Collection2FileName1) - assert.True(t, true, files.IsExisting(file1)) - assert.True(t, true, files.IsExisting(file2)) + assert.True(t, files.IsExisting(file1)) + assert.True(t, files.IsExisting(file2)) mockFunc.AssertNumberOfCalls(t, "messageFunc", 2) // 2 folders diff --git a/internal/images/image.go b/internal/images/image.go index e1f1621..05300ff 100644 --- a/internal/images/image.go +++ b/internal/images/image.go @@ -9,8 +9,8 @@ import ( "strings" "github.com/disintegration/imaging" + "github.com/rs/zerolog/log" "github.com/waynezhang/foto/internal/files" - "github.com/waynezhang/foto/internal/log" ) type ImageSize struct { @@ -41,7 +41,7 @@ func AspectedHeight(size ImageSize, width int) int { } func ResizeImage(src string, to string, width int) error { - log.Debug("Resizing %s to %d", src, width) + log.Debug().Msgf("Resizing %s to %d", src, width) data, err := ResizeData(src, width) if err != nil { return err diff --git a/internal/indexer/indexer.go b/internal/indexer/indexer.go index 18b37d3..7d93378 100644 --- a/internal/indexer/indexer.go +++ b/internal/indexer/indexer.go @@ -9,9 +9,9 @@ import ( "sort" "sync" + "github.com/rs/zerolog/log" "github.com/waynezhang/foto/internal/config" "github.com/waynezhang/foto/internal/images" - "github.com/waynezhang/foto/internal/log" ) type Section struct { @@ -44,7 +44,7 @@ func Build(metadata []config.SectionMetadata, option config.ExtractOption) ([]Se return nil, fmt.Errorf("Slug \"%s\" already exists. Slug needs to be unique.", slug) } - log.Debug("Extacting section [%s][/%s] %s", val.Title, val.Slug, val.Folder) + log.Debug().Msgf("Extacting section [%s][/%s] %s", val.Title, val.Slug, val.Folder) s := Section{ Title: val.Title, Text: val.Text, @@ -83,7 +83,7 @@ func buildImageSets(folder string, ascending bool, option config.ExtractOption) sets = append(sets, *s) mutext.Unlock() } else { - log.Fatal("Failed to extract info from %s (%v)", src, err) + log.Warn().Msgf("Failed to extract info from %s (%v)", src, err) } }(path) diff --git a/internal/log/log.go b/internal/log/log.go deleted file mode 100644 index f4ed701..0000000 --- a/internal/log/log.go +++ /dev/null @@ -1,51 +0,0 @@ -package log - -import ( - "fmt" - "sync" - - "github.com/gookit/color" -) - -func Debug(format string, a ...interface{}) { Shared().debug(format, a...) } -func Info(format string, a ...interface{}) { Shared().info(format, a...) } -func Println(format string, a ...interface{}) { Shared().println(format, a...) } -func Fatal(format string, a ...interface{}) { Shared().fatal(format, a...) } - -func SetVerbose(v bool) { Shared().verbose = v } - -type logger struct { - verbose bool -} - -var ( - once sync.Once - instance logger -) - -func Shared() *logger { - once.Do(func() { - instance = logger{verbose: false} - }) - - return &instance -} - -func (l *logger) debug(format string, a ...interface{}) { - if l.verbose { - fmt.Printf(format+"\n", a...) - } -} - -func (l *logger) info(format string, a ...interface{}) { - color.Info.Printf(format+"\n", a...) -} - -func (l *logger) println(format string, a ...interface{}) { - fmt.Printf(format+"\n", a...) -} - -func (l *logger) fatal(format string, a ...interface{}) { - str := fmt.Sprintf(format, a...) - color.Println("ERROR: " + str) -} diff --git a/internal/utils/error.go b/internal/utils/error.go index c4785fb..b272a27 100644 --- a/internal/utils/error.go +++ b/internal/utils/error.go @@ -1,9 +1,7 @@ package utils import ( - "os" - - "github.com/waynezhang/foto/internal/log" + "github.com/rs/zerolog/log" ) func CheckFatalError(err error, errMessage string) { @@ -11,6 +9,5 @@ func CheckFatalError(err error, errMessage string) { return } - log.Fatal("%s (%s)", errMessage, err) - os.Exit(1) + log.Fatal().Msgf("%s (%s)", errMessage, err) } From ec097bf8002ba27eabbd2a1d2bee372e78e0a11b Mon Sep 17 00:00:00 2001 From: Linghua Zhang Date: Fri, 5 Jan 2024 19:33:23 +0900 Subject: [PATCH 2/4] fix: show error if failed to clean output directory --- internal/export/export.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/export/export.go b/internal/export/export.go index 3947c67..e6f71bd 100644 --- a/internal/export/export.go +++ b/internal/export/export.go @@ -72,7 +72,7 @@ func export( spinnerMsg("removing directory %s", outputPath) err := ctx.cleanDirectory(outputPath) if err != nil { - return err + utils.CheckFatalError(err, "Failed to remove directory.") } spinnerMsg("building index") From 460f56d141f7b4eaf333cc87fad4553485a4ce0e Mon Sep 17 00:00:00 2001 From: Linghua Zhang Date: Fri, 5 Jan 2024 19:34:39 +0900 Subject: [PATCH 3/4] chore: remove some lint warnings --- internal/cache/file_cache.go | 2 +- internal/config/file_config.go | 6 +++--- internal/export/export.go | 10 ++++------ internal/export/export_test.go | 10 +++++----- internal/files/directory_test.go | 8 ++++---- internal/images/image_test.go | 4 ++-- internal/indexer/indexer_test.go | 8 ++++---- 7 files changed, 23 insertions(+), 25 deletions(-) diff --git a/internal/cache/file_cache.go b/internal/cache/file_cache.go index 44e7ef7..d0d36e0 100644 --- a/internal/cache/file_cache.go +++ b/internal/cache/file_cache.go @@ -65,7 +65,7 @@ func (cache folderCache) Clear() { if !files.IsExisting(dir) { log.Warn().Msgf("Failed to find cache directory %s.", dir) } - files.PruneDirectory(dir) + _ = files.PruneDirectory(dir) } func (cache folderCache) imagePath(checksum string, width int) string { diff --git a/internal/config/file_config.go b/internal/config/file_config.go index ab61f65..acee640 100644 --- a/internal/config/file_config.go +++ b/internal/config/file_config.go @@ -26,9 +26,9 @@ func NewFileConfig(file string) Config { config := fileConfig{v: v} - v.UnmarshalKey("section", &config.sections) - v.UnmarshalKey("image", &config.option) - v.UnmarshalKey("others.folders", &config.otherFolders) + _ = v.UnmarshalKey("section", &config.sections) + _ = v.UnmarshalKey("image", &config.option) + _ = v.UnmarshalKey("others.folders", &config.otherFolders) log.Debug().Msgf("Config parsed: %v", config) diff --git a/internal/export/export.go b/internal/export/export.go index e6f71bd..1a86e6c 100644 --- a/internal/export/export.go +++ b/internal/export/export.go @@ -15,8 +15,8 @@ import ( "github.com/waynezhang/foto/internal/utils" ) -func Export(outputPath string, minimize bool) error { - return export( +func Export(outputPath string, minimize bool) { + export( config.Shared(), outputPath, minimizer(minimize), @@ -57,7 +57,7 @@ func export( minimizer mm.Minimizer, cache cache.Cache, ctx context, -) error { +) { sm := ysmrr.NewSpinnerManager( ysmrr.WithAnimation(animations.Dots), ) @@ -79,7 +79,7 @@ func export( photosDirectory := files.OutputPhotosFilePath(outputPath) section, err := ctx.buildIndex(cfg) if err != nil { - ctx.cleanDirectory(outputPath) + _ = ctx.cleanDirectory(outputPath) utils.CheckFatalError(err, "Failed to build index.") } @@ -99,8 +99,6 @@ func export( spinner.Complete() sm.Stop() - - return nil } func minimizer(minimize bool) mm.Minimizer { diff --git a/internal/export/export_test.go b/internal/export/export_test.go index 7209550..e608d0b 100644 --- a/internal/export/export_test.go +++ b/internal/export/export_test.go @@ -134,8 +134,8 @@ func TestExport(t *testing.T) { var section1 indexer.Section var section2 indexer.Section - mapstructure.Decode(testdata.Collection1, §ion1) - mapstructure.Decode(testdata.Collection1, §ion2) + _ = mapstructure.Decode(testdata.Collection1, §ion1) + _ = mapstructure.Decode(testdata.Collection1, §ion2) sections := []indexer.Section{section1, section2} mockCtx := new(MockContext) @@ -164,7 +164,7 @@ func TestCleanDirectory(t *testing.T) { defer os.RemoveAll(tmp) ctx := defaultExportContext{} - ctx.cleanDirectory(tmp) + _ = ctx.cleanDirectory(tmp) assert.False(t, files.IsExisting(tmp)) } @@ -174,8 +174,8 @@ func TestExportPhotos(t *testing.T) { var section1 indexer.Section var section2 indexer.Section - mapstructure.Decode(testdata.Collection1, §ion1) - mapstructure.Decode(testdata.Collection1, §ion2) + _ = mapstructure.Decode(testdata.Collection1, §ion1) + _ = mapstructure.Decode(testdata.Collection1, §ion2) sections := []indexer.Section{section1, section2} mockFunc := new(MockFunc) diff --git a/internal/files/directory_test.go b/internal/files/directory_test.go index 3169cbf..46a0125 100644 --- a/internal/files/directory_test.go +++ b/internal/files/directory_test.go @@ -16,20 +16,20 @@ func TestDirectoryManipulating(t *testing.T) { assert.True(t, IsExisting(tmp)) dir1 := filepath.Join(tmp, "parent1", "child1") - EnsureDirectory(dir1) + _ = EnsureDirectory(dir1) assert.True(t, IsExisting(dir1)) // no failure to create existing directory - EnsureParentDirectory(dir1) + _ = EnsureParentDirectory(dir1) assert.True(t, IsExisting(dir1)) dir2Parent := filepath.Join(tmp, "parent2") dir2 := filepath.Join(dir2Parent, "child2") - EnsureParentDirectory(dir2) + _ = EnsureParentDirectory(dir2) assert.True(t, IsExisting(dir2Parent)) assert.False(t, IsExisting(dir2)) - PruneDirectory(tmp) + _ = PruneDirectory(tmp) assert.False(t, IsExisting(tmp)) } diff --git a/internal/images/image_test.go b/internal/images/image_test.go index 0121fe2..070abdb 100644 --- a/internal/images/image_test.go +++ b/internal/images/image_test.go @@ -23,7 +23,7 @@ func TestGetPhotoSize(t *testing.T) { assert.Equal(t, testdata.TestfileHeight, size.Height) // test against image with orientation data - size, err = GetPhotoSize(testdata.RotatedImageFile) + size, _ = GetPhotoSize(testdata.RotatedImageFile) assert.Equal(t, testdata.RotatedImageWidth, size.Width) assert.Equal(t, testdata.RotatedImageHeight, size.Height) @@ -49,7 +49,7 @@ func TestResizeImage(t *testing.T) { err = ResizeImage(testdata.Testfile, path, testdata.ThumbnailWidth) assert.Nil(t, err) - checksum, err := files.Checksum(path) + checksum, _ := files.Checksum(path) assert.Equal(t, testdata.ExpectedThubmnailChecksum, *checksum) } diff --git a/internal/indexer/indexer_test.go b/internal/indexer/indexer_test.go index 9d6585d..8675962 100644 --- a/internal/indexer/indexer_test.go +++ b/internal/indexer/indexer_test.go @@ -29,8 +29,8 @@ func TestValidSlug(t *testing.T) { func TestBuild(t *testing.T) { var meta1 config.SectionMetadata var meta2 config.SectionMetadata - mapstructure.Decode(testdata.Collection1, &meta1) - mapstructure.Decode(testdata.Collection2, &meta2) + _ = mapstructure.Decode(testdata.Collection1, &meta1) + _ = mapstructure.Decode(testdata.Collection2, &meta2) data := []config.SectionMetadata{meta1, meta2} @@ -49,8 +49,8 @@ func TestBuild(t *testing.T) { func TestBuildDuplicatedSlugs(t *testing.T) { var meta1 config.SectionMetadata var meta2 config.SectionMetadata - mapstructure.Decode(testdata.Collection1, &meta1) - mapstructure.Decode(testdata.Collection2, &meta2) + _ = mapstructure.Decode(testdata.Collection1, &meta1) + _ = mapstructure.Decode(testdata.Collection2, &meta2) meta2.Slug = meta1.Slug data := []config.SectionMetadata{meta1, meta2} From 3dc7b96d47327c937f695fee5fe911f4bf9b77d1 Mon Sep 17 00:00:00 2001 From: Linghua Zhang Date: Fri, 5 Jan 2024 21:21:25 +0900 Subject: [PATCH 4/4] fix: handle relative folders --- internal/export/default_context.go | 2 +- internal/export/export_test.go | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/internal/export/default_context.go b/internal/export/default_context.go index 66dc440..b8f213c 100644 --- a/internal/export/default_context.go +++ b/internal/export/default_context.go @@ -92,7 +92,7 @@ func (ctx defaultExportContext) generateIndexHtml(cfg config.Config, templatePat func (ctx defaultExportContext) processOtherFolders(folders []string, outputPath string, minimizer mm.Minimizer, messageFunc func(src string, dst string)) { for _, folder := range folders { - targetFolder := filepath.Join(outputPath, folder) + targetFolder := filepath.Join(outputPath, filepath.Base(folder)) if messageFunc != nil { messageFunc(folder, targetFolder) } diff --git a/internal/export/export_test.go b/internal/export/export_test.go index e608d0b..c3d7a10 100644 --- a/internal/export/export_test.go +++ b/internal/export/export_test.go @@ -223,6 +223,8 @@ func TestGenerateIndexHTML(t *testing.T) { func TestProcessOtherFolders(t *testing.T) { tmp, _ := prepareTempDirAndCache(t) + tmp = "/tmp/a" + files.EnsureDirectory(tmp) defer os.RemoveAll(tmp) mockMinimizer := new(MockMinimizer) @@ -242,8 +244,8 @@ func TestProcessOtherFolders(t *testing.T) { collection2Folder, }, tmp, mockMinimizer, messageFunc) - file1 := filepath.Join(tmp, collection1Folder, testdata.Collection1FileName1) - file2 := filepath.Join(tmp, collection2Folder, testdata.Collection2FileName1) + file1 := filepath.Join(tmp, filepath.Base(collection1Folder), testdata.Collection1FileName1) + file2 := filepath.Join(tmp, filepath.Base(collection2Folder), testdata.Collection2FileName1) assert.True(t, files.IsExisting(file1)) assert.True(t, files.IsExisting(file2))