|
| 1 | +/* |
| 2 | + Copyright 2020 The Compose Specification Authors. |
| 3 | +
|
| 4 | + Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + you may not use this file except in compliance with the License. |
| 6 | + You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | + Unless required by applicable law or agreed to in writing, software |
| 11 | + distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + See the License for the specific language governing permissions and |
| 14 | + limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package loader |
| 18 | + |
| 19 | +import "github.com/compose-spec/compose-go/v2/tree" |
| 20 | + |
| 21 | +var omitempty = []tree.Path{ |
| 22 | + "services.*.dns"} |
| 23 | + |
| 24 | +// OmitEmpty removes empty attributes which are irrelevant when unset |
| 25 | +func OmitEmpty(yaml map[string]any) map[string]any { |
| 26 | + cleaned := omitEmpty(yaml, tree.NewPath()) |
| 27 | + return cleaned.(map[string]any) |
| 28 | +} |
| 29 | + |
| 30 | +func omitEmpty(data any, p tree.Path) any { |
| 31 | + switch v := data.(type) { |
| 32 | + case map[string]any: |
| 33 | + for k, e := range v { |
| 34 | + if isEmpty(e) && mustOmit(p) { |
| 35 | + delete(v, k) |
| 36 | + continue |
| 37 | + } |
| 38 | + |
| 39 | + v[k] = omitEmpty(e, p.Next(k)) |
| 40 | + } |
| 41 | + return v |
| 42 | + case []any: |
| 43 | + var c []any |
| 44 | + for _, e := range v { |
| 45 | + if isEmpty(e) && mustOmit(p) { |
| 46 | + continue |
| 47 | + } |
| 48 | + |
| 49 | + c = append(c, omitEmpty(e, p.Next("[]"))) |
| 50 | + } |
| 51 | + return c |
| 52 | + default: |
| 53 | + return data |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +func mustOmit(p tree.Path) bool { |
| 58 | + for _, pattern := range omitempty { |
| 59 | + if p.Matches(pattern) { |
| 60 | + return true |
| 61 | + } |
| 62 | + } |
| 63 | + return false |
| 64 | +} |
| 65 | + |
| 66 | +func isEmpty(e any) bool { |
| 67 | + if e == nil { |
| 68 | + return true |
| 69 | + } |
| 70 | + if v, ok := e.(string); ok && v == "" { |
| 71 | + return true |
| 72 | + } |
| 73 | + return false |
| 74 | +} |
0 commit comments