-
-
Notifications
You must be signed in to change notification settings - Fork 119
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Preserve indentation when using parseDocument
#338
Changes from 3 commits
d0c752e
9a4fe29
5083b19
34a37e2
4a1b2cc
15c363c
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -102,7 +102,24 @@ export function resolveBlockMap( | |
: composeEmptyNode(ctx, offset, sep, null, valueProps, onError) | ||
offset = valueNode.range[2] | ||
const pair = new Pair(keyNode, valueNode) | ||
if (ctx.options.keepSourceTokens) pair.srcToken = collItem | ||
if (ctx.options.keepSourceTokens) { | ||
pair.srcToken = collItem | ||
|
||
// Check to see if the key tokens exist and have an indentation set. | ||
// If so, we can compute the difference between them and preserve it | ||
// if the preserveCollectionIndentation option is set. | ||
const keyIndent: number | undefined = (collItem?.key as any)?.indent | ||
const valueIndent: number | undefined = (collItem?.value as any)?.indent | ||
|
||
if ( | ||
ctx.options.preserveCollectionIndentation && | ||
keyIndent !== undefined && | ||
valueIndent !== undefined && | ||
valueIndent >= keyIndent | ||
) { | ||
pair.srcIndentStep = valueIndent - keyIndent | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why do you think this ought to be conditional on both There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Huh, for some reason in my initial tests I thought that we wouldn't have the right source indent info without |
||
} | ||
} | ||
map.items.push(pair) | ||
} else { | ||
// key with no value | ||
|
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
|
@@ -27,6 +27,17 @@ export type ParseOptions = { | |||||
*/ | ||||||
keepSourceTokens?: boolean | ||||||
|
||||||
/** | ||||||
* When parsing a document, stores indentation levels on each collection node, | ||||||
* allowing them to be preserved when latery stringified. | ||||||
* | ||||||
* If 'keepSourceTokens' is not `true`, this has no affect, since source tokens | ||||||
* must be provided in order to determine indentation. | ||||||
* | ||||||
* Default: `false` | ||||||
*/ | ||||||
preserveCollectionIndentation?: boolean | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
The verb "keep" is used more commonly here; see e.g. the The consideration here is also only for maps, rather than all collections, and the name of the option ought to reflect that. Also, these options ought to be kept alphabetically sorted. |
||||||
|
||||||
/** | ||||||
* If set, newlines will be tracked, to allow for `lineCounter.linePos(offset)` | ||||||
* to provide the `{ line, col }` positions within the input. | ||||||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -5,18 +5,39 @@ import { stringify, StringifyContext } from './stringify.js' | |
import { addComment, stringifyComment } from './stringifyComment.js' | ||
|
||
export function stringifyPair( | ||
{ key, value }: Readonly<Pair>, | ||
{ key, value, srcIndentStep }: Readonly<Pair>, | ||
ctx: StringifyContext, | ||
onComment?: () => void, | ||
onChompKeep?: () => void | ||
) { | ||
const { | ||
let { | ||
allNullValues, | ||
doc, | ||
indent, | ||
indentStep, | ||
options: { indentSeq, simpleKeys } | ||
} = ctx | ||
if (srcIndentStep !== undefined) { | ||
// If the pair originally had some indentation step, preserve that | ||
// value. | ||
if (srcIndentStep > 0 || (srcIndentStep === 0 && isSeq(value))) { | ||
// Indentation can only be preserved if it's positive, or if it's 0 | ||
// and the item to render is a seq, since: | ||
Comment on lines
+23
to
+25
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This isn't quite so clear-cut, as this doesn't take into account flow sequences, explicit tags, or anchors. There's an if statement starting on line 112 that covers that case for the To properly support keeping block sequence indents starting with |
||
|
||
// foo: | ||
// - a | ||
// - b | ||
// - c | ||
|
||
// is a valid seq with 0 indentStep. | ||
|
||
// Note that ctx.indentStep is *not* modified, so later indentations | ||
// will still use the original indentStep if not being preserved from | ||
// input. | ||
indentStep = ' '.repeat(srcIndentStep) | ||
} | ||
} | ||
|
||
let keyComment = (isNode(key) && key.comment) || null | ||
if (simpleKeys) { | ||
if (keyComment) { | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,160 @@ | ||
import { parseDocument } from 'yaml' | ||
|
||
describe('preserveCollectionIndentation', () => { | ||
// This sample document has very unusual indentation, which helps | ||
// to ensure that it really does end up being preserved exactly. | ||
const sample = ` | ||
a: | ||
b: | ||
c: d | ||
more: e | ||
|
||
big_indent: | ||
- a | ||
- b | ||
- c | ||
more: | ||
# A comment goes here, | ||
# which spans multiple lines. | ||
|
||
# Ideally, a blank line is still preserved as well, | ||
# so that large comment blocks can be separated. | ||
a: | ||
- x # after the item | ||
# between items | ||
- y: | ||
further: | ||
indentation: | ||
- is | ||
- possible | ||
- even: | ||
tho: | ||
it: | ||
changes: a lot | ||
- z | ||
# after last | ||
` | ||
|
||
test('preserveCollectionIndentation: toString() preserve document indentation', () => { | ||
const document = parseDocument(sample, { | ||
keepSourceTokens: true, | ||
preserveCollectionIndentation: true | ||
}) | ||
const roundtrippedSource = document.toString() | ||
|
||
expect(roundtrippedSource.trim()).toEqual(sample.trim()) | ||
}) | ||
|
||
// sample2 corresponds to the JSON `{"foo": ["a", "b", "c"]}` | ||
// The Seq is not indented at all, and we can preserve that when | ||
// parsing. | ||
const sample2 = ` | ||
foo: | ||
- a | ||
- b | ||
- c | ||
` | ||
// However, when we edit the field to replace the list with an object, | ||
// some indentation is now required. In this case, we default to the | ||
// original 'indentStep' value (e.g. 2 in this case) because some | ||
// level of indentation is required. | ||
const sample3 = ` | ||
foo: | ||
a: 1 | ||
b: 2 | ||
c: 3 | ||
` | ||
|
||
test('preserveCollectionIndentation: produces correct yaml when preserving indentation with edits', () => { | ||
const document = parseDocument(sample2, { | ||
keepSourceTokens: true, | ||
preserveCollectionIndentation: true | ||
}) | ||
expect(document.toString().trim()).toEqual(sample2.trim()) | ||
|
||
// When replacing the item, we now need indentation, since otherwise | ||
// the document has a different structure than it initially did. | ||
document.set('foo', { a: 1, b: 2, c: 3 }) | ||
expect(document.toString().trim()).toEqual(sample3.trim()) | ||
}) | ||
|
||
const combined = ` | ||
a: | ||
b: | ||
c: d | ||
more: e | ||
|
||
big_indent: | ||
- a | ||
- b | ||
- c | ||
more: | ||
# A comment goes here, | ||
# which spans multiple lines. | ||
|
||
# Ideally, a blank line is still preserved as well, | ||
# so that large comment blocks can be separated. | ||
a: | ||
- x # after the item | ||
# between items | ||
- y: | ||
further: | ||
indentation: | ||
- is | ||
- possible | ||
- even: | ||
tho: | ||
it: | ||
changes: a lot | ||
- z | ||
# after last | ||
preservedDocument: | ||
a: | ||
b: | ||
c: d | ||
more: e | ||
|
||
big_indent: | ||
- a | ||
- b | ||
- c | ||
more: | ||
# A comment goes here, | ||
# which spans multiple lines. | ||
|
||
# Ideally, a blank line is still preserved as well, | ||
# so that large comment blocks can be separated. | ||
a: | ||
- x # after the item | ||
# between items | ||
- y: | ||
further: | ||
indentation: | ||
- is | ||
- possible | ||
- even: | ||
tho: | ||
it: | ||
changes: a lot | ||
- z | ||
# after last | ||
` | ||
|
||
test('preserveCollectionIndentation: documents with preserved indentation can be inserted into other documents', () => { | ||
const document = parseDocument(sample, { | ||
keepSourceTokens: true, | ||
preserveCollectionIndentation: true | ||
}) | ||
|
||
// In this new document, we purposefully skip preserving indentation: | ||
const newDocument = parseDocument(sample, { | ||
preserveCollectionIndentation: false | ||
}) | ||
|
||
// The indentation-preserved document is inserted into the "main" document, | ||
// and maintains its original indentation level. | ||
newDocument.set('preservedDocument', document) | ||
|
||
expect(newDocument.toString().trim()).toEqual(combined.trim()) | ||
}) | ||
}) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
collItem
has already been destructured on line 23, and there should be no case where these values are not numbers. And if there is, any>=
with anundefined
will fail.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
TypeScript doesn't permit you to compare
number|undefined
values with>=
, even though JavaScript has the right semantics. So we either need a cast (which seems unnecessary) or we need to explicitly include the logic to excludeundefined
values.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I've fixed this to avoid the
as any
casts; I didn't notice the destructuring in the first past. Now it's simplified (somewhat) toThe extra logic here is needed to convince TypeScript that it's okay:
key.indent
is only valid if we know that"indent"
is inkey
in the first place (and some of the variants don't include anindent
field), so we have to do"indent" in key
before we can writekey.indent
'indent' in key
is only valid ifkey
is not null/undefined, so we have to checkkey &&
first