Confirmed recursive and nonrecursive functions both work as expected

This commit is contained in:
Seednode 2022-09-08 13:12:50 -05:00
parent eee4917322
commit d052fd6af9
2 changed files with 25 additions and 30 deletions

View File

@ -5,75 +5,66 @@ Copyright © 2022 Seednode <seednode@seedno.de>
package cmd package cmd
import ( import (
"fmt"
"math/rand" "math/rand"
"os" "os"
"path/filepath" "path/filepath"
"time" "time"
) )
func getRandomFile(fileList []os.DirEntry) string {
rand.Seed(time.Now().Unix())
file := fileList[rand.Intn(len(fileList))].Name()
absolutePath, err := filepath.Abs(file)
if err != nil {
panic(err)
}
return absolutePath
}
func getFiles(path string) ([]string, error) { func getFiles(path string) ([]string, error) {
fileList, err := os.ReadDir(path) var paths []string
return fileList, err err := filepath.WalkDir(path, func(p string, info os.DirEntry, err error) error {
if info.IsDir() && p != path {
return filepath.SkipDir
} else {
paths = append(paths, p)
}
return err
})
if err != nil {
return nil, err
}
return paths, nil
} }
func getFilesRecursive(path string) ([]string, error) { func getFilesRecursive(path string) ([]string, error) {
var paths []string var paths []string
err := filepath.WalkDir(path, func(p string, info os.DirEntry, err error) error { 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() { if !info.IsDir() {
paths = append(paths, p) paths = append(paths, p)
} }
return err return err
}) })
if err != nil {
rand.Seed(time.Now().Unix()) return nil, err
file := paths[rand.Intn(len(paths))]
fmt.Println(file)
return paths, err
} }
func getFileList(args []string) []string { return paths, nil
}
func getFileList(args []string) ([]string, error) {
fileList := []string{} fileList := []string{}
for i := 0; i < len(args); i++ { for i := 0; i < len(args); i++ {
if Recursive { if Recursive {
f, err := getFilesRecursive(args[i]) f, err := getFilesRecursive(args[i])
if err != nil { if err != nil {
panic(err) return nil, err
} }
fileList = append(fileList, f...) fileList = append(fileList, f...)
} else { } else {
f, err := getFiles(args[i]) f, err := getFiles(args[i])
if err != nil { if err != nil {
panic(err) return nil, err
} }
fileList = append(fileList, f...) fileList = append(fileList, f...)
} }
} }
return fileList return fileList, nil
} }
func pickFile(fileList []string) (string, string) { func pickFile(fileList []string) (string, string) {

View File

@ -126,7 +126,11 @@ func doNothing(http.ResponseWriter, *http.Request) {}
func ServePage(args []string) { func ServePage(args []string) {
fileList := getFileList(args) fileList, err := getFileList(args)
if err != nil {
panic(err)
}
fileName, filePath := pickFile(fileList) fileName, filePath := pickFile(fileList)
fmt.Println(fileName) fmt.Println(fileName)
fmt.Println(filePath) fmt.Println(filePath)