Combined root variable declarations into a block, changed increment/decrement functions to unexported

This commit is contained in:
Seednode 2023-01-27 13:17:13 -06:00
parent 635df29fbc
commit 335f6bffde
4 changed files with 51 additions and 49 deletions

View File

@ -43,7 +43,7 @@ type Concurrency struct {
var ( var (
ErrNoImagesFound = fmt.Errorf("no supported image formats found which match all criteria") 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 { type Dimensions struct {
@ -102,11 +102,11 @@ type Path struct {
extension string extension string
} }
func (p *Path) Increment() { func (p *Path) increment() {
p.number = p.number + 1 p.number = p.number + 1
} }
func (p *Path) Decrement() { func (p *Path) decrement() {
p.number = p.number - 1 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 { func appendPaths(path string, files *Files, filters *Filters, stats *ScanStats) error {
shouldCache := Cache && filters.IsEmpty() shouldCache := cache && filters.IsEmpty()
absolutePath, err := filepath.Abs(path) absolutePath, err := filepath.Abs(path)
if err != nil { if err != nil {
@ -259,7 +259,7 @@ func newFile(paths []string, filters *Filters, sortOrder string, Regexes *Regexe
} }
case sortOrder == "desc": case sortOrder == "desc":
for { for {
path.Increment() path.increment()
filePath, err = tryExtensions(path) filePath, err = tryExtensions(path)
if err != nil { if err != nil {
@ -267,7 +267,7 @@ func newFile(paths []string, filters *Filters, sortOrder string, Regexes *Regexe
} }
if filePath == "" { if filePath == "" {
path.Decrement() path.decrement()
filePath, err = tryExtensions(path) filePath, err = tryExtensions(path)
if err != nil { if err != nil {
@ -290,9 +290,9 @@ func nextFile(filePath, sortOrder string, Regexes *Regexes) (string, error) {
switch { switch {
case sortOrder == "asc": case sortOrder == "asc":
path.Increment() path.increment()
case sortOrder == "desc": case sortOrder == "desc":
path.Decrement() path.decrement()
default: default:
return "", nil return "", nil
} }
@ -331,7 +331,7 @@ func splitPath(path string, Regexes *Regexes) (*Path, error) {
func tryExtensions(p *Path) (string, error) { func tryExtensions(p *Path) (string, error) {
var fileName string var fileName string
for _, extension := range extensions { for _, extension := range Extensions {
fileName = fmt.Sprintf("%s%.3d%s", p.base, p.number, extension) fileName = fmt.Sprintf("%s%.3d%s", p.base, p.number, extension)
exists, err := fileExists(fileName) exists, err := fileExists(fileName)
@ -369,7 +369,7 @@ func pathIsValid(filePath string, paths []string) bool {
} }
switch { switch {
case Verbose && !matchesPrefix: case verbose && !matchesPrefix:
fmt.Printf("%s | Error: Failed to serve file outside specified path(s): %s\n", fmt.Printf("%s | Error: Failed to serve file outside specified path(s): %s\n",
time.Now().Format(LogDate), time.Now().Format(LogDate),
filePath, filePath,
@ -408,7 +408,7 @@ func scanPath(path string, files *Files, filters *Filters, stats *ScanStats, con
} }
switch { switch {
case !Recursive && info.IsDir() && p != path: case !recursive && info.IsDir() && p != path:
return filepath.SkipDir return filepath.SkipDir
case !info.IsDir(): case !info.IsDir():
wg.Add(1) 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) { 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 return index.Index(), true
} }
@ -489,7 +489,7 @@ func fileList(paths []string, filters *Filters, sort string, index *Index) ([]st
fileList = prepareDirectories(files, sort) fileList = prepareDirectories(files, sort)
if Verbose { if verbose {
fmt.Printf("%s | Indexed %d/%d files across %d directories in %s\n", fmt.Printf("%s | Indexed %d/%d files across %d directories in %s\n",
time.Now().Format(LogDate), time.Now().Format(LogDate),
stats.FilesMatched(), 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) index.setIndex(fileList)
} }

View File

@ -11,15 +11,16 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
var Cache bool var (
var Debug bool cache bool
var Filter bool debug bool
var Port uint16 filtering bool
var Recursive bool port uint16
var Sort bool recursive bool
var Verbose bool sorting bool
verbose bool
var rootCmd = &cobra.Command{ rootCmd = &cobra.Command{
Use: "roulette <path> [path]...", Use: "roulette <path> [path]...",
Short: "Serves random images from the specified directories.", Short: "Serves random images from the specified directories.",
Args: cobra.MinimumNArgs(1), Args: cobra.MinimumNArgs(1),
@ -30,6 +31,7 @@ var rootCmd = &cobra.Command{
} }
}, },
} }
)
func Execute() { func Execute() {
err := rootCmd.Execute() err := rootCmd.Execute()
@ -39,12 +41,12 @@ func Execute() {
} }
func init() { func init() {
rootCmd.Flags().BoolVarP(&Cache, "cache", "c", false, "only scan directories once, at startup (or when filters are applied)") rootCmd.Flags().BoolVarP(&cache, "cache", "c", false, "generate directory cache at startup")
rootCmd.Flags().BoolVarP(&Debug, "debug", "d", false, "store list of files served and number of times they were served") rootCmd.Flags().BoolVarP(&debug, "debug", "d", false, "expose stats endpoint")
rootCmd.Flags().BoolVarP(&Filter, "filter", "f", false, "enable filtering via query parameters") rootCmd.Flags().BoolVarP(&filtering, "filter", "f", false, "enable filtering")
rootCmd.Flags().Uint16VarP(&Port, "port", "p", 8080, "port to listen on") rootCmd.Flags().Uint16VarP(&port, "port", "p", 8080, "port to listen on")
rootCmd.Flags().BoolVarP(&Recursive, "recursive", "r", false, "recurse into subdirectories") 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(&sorting, "sort", "s", false, "enable sorting")
rootCmd.Flags().BoolVarP(&Verbose, "verbose", "v", false, "log accessed files to stdout") rootCmd.Flags().BoolVarP(&verbose, "verbose", "v", false, "log accessed files to stdout")
rootCmd.Flags().SetInterspersed(true) rootCmd.Flags().SetInterspersed(true)
} }

View File

@ -10,7 +10,7 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
var Version = "0.34.0" var Version = "0.34.1"
func init() { func init() {
rootCmd.AddCommand(versionCmd) rootCmd.AddCommand(versionCmd)

View File

@ -159,7 +159,7 @@ type timesServed struct {
func notFound(w http.ResponseWriter, r *http.Request, filePath string) error { func notFound(w http.ResponseWriter, r *http.Request, filePath string) error {
startTime := time.Now() startTime := time.Now()
if Verbose { if verbose {
fmt.Printf("%s | Unavailable file %s requested by %s\n", fmt.Printf("%s | Unavailable file %s requested by %s\n",
startTime.Format(LogDate), startTime.Format(LogDate),
filePath, filePath,
@ -235,7 +235,7 @@ func generateQueryParams(filters *Filters, sortOrder, refreshInterval string) st
queryParams.WriteString("?") queryParams.WriteString("?")
if Filter { if filtering {
queryParams.WriteString("include=") queryParams.WriteString("include=")
if filters.HasIncludes() { if filters.HasIncludes() {
queryParams.WriteString(filters.Includes()) queryParams.WriteString(filters.Includes())
@ -249,7 +249,7 @@ func generateQueryParams(filters *Filters, sortOrder, refreshInterval string) st
hasParams = true hasParams = true
} }
if Sort { if sorting {
if hasParams { if hasParams {
queryParams.WriteString("&") queryParams.WriteString("&")
} }
@ -413,7 +413,7 @@ func serveStaticFile(w http.ResponseWriter, r *http.Request, paths []string, sta
fileSize := humanReadableSize(len(buf)) fileSize := humanReadableSize(len(buf))
if Verbose { if verbose {
fmt.Printf("%s | Served %s (%s) to %s in %s\n", fmt.Printf("%s | Served %s (%s) to %s in %s\n",
startTime.Format(LogDate), startTime.Format(LogDate),
filePath, 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) stats.incrementCounter(filePath, startTime, fileSize)
} }
@ -454,7 +454,7 @@ func serveStatsHandler(args []string, stats *ServeStats) http.HandlerFunc {
w.Write(response) w.Write(response)
if Verbose { if verbose {
fmt.Printf("%s | Served statistics page (%s) to %s in %s\n", fmt.Printf("%s | Served statistics page (%s) to %s in %s\n",
startTime.Format(LogDate), startTime.Format(LogDate),
humanReadableSize(len(response)), humanReadableSize(len(response)),
@ -584,7 +584,7 @@ func ServePage(args []string) error {
list: []string{}, list: []string{},
} }
if Cache { if cache {
index.generateCache(args) index.generateCache(args)
http.Handle("/_/clear_cache", serveCacheClearHandler(args, index)) 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.Handle(Prefix+"/", http.StripPrefix(Prefix, serveStaticFileHandler(paths, stats)))
http.HandleFunc("/favicon.ico", doNothing) http.HandleFunc("/favicon.ico", doNothing)
if Debug { if debug {
http.Handle("/_/stats", serveStatsHandler(args, stats)) 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 { if err != nil {
return err return err
} }