From 296d4007ff17deb6b17cd6043afcd0aa4f839a0f Mon Sep 17 00:00:00 2001 From: Alejandro Mery Date: Sun, 27 Aug 2023 19:54:01 +0000 Subject: [PATCH] zones: add methods to work with files at the root of m/ Signed-off-by: Alejandro Mery --- pkg/zones/zones_file.go | 46 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 pkg/zones/zones_file.go diff --git a/pkg/zones/zones_file.go b/pkg/zones/zones_file.go new file mode 100644 index 0000000..b711163 --- /dev/null +++ b/pkg/zones/zones_file.go @@ -0,0 +1,46 @@ +package zones + +import ( + "fmt" + "io" + "os" + + fs "github.com/hack-pad/hackpadfs" +) + +// OpenFile opens a file on the cluster's config directory with the specified flags +func (m *Zones) OpenFile(name string, flags int, args ...any) (fs.File, error) { + if len(args) > 0 { + name = fmt.Sprintf(name, args...) + } + + return fs.OpenFile(m.dir, name, flags, 0644) +} + +// CreateTruncFile creates or truncates a file on the cluster's config directory +func (m *Zones) CreateTruncFile(name string, args ...any) (io.WriteCloser, error) { + return m.openWriter(name, os.O_CREATE|os.O_TRUNC, args...) +} + +// CreateFile creates a file on the cluster's config directory +func (m *Zones) CreateFile(name string, args ...any) (io.WriteCloser, error) { + return m.openWriter(name, os.O_CREATE, args...) +} + +func (m *Zones) openWriter(name string, flags int, args ...any) (io.WriteCloser, error) { + f, err := m.OpenFile(name, os.O_WRONLY|flags, args...) + if err != nil { + return nil, err + } + + return f.(io.WriteCloser), nil +} + +// ReadFile reads a file from the cluster's config directory +func (m *Zones) ReadFile(name string, args ...any) ([]byte, error) { + if len(args) > 0 { + name = fmt.Sprintf(name, args...) + } + + return fs.ReadFile(m.dir, name) +} -- 2.17.1