Skip to content

Commit

Permalink
feat: dedent code after transforming
Browse files Browse the repository at this point in the history
  • Loading branch information
ext committed Nov 5, 2024
1 parent fc27347 commit 744f9c5
Showing 1 changed file with 37 additions and 2 deletions.
39 changes: 37 additions & 2 deletions src/examples/transform-code.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import dedent from "dedent";

function removeLinesInline(
lines: string[],
{ begin, end }: { begin: number; end: number },
Expand Down Expand Up @@ -104,10 +106,43 @@ function stripEslintComments(code: string): string {
return code.replace(matchLine, "").replace(matchEmbedded, "");
}

function maybeDedent(value: string): string {
/* if the string is only whitespace we preserve it exactly as is */
if (/^\s*$/.test(value)) {
return value;
}

/* Conditionally calling dedent due to
* https://github.com/dmnd/dedent/issues/20
*
* - If the first line is indented we dedent the string as usual.
*
* - If the first line is not indented the dedention should be a no-op as
* the indentation level is zero already but the referenced bug causes
* `dedent` to pick up any other indented line as basis for the current
* indentation level and thus removes to much.
*
* Consider the following input:
*
* ```
* function foo() {
* return "...";
* }
* ```
*
* The expected output is the same as the input.
*/
if (/^\s/.test(value)) {
return dedent(value);
} else {
return value;
}
}

/* transformations to apply based on language, transforms are run from left to right */
const transformations: Record<string, Array<(code: string) => string>> = {
javascript: [cutSnippets, stripEslintComments],
typescript: [cutSnippets, stripEslintComments],
javascript: [cutSnippets, stripEslintComments, maybeDedent],
typescript: [cutSnippets, stripEslintComments, maybeDedent],
};

export function transformCode(code: string, lang: string): string {
Expand Down

0 comments on commit 744f9c5

Please sign in to comment.