Skip to content

Commit 778da8d

Browse files
alexlarssonachilleas-k
authored andcommitted
disk: Make Filesystem.MkfsOptions an enum instead of a string
The encoding is the same in json, but on the golang side we avoid potential typos, etc.
1 parent 035cd49 commit 778da8d

2 files changed

Lines changed: 47 additions & 2 deletions

File tree

pkg/disk/filesystem.go

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,57 @@
11
package disk
22

33
import (
4+
"encoding/json"
5+
"fmt"
46
"math/rand"
57
"reflect"
68

79
"github.com/google/uuid"
810
)
911

12+
type MkfsOption int
13+
14+
const ( // MkfsOption type enum
15+
MkfsVerity MkfsOption = iota // Enable fs-verity option if needed (typically for EXT4)
16+
)
17+
18+
func getMkfsOptionMapping() []string {
19+
return []string{"verity"}
20+
}
21+
22+
// ToString converts MkfsOption into a human readable string
23+
func (option MkfsOption) ToString() string {
24+
return getMkfsOptionMapping()[int(option)]
25+
}
26+
27+
func unmarshalHelper(data []byte, mapping []string) (int, error) {
28+
var stringInput string
29+
err := json.Unmarshal(data, &stringInput)
30+
if err != nil {
31+
return 0, err
32+
}
33+
for n, str := range mapping {
34+
if str == stringInput {
35+
return n, nil
36+
}
37+
}
38+
return 0, fmt.Errorf("invalid mkfsoption: %s", stringInput)
39+
}
40+
41+
// UnmarshalJSON converts a JSON string into an MkfsOption
42+
func (option *MkfsOption) UnmarshalJSON(data []byte) error {
43+
val, err := unmarshalHelper(data, getMkfsOptionMapping())
44+
if err != nil {
45+
return err
46+
}
47+
*option = MkfsOption(val)
48+
return nil
49+
}
50+
51+
func (option MkfsOption) MarshalJSON() ([]byte, error) {
52+
return json.Marshal(getMkfsOptionMapping()[option])
53+
}
54+
1055
// Filesystem related functions
1156
type Filesystem struct {
1257
Type string `json:"type" yaml:"type"`
@@ -23,7 +68,7 @@ type Filesystem struct {
2368
// The sixth field of fstab(5); fs_passno
2469
FSTabPassNo uint64 `json:"fstab_passno,omitempty" yaml:"fstab_passno,omitempty"`
2570
// Custom mkfs options
26-
MkfsOptions []string `json:"mkfs_options,omitempty" yaml:"mkfs_options,omitempty"`
71+
MkfsOptions []MkfsOption `json:"mkfs_options,omitempty" yaml:"mkfs_options,omitempty"`
2772
}
2873

2974
func init() {

pkg/osbuild/mkfs_stage.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ func GenFsStages(pt *disk.PartitionTable, filename string) []*Stage {
4848
UUID: e.UUID,
4949
Label: e.Label,
5050
}
51-
if slices.Contains(e.MkfsOptions, "verity") {
51+
if slices.Contains(e.MkfsOptions, disk.MkfsVerity) {
5252
options.Verity = common.ToPtr(true)
5353
}
5454

0 commit comments

Comments
 (0)