github.com/wallyworld/juju@v0.0.0-20161013125918-6cf1bc9d917a/service/systemd/serialize.go (about)

     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 systemd
    16  
    17  import (
    18  	"bytes"
    19  	"io"
    20  
    21  	"github.com/coreos/go-systemd/unit"
    22  )
    23  
    24  // UnitSerialize encodes all of the given UnitOption objects into a unit file.
    25  // Renamed from Serialize from github.com/coreos/go-systemd/unit so as to not
    26  // confict with the exported internal function in export_test.go.
    27  func UnitSerialize(opts []*unit.UnitOption) io.Reader {
    28  	var buf bytes.Buffer
    29  
    30  	if len(opts) == 0 {
    31  		return &buf
    32  	}
    33  
    34  	idx := map[string][]*unit.UnitOption{}
    35  	for _, opt := range opts {
    36  		idx[opt.Section] = append(idx[opt.Section], opt)
    37  	}
    38  
    39  	// CHANGED HERE: Output in the following order:
    40  	// - Unit
    41  	// - Service
    42  	// - Install
    43  	// rather than just iterating over the map in random order.
    44  	for _, curSection := range []string{"Unit", "Service", "Install"} {
    45  		curOpts, found := idx[curSection]
    46  		if !found {
    47  			continue
    48  		}
    49  		writeSectionHeader(&buf, curSection)
    50  		writeNewline(&buf)
    51  
    52  		for _, opt := range curOpts {
    53  			writeOption(&buf, opt)
    54  			writeNewline(&buf)
    55  		}
    56  		writeNewline(&buf)
    57  	}
    58  
    59  	return &buf
    60  }
    61  
    62  func writeNewline(buf *bytes.Buffer) {
    63  	buf.WriteRune('\n')
    64  }
    65  
    66  func writeSectionHeader(buf *bytes.Buffer, section string) {
    67  	buf.WriteRune('[')
    68  	buf.WriteString(section)
    69  	buf.WriteRune(']')
    70  }
    71  
    72  func writeOption(buf *bytes.Buffer, opt *unit.UnitOption) {
    73  	buf.WriteString(opt.Name)
    74  	buf.WriteRune('=')
    75  	buf.WriteString(opt.Value)
    76  }