diff --git a/cmd/files.go b/cmd/files.go new file mode 100644 index 0000000..f320d6d --- /dev/null +++ b/cmd/files.go @@ -0,0 +1,72 @@ +/* +Copyright © 2022 Seednode +*/ + +package cmd + +import ( + "io/fs" + "math/rand" + "os" + "path/filepath" + "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 { + 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) []fs.DirEntry { + fileList, err := os.ReadDir(path) + if err != nil { + panic(err) + } + + return fileList +} + +func getFile(args []string) (string, string) { + fileList := []fs.DirEntry{} + + for i := 0; i < len(args); i++ { + f := getFiles(args[i]) + fileList = append(fileList, f...) + } + + fileName := pickFile(fileList) + + filePath, err := filepath.Abs(fileName) + if err != nil { + panic(err) + } + + return fileName, filePath +} diff --git a/cmd/root.go b/cmd/root.go index 4d49188..a17b584 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -17,8 +17,9 @@ var Verbose bool var rootCmd = &cobra.Command{ Use: "roulette [path2] ... [pathN]", Short: "Serves random images from the specified directories.", + Args: cobra.MinimumNArgs(1), Run: func(cmd *cobra.Command, args []string) { - ServePage() + ServePage(args) }, Version: Version, } diff --git a/cmd/web.go b/cmd/web.go index faccee5..b83a2f2 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -9,6 +9,7 @@ import ( "io" "log" "net/http" + "os" "strconv" "strings" ) @@ -123,7 +124,13 @@ func servePageHandler() http.HandlerFunc { func doNothing(http.ResponseWriter, *http.Request) {} -func ServePage() { +func ServePage(args []string) { + + fileName, filePath := getFile(args) + fmt.Println(fileName) + fmt.Println(filePath) + os.Exit(0) + defer HandleExit() http.HandleFunc("/", servePageHandler())