Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions rewrite-javascript/rewrite/src/javascript/assertions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<JS.CompilationUnit> {
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<JS.CompilationUnit> {
return {
kind: JS.Kind.CompilationUnit,
Expand Down
11 changes: 10 additions & 1 deletion rewrite-javascript/rewrite/test/javascript/format/format.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ import {
autoFormat,
AutoformatVisitor,
JavaScriptVisitor,
typescript
typescript,
withDetectedStyle
} from "../../../src/javascript";


Expand Down Expand Up @@ -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
})
});

});