continue working on config and default parsing

This commit is contained in:
Daniel Fichtinger 2024-11-25 16:05:35 -05:00
parent 4d1b18fd12
commit c6c801e248
8 changed files with 183 additions and 109 deletions

58
internal/util/file.go Normal file
View file

@ -0,0 +1,58 @@
package util
import (
"io"
"os"
)
// WriteFile writes a given byte array to the given path.
func WriteFile(b []byte, p string) error {
f, err := os.Create(p)
if err != nil {
return err
}
_, err = f.Write(b)
defer f.Close()
if err != nil {
return err
}
return nil
}
// ReadFile reads a byte array from a given path.
func ReadFile(p string) ([]byte, error) {
f, err := os.Open(p)
if err != nil {
return nil, err
}
var result []byte
buf := make([]byte, 1024)
for {
n, err := f.Read(buf)
// check for a non EOF error
if err != nil && err != io.EOF {
return nil, err
}
// n==0 when there are no chunks left to read
if n == 0 {
defer f.Close()
break
}
result = append(result, buf[:n]...)
}
return result, nil
}
// CopyFile reads the file at the input path, and write
// it to the output path.
func CopyFile(inPath string, outPath string) error {
inB, err := ReadFile(inPath)
if err != nil {
return err
}
if err := WriteFile(inB, outPath); err != nil {
return err
} else {
return nil
}
}

View file

@ -40,6 +40,13 @@ func ReplaceRoot(inPath, outRoot string) string {
return outPath
}
// FileExists returns a boolean indicating
// whether something exists at the path.
func FileExists(path string) bool {
_, err := os.Stat(path)
return !os.IsNotExist(err)
}
func CreateParents(path string) error {
dir := filepath.Dir(path)
// Check if the parent directory already exists

View file

@ -1,6 +1,9 @@
package util
import "strings"
import (
"errors"
"strings"
)
func NormalizeContent(content string) string {
var normalized []string
@ -13,3 +16,8 @@ func NormalizeContent(content string) string {
}
return strings.Join(normalized, "\n")
}
// ErrorPrepend returns a new error with a message prepended to the given error.
func ErrorPrepend(m string, err error) error {
return errors.Join(errors.New(m), err)
}