| 1 |
package types |
| 2 |
|
| 3 |
import ( |
| 4 |
"encoding/json" |
| 5 |
"fmt" |
| 6 |
"io/fs" |
| 7 |
"os" |
| 8 |
) |
| 9 |
|
| 10 |
type FS struct { |
| 11 |
fs.FS |
| 12 |
|
| 13 |
path string |
| 14 |
} |
| 15 |
|
| 16 |
func NewFS(filePath string) (FS, error) { |
| 17 |
dirFS := NewRootFS(filePath) |
| 18 |
|
| 19 |
dir, err := dirFS.Open(".") |
| 20 |
if err != nil { |
| 21 |
return FS{}, fmt.Errorf("error open %q: %w", filePath, err) |
| 22 |
} |
| 23 |
|
| 24 |
dirState, err := dir.Stat() |
| 25 |
if err != nil { |
| 26 |
return FS{}, fmt.Errorf("error stat %q: %w", filePath, err) |
| 27 |
} |
| 28 |
|
| 29 |
if !dirState.IsDir() { |
| 30 |
return FS{}, fmt.Errorf("path %q is not a directory", filePath) |
| 31 |
} |
| 32 |
|
| 33 |
return dirFS, nil |
| 34 |
} |
| 35 |
|
| 36 |
// NewRootFS returns a file system rooted at filePath. |
| 37 |
// |
| 38 |
// Unlike [os.DirFS], the returned file system prevents symbolic links from |
| 39 |
// escaping the root. Both implementations reject paths containing "." or |
| 40 |
// ".." elements as required by [fs.ValidPath]. |
| 41 |
func NewRootFS(filePath string) FS { |
| 42 |
return FS{FS: rootFS(filePath), path: filePath} |
| 43 |
} |
| 44 |
|
| 45 |
type rootFS string |
| 46 |
|
| 47 |
func (f rootFS) Open(name string) (fs.File, error) { |
| 48 |
root, err := os.OpenRoot(string(f)) |
| 49 |
if err != nil { |
| 50 |
return nil, fmt.Errorf("open root %q: %w", f, err) |
| 51 |
} |
| 52 |
defer root.Close() |
| 53 |
|
| 54 |
return root.FS().Open(name) //nolint:wrapcheck |
| 55 |
} |
| 56 |
|
| 57 |
// IsEmpty checks if the template is empty. |
| 58 |
// |
| 59 |
//goland:noinspection GoMixedReceiverTypes |
| 60 |
func (f *FS) IsEmpty() bool { |
| 61 |
return f == nil || f.FS == nil |
| 62 |
} |
| 63 |
|
| 64 |
// String returns the path of the template. |
| 65 |
// |
| 66 |
//goland:noinspection GoMixedReceiverTypes |
| 67 |
func (f *FS) String() string { |
| 68 |
return f.path |
| 69 |
} |
| 70 |
|
| 71 |
// MarshalText implements the [encoding.TextMarshaler] interface. |
| 72 |
// |
| 73 |
//goland:noinspection GoMixedReceiverTypes |
| 74 |
func (f FS) MarshalText() ([]byte, error) { |
| 75 |
return []byte(f.String()), nil |
| 76 |
} |
| 77 |
|
| 78 |
// UnmarshalText implements the [encoding.TextUnmarshaler] interface. |
| 79 |
// |
| 80 |
//goland:noinspection GoMixedReceiverTypes |
| 81 |
func (f *FS) UnmarshalText(text []byte) error { |
| 82 |
dirFS, err := NewFS(string(text)) |
| 83 |
if err != nil { |
| 84 |
return err |
| 85 |
} |
| 86 |
|
| 87 |
*f = dirFS |
| 88 |
|
| 89 |
return nil |
| 90 |
} |
| 91 |
|
| 92 |
// MarshalJSON implements the [json.Marshaler] interface. |
| 93 |
// |
| 94 |
//goland:noinspection GoMixedReceiverTypes |
| 95 |
func (f *FS) MarshalJSON() ([]byte, error) { |
| 96 |
return json.Marshal(f.String()) //nolint:wrapcheck |
| 97 |
} |