Skip to content

Option for format rule for matching indentation? #9

Closed
@karlhorky

Description

@karlhorky

Hi @gajus ! First of all, thanks for your great work in the PostgreSQL + JS ecosystem, really cool stuff that you're doing always with Slonik and everything! 💯

I was wondering if it would be possible to have an option for the format rule to adjust the formatted string . Here's an example of code that could be improved because of this:

async function a() {
  if (condition) {
    // ...some code...
    if (anotherCondition) {
      const b = await sql`
SELECT
  ${'foo'}
FROM
  ${'bar'}
`;
    }
  }
}

How this code could look:

async function a() {
  if (condition) {
    // ...some code...
    if (anotherCondition) {
      const b = await sql`
        SELECT
          ${'foo'}
        FROM
          ${'bar'}
      `;
    }
  }
}

Since SQL is not whitespace-sensitive I am assuming this would not be a destructive action.

If this option would be something conceivable to add to the plugin, I guess the AST tells us that some information of the starting indentation of the TaggedTemplateExpression may be available under the loc.start.column object property path:

Screen Shot 2020-11-19 at 20 15 40

And then splitting the formatted string by '\n', mapping over each line (except the first one) to add spaces:

formatted.map((line, i) => {
  if (i === 0) return line;

  const spaces = context.options[1].spaces || 4;
  const indentation = ' '.repeat(column + spaces);
  return `${indentation}${line}`;
}

...and then joining again with \n.

What are your thoughts?

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions