netcaptain/internal/cli/helpers.go

66 lines
1.1 KiB
Go
Raw Normal View History

2020-10-14 21:59:41 +00:00
package cli
2020-10-09 20:45:04 +00:00
import (
"bufio"
"fmt"
"os"
2020-10-14 21:59:41 +00:00
"path/filepath"
2020-10-09 20:45:04 +00:00
"strings"
)
func PromptWDefault(label, def string) string {
ret := Prompt(label, false)
if ret == "" {
return def
}
return ret
}
func Prompt(label string, required bool) string {
reader := bufio.NewReader(os.Stdin)
var res string
fmt.Println(label + ": ")
res, _ = reader.ReadString('\n')
res = strings.TrimSpace(res)
if res == "" && required {
fmt.Println("Non-empty response is required")
return Prompt(label, required)
}
return res
}
func FileExists(path string) bool {
info, err := os.Stat(path)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}
func DirExists(path string) bool {
info, err := os.Stat(path)
if os.IsNotExist(err) {
return false
}
return info.IsDir()
}
2020-10-14 21:59:41 +00:00
func ListFiles(path string) []string {
var files []string
err := filepath.Walk(path, func(p string, info os.FileInfo, err error) error {
p = strings.TrimPrefix(p, path)
if p != "" {
files = append(files, strings.TrimPrefix(p, "/"))
}
return nil
})
if err != nil {
return []string{}
}
return files
}
2020-10-09 20:45:04 +00:00
func PrintErr(o string) {
2020-10-14 21:59:41 +00:00
fmt.Fprintln(os.Stderr, o)
2020-10-09 20:45:04 +00:00
}