~nskaggs/+junk/xenial-test

« back to all changes in this revision

Viewing changes to src/github.com/coreos/go-systemd/unit/serialize.go

  • Committer: Nicholas Skaggs
  • Date: 2016-10-24 20:56:05 UTC
  • Revision ID: nicholas.skaggs@canonical.com-20161024205605-z8lta0uvuhtxwzwl
Initi with beta15

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
// Copyright 2015 CoreOS, Inc.
 
2
//
 
3
// Licensed under the Apache License, Version 2.0 (the "License");
 
4
// you may not use this file except in compliance with the License.
 
5
// You may obtain a copy of the License at
 
6
//
 
7
//     http://www.apache.org/licenses/LICENSE-2.0
 
8
//
 
9
// Unless required by applicable law or agreed to in writing, software
 
10
// distributed under the License is distributed on an "AS IS" BASIS,
 
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
12
// See the License for the specific language governing permissions and
 
13
// limitations under the License.
 
14
 
 
15
package unit
 
16
 
 
17
import (
 
18
        "bytes"
 
19
        "io"
 
20
)
 
21
 
 
22
// Serialize encodes all of the given UnitOption objects into a
 
23
// unit file. When serialized the options are sorted in their
 
24
// supplied order but grouped by section.
 
25
func Serialize(opts []*UnitOption) io.Reader {
 
26
        var buf bytes.Buffer
 
27
 
 
28
        if len(opts) == 0 {
 
29
                return &buf
 
30
        }
 
31
 
 
32
        // Index of sections -> ordered options
 
33
        idx := map[string][]*UnitOption{}
 
34
        // Separately preserve order in which sections were seen
 
35
        sections := []string{}
 
36
        for _, opt := range opts {
 
37
                sec := opt.Section
 
38
                if _, ok := idx[sec]; !ok {
 
39
                        sections = append(sections, sec)
 
40
                }
 
41
                idx[sec] = append(idx[sec], opt)
 
42
        }
 
43
 
 
44
        for i, sect := range sections {
 
45
                writeSectionHeader(&buf, sect)
 
46
                writeNewline(&buf)
 
47
 
 
48
                opts := idx[sect]
 
49
                for _, opt := range opts {
 
50
                        writeOption(&buf, opt)
 
51
                        writeNewline(&buf)
 
52
                }
 
53
                if i < len(sections)-1 {
 
54
                        writeNewline(&buf)
 
55
                }
 
56
        }
 
57
 
 
58
        return &buf
 
59
}
 
60
 
 
61
func writeNewline(buf *bytes.Buffer) {
 
62
        buf.WriteRune('\n')
 
63
}
 
64
 
 
65
func writeSectionHeader(buf *bytes.Buffer, section string) {
 
66
        buf.WriteRune('[')
 
67
        buf.WriteString(section)
 
68
        buf.WriteRune(']')
 
69
}
 
70
 
 
71
func writeOption(buf *bytes.Buffer, opt *UnitOption) {
 
72
        buf.WriteString(opt.Name)
 
73
        buf.WriteRune('=')
 
74
        buf.WriteString(opt.Value)
 
75
}