serialize.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. package unit
  15. import (
  16. "bytes"
  17. "io"
  18. )
  19. // Serialize encodes all of the given UnitOption objects into a
  20. // unit file. When serialized the options are sorted in their
  21. // supplied order but grouped by section.
  22. func Serialize(opts []*UnitOption) io.Reader {
  23. var buf bytes.Buffer
  24. if len(opts) == 0 {
  25. return &buf
  26. }
  27. // Index of sections -> ordered options
  28. idx := map[string][]*UnitOption{}
  29. // Separately preserve order in which sections were seen
  30. sections := []string{}
  31. for _, opt := range opts {
  32. sec := opt.Section
  33. if _, ok := idx[sec]; !ok {
  34. sections = append(sections, sec)
  35. }
  36. idx[sec] = append(idx[sec], opt)
  37. }
  38. for i, sect := range sections {
  39. writeSectionHeader(&buf, sect)
  40. writeNewline(&buf)
  41. opts := idx[sect]
  42. for _, opt := range opts {
  43. writeOption(&buf, opt)
  44. writeNewline(&buf)
  45. }
  46. if i < len(sections)-1 {
  47. writeNewline(&buf)
  48. }
  49. }
  50. return &buf
  51. }
  52. func writeNewline(buf *bytes.Buffer) {
  53. buf.WriteRune('\n')
  54. }
  55. func writeSectionHeader(buf *bytes.Buffer, section string) {
  56. buf.WriteRune('[')
  57. buf.WriteString(section)
  58. buf.WriteRune(']')
  59. }
  60. func writeOption(buf *bytes.Buffer, opt *UnitOption) {
  61. buf.WriteString(opt.Name)
  62. buf.WriteRune('=')
  63. buf.WriteString(opt.Value)
  64. }