ReplaceEnvFile changes value for service.extends.env_file in input yaml stream, preserving formatting
(in []byte, service string, i int, value string)
| 63 | |
| 64 | // ReplaceEnvFile changes value for service.extends.env_file in input yaml stream, preserving formatting |
| 65 | func ReplaceEnvFile(in []byte, service string, i int, value string) ([]byte, error) { |
| 66 | var doc yaml.Node |
| 67 | err := yaml.Unmarshal(in, &doc) |
| 68 | if err != nil { |
| 69 | return nil, err |
| 70 | } |
| 71 | if doc.Kind != yaml.DocumentNode { |
| 72 | return nil, fmt.Errorf("expected document kind %v, got %v", yaml.DocumentNode, doc.Kind) |
| 73 | } |
| 74 | root := doc.Content[0] |
| 75 | if root.Kind != yaml.MappingNode { |
| 76 | return nil, fmt.Errorf("expected document root to be a mapping, got %v", root.Kind) |
| 77 | } |
| 78 | |
| 79 | services, err := getMapping(root, "services") |
| 80 | if err != nil { |
| 81 | return nil, err |
| 82 | } |
| 83 | |
| 84 | target, err := getMapping(services, service) |
| 85 | if err != nil { |
| 86 | return nil, err |
| 87 | } |
| 88 | |
| 89 | envFile, err := getMapping(target, "env_file") |
| 90 | if err != nil { |
| 91 | return nil, err |
| 92 | } |
| 93 | |
| 94 | // env_file can be either a string, sequence of strings, or sequence of mappings with path attribute |
| 95 | if envFile.Kind == yaml.SequenceNode { |
| 96 | envFile = envFile.Content[i] |
| 97 | if envFile.Kind == yaml.MappingNode { |
| 98 | envFile, err = getMapping(envFile, "path") |
| 99 | if err != nil { |
| 100 | return nil, err |
| 101 | } |
| 102 | } |
| 103 | return replace(in, envFile.Line, envFile.Column, value), nil |
| 104 | } else { |
| 105 | return replace(in, envFile.Line, envFile.Column, value), nil |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | func getMapping(root *yaml.Node, key string) (*yaml.Node, error) { |
| 110 | var node *yaml.Node |
no test coverage detected