Example #1
0
func ParseIni(config_lines []string) map[string]map[string]string {
	config := make(map[string]map[string]string)
	current_seg := "General"
	for _, line := range config_lines {
		line = strings.TrimLeftFunc(line, unicode.IsSpace)
		if len(line) <= 0 || line[0] == ';' {
			continue
		}
		if line[0] == '[' && line[len(line)-1] == ']' {
			current_seg = line[1 : len(line)-1]
			continue
		}
		fields := strings.SplitN(line, "=", 2)
		if len(fields) != 2 {
			log.Fatal("Invalid Config Item: ", line)
			os.Exit(1)
		}
		key := strings.TrimLeftFunc(fields[0], unicode.IsSpace)
		value := strings.TrimLeftFunc(fields[1], unicode.IsSpace)
		if _, found := config[current_seg]; !found {
			config[current_seg] = make(map[string]string)
		}
		config[current_seg][key] = value
	}
	return config
}
Example #2
0
func consumeMediaParam(v string) (param, value, rest string) { // 解析mediatype
	rest = strings.TrimLeftFunc(v, unicode.IsSpace)
	if !strings.HasPrefix(rest, ";") {
		return "", "", v
	}

	rest = rest[1:] // consume semicolon
	rest = strings.TrimLeftFunc(rest, unicode.IsSpace)
	param, rest = consumeToken(rest)
	param = strings.ToLower(param)
	if param == "" {
		return "", "", v
	}

	rest = strings.TrimLeftFunc(rest, unicode.IsSpace)
	if !strings.HasPrefix(rest, "=") {
		return "", "", v
	}
	rest = rest[1:] // consume equals sign
	rest = strings.TrimLeftFunc(rest, unicode.IsSpace)
	value, rest = consumeValue(rest)
	if value == "" {
		return "", "", v
	}
	return param, value, rest
}
Example #3
0
// TrimLeftFunc returns a slice of the string s with all leading Unicode code point
// c satisfying f(c) removed
func TrimLeftFunc(s string, f func(rune) bool) string {
	inner_func := func(r rune) bool {
		return r <= 'c' || r >= 'i'
	}
	fmt.Println(strings.TrimLeftFunc("abcdefghijk", inner_func))   // defghijk
	fmt.Println(strings.TrimLeftFunc("agbcdefghijk", inner_func))  // gbcdefghijk
	fmt.Println(strings.TrimLeftFunc("asgbcdefghijk", inner_func)) // gbcdefghijk
	return strings.TrimLeftFunc(s, f)
}
Example #4
0
func ParseString(ss []string, is_end bool, vs string) (Variable, []string, error) {
	simple_line := strings.TrimSpace(vs)
	if !strings.HasPrefix(simple_line, "\"") {
		return nil, nil, errors.New("parse `" + strings.Join(ss, "\r\n") + "` failed, \"" + simple_line + "\" is not start with \".")
	}
	if 1 < len(simple_line) {
		if strings.HasSuffix(simple_line, "\"") {
			return NewOctetString([]byte(simple_line[1 : len(simple_line)-1])), ss[1:], nil
		}
	}

	p := -1
	for idx, sss := range ss[1:] {
		if re.MatchString(sss) {
			p = idx
			break
		} else if strings.Contains(sss, "MIB search path") ||
			//strings.HasPrefix(sss, "#") ||
			strings.Contains(sss, "Cannot find module") ||
			strings.Contains(sss, "#tools\\snmpwalk.exe") {
			p = idx
			break
		}
	}

	if -1 == p {
		if is_end {
			simple_line = strings.TrimLeftFunc(vs, unicode.IsSpace)
			if 1 != len(ss) {
				simple_line = simple_line[1:] + "\r\n" + strings.Join(ss[1:], "\r\n")
			}
			if strings.HasSuffix(simple_line, "\"") {
				simple_line = simple_line[:len(simple_line)-1]
			}
			if strings.HasPrefix(simple_line, "\"") {
				simple_line = simple_line[1:]
			}
			return NewOctetString([]byte(simple_line)), nil, nil
		}
		return nil, ss, more_line
	}
	p += 1

	simple_line = strings.TrimLeftFunc(vs, unicode.IsSpace)
	if 1 != p {
		simple_line = simple_line + "\r\n" + strings.Join(ss[1:p], "\r\n")
	}
	if strings.HasSuffix(simple_line, "\"") {
		simple_line = simple_line[:len(simple_line)-1]
	}

	if strings.HasPrefix(simple_line, "\"") {
		simple_line = simple_line[1:]
	}

	return NewOctetString([]byte(simple_line)), ss[p:], nil
}
Example #5
0
func splitShellCmd(cmd string) (name, args string) {
	cmd = strings.TrimLeftFunc(cmd, unicode.IsSpace)
	switch pre := strings.IndexFunc(cmd, unicode.IsSpace); {
	case pre > 0:
		name, args = cmd[:pre], strings.TrimLeftFunc(cmd[pre:], unicode.IsSpace)
	case pre == -1:
		name = cmd
	default:
		panic("unexpected case (untrimmed)")
	}
	return
}
Example #6
0
func (n *ninjaWriterWithWrap) writeString(s string, space bool) {
	if n.err != nil {
		return
	}

	spaceLen := 0
	if space {
		spaceLen = 1
	}

	if n.writtenLen+len(s)+spaceLen > n.maxLineLen {
		_, n.err = io.WriteString(n.writer, " $\n")
		if n.err != nil {
			return
		}
		_, n.err = io.WriteString(n.writer, indentString[:indentWidth*2])
		if n.err != nil {
			return
		}
		n.writtenLen = indentWidth * 2
		s = strings.TrimLeftFunc(s, unicode.IsSpace)
	} else if space {
		io.WriteString(n.writer, " ")
		n.writtenLen++
	}

	_, n.err = io.WriteString(n.writer, s)
	n.writtenLen += len(s)
}
Example #7
0
// Parse is the main parse routine.
// It handles an io.ReadWriteCloser and returns the root of the AST.
func Parse(rwc io.Reader) (*Node, error) {
	directiveEscapeSeen = false
	lookingForDirectives = true
	setTokenEscape(defaultTokenEscape) // Assume the default token for escape
	currentLine := 0
	root := &Node{}
	root.StartLine = -1
	scanner := bufio.NewScanner(rwc)

	for scanner.Scan() {
		scannedLine := strings.TrimLeftFunc(scanner.Text(), unicode.IsSpace)
		currentLine++
		line, child, err := ParseLine(scannedLine)
		if err != nil {
			return nil, err
		}
		startLine := currentLine

		if line != "" && child == nil {
			for scanner.Scan() {
				newline := scanner.Text()
				currentLine++

				if stripComments(strings.TrimSpace(newline)) == "" {
					continue
				}

				line, child, err = ParseLine(line + newline)
				if err != nil {
					return nil, err
				}

				if child != nil {
					break
				}
			}
			if child == nil && line != "" {
				_, child, err = ParseLine(line)
				if err != nil {
					return nil, err
				}
			}
		}

		if child != nil {
			// Update the line information for the current child.
			child.StartLine = startLine
			child.EndLine = currentLine
			// Update the line information for the root. The starting line of the root is always the
			// starting line of the first child and the ending line is the ending line of the last child.
			if root.StartLine < 0 {
				root.StartLine = currentLine
			}
			root.EndLine = currentLine
			root.Children = append(root.Children, child)
		}
	}

	return root, nil
}
Example #8
0
func replaceTagsLi(c string, n *html.Node) string {
	data := strings.TrimLeftFunc(c, unicode.IsSpace)
	data = strings.Replace(data, "\n", "\n    ", -1)

	pref := "*   "

	p := n.Parent

	if p != nil {
		i := 0
		for c := p.FirstChild; c != nil; c = c.NextSibling {
			if c.DataAtom == atom.Li {
				i++
				if c == n {
					break
				}
			}
		}

		if p.DataAtom == atom.Ol {
			pref = fmt.Sprintf("%d.   ", i)
		}
	}

	return pref + data
}
Example #9
0
func (w wsCollapser) Write(p []byte) (n int, err error) {
	lines := strings.Split(string(p), "\n")
	for i, line := range lines {
		l := line
		if *w.prevNewLine {
			l = strings.TrimLeftFunc(l, unicode.IsSpace)
		}
		curNewLine := (i < len(lines)-1) || (len(p) > 0 && p[len(p)-1] == '\n')
		if curNewLine {
			l = strings.TrimRightFunc(l, unicode.IsSpace)
		}
		if len(l) == 0 {
			*w.prevNewLine = curNewLine
			continue
		}
		if *w.prevNewLine && !*w.prevTag && l[0] != '<' {
			_, err := (*w.writer).Write([]byte(" "))
			if err != nil {
				return 0, err
			}
		}
		_, err := (*w.writer).Write([]byte(l))
		if err != nil {
			return 0, err
		}
		*w.prevTag = l[len(l)-1] == '>'
		*w.prevNewLine = curNewLine
	}
	return len(p), nil
}
Example #10
0
func (r *CommentStripper) Read(p []byte) (int, error) {
	for {
		if r.buf.Len() >= len(p) {
			return r.buf.Read(p)
		}
		line, err := r.r.ReadString(r.Delimiter)
		if len(line) > 0 {
			checkLine := line
			if r.Whitespace {
				checkLine = strings.TrimLeftFunc(checkLine, unicode.IsSpace)
			}
			if strings.HasPrefix(checkLine, r.Comment) {
				// yay, skip this line
				continue
			}
			r.buf.WriteString(line)
		}
		if err != nil {
			if r.buf.Len() > 0 {
				return r.buf.Read(p)
			}
			return 0, err
		}
	}
}
Example #11
0
func parseEngineeringNotation(in string) (uint64, error) {
	if in == "" {
		return 0, nil
	}
	var numerics = func(r rune) bool {
		return r >= '0' && r <= '9'
	}
	var nonNumerics = func(r rune) bool {
		return !numerics(r)
	}
	suffix := strings.TrimLeftFunc(in, numerics)
	numeric := strings.TrimRightFunc(in, nonNumerics)
	val, err := strconv.ParseUint(numeric, 10, 64)
	if err != nil {
		return 0, fmt.Errorf("Parsing engineering notation for '%s'", in)
	}
	switch suffix {
	case "K", "k":
		val *= (1 << 10)
	case "M", "m":
		val *= (1 << 20)
	case "G", "g":
		val *= (1 << 30)
	case "T", "t":
		val *= (1 << 40)
	case "":
		break
	default:
		return 0, fmt.Errorf("Parsing engineering notation for '%s'", in)
	}
	return val, nil
}
Example #12
0
func ParseCaptions(source string) (*CaptionsConfiguration, error) {
	c := new(CaptionsConfiguration)
	c.Captions = make(map[string]string)
	c.Variables = make(map[string]string)

	source = strings.Replace(source, "\r\n", "\n", -1)
	for i, line := range strings.Split(source, "\n") {
		line = strings.TrimLeftFunc(line, unicode.IsSpace) // remove leading space

		// ignore comments and empty lines
		if strings.HasPrefix(line, "#") || strings.HasPrefix(line, "//") || line == "" {
			continue
		}

		parts := strings.SplitN(line, ": ", 2)

		if len(parts) != 2 {
			return nil, errors.New("Wrong format in line " + strconv.Itoa(i))
		}

		if strings.HasPrefix(line, "$") {
			name := strings.TrimLeft(parts[0], "$")
			c.Variables[name] = parts[1]
			continue
		}

		c.Captions[parts[0]] = parts[1]
	}
	return c, nil
}
Example #13
0
func comment(text string) string {
	lines := strings.Split(text, "\n")

	var output string
	if len(lines) == 1 && lines[0] == "" {
		return ""
	}

	// Helps to determine if
	// there is an actual comment
	// without screwing newlines
	// in real comments.
	hasComment := false

	for _, line := range lines {
		line = strings.TrimLeftFunc(line, unicode.IsSpace)
		if line != "" {
			hasComment = true
		}
		output += "\n// " + line
	}

	if hasComment {
		return output
	}
	return ""
}
Example #14
0
// Clean a message, remove leading username
func cleanMessage(rawMessage string) string {
	msg := strings.TrimPrefix(rawMessage, conf.Nick)
	msg = strings.TrimLeftFunc(msg, func(char rune) bool {
		return char == ',' || char == ':' || char == '-' || char == ' '
	})
	return msg
}
Example #15
0
// parseJSON converts JSON arrays to an AST.
func parseJSON(rest string) (*Node, map[string]bool, error) {
	rest = strings.TrimLeftFunc(rest, unicode.IsSpace)
	if !strings.HasPrefix(rest, "[") {
		return nil, nil, fmt.Errorf(`Error parsing "%s" as a JSON array`, rest)
	}

	var myJSON []interface{}
	if err := json.NewDecoder(strings.NewReader(rest)).Decode(&myJSON); err != nil {
		return nil, nil, err
	}

	var top, prev *Node
	for _, str := range myJSON {
		s, ok := str.(string)
		if !ok {
			return nil, nil, errDockerfileNotStringArray
		}

		node := &Node{Value: s}
		if prev == nil {
			top = node
		} else {
			prev.Next = node
		}
		prev = node
	}

	return top, map[string]bool{"json": true}, nil
}
Example #16
0
func parseFormat(format string) (frmt _frmt) {
	if ctlTest.MatchString(format) {
		format = strings.TrimLeftFunc(format, unicode.IsSpace)
		index := strings.Index(format, "//")
		if index != -1 {
			frmt.ctl = format[0:index]
			format = format[index+2:] // Skip the second slash via +2 (instead of +1)
		} else {
			frmt.ctl = format
			format = ""
		}
		for _, tmp := range ctlScan.FindAllStringSubmatch(frmt.ctl, -1) {
			for _, value := range tmp[1:] {
				switch value {
				case "panic":
					frmt.panic = true
				case "fatal":
					frmt.fatal = true
				case "check":
					frmt.check = true
				}
			}
		}
	}
	frmt.format = format
	frmt.operandCount = operandCount(format)
	return
}
Example #17
0
func (s *Service) PostApps_Repos_Points(args *cmdArgs, env *rpcutil.Env) (err error) {

	appid := args.CmdArgs[0]
	repoid := args.CmdArgs[1]
	data, err := ioutil.ReadAll(env.Req.Body)
	if err != nil {
		return err
	}

	reqSql := strings.TrimLeftFunc(string(data), isWhiteSpace)
	point := strings.TrimRightFunc(reqSql, isWhiteSpace)

	wurl := fmt.Sprintf("/v4/apps/%s/repos/%s/points", appid, repoid)
	err = s.PandoraClient.CallWith(nil, nil, "POST", wurl, "text/plain", bytes.NewBuffer([]byte(point)), len(point))
	if err != nil {
		return fmt.Errorf("write pandora fail, error:%v", err)
	}

	err = s.InfluxdbClient.CallWith(nil, nil, "POST", "/write?db=pandora&rp=default", "text/plain", bytes.NewBuffer([]byte(point)), len(point))
	if err != nil && err.Error() != "No Content" {
		return fmt.Errorf("write influxdb fail, error:%v", err)
	}

	return
}
Example #18
0
func DefaultConfigIni() string {
	s := strings.TrimLeftFunc(defaultConfigIni, unicode.IsSpace)
	if runtime.GOOS == "windows" {
		s = strings.Replace(s, "\n", "\r\n", -1)
	}
	return s
}
func main() {
	show("original", simple)
	show("leading ws removed", strings.TrimLeftFunc(simple, unicode.IsSpace))
	show("trailing ws removed", strings.TrimRightFunc(simple, unicode.IsSpace))
	// equivalent to strings.TrimFunc(simple, unicode.IsSpace)
	show("both removed", strings.TrimSpace(simple))
}
Example #20
0
func (templater *templater) templateFuncs(exposedFlags ...string) template.FuncMap {
	return template.FuncMap{
		"trim":                strings.TrimSpace,
		"trimRight":           func(s string) string { return strings.TrimRightFunc(s, unicode.IsSpace) },
		"trimLeft":            func(s string) string { return strings.TrimLeftFunc(s, unicode.IsSpace) },
		"gt":                  cobra.Gt,
		"eq":                  cobra.Eq,
		"rpad":                rpad,
		"appendIfNotPresent":  appendIfNotPresent,
		"flagsNotIntersected": flagsNotIntersected,
		"visibleFlags":        visibleFlags,
		"flagsUsages":         flagsUsages,
		"cmdGroups":           templater.cmdGroups,
		"cmdGroupsString":     templater.cmdGroupsString,
		"rootCmd":             templater.rootCmdName,
		"isRootCmd":           templater.isRootCmd,
		"optionsCmdFor":       templater.optionsCmdFor,
		"usageLine":           templater.usageLine,
		"exposed": func(c *cobra.Command) *flag.FlagSet {
			exposed := flag.NewFlagSet("exposed", flag.ContinueOnError)
			if len(exposedFlags) > 0 {
				for _, name := range exposedFlags {
					if flag := c.Flags().Lookup(name); flag != nil {
						exposed.AddFlag(flag)
					}
				}
			}
			return exposed
		},
	}
}
Example #21
0
func (c *ToggleCommentCommand) Run(v *View, e *Edit) error {
	// TODO: Comment the line if we only have a cursor.
	// TODO: Expand the selection after altering it.
	// TODO: Align the comment characters for multiline selections.
	// TODO: Get the comment value from the Textmate files.
	comm := "//"

	for _, r := range v.Sel().Regions() {
		if r.Size() != 0 {
			t := v.Buffer().Substr(r)

			trim := strings.TrimLeftFunc(t, unicode.IsSpace)
			if strings.HasPrefix(trim, comm) {
				repl := comm
				if strings.HasPrefix(trim, comm+" ") {
					repl += " "
				}

				t = strings.Replace(t, repl, "", 1)
			} else {
				t = strings.Replace(t, trim, comm+" "+trim, 1)
			}

			v.Replace(e, r, t)
		}
	}

	return nil
}
Example #22
0
func register(cmd string, f interface{}, usage string) {
	switch f.(type) {
	case func(*docopt.Args, *controller.Client) error, func(*docopt.Args) error, func() error, func():
	default:
		panic(fmt.Sprintf("invalid command function %s '%T'", cmd, f))
	}
	commands[cmd] = command{strings.TrimLeftFunc(usage, unicode.IsSpace), f}
}
Example #23
0
func main() {
	fmt.Println(strings.TrimLeftFunc("&widuu&", func(r rune) bool {
		if r == '&' {
			return true
		}
		return false
	})) //	widuu&是不是跟上边的那个函数效果一样了
}
Example #24
0
File: main.go Project: qt/qtqa
func extractChangeLog(commitMessage string) (entry changeLogEntry) {
	scanner := bufio.NewScanner(bytes.NewBufferString(commitMessage))

	for scanner.Scan() {
		trimmedLine := strings.TrimSpace(scanner.Text())

		if entry.text == "" {
			withoutChangeLog := strings.TrimPrefix(trimmedLine, "[ChangeLog]")
			if withoutChangeLog == trimmedLine {
				continue
			}

			remainder := withoutChangeLog
			for {
				withoutBracket := strings.TrimPrefix(remainder, "[")
				if withoutBracket == remainder {
					break
				}
				var group string
				remainder = strings.TrimLeftFunc(withoutBracket, func(ch rune) bool {
					endOfGroup := ch == ']'
					if !endOfGroup {
						group += string(ch)
					}
					return !endOfGroup
				})
				remainder = strings.TrimPrefix(remainder, "]")
				if entry.module == "" {
					entry.module = group
				} else if entry.class == "" {
					entry.class = group
				} else {
					remainder = "[" + withoutBracket
					break
				}
			}

			entry.text = strings.TrimSpace(remainder)
		} else if trimmedLine == "" {
			break
		} else {
			entry.text = entry.text + " " + trimmedLine
		}
	}

	if entry.text != "" {
		for scanner.Scan() {
			trimmedLine := strings.TrimSpace(scanner.Text())
			if !strings.HasPrefix(strings.ToLower(trimmedLine), "task-number:") {
				continue
			}
			entry.text = "[" + strings.TrimSpace(trimmedLine[len("task-number:"):]) + "] " + entry.text
			break
		}
	}

	return
}
Example #25
0
func stripEscapedWhitespace(s string) string {
	esc := strings.Split(s, "\\\n")
	if len(esc) > 1 {
		for i := 1; i < len(esc); i++ {
			esc[i] = strings.TrimLeftFunc(esc[i], unicode.IsSpace)
		}
	}
	return strings.Join(esc, "")
}
Example #26
0
//export go_fast_blank
func go_fast_blank(s C.VALUE) C.VALUE {
	gs := C.GoString(C.rb_string_value_cstr(&s))

	if gs == "" || strings.TrimLeftFunc(gs, unicode.IsSpace) == "" {
		return C.Qtrue
	}

	return C.Qfalse
}
Example #27
0
// ParseTagNames parses a string for hashtags.
func ParseTagNames(text string) []string {
	var names []string
	matches := hashtag.Regex.FindAllString(text, len(text))
	for _, match := range matches {
		name := strings.TrimLeftFunc(match, isHashtagDecoration)
		names = append(names, name)
	}
	return names
}
Example #28
0
// TrimLeftFunc trims the runes from the left end of the text where the specified callback function returns true,
// returning a new structure and leaving the original unchanged.
func (piece *RichText) TrimLeftFunc(f func(rune) bool) *RichText {
	s := piece.String()
	trimmed := strings.TrimLeftFunc(s, f)
	if len(trimmed) == len(s) {
		return piece
	}
	_, right := piece.Split(len(s) - len(trimmed))
	return right
}
Example #29
0
func Register(cmd string, f interface{}, usage string) *command {
	switch f.(type) {
	case func(*docopt.Args, cluster.Host) error, func(*docopt.Args):
	default:
		panic(fmt.Sprintf("invalid command function %s '%T'", cmd, f))
	}
	c := &command{usage: strings.TrimLeftFunc(usage, unicode.IsSpace), f: f}
	commands[cmd] = c
	return c
}
Example #30
0
func (grub *Grub2) parseTitle(line string) (string, bool) {
	line = strings.TrimLeftFunc(line, unicode.IsSpace)
	if entryRegexpSingleQuote.MatchString(line) {
		return entryRegexpSingleQuote.FindStringSubmatch(line)[2], true
	} else if entryRegexpDoubleQuote.MatchString(line) {
		return entryRegexpDoubleQuote.FindStringSubmatch(line)[2], true
	} else {
		return "", false
	}
}