Files
advent-of-code-go/util/ReadFile.go
T
2020-11-27 02:53:18 -05:00

43 lines
1002 B
Go

package util
import (
"io/ioutil"
"path"
"path/filepath"
"runtime"
"strings"
)
/*
ReadFile is a wrapper over io/ioutil.ReadFile but also determines the
dynamic absolute path to the file.
*/
func ReadFile(pathFromCaller string) string {
// Docs: https://golang.org/pkg/runtime/#Caller
_, filename, _, ok := runtime.Caller(1)
if !ok {
panic("Could not find Caller of util.ReadFile")
}
// parse directory with pathFromCaller (which could be relative to Directory)
absolutePath := path.Join(path.Dir(filename), pathFromCaller)
// read the entire file & return the byte slice as a string
content, err := ioutil.ReadFile(absolutePath)
if err != nil {
panic(err)
}
// trim off new lines and tabs at end of input files
strContent := string(content)
return strings.TrimRight(strContent, "\n")
}
// Dirname is a port of __dirname in node
func Dirname() string {
_, filename, _, ok := runtime.Caller(1)
if !ok {
panic("getting calling function")
}
return filepath.Dir(filename)
}