-
Notifications
You must be signed in to change notification settings - Fork 33
/
writer.go
179 lines (162 loc) · 5.01 KB
/
writer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
/*
Copyright 2019 HAProxy Technologies
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package parser
import (
//nolint:gosec
"crypto/md5" // G501: Blocklisted import crypto/md5: weak cryptographic primitive
"fmt"
"io"
"strings"
"github.com/gofrs/flock"
"github.com/google/renameio/maybe"
"github.com/haproxytech/config-parser/v5/types"
)
// String returns configuration in writable form
func (p *configParser) String() string {
if p.Options.Log {
p.Options.Logger.Debugf("%screating string representation", p.Options.LogPrefix)
}
p.lock()
defer p.unLock()
var result strings.Builder
p.writeParsers("", p.Parsers[Comments][CommentsSectionName], &result, false)
p.writeParsers("global", p.Parsers[Global][GlobalSectionName], &result, true)
sections := []Section{Defaults, UserList, Peers, Mailers, Resolvers, Cache, Ring, LogForward, HTTPErrors, CrtStore, Frontends, Backends, Listen, Program, FCGIApp}
for _, section := range sections {
var sortedSections []string
if section == Defaults {
var err error
sortedSections, err = getSortedListWithFrom(p.Parsers[section])
if err != nil && p.Options.Log {
p.Options.Logger.Errorf("%s", err.Error())
}
} else {
sortedSections = p.getSortedList(p.Parsers[section])
}
for _, sectionName := range sortedSections {
var sName string
if sectionName != "" {
sName = fmt.Sprintf("%s %s", section, sectionName)
} else {
sName = string(section)
}
p.writeParsers(sName, p.Parsers[section][sectionName], &result, true)
}
}
return result.String()
}
func (p *configParser) Save(filename string) error {
if p.Options.Log {
p.Options.Logger.Debugf("%ssaving configuration to file %s", p.Options.LogPrefix, filename)
}
if p.Options.UseMd5Hash {
data, err := p.StringWithHash()
if err != nil {
return err
}
return p.save([]byte(data), filename)
}
return p.save([]byte(p.String()), filename)
}
func (p *configParser) save(data []byte, filename string) error {
f := flock.New(filename)
if err := f.Lock(); err != nil {
return err
}
err := maybe.WriteFile(filename, data, 0o644)
if err != nil {
f.Unlock() //nolint:errcheck
return err
}
if err := f.Unlock(); err != nil {
errMsg := err.Error()
return fmt.Errorf("%w %s", UnlockError{}, errMsg)
}
return nil
}
func (p *configParser) StringWithHash() (string, error) {
var result strings.Builder
content := p.String()
//nolint:gosec
hash := md5.Sum([]byte(content))
result.WriteString(fmt.Sprintf("# _md5hash=%x\n", hash))
result.WriteString(content)
if err := p.Set(Comments, CommentsSectionName, "# _md5hash", &types.ConfigHash{Value: fmt.Sprintf("%x", hash)}); err != nil {
return "", err
}
return result.String(), nil
}
func (p *configParser) writeSection(sectionName string, comments []string, defaultsSection string, result io.StringWriter) {
_, _ = result.WriteString("\n")
for _, line := range comments {
_, _ = result.WriteString("# ")
_, _ = result.WriteString(line)
_, _ = result.WriteString("\n")
}
_, _ = result.WriteString(sectionName)
if defaultsSection != "" {
_, _ = result.WriteString(" from ")
_, _ = result.WriteString(defaultsSection)
}
_, _ = result.WriteString("\n")
}
func (p *configParser) writeParsers(sectionName string, parsersData *Parsers, result io.StringWriter, useIndentation bool) {
sectionNameWritten := false
switch sectionName {
case "":
sectionNameWritten = true
case "global":
break
default:
p.writeSection(sectionName, parsersData.PreComments, parsersData.DefaultSectionName, result)
sectionNameWritten = true
}
for _, parserName := range parsersData.ParserSequence {
parser := parsersData.Parsers[string(parserName)]
lines, comments, err := parser.ResultAll()
if err != nil {
continue
}
if !sectionNameWritten {
p.writeSection(sectionName, parsersData.PreComments, parsersData.DefaultSectionName, result)
sectionNameWritten = true
}
for _, line := range comments {
if useIndentation {
_, _ = result.WriteString(" ")
}
_, _ = result.WriteString("# ")
_, _ = result.WriteString(line)
_, _ = result.WriteString("\n")
}
for _, line := range lines {
if useIndentation {
_, _ = result.WriteString(" ")
}
_, _ = result.WriteString(line.Data)
if line.Comment != "" {
_, _ = result.WriteString(" # ")
_, _ = result.WriteString(line.Comment)
}
_, _ = result.WriteString("\n")
}
}
for _, line := range parsersData.PostComments {
if useIndentation {
_, _ = result.WriteString(" ")
}
_, _ = result.WriteString("# ")
_, _ = result.WriteString(line)
_, _ = result.WriteString("\n")
}
}