String returns a string representation of the supplied cft.Template
(t *cft.Template, opt Options)
| 31 | |
| 32 | // String returns a string representation of the supplied cft.Template |
| 33 | func String(t *cft.Template, opt Options) string { |
| 34 | node := t.Node |
| 35 | |
| 36 | buf := strings.Builder{} |
| 37 | enc := yaml.NewEncoder(&buf) |
| 38 | enc.SetIndent(2) |
| 39 | |
| 40 | node = formatNode(node) |
| 41 | |
| 42 | if !opt.Unsorted { |
| 43 | node = orderTemplate(node) |
| 44 | } |
| 45 | |
| 46 | err := enc.Encode(node) |
| 47 | if err != nil { |
| 48 | panic(err) |
| 49 | } |
| 50 | |
| 51 | parts := strings.Split(strings.TrimSpace(buf.String()), "\n") |
| 52 | result := strings.Builder{} |
| 53 | |
| 54 | lastIndent := 0 |
| 55 | indent := 0 |
| 56 | lastPartWasComment := false |
| 57 | lastLineWasEmpty := false |
| 58 | startMultilineIndent := -1 |
| 59 | |
| 60 | for _, part := range parts { |
| 61 | |
| 62 | trimmedPart := strings.TrimLeft(part, " ") |
| 63 | indent = len(part) - len(trimmedPart) |
| 64 | |
| 65 | // Leave lines alone if they are in a multiline block |
| 66 | // Note: CloudFormation does not comply with the YAML spec. It treats > just like | |
| 67 | // https://yaml-multiline.info/ |
| 68 | // https://stackoverflow.com/questions/3790454/how-do-i-break-a-string-in-yaml-over-multiple-lines |
| 69 | // https://yaml.org/spec/1.2-old/spec.html#id2760844 |
| 70 | isMultiline := false |
| 71 | if startMultilineIndent > -1 { |
| 72 | // Note: len(part) == 0 means empty line without indentation |
| 73 | // https://github.com/aws-cloudformation/rain/issues/126 |
| 74 | if indent <= startMultilineIndent && len(part) != 0 { |
| 75 | startMultilineIndent = -1 |
| 76 | } else { |
| 77 | isMultiline = true |
| 78 | } |
| 79 | } |
| 80 | trimmedRight := strings.TrimRight(part, " ") |
| 81 | if !isMultiline && CheckMultilineBegin(trimmedRight) { |
| 82 | startMultilineIndent = indent |
| 83 | } |
| 84 | |
| 85 | isComment := false |
| 86 | if len(part) > 0 && strings.HasPrefix(trimmedPart, "#") { |
| 87 | isComment = true |
| 88 | } |
| 89 | |
| 90 | isEmpty := len(part) == 0 // This should never be true |