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

Fix TypeError for syntaxes that use Document in indentation #5771

Merged
merged 1 commit into from Dec 20, 2021
Merged
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
37 changes: 37 additions & 0 deletions lib/rules/indentation/__tests__/document-with-roots.js
@@ -0,0 +1,37 @@
'use strict';

const { parse: postcssParse, 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: [],
});
8 changes: 5 additions & 3 deletions lib/rules/indentation/index.js
Expand Up @@ -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) {
Expand Down Expand Up @@ -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;
Expand All @@ -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.codeBefore);

// 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) {
Expand Down