github.com/kekek/gb@v0.4.5-0.20170222120241-d4ba64b0b297/cmd/gb/flag.go (about)

     1  // Copyright 2011 The Go 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 main
     6  
     7  import "fmt"
     8  
     9  type stringsFlag []string
    10  
    11  func (v *stringsFlag) Set(s string) error {
    12  	var err error
    13  	*v, err = splitQuotedFields(s)
    14  	if *v == nil {
    15  		*v = []string{}
    16  	}
    17  	return err
    18  }
    19  
    20  func splitQuotedFields(s string) ([]string, error) {
    21  	// Split fields allowing '' or "" around elements.
    22  	// Quotes further inside the string do not count.
    23  	var f []string
    24  	for len(s) > 0 {
    25  		for len(s) > 0 && isSpaceByte(s[0]) {
    26  			s = s[1:]
    27  		}
    28  		if len(s) == 0 {
    29  			break
    30  		}
    31  		// Accepted quoted string. No unescaping inside.
    32  		if s[0] == '"' || s[0] == '\'' {
    33  			quote := s[0]
    34  			s = s[1:]
    35  			i := 0
    36  			for i < len(s) && s[i] != quote {
    37  				i++
    38  			}
    39  			if i >= len(s) {
    40  				return nil, fmt.Errorf("unterminated %c string", quote)
    41  			}
    42  			f = append(f, s[:i])
    43  			s = s[i+1:]
    44  			continue
    45  		}
    46  		i := 0
    47  		for i < len(s) && !isSpaceByte(s[i]) {
    48  			i++
    49  		}
    50  		f = append(f, s[:i])
    51  		s = s[i:]
    52  	}
    53  	return f, nil
    54  }
    55  
    56  func (v *stringsFlag) String() string {
    57  	return "<stringsFlag>"
    58  }
    59  
    60  func isSpaceByte(c byte) bool {
    61  	return c == ' ' || c == '\t' || c == '\n' || c == '\r'
    62  }