env_file.go 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  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 system
  15. import (
  16. "bytes"
  17. "fmt"
  18. "io/ioutil"
  19. "os"
  20. "path"
  21. "regexp"
  22. "sort"
  23. )
  24. type EnvFile struct {
  25. Vars map[string]string
  26. // mask File.Content, it shouldn't be used.
  27. Content interface{} `json:"-" yaml:"-"`
  28. *File
  29. }
  30. // only allow sh compatible identifiers
  31. var validKey = regexp.MustCompile(`^[a-zA-Z0-9_]+$`)
  32. // match each line, optionally capturing valid identifiers, discarding dos line endings
  33. var lineLexer = regexp.MustCompile(`(?m)^((?:([a-zA-Z0-9_]+)=)?.*?)\r?\n`)
  34. // mergeEnvContents: Update the existing file contents with new values,
  35. // preserving variable ordering and all content this code doesn't understand.
  36. // All new values are appended to the bottom of the old, sorted by key.
  37. func mergeEnvContents(old []byte, pending map[string]string) []byte {
  38. var buf bytes.Buffer
  39. var match [][]byte
  40. // it is awkward for the regex to handle a missing newline gracefully
  41. if len(old) != 0 && !bytes.HasSuffix(old, []byte{'\n'}) {
  42. old = append(old, byte('\n'))
  43. }
  44. for _, match = range lineLexer.FindAllSubmatch(old, -1) {
  45. key := string(match[2])
  46. if value, ok := pending[key]; ok {
  47. fmt.Fprintf(&buf, "%s=%s\n", key, value)
  48. delete(pending, key)
  49. } else {
  50. fmt.Fprintf(&buf, "%s\n", match[1])
  51. }
  52. }
  53. for _, key := range keys(pending) {
  54. value := pending[key]
  55. fmt.Fprintf(&buf, "%s=%s\n", key, value)
  56. }
  57. return buf.Bytes()
  58. }
  59. // WriteEnvFile updates an existing env `KEY=value` formated file with
  60. // new values provided in EnvFile.Vars; File.Content is ignored.
  61. // Existing ordering and any unknown formatting such as comments are
  62. // preserved. If no changes are required the file is untouched.
  63. func WriteEnvFile(ef *EnvFile, root string) error {
  64. // validate new keys, mergeEnvContents uses pending to track writes
  65. pending := make(map[string]string, len(ef.Vars))
  66. for key, value := range ef.Vars {
  67. if !validKey.MatchString(key) {
  68. return fmt.Errorf("Invalid name %q for %s", key, ef.Path)
  69. }
  70. pending[key] = value
  71. }
  72. if len(pending) == 0 {
  73. return nil
  74. }
  75. oldContent, err := ioutil.ReadFile(path.Join(root, ef.Path))
  76. if err != nil {
  77. if os.IsNotExist(err) {
  78. oldContent = []byte{}
  79. } else {
  80. return err
  81. }
  82. }
  83. newContent := mergeEnvContents(oldContent, pending)
  84. if bytes.Equal(oldContent, newContent) {
  85. return nil
  86. }
  87. ef.File.Content = string(newContent)
  88. _, err = WriteFile(ef.File, root)
  89. return err
  90. }
  91. // keys returns the keys of a map in sorted order
  92. func keys(m map[string]string) (s []string) {
  93. for k := range m {
  94. s = append(s, k)
  95. }
  96. sort.Strings(s)
  97. return
  98. }