diff --git a/rewrite-javascript/rewrite/src/javascript/assertions.ts b/rewrite-javascript/rewrite/src/javascript/assertions.ts index 75ff1f9790..6ed1a349c9 100644 --- a/rewrite-javascript/rewrite/src/javascript/assertions.ts +++ b/rewrite-javascript/rewrite/src/javascript/assertions.ts @@ -256,6 +256,21 @@ export function packageLockJson(before: string, after?: AfterRecipeText): Source }; } +/** + * Gives a source file the style its own text is written in. A spec that formats its output is + * measured against the built-in defaults unless it opts in with + * `{...typescript(src), beforeRecipe: withDetectedStyle}`; a file parsed through {@link npm} is + * sampled alongside its siblings and needs no opt-in. + */ +export async function withDetectedStyle(sourceFile: JS.CompilationUnit): Promise { + const detector = Autodetect.detector(); + await detector.sample(sourceFile); + const detected = detector.build(); + return produce(sourceFile, draft => { + draft.markers = replaceMarkerByKind(draft.markers, detected); + }); +} + export function javascript(before: string | null, after?: AfterRecipeText): SourceSpec { return { kind: JS.Kind.CompilationUnit, diff --git a/rewrite-javascript/rewrite/test/javascript/format/format.test.ts b/rewrite-javascript/rewrite/test/javascript/format/format.test.ts index 4ac75e9399..f8d7673947 100644 --- a/rewrite-javascript/rewrite/test/javascript/format/format.test.ts +++ b/rewrite-javascript/rewrite/test/javascript/format/format.test.ts @@ -40,7 +40,8 @@ import { autoFormat, AutoformatVisitor, JavaScriptVisitor, - typescript + typescript, + withDetectedStyle } from "../../../src/javascript"; @@ -702,5 +703,13 @@ const x = 1;` ) }); + test('a spec opting into its own style keeps the tabs it is written with', () => { + return spec.rewriteRun({ + //language=typescript + ...typescript("function f() {\n\tconst x = 1;\n\treturn x;\n}\n"), + beforeRecipe: withDetectedStyle + }) + }); + });