2 recfile -- GNU recutils'es recfiles parser on pure Go
3 Copyright (C) 2020 Sergey Matveev <stargrave@stargrave.org>
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, version 3 of the License.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
18 // GNU recutils'es recfiles parser on pure Go
29 var KeyValRe = regexp.MustCompile(`([a-zA-Z%][a-zA-Z0-9_]*):\s*(.*)$`)
32 scanner *bufio.Scanner
35 // Create Reader for iterating through the records. It uses
36 // bufio.Scanner, so can read more than currently parsed records take.
37 func NewReader(r io.Reader) *Reader {
38 return &Reader{bufio.NewScanner(r)}
46 // Get next record. Each record is just a collection of fields. io.EOF
47 // is returned if there is nothing to read more.
48 func (r *Reader) Next() ([]Field, error) {
49 fields := make([]Field, 0, 1)
53 lines := make([]string, 0)
57 if !r.scanner.Scan() {
58 if err := r.scanner.Err(); err != nil {
64 text = r.scanner.Text()
67 if text[len(text)-1] == '\\' {
68 lines = append(lines, text[:len(text)-1])
70 lines = append(lines, text)
71 fields = append(fields, Field{name, strings.Join(lines, "")})
72 lines = make([]string, 0)
78 if len(text) > 0 && text[0] == '#' {
82 if len(text) > 0 && text[0] == '+' {
83 lines = append(lines, "\n")
86 lines = append(lines, text[2:])
88 lines = append(lines, text[1:])
95 fields = append(fields, Field{name, strings.Join(lines, "")})
96 lines = make([]string, 0)
103 matches := KeyValRe.FindStringSubmatch(text)
104 if len(matches) == 0 {
105 return fields, errors.New("invalid field format")
110 if len(line) > 0 && line[len(line)-1] == '\\' {
112 lines = append(lines, line[:len(line)-1])
114 lines = append(lines, line)
118 return fields, errors.New("left continuation")
121 fields = append(fields, Field{name, strings.Join(lines, "")})
123 if len(fields) == 0 {