roulette/cmd/files.go

87 lines
1.5 KiB
Go
Raw Normal View History

2022-09-08 15:57:59 +00:00
/*
Copyright © 2022 Seednode <seednode@seedno.de>
*/
package cmd
import (
2022-09-08 17:12:58 +00:00
"fmt"
2022-09-08 15:57:59 +00:00
"math/rand"
"os"
"path/filepath"
"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
}
2022-09-08 17:12:58 +00:00
func getFiles(path string) ([]string, error) {
2022-09-08 15:57:59 +00:00
fileList, err := os.ReadDir(path)
2022-09-08 17:12:58 +00:00
return fileList, err
2022-09-08 15:57:59 +00:00
}
2022-09-08 17:12:58 +00:00
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{}
2022-09-08 15:57:59 +00:00
for i := 0; i < len(args); i++ {
2022-09-08 17:12:58 +00:00
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...)
}
2022-09-08 15:57:59 +00:00
}
2022-09-08 17:12:58 +00:00
return fileList
}
2022-09-08 15:57:59 +00:00
2022-09-08 17:12:58 +00:00
func pickFile(fileList []string) (string, string) {
rand.Seed(time.Now().Unix())
filePath := fileList[rand.Intn(len(fileList))]
fileName := filepath.Base(filePath)
2022-09-08 15:57:59 +00:00
2022-09-08 17:12:58 +00:00
return filePath, fileName
2022-09-08 15:57:59 +00:00
}