]> Cypherpunks.ru repositories - gorecfile.git/blob - w.go
Enspace trailing backslash for convenience
[gorecfile.git] / w.go
1 /*
2 recfile -- GNU recutils'es recfiles parser on pure Go
3 Copyright (C) 2020-2023 Sergey Matveev <stargrave@stargrave.org>
4
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.
8
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.
13
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/>.
16 */
17
18 package recfile
19
20 import (
21         "io"
22         "strings"
23 )
24
25 type Writer struct {
26         w io.StringWriter
27 }
28
29 func NewWriter(w io.StringWriter) *Writer { return &Writer{w} }
30
31 func (w *Writer) RecordStart() (written int, err error) { return w.w.WriteString("\n") }
32
33 func backslashSpace(s string) string {
34         if strings.HasSuffix(s, "\\") {
35                 return s + " "
36         }
37         return s
38 }
39
40 func (w *Writer) WriteFields(fs ...Field) (written int, err error) {
41         var n int
42         for _, f := range fs {
43                 n, err = w.w.WriteString(
44                         f.Name + ": " + backslashSpace(strings.TrimLeft(f.Value, " ")) + "\n",
45                 )
46                 written += n
47                 if err != nil {
48                         return
49                 }
50         }
51         return
52 }
53
54 func (w *Writer) WriteFieldMultiline(name string, lines []string) (written int, err error) {
55         var n int
56         n, err = w.w.WriteString(
57                 name + ": " + backslashSpace(strings.TrimLeft(lines[0], " ")) + "\n",
58         )
59         written += n
60         if err != nil {
61                 return
62         }
63         for _, l := range lines[1:] {
64                 n, err = w.w.WriteString("+ " + backslashSpace(l) + "\n")
65                 written += n
66                 if err != nil {
67                         return
68                 }
69         }
70         return
71 }