From fd1c57d37729c2c54859aa2b862a955be861bd74 Mon Sep 17 00:00:00 2001 From: Alejandro Mery Date: Sun, 29 Oct 2023 18:37:53 +0000 Subject: [PATCH] cluster: introduce Cluster.ReadLines() reading a file, splitting and trimming lines, and allowing # to comment a line out Signed-off-by: Alejandro Mery --- pkg/cluster/cluster_file.go | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/pkg/cluster/cluster_file.go b/pkg/cluster/cluster_file.go index c5277be..0d885e1 100644 --- a/pkg/cluster/cluster_file.go +++ b/pkg/cluster/cluster_file.go @@ -1,10 +1,12 @@ package cluster import ( + "bufio" "bytes" "fmt" "io" "os" + "strings" fs "github.com/hack-pad/hackpadfs" ) @@ -65,6 +67,31 @@ func (m *Cluster) ReadFile(name string, args ...any) ([]byte, error) { return fs.ReadFile(m.dir, name) } +// ReadLines reads a file from the cluster's config directory, +// split by lines, trimmed, and accepting `#` to comment lines out. +func (m *Cluster) ReadLines(name string, args ...any) ([]string, error) { + var out []string + + data, err := m.ReadFile(name, args...) + if err != nil { + return nil, err + } + + sc := bufio.NewScanner(bytes.NewReader(data)) + for sc.Scan() { + s := strings.TrimSpace(sc.Text()) + switch { + case s == "", strings.HasPrefix(s, "#"): + // ignore + default: + // accepted + out = append(out, s) + } + } + + return out, nil +} + // WriteStringFile writes the given content to a file on the machine's config directory func (m *Cluster) WriteStringFile(value string, name string, args ...any) error { f, err := m.CreateTruncFile(name, args...)