Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 23 additions & 5 deletions kernelargs.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,36 +23,54 @@ import "strings"
// "key" will result in map["key"] = nil
type kernelArgs map[string]*string

const initSeparator = "--"
const initKey = "init"

// serialize the kernelArgs back to a string that can be provided
// to the kernel
func (kargs kernelArgs) String() string {
var fields []string
var initField string
if initValue, ok := kargs[initKey]; ok && initValue != nil {
initField = initKey + "=" + *initValue
}
for key, value := range kargs {
if key == initKey {
continue
}
field := key
if value != nil {
field += "=" + *value
}
fields = append(fields, field)
}
fields = append(fields, initField)
return strings.Join(fields, " ")
}

// deserialize the provided string to a kernelArgs map
func parseKernelArgs(rawString string) kernelArgs {
argMap := make(map[string]*string)
for _, kv := range strings.Fields(rawString) {
// only split into up to 2 fields (before and after the first "=")
kvSplit := strings.SplitN(kv, "=", 2)
fields := strings.Fields(rawString)
passToInit := false

for i := 0; i < len(fields); i++ {
kvSplit := strings.SplitN(fields[i], "=", 2)
key := kvSplit[0]
if key == initSeparator {
passToInit = true
}

var value *string
if len(kvSplit) == 2 {
if passToInit {
key = initKey
initValue := *argMap[key] + " " + kvSplit[0]
value = &initValue
} else if len(kvSplit) == 2 {
value = &kvSplit[1]
}

argMap[key] = value
}

return argMap
}
7 changes: 6 additions & 1 deletion kernelargs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,19 +24,22 @@ func TestKernelArgsSerder(t *testing.T) {
fooVal := "bar"
booVal := "far"
dooVal := "a=silly=val"
initVal := "/bin/sh -- -c \"echo hello\""
emptyVal := ""

argsString := fmt.Sprintf("foo=%s blah doo=%s huh=%s bleh duh=%s boo=%s",
argsString := fmt.Sprintf("foo=%s blah doo=%s huh=%s bleh duh=%s boo=%s init=%s",
fooVal,
dooVal,
emptyVal,
emptyVal,
booVal,
initVal,
)

expectedParsedArgs := kernelArgs(map[string]*string{
"foo": &fooVal,
"doo": &dooVal,
"init": &initVal,
"blah": nil,
"huh": &emptyVal,
"bleh": nil,
Expand All @@ -45,6 +48,8 @@ func TestKernelArgsSerder(t *testing.T) {
})

actualParsedArgs := parseKernelArgs(argsString)
fmt.Printf("%v\n", actualParsedArgs)
fmt.Printf("%v\n", expectedParsedArgs)
require.Equal(t, expectedParsedArgs, actualParsedArgs, "kernel args parsed to unexpected values")

reparsedArgs := parseKernelArgs(actualParsedArgs.String())
Expand Down