package comfunc
import (
"fmt"
"strings"
)
func Cmdline (args []string , binName ...string ) string {
b := new (strings .Builder )
if len (binName ) > 0 {
b .WriteString (binName [0 ])
b .WriteByte (' ' )
}
for i , a := range args {
if i > 0 {
b .WriteByte (' ' )
}
if strings .ContainsRune (a , '"' ) {
b .WriteString (fmt .Sprintf (`'%s'` , a ))
} else if a == "" || strings .ContainsRune (a , '\'' ) || strings .ContainsRune (a , ' ' ) {
b .WriteString (fmt .Sprintf (`"%s"` , a ))
} else {
b .WriteString (a )
}
}
return b .String ()
}
func ShellQuote (a string ) string {
if a == "" {
return `""`
}
var quote byte
if pos := strings .IndexByte (a , '"' ); pos > -1 {
if !checkNeedQuote (a , pos , '"' ) {
return a
}
quote = '\''
} else if pos := strings .IndexByte (a , '\'' ); pos > -1 {
if !checkNeedQuote (a , pos , '\'' ) {
return a
}
quote = '"'
} else if strings .IndexByte (a , ' ' ) > -1 {
quote = '"'
}
if quote == 0 {
return a
}
return fmt .Sprintf ("%c%s%c" , quote , a , quote )
}
func checkNeedQuote(a string , pos int , char byte ) bool {
lastIsQ := a [len (a )-1 ] == char
if pos == 0 {
if lastIsQ {
return false
}
if pos1 := strings .IndexByte (a [pos +1 :], char ); pos1 > -1 {
lastS := a [pos1 +pos +1 :]
if !strings .ContainsRune (lastS , ' ' ) {
return false
}
}
} else {
startS := a [:pos ]
if lastIsQ && strings .IndexByte (startS , ' ' ) == -1 {
return false
}
}
return true
}
The pages are generated with Golds v0.8.4 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .