Debian Codegraph @

plumbing/format/config/encoder.go

raw
1 package config
2
3 import (
4 "fmt"
5 "io"
6 "strings"
7 )
8
9 // An Encoder writes config files to an output stream.
10 type Encoder struct {
11 w io.Writer
12 }
13
14 var (
15 subsectionReplacer = strings.NewReplacer(`"`, `\"`, `\`, `\\`)
16 valueReplacer = strings.NewReplacer(`"`, `\"`, `\`, `\\`, "\n", `\n`, "\t", `\t`, "\b", `\b`)
17 )
18 // NewEncoder returns a new encoder that writes to w.
19 func NewEncoder(w io.Writer) *Encoder {
20 return &Encoder{w}
21 }
22
23 // Encode writes the config in git config format to the stream of the encoder.
24 func (e *Encoder) Encode(cfg *Config) error {
25 for _, s := range cfg.Sections {
26 if err := e.encodeSection(s); err != nil {
27 return err
28 }
29 }
30
31 return nil
32 }
33
34 func (e *Encoder) encodeSection(s *Section) error {
35 if len(s.Options) > 0 {
36 if err := e.printf("[%s]\n", s.Name); err != nil {
37 return err
38 }
39
40 if err := e.encodeOptions(s.Options); err != nil {
41 return err
42 }
43 }
44
45 for _, ss := range s.Subsections {
46 if err := e.encodeSubsection(s.Name, ss); err != nil {
47 return err
48 }
49 }
50
51 return nil
52 }
53
54 func (e *Encoder) encodeSubsection(sectionName string, s *Subsection) error {
55 if err := e.printf("[%s \"%s\"]\n", sectionName, subsectionReplacer.Replace(s.Name)); err != nil {
56 return err
57 }
58
59 return e.encodeOptions(s.Options)
60 }
61
62 func (e *Encoder) encodeOptions(opts Options) error {
63 for _, o := range opts {
64 var value string
65 if strings.ContainsAny(o.Value, "#;\"\t\n\\") || strings.HasPrefix(o.Value, " ") || strings.HasSuffix(o.Value, " ") {
66 value = `"`+valueReplacer.Replace(o.Value)+`"`
67 } else {
68 value = o.Value
69 }
70
71 if err := e.printf("\t%s = %s\n", o.Key, value); err != nil {
72 return err
73 }
74 }
75
76 return nil
77 }
78
79 func (e *Encoder) printf(msg string, args ...interface{}) error {
80 _, err := fmt.Fprintf(e.w, msg, args...)
81 return err
82 }