UNPKG

3.1 kBJavaScriptView Raw
1'use strict';
2
3var identity = require('../nodes/identity.js');
4var stringify = require('./stringify.js');
5var stringifyComment = require('./stringifyComment.js');
6
7function stringifyDocument(doc, options) {
8 const lines = [];
9 let hasDirectives = options.directives === true;
10 if (options.directives !== false && doc.directives) {
11 const dir = doc.directives.toString(doc);
12 if (dir) {
13 lines.push(dir);
14 hasDirectives = true;
15 }
16 else if (doc.directives.docStart)
17 hasDirectives = true;
18 }
19 if (hasDirectives)
20 lines.push('---');
21 const ctx = stringify.createStringifyContext(doc, options);
22 const { commentString } = ctx.options;
23 if (doc.commentBefore) {
24 if (lines.length !== 1)
25 lines.unshift('');
26 const cs = commentString(doc.commentBefore);
27 lines.unshift(stringifyComment.indentComment(cs, ''));
28 }
29 let chompKeep = false;
30 let contentComment = null;
31 if (doc.contents) {
32 if (identity.isNode(doc.contents)) {
33 if (doc.contents.spaceBefore && hasDirectives)
34 lines.push('');
35 if (doc.contents.commentBefore) {
36 const cs = commentString(doc.contents.commentBefore);
37 lines.push(stringifyComment.indentComment(cs, ''));
38 }
39 // top-level block scalars need to be indented if followed by a comment
40 ctx.forceBlockIndent = !!doc.comment;
41 contentComment = doc.contents.comment;
42 }
43 const onChompKeep = contentComment ? undefined : () => (chompKeep = true);
44 let body = stringify.stringify(doc.contents, ctx, () => (contentComment = null), onChompKeep);
45 if (contentComment)
46 body += stringifyComment.lineComment(body, '', commentString(contentComment));
47 if ((body[0] === '|' || body[0] === '>') &&
48 lines[lines.length - 1] === '---') {
49 // Top-level block scalars with a preceding doc marker ought to use the
50 // same line for their header.
51 lines[lines.length - 1] = `--- ${body}`;
52 }
53 else
54 lines.push(body);
55 }
56 else {
57 lines.push(stringify.stringify(doc.contents, ctx));
58 }
59 if (doc.directives?.docEnd) {
60 if (doc.comment) {
61 const cs = commentString(doc.comment);
62 if (cs.includes('\n')) {
63 lines.push('...');
64 lines.push(stringifyComment.indentComment(cs, ''));
65 }
66 else {
67 lines.push(`... ${cs}`);
68 }
69 }
70 else {
71 lines.push('...');
72 }
73 }
74 else {
75 let dc = doc.comment;
76 if (dc && chompKeep)
77 dc = dc.replace(/^\n+/, '');
78 if (dc) {
79 if ((!chompKeep || contentComment) && lines[lines.length - 1] !== '')
80 lines.push('');
81 lines.push(stringifyComment.indentComment(commentString(dc), ''));
82 }
83 }
84 return lines.join('\n') + '\n';
85}
86
87exports.stringifyDocument = stringifyDocument;