diff --git a/lib/rules/indentation/__tests__/document-with-roots.js b/lib/rules/indentation/__tests__/document-with-roots.js new file mode 100644 index 0000000000..a3ee8066fb --- /dev/null +++ b/lib/rules/indentation/__tests__/document-with-roots.js @@ -0,0 +1,38 @@ +'use strict'; + +const postcssParse = require('postcss/lib/parse'); +const { stringify, Document, Input } = require('postcss'); +const { ruleName } = require('..'); + +const parse = (source, opts) => { + const doc = new Document(); + const root = postcssParse(source, opts); + + root.parent = doc; + root.document = doc; + doc.nodes.push(root); + doc.source = { + input: new Input(source, opts), + start: { line: 1, column: 1, offset: 0 }, + }; + + return doc; +}; + +testRule({ + ruleName, + config: [2], + fix: true, + customSyntax: { + parse, + stringify, + }, + + accept: [ + { + code: '.foo {\n' + ' color: hotpink;\n' + '}', + }, + ], + + reject: [], +}); diff --git a/lib/rules/indentation/index.js b/lib/rules/indentation/index.js index 6438a1874a..75582cebc9 100644 --- a/lib/rules/indentation/index.js +++ b/lib/rules/indentation/index.js @@ -93,7 +93,9 @@ const rule = (primary, secondaryOptions = {}, context) => { // it is some other kind of separation, checked by some separate rule if ( (lastIndexOfNewline !== -1 || - (isFirstChild && (!getDocument(parent) || parent.raws.beforeStart.endsWith('\n')))) && + (isFirstChild && + (!getDocument(parent) || + (parent.raws.codeBefore && parent.raws.codeBefore.endsWith('\n'))))) && before.slice(lastIndexOfNewline + 1) !== expectedOpeningBraceIndentation ) { if (context.fix) { @@ -607,7 +609,7 @@ function inferRootIndentLevel(root, baseIndentLevel, indentSize) { let source = root.source.input.css; source = source.replace(/^[^\r\n]+/, (firstLine) => { - const match = /(?:^|\n)([ \t]*)$/.exec(root.raws.beforeStart); + const match = root.raws.codeBefore && /(?:^|\n)([ \t]*)$/.exec(root.raws.codeBefore); if (match) { return match[1] + firstLine; @@ -628,7 +630,7 @@ function inferRootIndentLevel(root, baseIndentLevel, indentSize) { } const indents = []; - const foundIndents = /(?:^|\n)([ \t]*)\S/m.exec(root.raws.beforeStart); + const foundIndents = root.raws.codeBefore && /(?:^|\n)([ \t]*)\S/m.exec(root.raws.beforeStart); // The indent level of the CSS code block in non-CSS-like files is determined by the shortest indent of non-empty line. if (foundIndents) {