From a8b4769fdf15ab533e24792859adfab6e5804739 Mon Sep 17 00:00:00 2001 From: Alexander Weinhold Date: Sun, 1 Jul 2018 16:03:26 +0200 Subject: [PATCH] new helpers (needed for drivel) --- goutil.go | 62 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/goutil.go b/goutil.go index 06e9f0e..62a3cc7 100644 --- a/goutil.go +++ b/goutil.go @@ -1,12 +1,24 @@ package goutil import ( + "bufio" + "errors" + "fmt" "io/ioutil" + "os" "path" "path/filepath" "strings" ) +func DecorateError(s string, err error) error { + if err != nil { + return errors.New(s + ": " + err.Error()) + } else { + return nil + } +} + func WriteFile(filename string, data string) error { return ioutil.WriteFile(filename, []byte(data), 0644) } @@ -36,3 +48,53 @@ func ListFilesExt(dir string, ext string) []string { } return list } + +func PathExists(path string) bool { + if _, err := os.Stat(path); os.IsNotExist(err) { + return false + } else { + return true + } +} + +func AskFor(question string) (string, error) { + fmt.Print(question + ": ") + reader := bufio.NewReader(os.Stdin) + s, err := reader.ReadString('\n') + if err == nil { + return strings.TrimSpace(s), nil + } else { + return "", err + } +} + +func IntMin(x, y int) int { + if x < y { + return x + } else { + return y + } +} + +func IntMax(x, y int) int { + if x > y { + return x + } else { + return y + } +} + +func StrSliceAt(sl []string, i int) string { + if i < len(sl) { + return sl[i] + } else { + return "" + } +} + +func StrSlice(sl []string, start int, end int) []string { + bound := func(i int) int { return IntMin(IntMax(0, i), len(sl)) } + start = bound(start) + end = bound(end) + return sl[start:end] +}