func ParseString()

in pkg/ndbconfig/configparser/config_parser.go [140:218]


func ParseString(configStr string) (ConfigIni, error) {

	c := make(ConfigIni)
	var lineNo int
	var currentSection Section

	// Parse the config string using a bufio.Scanner
	scanner := bufio.NewScanner(strings.NewReader(configStr))
	for scanner.Scan() {
		// Process one line at a time
		line := strings.TrimSpace(scanner.Text())
		lineNo++
		if line == "" {
			// Empty line
			continue
		}

		// Check if this is a comment.
		// Any key value pair declared inside the first comment block
		// on top of the config, before any section is declared, will
		// be collected under the "header" section.
		var isComment bool
		if line[0] == ';' || line[0] == '#' {
			isComment = true
			line = strings.TrimSpace(strings.TrimLeft(line, ";#"))
			if line == "" {
				// No more text in comment
				continue
			}

			if len(c) == 0 {
				// No sections have been declared yet and this is the first comment block.
				// Collect any key=value pairs under the section "header"
				currentSection = c.addSection(headerSection)
			} else if len(c) == 1 && c.GetSection(headerSection) != nil {
				// First comment block and headerSection is being read
				currentSection = c.GetSection(headerSection)
			} else {
				// We can ignore this comment
				continue
			}
		} else if line[0] == '[' {
			// A section starts
			if line[len(line)-1] != ']' {
				return nil, fmt.Errorf("Incomplete section name at line %d : %s", lineNo, line)
			}

			// create/load the section
			sectionName := line[1 : len(line)-1]
			currentSection = c.addSection(sectionName)
			continue
		}

		if currentSection == nil {
			// No section is currently being read
			return nil, fmt.Errorf("Non-empty line without section at line %d : %s", lineNo, line)
		}

		// Split the line to look for a key value pair
		tokens := strings.SplitN(line, "=", 2)
		if len(tokens) != 2 || tokens[1] == "" {
			if isComment {
				// Ignore errors in a comment
				continue
			}
			return nil, fmt.Errorf("Format error at line %d : %s", lineNo, line)
		}

		// store the config key value pair
		currentSection.SetValue(tokens[0], tokens[1])
	}

	if err := scanner.Err(); err != nil {
		// Error occurred during config scan
		return nil, err
	}

	return c, nil
}