netcaptain/internal/cli/helpers.go

89 lines
1.7 KiB
Go

package cli
import (
"bufio"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
)
func HasParameter(label string, parms []string) bool {
for _, v := range parms {
if strings.HasPrefix(v, "-"+label) || strings.HasPrefix(v, "--"+label) {
return true
}
}
return false
}
func GetParameter(label string, parms []string) (string, error) {
for _, v := range parms {
if strings.HasPrefix(v, "-"+label) || strings.HasPrefix(v, "--"+label) {
parts := strings.Split(v, "=")
if len(parts) > 1 {
return parts[1], nil
}
return "", nil
}
}
return "", errors.New("Parameter does not exist")
}
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()
}
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
}
func PrintErr(o string) {
fmt.Fprintln(os.Stderr, o)
}