]> Cypherpunks.ru repositories - gorecfile.git/blob - w.go
Unify copyright comment format
[gorecfile.git] / w.go
1 // recfile -- GNU recutils'es recfiles parser on pure Go
2 // Copyright (C) 2020-2024 Sergey Matveev <stargrave@stargrave.org>
3 //
4 // This program is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, version 3 of the License.
7 //
8 // This program is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 // GNU General Public License for more details.
12 //
13 // You should have received a copy of the GNU General Public License
14 // along with this program.  If not, see <http://www.gnu.org/licenses/>.
15
16 package recfile
17
18 import (
19         "io"
20         "strings"
21 )
22
23 type Writer struct {
24         w io.StringWriter
25 }
26
27 func NewWriter(w io.StringWriter) *Writer { return &Writer{w} }
28
29 func (w *Writer) RecordStart() (written int, err error) { return w.w.WriteString("\n") }
30
31 func backslashSpace(s string) string {
32         if strings.HasSuffix(s, "\\") {
33                 return s + " "
34         }
35         return s
36 }
37
38 func (w *Writer) WriteFields(fs ...Field) (written int, err error) {
39         var n int
40         for _, f := range fs {
41                 n, err = w.w.WriteString(
42                         f.Name + ": " + backslashSpace(strings.TrimLeft(f.Value, " ")) + "\n",
43                 )
44                 written += n
45                 if err != nil {
46                         return
47                 }
48         }
49         return
50 }
51
52 func (w *Writer) WriteFieldMultiline(name string, lines []string) (written int, err error) {
53         var n int
54         n, err = w.w.WriteString(
55                 name + ": " + backslashSpace(strings.TrimLeft(lines[0], " ")) + "\n",
56         )
57         written += n
58         if err != nil {
59                 return
60         }
61         for _, l := range lines[1:] {
62                 n, err = w.w.WriteString("+ " + backslashSpace(l) + "\n")
63                 written += n
64                 if err != nil {
65                         return
66                 }
67         }
68         return
69 }