Skip to content

feat: Add matchIndentation option #31

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

Closed
wants to merge 1 commit into from
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
module.exports = {
extends: ['canonical/auto', 'canonical/node'],
ignorePatterns: ['dist', 'package-lock.json'],
ignorePatterns: ['dist', 'package-lock.json', 'node_modules'],
root: true,
rules: {
'complexity': 0,
'no-template-curly-in-string': 0,
'node/no-sync': 0,
},
Expand Down
57 changes: 48 additions & 9 deletions src/rules/format.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { indentString, stripIndent } from '../utilities/indent';
import isSqlQuery from '../utilities/isSqlQuery';
import { generate } from 'astring';
import { format } from 'pg-formatter';
Expand All @@ -11,6 +12,7 @@ const create = (context) => {
const ignoreInline = pluginOptions.ignoreInline !== false;
const ignoreTagless = pluginOptions.ignoreTagless !== false;
const ignoreStartWithNewLine = pluginOptions.ignoreStartWithNewLine !== false;
const matchIndentation = pluginOptions.matchIndentation !== false;

return {
TemplateLiteral(node) {
Expand Down Expand Up @@ -41,18 +43,49 @@ const create = (context) => {
return;
}

if (ignoreInline && !literal.includes('\n')) {
const eolMatch = literal.match(/\r?\n/u);
if (ignoreInline && !eolMatch) {
return;
}

let formatted = format(literal, context.options[1]);
const [eol = '\n'] = eolMatch || [];

const sourceCode = context.getSourceCode();
const startLine = sourceCode.lines[node.loc.start.line - 1];
const marginMatch = startLine.match(/^(\s*)\S/u);
const parentMargin = marginMatch ? marginMatch[1] : '';

const pgFormatterOptions = { ...context.options[1] };
const { tabs, spaces = 4 } = pgFormatterOptions;

const indent = tabs ? `\t` : ' '.repeat(spaces || 4);
let formatted = format(literal, pgFormatterOptions).trim();

if (matchIndentation) {
const stripped = stripIndent(formatted);
const trimmed = stripped.replaceAll(
new RegExp(`^${eol}|${eol}[ \t]*$`, 'gu'),
'',
);
const formattedLines = trimmed.split(eol);
const indented =
formattedLines
.map((line) => {
return parentMargin + indentString(line, 1, { indent });
})
.join(eol) +
// The last line has an eol to make the backtick line up
eol +
parentMargin;

formatted = indented;
}

const shouldPrependEol =
ignoreStartWithNewLine && literal.startsWith(eol);

if (
ignoreStartWithNewLine &&
literal.startsWith('\n') &&
!formatted.startsWith('\n')
) {
formatted = '\n' + formatted;
if (shouldPrependEol && !formatted.startsWith(eol)) {
formatted = eol + formatted;
}

if (formatted !== literal) {
Expand All @@ -77,7 +110,9 @@ const create = (context) => {
node.quasis[0].range[0],
node.quasis[node.quasis.length - 1].range[1],
],
'`\n' + final + '`',
`\`${shouldPrependEol && formatted.startsWith(eol) ? '' : '\n'}` +
final +
'`',
);
},
message: 'Format the query',
Expand Down Expand Up @@ -117,6 +152,10 @@ export = {
default: true,
type: 'boolean',
},
matchIndentation: {
default: true,
type: 'boolean',
},
},
type: 'object',
},
Expand Down
48 changes: 48 additions & 0 deletions src/utilities/indent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
type IndentOptions = {
includeEmptyLines?: boolean;
indent?: string;
};

const minIndent = function (string: string): number {
const match = string.match(/^[\t ]*(?=\S)/gmu);

if (!match) {
return 0;
}

let min = Number.POSITIVE_INFINITY;

for (const indent of match) {
min = Math.min(min, indent.length);
}

return min;
};

export const stripIndent = function (string: string): string {
const indent = minIndent(string);

if (indent === 0) {
return string;
}

const regex = new RegExp(`^[ \\t]{${indent}}`, 'gmu');

return string.replace(regex, '');
};

export const indentString = function (
string: string,
count: number = 1,
options: IndentOptions = {},
): string {
const { indent = ' ', includeEmptyLines = false } = options;

if (count === 0) {
return string;
}

const regex = includeEmptyLines ? /^/gmu : /^(?!\s*$)/gmu;

return string.replace(regex, indent.repeat(count));
};
150 changes: 145 additions & 5 deletions test/rules/assertions/format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export default {
ignoreTagless: false,
},
],
output: '`\nSELECT\n 1\n`',
output: '`\n SELECT\n 1\n`',
},
{
code: '`SELECT 2`',
Expand All @@ -31,7 +31,7 @@ export default {
spaces: 2,
},
],
output: '`\nSELECT\n 2\n`',
output: '`\n SELECT\n 2\n`',
},
{
code: 'sql.unsafe`SELECT 3`',
Expand All @@ -45,7 +45,7 @@ export default {
ignoreInline: false,
},
],
output: 'sql.unsafe`\nSELECT\n 3\n`',
output: 'sql.unsafe`\n SELECT\n 3\n`',
},
{
code: 'sql.type()`SELECT 3`',
Expand All @@ -59,7 +59,7 @@ export default {
ignoreInline: false,
},
],
output: 'sql.type()`\nSELECT\n 3\n`',
output: 'sql.type()`\n SELECT\n 3\n`',
},
{
code: "`SELECT ${'foo'} FROM ${'bar'}`",
Expand All @@ -74,10 +74,132 @@ export default {
ignoreTagless: false,
},
],
output: "`\nSELECT\n ${'foo'}\nFROM\n ${'bar'}\n`",
output: "`\n SELECT\n ${'foo'}\n FROM\n ${'bar'}\n`",
},
{
code: "\t\t`SELECT ${'foo'} FROM ${'bar'}`",
errors: [
{
message: 'Format the query',
},
],
options: [
{
ignoreInline: false,
ignoreTagless: false,
},
],
output:
"\t\t`\n\t\t SELECT\n\t\t ${'foo'}\n\t\t FROM\n\t\t ${'bar'}\n\t\t`",
},
{
code: '\tconst s = sql`SELECT\n1\nFROM\ntable`',
errors: [
{
message: 'Format the query',
},
],
options: [
{},
{
spaces: 2,
},
],
output:
'\tconst s = sql`\n\t SELECT\n\t 1\n\t FROM\n\t table\n\t`',
},
{
code: '\tconst s = sql`SELECT 1 FROM table`',
errors: [
{
message: 'Format the query',
},
],
options: [
{
ignoreInline: false,
},
{
tabs: true,
},
],
output:
'\tconst s = sql`\n\t\tSELECT\n\t\t\t1\n\t\tFROM\n\t\t\ttable\n\t`',
},
{
code: '\tconst s = sql`SELECT 1 FROM table`',
errors: [
{
message: 'Format the query',
},
],
options: [
{
ignoreInline: false,
},
{
spaces: 0,
tabs: false,
},
],
output:
'\tconst s = sql`\n\t SELECT\n\t 1\n\t FROM\n\t table\n\t`',
},
{
code: ' const s = sql`SELECT 1 FROM table`',
errors: [
{
message: 'Format the query',
},
],
options: [
{
ignoreInline: false,
},
{
spaces: 0,
tabs: false,
},
],
output:
' const s = sql`\n SELECT\n 1\n FROM\n table\n `',
},
{
code: '\tsql`SELECT 1 FROM table`',
errors: [
{
message: 'Format the query',
},
],
options: [
{
ignoreInline: false,
matchIndentation: false,
},
],
output: '\tsql`\nSELECT\n 1\nFROM\n table`',
},
{
code: '\tconst query = sql`\nDELETE FROM table AS t\nWHERE t.id = ${foo}AND t.type = ${type};`',
errors: [
{
message: 'Format the query',
},
],
options: [
{
ignoreInline: false,
matchIndentation: true,
},
],
output:
'\tconst query = sql`\n\t DELETE FROM table AS t\n\t WHERE t.id = ${foo}\n\t AND t.type = ${type};\n\t`',
},
],
valid: [
{
code: 'sql`SELECT 1`',
},
{
code: 'sql`SELECT 1`',
options: [
Expand All @@ -104,5 +226,23 @@ export default {
},
],
},
{
code: '\tconst s = sql`\n\t SELECT\n\t 1\n\t FROM\n\t table\n\t`',
options: [
{},
{
spaces: 2,
},
],
},
{
code: '\tconst query = sql`\n\t DELETE FROM table AS t\n\t WHERE t.id = ${foo}\n\t AND t.type = ${type};\n\t`',
options: [
{},
{
spaces: 2,
},
],
},
],
};
3 changes: 3 additions & 0 deletions test/rules/assertions/noUnsafeQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,5 +53,8 @@ export default {
{
code: "sql`SELECT ${'foo'}`",
},
{
code: 'sql``',
},
],
};
Loading