-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathrun-prettier.ts
More file actions
68 lines (58 loc) · 2.2 KB
/
run-prettier.ts
File metadata and controls
68 lines (58 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import type { Integration } from '../lib/constants.js';
import { traceStep } from '../telemetry.js';
import { analytics } from '../utils/analytics.js';
import clack from '../utils/clack.js';
import { getPackageDotJson, getUncommittedOrUntrackedFiles, isInGitRepo } from '../utils/clack-utils.js';
import { hasPackageInstalled } from '../utils/package-json.js';
import type { InstallerOptions } from '../utils/types.js';
import * as childProcess from 'node:child_process';
export async function runPrettierStep({
installDir,
integration,
}: Pick<InstallerOptions, 'installDir'> & {
integration: Integration;
}): Promise<void> {
return traceStep('run-prettier', async () => {
if (!isInGitRepo()) {
// We only run formatting on changed files. If we're not in a git repo, we can't find
// changed files. So let's early-return without showing any formatting-related messages.
return;
}
const changedOrUntrackedFiles = getUncommittedOrUntrackedFiles()
.map((filename) => {
return filename.startsWith('- ') ? filename.slice(2) : filename;
})
.join(' ');
if (!changedOrUntrackedFiles.length) {
// Likewise, if we can't find changed or untracked files, there's no point in running Prettier.
return;
}
const packageJson = await getPackageDotJson({ installDir });
const prettierInstalled = hasPackageInstalled('prettier', packageJson);
analytics.setTag('prettier-installed', prettierInstalled);
if (!prettierInstalled) {
return;
}
const prettierSpinner = clack.spinner();
prettierSpinner.start('Running Prettier on your files.');
try {
await new Promise<void>((resolve, reject) => {
childProcess.exec(`npx prettier --ignore-unknown --write ${changedOrUntrackedFiles}`, (err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
} catch {
prettierSpinner.stop('Prettier failed to run. You may want to format the changes manually.');
return;
}
prettierSpinner.stop('Prettier has formatted your files.');
analytics.capture('installer interaction', {
action: 'ran prettier',
integration,
});
});
}