Added separate recursive path walker

This commit is contained in:
Seednode 2022-09-08 12:12:58 -05:00
parent 7ae3c72697
commit eee4917322
2 changed files with 54 additions and 38 deletions

View File

@ -5,32 +5,13 @@ Copyright © 2022 Seednode <seednode@seedno.de>
package cmd package cmd
import ( import (
"io/fs" "fmt"
"math/rand" "math/rand"
"os" "os"
"path/filepath" "path/filepath"
"time" "time"
) )
func pickFile(fileList []fs.DirEntry) string {
rand.Seed(time.Now().Unix())
isFile := false
var fileName string
for isFile == false {
file := fileList[rand.Intn(len(fileList))]
if file.IsDir() == false {
isFile = true
fileName = file.Name()
}
}
return fileName
}
func getRandomFile(fileList []os.DirEntry) string { func getRandomFile(fileList []os.DirEntry) string {
rand.Seed(time.Now().Unix()) rand.Seed(time.Now().Unix())
@ -44,29 +25,62 @@ func getRandomFile(fileList []os.DirEntry) string {
return absolutePath return absolutePath
} }
func getFiles(path string) []fs.DirEntry { func getFiles(path string) ([]string, error) {
fileList, err := os.ReadDir(path) fileList, err := os.ReadDir(path)
if err != nil {
panic(err) return fileList, err
}
func getFilesRecursive(path string) ([]string, error) {
var paths []string
err := filepath.WalkDir(path, func(p string, info os.DirEntry, err error) error {
// if strings.HasPrefix(info.Name(), ".") {
// if info.IsDir() {
// return filepath.SkipDir
// }
// return err
// }
if !info.IsDir() {
paths = append(paths, p)
}
return err
})
rand.Seed(time.Now().Unix())
file := paths[rand.Intn(len(paths))]
fmt.Println(file)
return paths, err
}
func getFileList(args []string) []string {
fileList := []string{}
for i := 0; i < len(args); i++ {
if Recursive {
f, err := getFilesRecursive(args[i])
if err != nil {
panic(err)
}
fileList = append(fileList, f...)
} else {
f, err := getFiles(args[i])
if err != nil {
panic(err)
}
fileList = append(fileList, f...)
}
} }
return fileList return fileList
} }
func getFile(args []string) (string, string) { func pickFile(fileList []string) (string, string) {
fileList := []fs.DirEntry{} rand.Seed(time.Now().Unix())
for i := 0; i < len(args); i++ { filePath := fileList[rand.Intn(len(fileList))]
f := getFiles(args[i]) fileName := filepath.Base(filePath)
fileList = append(fileList, f...)
}
fileName := pickFile(fileList) return filePath, fileName
filePath, err := filepath.Abs(fileName)
if err != nil {
panic(err)
}
return fileName, filePath
} }

View File

@ -126,9 +126,11 @@ func doNothing(http.ResponseWriter, *http.Request) {}
func ServePage(args []string) { func ServePage(args []string) {
fileName, filePath := getFile(args) fileList := getFileList(args)
fileName, filePath := pickFile(fileList)
fmt.Println(fileName) fmt.Println(fileName)
fmt.Println(filePath) fmt.Println(filePath)
os.Exit(0) os.Exit(0)
defer HandleExit() defer HandleExit()