goutil/goutil.go

101 lines
1.7 KiB
Go
Raw Normal View History

2016-11-15 16:23:20 +01:00
package goutil
import (
2018-07-01 16:03:26 +02:00
"bufio"
"errors"
"fmt"
2016-11-15 16:23:20 +01:00
"io/ioutil"
2018-07-01 16:03:26 +02:00
"os"
2016-11-19 01:08:56 +01:00
"path"
2016-11-15 16:23:20 +01:00
"path/filepath"
"strings"
2016-11-15 16:23:20 +01:00
)
2018-07-01 16:03:26 +02:00
func DecorateError(s string, err error) error {
if err != nil {
return errors.New(s + ": " + err.Error())
} else {
return nil
}
}
2016-11-15 16:23:20 +01:00
func WriteFile(filename string, data string) error {
return ioutil.WriteFile(filename, []byte(data), 0644)
}
func ReadFile(filename string) (string, error) {
data, err := ioutil.ReadFile(filename)
return string(data), err
}
func TrimExt(path string) string {
extension := filepath.Ext(path)
return path[0 : len(path)-len(extension)]
}
func ListFilesExt(dir string, ext string) []string {
list := make([]string, 0)
ext = strings.ToUpper(ext)
files, err := ioutil.ReadDir(dir)
if err == nil {
for _, file := range files {
if !file.IsDir() {
if strings.ToUpper(filepath.Ext(file.Name())) == ext {
2016-11-19 01:08:56 +01:00
list = append(list, path.Join(dir, file.Name()))
}
}
}
}
return list
}
2018-07-01 16:03:26 +02:00
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]
}