package comfunc

import (
	
	
)

// Cmdline build
func ( []string,  ...string) string {
	 := new(strings.Builder)

	if len() > 0 {
		.WriteString([0])
		.WriteByte(' ')
	}

	for ,  := range  {
		if  > 0 {
			.WriteByte(' ')
		}

		if strings.ContainsRune(, '"') {
			.WriteString(fmt.Sprintf(`'%s'`, ))
		} else if  == "" || strings.ContainsRune(, '\'') || strings.ContainsRune(, ' ') {
			.WriteString(fmt.Sprintf(`"%s"`, ))
		} else {
			.WriteString()
		}
	}
	return .String()
}

// ShellQuote quote a string on contains ', ", SPACE. refer strconv.Quote()
func ( string) string {
	if  == "" {
		return `""`
	}

	// use quote char
	var  byte

	// has double quote
	if  := strings.IndexByte(, '"');  > -1 {
		if !checkNeedQuote(, , '"') {
			return 
		}

		 = '\''
	} else if  := strings.IndexByte(, '\'');  > -1 {
		// single quote
		if !checkNeedQuote(, , '\'') {
			return 
		}
		 = '"'
	} else if strings.IndexByte(, ' ') > -1 {
		 = '"'
	}

	// no quote char OR not need quote
	if  == 0 {
		return 
	}
	return fmt.Sprintf("%c%s%c", , , )
}

func checkNeedQuote( string,  int,  byte) bool {
	// end with char. eg: "
	 := [len()-1] == 

	// start with char. eg: "
	if  == 0 {
		if  {
			return false
		}

		if  := strings.IndexByte([+1:], );  > -1 {
			// eg: `"one two" three four`
			 := [++1:]
			if !strings.ContainsRune(, ' ') {
				return false
			}
		}
	} else {
		 := [:]

		// eg: `--one="two three"`
		if  && strings.IndexByte(, ' ') == -1 {
			return false
		}
	}

	return true
}