diff --git a/procfs/cmdline.go b/procfs/cmdline.go index 42aa426..e4dbf70 100644 --- a/procfs/cmdline.go +++ b/procfs/cmdline.go @@ -198,10 +198,47 @@ func (c *Cmdline) Append(k, v string) { insert(&c.Parameters, k, v) } +// AppendAllOptions provides additional options for AppendAll. +type AppendAllOptions struct { + OverwriteArgs []string +} + +// AppendAllOption is a functional option for AppendAll. +type AppendAllOption func(*AppendAllOptions) + +// WithOverwriteArgs specifies kernel arguments which should be overwritten with AppendAll. +func WithOverwriteArgs(args ...string) AppendAllOption { + return func(opts *AppendAllOptions) { + opts.OverwriteArgs = append(opts.OverwriteArgs, args...) + } +} + // AppendAll appends a set of kernel parameters. -func (c *Cmdline) AppendAll(args []string) error { +func (c *Cmdline) AppendAll(args []string, opts ...AppendAllOption) error { + var options AppendAllOptions + + for _, opt := range opts { + opt(&options) + } + parameters := parse(strings.Join(args, " ")) for _, p := range parameters { + overwrite := false + + for _, key := range options.OverwriteArgs { + if key == p.key { + overwrite = true + + break + } + } + + if overwrite { + c.Set(p.key, p) + + continue + } + for _, v := range p.values { c.Append(p.key, v) } diff --git a/procfs/cmdline_test.go b/procfs/cmdline_test.go index 730985c..9de91b6 100644 --- a/procfs/cmdline_test.go +++ b/procfs/cmdline_test.go @@ -146,21 +146,36 @@ func (suite *KernelSuite) TestCmdlineAppendAll() { for _, t := range []struct { initial string params []string + opts []AppendAllOption expected string }{ { "ip=dhcp console=x root=/dev/sdc", []string{"root=/dev/sda", "root=/dev/sdb"}, + nil, "ip=dhcp console=x root=/dev/sdc root=/dev/sda root=/dev/sdb", }, { "root=/dev/sdb", []string{"this=that=those"}, + nil, "root=/dev/sdb this=that=those", }, + { + "console=tty0 console=ttyS0 root=/dev/sdb", + []string{"console=tty0", "console=ttyS1,115200", "nogui"}, + nil, + "console=tty0 console=ttyS0 console=tty0 console=ttyS1,115200 root=/dev/sdb nogui", + }, + { + "console=tty0 console=ttyS0 root=/dev/sdb", + []string{"console=tty0", "console=ttyS1,115200", "nogui"}, + []AppendAllOption{WithOverwriteArgs("console")}, + "console=tty0 console=ttyS1,115200 root=/dev/sdb nogui", + }, } { cmdline := NewCmdline(t.initial) - err := cmdline.AppendAll(t.params) + err := cmdline.AppendAll(t.params, t.opts...) visited := map[string]bool{} for _, p := range cmdline.Parameters {