Skip to content
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

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
22 changes: 21 additions & 1 deletion src/compose/resolve-block-map.ts
Expand Up @@ -102,7 +102,27 @@ 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 =
key && 'indent' in key ? key.indent : undefined
const valueIndent: number | undefined =
value && 'indent' in value ? value.indent : undefined
Comment on lines +112 to +115
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would probably be clearer to skip defining these intermediate variables, and just use the conditionals in the subsequent if statement directly.


if (
ctx.options.preserveCollectionIndentation &&
keyIndent !== undefined &&
valueIndent !== undefined &&
valueIndent >= keyIndent
) {
pair.srcIndentStep = valueIndent - keyIndent
}

map.items.push(pair)
} else {
// key with no value
Expand Down
6 changes: 6 additions & 0 deletions src/nodes/Pair.ts
Expand Up @@ -29,6 +29,12 @@ export class Pair<K = unknown, V = unknown> {
/** The CST token that was composed into this pair. */
declare srcToken?: CollectionItem

/**
* The indentation step between key and value in the source, to be
* preserved during stringification.
*/
declare srcIndentStep?: number

constructor(key: K, value: V | null = null) {
Object.defineProperty(this, NODE_TYPE, { value: PAIR })
this.key = key
Expand Down
8 changes: 8 additions & 0 deletions src/options.ts
Expand Up @@ -27,6 +27,14 @@ export type ParseOptions = {
*/
keepSourceTokens?: boolean

/**
* When parsing a document, stores indentation levels on each collection node,
* allowing them to be preserved when later stringified.
*
* Default: `false`
*/
preserveCollectionIndentation?: boolean
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
preserveCollectionIndentation?: boolean
keepMapIndent?: boolean

The verb "keep" is used more commonly here; see e.g. the keepSourceTokens option.

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.
Expand Down
25 changes: 23 additions & 2 deletions src/stringify/stringifyPair.ts
Expand Up @@ -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
Copy link
Owner

Choose a reason for hiding this comment

The 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 indentSeq: true option.

To properly support keeping block sequence indents starting with -, it may be necessary to keep track of something like a srcIndentSeq boolean, and to use that when appropriate to set the indentSeq value.


// 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) {
Expand Down
203 changes: 203 additions & 0 deletions tests/preserve-indentation.ts
@@ -0,0 +1,203 @@
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
list_map1:
- foo: 1
bar: 2
qux: 3
- foo: 4
bar: 5
qux: 6
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, {
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, {
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
list_map1:
- foo: 1
bar: 2
qux: 3
- foo: 4
bar: 5
qux: 6
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
list_map1:
- foo: 1
bar: 2
qux: 3
- foo: 4
bar: 5
qux: 6
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, {
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())
})

const editingSample = `
foo:
big_indent: 1
again: 2
more: 3
`.trim()

const editingSampleAfter = `
foo:
big_indent: 1
again: 2
more: 3
new: 4
`.trim()

test('preserveCollectionIndentation: adds new item preserving indentation', () => {
const document = parseDocument(editingSample, {
preserveCollectionIndentation: true
})

document.setIn(['foo', 'new'], 4)

expect(document.toString().trim()).toEqual(editingSampleAfter)
})
})
14 changes: 14 additions & 0 deletions tests/yaml-test-suite.ts
Expand Up @@ -98,6 +98,20 @@ for (const dir of testDirs) {
const docs2 = parseAllDocuments(src2, { resolveKnownTags: false })
testJsonMatch(docs2, json)
})

test('stringify+re-parse when preserving indentation', () => {
const roundTripDocuments = parseAllDocuments(yaml, {
resolveKnownTags: false,
preserveCollectionIndentation: true
})
testJsonMatch(roundTripDocuments, json)

const src2 =
docs.map(doc => String(doc).replace(/\n$/, '')).join('\n...\n') +
'\n'
const docs2 = parseAllDocuments(src2, { resolveKnownTags: false })
testJsonMatch(docs2, json)
})
}

const outYaml = load('out.yaml')
Expand Down