github.com/u-root/u-root@v7.0.1-0.20200915234505-ad7babab0a8e+incompatible/pkg/cmdline/filters.go (about) 1 // Copyright 2018 the u-root Authors. All rights reserved 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package cmdline 6 7 import ( 8 "fmt" 9 "strings" 10 ) 11 12 // RemoveFilter filters out variable for a given space-separated kernel commandline 13 func removeFilter(input string, variables []string) string { 14 var newCl []string 15 16 // kernel variables must allow '-' and '_' to be equivalent in variable 17 // names. We will replace dashes with underscores for processing as 18 // `doParse` is doing. 19 for i, v := range variables { 20 variables[i] = strings.Replace(v, "-", "_", -1) 21 } 22 23 doParse(input, func(flag, key, canonicalKey, value, trimmedValue string) { 24 skip := false 25 for _, v := range variables { 26 if canonicalKey == v { 27 skip = true 28 break 29 } 30 } 31 if skip { 32 return 33 } 34 newCl = append(newCl, flag) 35 }) 36 return strings.Join(newCl, " ") 37 } 38 39 // Filter represents and kernel commandline filter 40 type Filter interface { 41 // Update filters a given space-separated kernel commandline 42 Update(cmdline string) string 43 } 44 45 type updater struct { 46 appendCmd string 47 removeVar []string 48 reuseVar []string 49 } 50 51 // NewUpdateFilter return a kernel command line Filter that: 52 // removes variables listed in 'removeVar', 53 // append extra parameters from the 'appendCmd' and 54 // append variables listed in 'reuseVar' using the value from the running kernel 55 func NewUpdateFilter(appendCmd string, removeVar, reuseVar []string) Filter { 56 return &updater{ 57 appendCmd: appendCmd, 58 removeVar: removeVar, 59 reuseVar: reuseVar, 60 } 61 } 62 63 func (u *updater) Update(cmdline string) string { 64 acl := "" 65 if len(u.appendCmd) > 0 { 66 acl = " " + u.appendCmd 67 } 68 for _, f := range u.reuseVar { 69 value, present := Flag(f) 70 if present { 71 acl = fmt.Sprintf("%s %s=%s", acl, f, value) 72 } 73 } 74 75 return removeFilter(cmdline, u.removeVar) + acl 76 }