github.com/u-root/u-root@v7.0.1-0.20200915234505-ad7babab0a8e+incompatible/pkg/uflag/flagfile.go (about) 1 // Copyright 2020 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 uflag supports u-root-custom flags as well as flag files. 6 package uflag 7 8 import ( 9 "fmt" 10 "strconv" 11 "strings" 12 ) 13 14 // ArgvToFile encodes argv program arguments such that they can be stored in a 15 // file. 16 func ArgvToFile(args []string) string { 17 // We separate flags in the flags file with new lines, so we 18 // have to escape new lines. 19 // 20 // Go already has a nifty Quote mechanism which will escape 21 // more than just new-line, which won't hurt anyway. 22 var quoted []string 23 for _, arg := range args { 24 quoted = append(quoted, strconv.Quote(arg)) 25 } 26 return strings.Join(quoted, "\n") 27 } 28 29 // FileToArgv converts argvs stored in a file back to an array of strings. 30 func FileToArgv(content string) []string { 31 quotedArgs := strings.Split(content, "\n") 32 var args []string 33 for _, arg := range quotedArgs { 34 if len(arg) > 0 { 35 s, err := strconv.Unquote(arg) 36 if err != nil { 37 panic(fmt.Sprintf("flags file encoded wrong, arg %q, error %v", arg, err)) 38 } 39 args = append(args, s) 40 } 41 } 42 return args 43 }