From 335f6bffde6ce5abc3e8f359b67bffd19cb122ce Mon Sep 17 00:00:00 2001 From: Seednode Date: Fri, 27 Jan 2023 13:17:13 -0600 Subject: [PATCH] Combined root variable declarations into a block, changed increment/decrement functions to unexported --- cmd/files.go | 28 +++++++++++++-------------- cmd/root.go | 52 ++++++++++++++++++++++++++------------------------ cmd/version.go | 2 +- cmd/web.go | 18 ++++++++--------- 4 files changed, 51 insertions(+), 49 deletions(-) diff --git a/cmd/files.go b/cmd/files.go index 9dec930..c8ad504 100644 --- a/cmd/files.go +++ b/cmd/files.go @@ -43,7 +43,7 @@ type Concurrency struct { var ( ErrNoImagesFound = fmt.Errorf("no supported image formats found which match all criteria") - extensions = [6]string{".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"} + Extensions = [6]string{".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"} ) type Dimensions struct { @@ -102,11 +102,11 @@ type Path struct { extension string } -func (p *Path) Increment() { +func (p *Path) increment() { p.number = p.number + 1 } -func (p *Path) Decrement() { +func (p *Path) decrement() { p.number = p.number - 1 } @@ -186,7 +186,7 @@ func appendPath(directory, path string, files *Files, stats *ScanStats, shouldCa } func appendPaths(path string, files *Files, filters *Filters, stats *ScanStats) error { - shouldCache := Cache && filters.IsEmpty() + shouldCache := cache && filters.IsEmpty() absolutePath, err := filepath.Abs(path) if err != nil { @@ -259,7 +259,7 @@ func newFile(paths []string, filters *Filters, sortOrder string, Regexes *Regexe } case sortOrder == "desc": for { - path.Increment() + path.increment() filePath, err = tryExtensions(path) if err != nil { @@ -267,7 +267,7 @@ func newFile(paths []string, filters *Filters, sortOrder string, Regexes *Regexe } if filePath == "" { - path.Decrement() + path.decrement() filePath, err = tryExtensions(path) if err != nil { @@ -290,9 +290,9 @@ func nextFile(filePath, sortOrder string, Regexes *Regexes) (string, error) { switch { case sortOrder == "asc": - path.Increment() + path.increment() case sortOrder == "desc": - path.Decrement() + path.decrement() default: return "", nil } @@ -331,7 +331,7 @@ func splitPath(path string, Regexes *Regexes) (*Path, error) { func tryExtensions(p *Path) (string, error) { var fileName string - for _, extension := range extensions { + for _, extension := range Extensions { fileName = fmt.Sprintf("%s%.3d%s", p.base, p.number, extension) exists, err := fileExists(fileName) @@ -369,7 +369,7 @@ func pathIsValid(filePath string, paths []string) bool { } switch { - case Verbose && !matchesPrefix: + case verbose && !matchesPrefix: fmt.Printf("%s | Error: Failed to serve file outside specified path(s): %s\n", time.Now().Format(LogDate), filePath, @@ -408,7 +408,7 @@ func scanPath(path string, files *Files, filters *Filters, stats *ScanStats, con } switch { - case !Recursive && info.IsDir() && p != path: + case !recursive && info.IsDir() && p != path: return filepath.SkipDir case !info.IsDir(): wg.Add(1) @@ -442,7 +442,7 @@ func scanPath(path string, files *Files, filters *Filters, stats *ScanStats, con } func fileList(paths []string, filters *Filters, sort string, index *Index) ([]string, bool) { - if Cache && filters.IsEmpty() && !index.IsEmpty() { + if cache && filters.IsEmpty() && !index.IsEmpty() { return index.Index(), true } @@ -489,7 +489,7 @@ func fileList(paths []string, filters *Filters, sort string, index *Index) ([]st fileList = prepareDirectories(files, sort) - if Verbose { + if verbose { fmt.Printf("%s | Indexed %d/%d files across %d directories in %s\n", time.Now().Format(LogDate), stats.FilesMatched(), @@ -499,7 +499,7 @@ func fileList(paths []string, filters *Filters, sort string, index *Index) ([]st ) } - if Cache && filters.IsEmpty() { + if cache && filters.IsEmpty() { index.setIndex(fileList) } diff --git a/cmd/root.go b/cmd/root.go index a0cdda5..35ca96b 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -11,25 +11,27 @@ import ( "github.com/spf13/cobra" ) -var Cache bool -var Debug bool -var Filter bool -var Port uint16 -var Recursive bool -var Sort bool -var Verbose bool +var ( + cache bool + debug bool + filtering bool + port uint16 + recursive bool + sorting bool + verbose bool -var rootCmd = &cobra.Command{ - Use: "roulette [path]...", - Short: "Serves random images from the specified directories.", - Args: cobra.MinimumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { - err := ServePage(args) - if err != nil { - log.Fatal(err) - } - }, -} + rootCmd = &cobra.Command{ + Use: "roulette [path]...", + Short: "Serves random images from the specified directories.", + Args: cobra.MinimumNArgs(1), + Run: func(cmd *cobra.Command, args []string) { + err := ServePage(args) + if err != nil { + log.Fatal(err) + } + }, + } +) func Execute() { err := rootCmd.Execute() @@ -39,12 +41,12 @@ func Execute() { } func init() { - rootCmd.Flags().BoolVarP(&Cache, "cache", "c", false, "only scan directories once, at startup (or when filters are applied)") - rootCmd.Flags().BoolVarP(&Debug, "debug", "d", false, "store list of files served and number of times they were served") - rootCmd.Flags().BoolVarP(&Filter, "filter", "f", false, "enable filtering via query parameters") - rootCmd.Flags().Uint16VarP(&Port, "port", "p", 8080, "port to listen on") - rootCmd.Flags().BoolVarP(&Recursive, "recursive", "r", false, "recurse into subdirectories") - rootCmd.Flags().BoolVarP(&Sort, "sort", "s", false, "enable sorting via query parameters") - rootCmd.Flags().BoolVarP(&Verbose, "verbose", "v", false, "log accessed files to stdout") + rootCmd.Flags().BoolVarP(&cache, "cache", "c", false, "generate directory cache at startup") + rootCmd.Flags().BoolVarP(&debug, "debug", "d", false, "expose stats endpoint") + rootCmd.Flags().BoolVarP(&filtering, "filter", "f", false, "enable filtering") + rootCmd.Flags().Uint16VarP(&port, "port", "p", 8080, "port to listen on") + rootCmd.Flags().BoolVarP(&recursive, "recursive", "r", false, "recurse into subdirectories") + rootCmd.Flags().BoolVarP(&sorting, "sort", "s", false, "enable sorting") + rootCmd.Flags().BoolVarP(&verbose, "verbose", "v", false, "log accessed files to stdout") rootCmd.Flags().SetInterspersed(true) } diff --git a/cmd/version.go b/cmd/version.go index 096d8d1..5eb1301 100644 --- a/cmd/version.go +++ b/cmd/version.go @@ -10,7 +10,7 @@ import ( "github.com/spf13/cobra" ) -var Version = "0.34.0" +var Version = "0.34.1" func init() { rootCmd.AddCommand(versionCmd) diff --git a/cmd/web.go b/cmd/web.go index 7903240..c9948d9 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -159,7 +159,7 @@ type timesServed struct { func notFound(w http.ResponseWriter, r *http.Request, filePath string) error { startTime := time.Now() - if Verbose { + if verbose { fmt.Printf("%s | Unavailable file %s requested by %s\n", startTime.Format(LogDate), filePath, @@ -235,7 +235,7 @@ func generateQueryParams(filters *Filters, sortOrder, refreshInterval string) st queryParams.WriteString("?") - if Filter { + if filtering { queryParams.WriteString("include=") if filters.HasIncludes() { queryParams.WriteString(filters.Includes()) @@ -249,7 +249,7 @@ func generateQueryParams(filters *Filters, sortOrder, refreshInterval string) st hasParams = true } - if Sort { + if sorting { if hasParams { queryParams.WriteString("&") } @@ -413,7 +413,7 @@ func serveStaticFile(w http.ResponseWriter, r *http.Request, paths []string, sta fileSize := humanReadableSize(len(buf)) - if Verbose { + if verbose { fmt.Printf("%s | Served %s (%s) to %s in %s\n", startTime.Format(LogDate), filePath, @@ -423,7 +423,7 @@ func serveStaticFile(w http.ResponseWriter, r *http.Request, paths []string, sta ) } - if Debug { + if debug { stats.incrementCounter(filePath, startTime, fileSize) } @@ -454,7 +454,7 @@ func serveStatsHandler(args []string, stats *ServeStats) http.HandlerFunc { w.Write(response) - if Verbose { + if verbose { fmt.Printf("%s | Served statistics page (%s) to %s in %s\n", startTime.Format(LogDate), humanReadableSize(len(response)), @@ -584,7 +584,7 @@ func ServePage(args []string) error { list: []string{}, } - if Cache { + if cache { index.generateCache(args) http.Handle("/_/clear_cache", serveCacheClearHandler(args, index)) @@ -602,11 +602,11 @@ func ServePage(args []string) error { http.Handle(Prefix+"/", http.StripPrefix(Prefix, serveStaticFileHandler(paths, stats))) http.HandleFunc("/favicon.ico", doNothing) - if Debug { + if debug { http.Handle("/_/stats", serveStatsHandler(args, stats)) } - err = http.ListenAndServe(":"+strconv.FormatInt(int64(Port), 10), nil) + err = http.ListenAndServe(":"+strconv.FormatInt(int64(port), 10), nil) if err != nil { return err }