| 1 |
package types |
| 2 |
|
| 3 |
import ( |
| 4 |
"encoding" |
| 5 |
"fmt" |
| 6 |
"io/fs" |
| 7 |
"strconv" |
| 8 |
"strings" |
| 9 |
) |
| 10 |
|
| 11 |
var ( |
| 12 |
_ encoding.TextMarshaler = FileMode(0) |
| 13 |
_ encoding.TextUnmarshaler = (*FileMode)(nil) |
| 14 |
) |
| 15 |
|
| 16 |
// FileMode is a Unix permission mode represented in configuration using explicit octal notation. |
| 17 |
type FileMode fs.FileMode |
| 18 |
|
| 19 |
// MarshalText implements the [encoding.TextMarshaler] interface. |
| 20 |
func (m FileMode) MarshalText() ([]byte, error) { |
| 21 |
if m > FileMode(fs.ModePerm) { |
| 22 |
return nil, fmt.Errorf("invalid file mode %04o: only permission bits up to 0777 are allowed", m) |
| 23 |
} |
| 24 |
|
| 25 |
return fmt.Appendf(nil, "%04o", m), nil |
| 26 |
} |
| 27 |
|
| 28 |
// UnmarshalText implements the [encoding.TextUnmarshaler] interface. |
| 29 |
func (m *FileMode) UnmarshalText(text []byte) error { |
| 30 |
value := string(text) |
| 31 |
|
| 32 |
var digits string |
| 33 |
|
| 34 |
switch { |
| 35 |
case len(value) == 4 && strings.HasPrefix(value, "0"): |
| 36 |
digits = value[1:] |
| 37 |
case len(value) == 5 && strings.HasPrefix(value, "0o"): |
| 38 |
digits = value[2:] |
| 39 |
default: |
| 40 |
return fmt.Errorf("invalid file mode %q: use explicit octal notation such as 0660", value) |
| 41 |
} |
| 42 |
|
| 43 |
parsed, err := strconv.ParseUint(digits, 8, 9) |
| 44 |
if err != nil { |
| 45 |
return fmt.Errorf("invalid file mode %q: use explicit octal notation such as 0660: %w", value, err) |
| 46 |
} |
| 47 |
|
| 48 |
*m = FileMode(parsed) |
| 49 |
|
| 50 |
return nil |
| 51 |
} |