| gio | e72b54f | 2024-04-22 10:44:41 +0400 | [diff] [blame] | 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "io" |
| 6 | "os" |
| 7 | "path/filepath" |
| 8 | ) |
| 9 | |
| 10 | type 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 | |
| 19 | type osFS struct { |
| 20 | root string |
| 21 | } |
| 22 | |
| 23 | func (f osFS) AbsolutePath(path string) string { |
| 24 | return filepath.Join(f.root, path) |
| 25 | } |
| 26 | |
| 27 | func (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 | |
| 38 | func (f osFS) Reader(path string) (io.ReadCloser, error) { |
| 39 | return os.Open(f.AbsolutePath(path)) |
| 40 | } |
| 41 | |
| 42 | func (f osFS) Writer(path string) (io.WriteCloser, error) { |
| 43 | return os.Create(f.AbsolutePath(path)) |
| 44 | } |
| 45 | |
| 46 | func (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 | |
| 59 | func (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 | } |