|
1 | | -import { Type } from '../cst/Node' |
| 1 | +import { Char, Type } from '../cst/Node' |
2 | 2 | import PlainValue from '../cst/PlainValue' |
3 | 3 | import { YAMLSemanticError, YAMLSyntaxError } from '../errors' |
4 | 4 | import Map from './Map' |
@@ -58,6 +58,33 @@ export default function parseMap(doc, cst) { |
58 | 58 | return map |
59 | 59 | } |
60 | 60 |
|
| 61 | +const valueHasPairComment = ({ context: { lineStart, node, src }, props }) => { |
| 62 | + if (props.length === 0) return false |
| 63 | + const { start } = props[0] |
| 64 | + if (node && start > node.valueRange.start) return false |
| 65 | + if (src[start] !== Char.COMMENT) return false |
| 66 | + for (let i = lineStart; i < start; ++i) if (src[i] === '\n') return false |
| 67 | + return true |
| 68 | +} |
| 69 | + |
| 70 | +function resolvePairComment(item, pair) { |
| 71 | + if (!valueHasPairComment(item)) return |
| 72 | + const comment = item.getPropValue(0, Char.COMMENT, true) |
| 73 | + let found = false |
| 74 | + const cb = pair.value.commentBefore |
| 75 | + if (cb && cb.startsWith(comment)) { |
| 76 | + pair.value.commentBefore = cb.substr(comment.length + 1) |
| 77 | + found = true |
| 78 | + } else { |
| 79 | + const cc = pair.value.comment |
| 80 | + if (!item.node && cc && cc.startsWith(comment)) { |
| 81 | + pair.value.comment = cc.substr(comment.length + 1) |
| 82 | + found = true |
| 83 | + } |
| 84 | + } |
| 85 | + if (found) pair.comment = comment |
| 86 | +} |
| 87 | + |
61 | 88 | function resolveBlockMapItems(doc, cst) { |
62 | 89 | const comments = [] |
63 | 90 | const items = [] |
@@ -102,15 +129,17 @@ function resolveBlockMapItems(doc, cst) { |
102 | 129 | valueNode = new PlainValue(Type.PLAIN, []) |
103 | 130 | valueNode.context = { parent: item, src: item.context.src } |
104 | 131 | const pos = item.range.start + 1 |
105 | | - const origPos = item.range.origStart + 1 |
106 | 132 | valueNode.range = { start: pos, end: pos } |
107 | 133 | valueNode.valueRange = { start: pos, end: pos } |
108 | 134 | if (typeof item.range.origStart === 'number') { |
| 135 | + const origPos = item.range.origStart + 1 |
109 | 136 | valueNode.range.origStart = valueNode.range.origEnd = origPos |
110 | 137 | valueNode.valueRange.origStart = valueNode.valueRange.origEnd = origPos |
111 | 138 | } |
112 | 139 | } |
113 | | - items.push(new Pair(key, doc.resolveNode(valueNode))) |
| 140 | + const pair = new Pair(key, doc.resolveNode(valueNode)) |
| 141 | + resolvePairComment(item, pair) |
| 142 | + items.push(pair) |
114 | 143 | checkKeyLength(doc.errors, cst, i, key, keyStart) |
115 | 144 | key = undefined |
116 | 145 | keyStart = null |
|
0 commit comments