1
// Copyright 2015 CoreOS, Inc.
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
7
// http://www.apache.org/licenses/LICENSE-2.0
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.
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 {
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 {
38
if _, ok := idx[sec]; !ok {
39
sections = append(sections, sec)
41
idx[sec] = append(idx[sec], opt)
44
for i, sect := range sections {
45
writeSectionHeader(&buf, sect)
49
for _, opt := range opts {
50
writeOption(&buf, opt)
53
if i < len(sections)-1 {
61
func writeNewline(buf *bytes.Buffer) {
65
func writeSectionHeader(buf *bytes.Buffer, section string) {
67
buf.WriteString(section)
71
func writeOption(buf *bytes.Buffer, opt *UnitOption) {
72
buf.WriteString(opt.Name)
74
buf.WriteString(opt.Value)