blob: 597a088ddd9fe5240c7bd5fb3724648e36bf6e99 [file] [log] [blame]
gioe72b54f2024-04-22 10:44:41 +04001package main
2
3import (
4 "errors"
5 "io"
6 "os"
7 "path/filepath"
8)
9
10type FS interface {
11 Exists(path string) (bool, error)
12 Reader(path string) (io.ReadCloser, error)
13 Writer(path string) (io.WriteCloser, error)
14 Read(path string) (string, error)
15 Write(path string, data string) error
16 AbsolutePath(path string) string
17}
18
19type osFS struct {
20 root string
21}
22
23func (f osFS) AbsolutePath(path string) string {
24 return filepath.Join(f.root, path)
25}
26
27func (f osFS) Exists(path string) (bool, error) {
28 _, err := os.Stat(f.AbsolutePath(path))
29 if err == nil {
30 return true, nil
31 }
32 if errors.Is(err, os.ErrNotExist) {
33 return false, nil
34 }
35 return false, nil // TODO(gio): return err
36}
37
38func (f osFS) Reader(path string) (io.ReadCloser, error) {
39 return os.Open(f.AbsolutePath(path))
40}
41
42func (f osFS) Writer(path string) (io.WriteCloser, error) {
43 return os.Create(f.AbsolutePath(path))
44}
45
46func (f osFS) Read(path string) (string, error) {
47 r, err := f.Reader(path)
48 if err != nil {
49 return "", err
50 }
51 defer r.Close()
52 d, err := io.ReadAll(r)
53 if err != nil {
54 return "", err
55 }
56 return string(d), err
57}
58
59func (f osFS) Write(path string, data string) error {
60 w, err := f.Writer(path)
61 if err != nil {
62 return err
63 }
64 defer w.Close()
65 _, err = io.WriteString(w, data)
66 return err
67}