-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformat-changed.mjs
More file actions
123 lines (105 loc) · 2.45 KB
/
format-changed.mjs
File metadata and controls
123 lines (105 loc) · 2.45 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
import { existsSync } from 'node:fs';
import { spawnSync } from 'node:child_process';
const textLikeExtensions = new Set([
'.astro',
'.cjs',
'.css',
'.cts',
'.html',
'.js',
'.json',
'.jsonc',
'.jsx',
'.less',
'.md',
'.mdx',
'.mjs',
'.mts',
'.scss',
'.svelte',
'.toml',
'.ts',
'.tsx',
'.vue',
'.yaml',
'.yml',
]);
function run(command, args, options = {}) {
const result = spawnSync(command, args, {
stdio: 'pipe',
encoding: 'utf8',
...options,
});
if (result.error) {
throw result.error;
}
return result;
}
function fail(message, detail = '') {
console.error(message);
if (detail.trim()) {
console.error(detail.trim());
}
process.exit(1);
}
function writeOutput(output, stream) {
if (typeof output === 'string' && output.length > 0) {
stream.write(output);
}
}
function isNoTargetError(result) {
const combinedOutput = `${result.stdout ?? ''}${result.stderr ?? ''}`;
return combinedOutput.includes(
'Expected at least one target file. All matched files may have been excluded by ignore rules.',
);
}
function parseNullSeparated(output) {
return output.split('\0').filter(Boolean);
}
function isFormattable(file) {
if (!existsSync(file)) {
return false;
}
if (file.startsWith('packages/docs/.astro/')) {
return false;
}
if (/^packages\/[^/]+\/convex\/_generated\//.test(file)) {
return false;
}
const extensionIndex = file.lastIndexOf('.');
if (extensionIndex === -1) {
return false;
}
return textLikeExtensions.has(file.slice(extensionIndex));
}
const trackedChanged = run('git', ['diff', '--name-only', '-z', 'HEAD', '--']);
if (trackedChanged.status !== 0) {
fail('Failed to read changed tracked files.', trackedChanged.stderr);
}
const untracked = run('git', [
'ls-files',
'--others',
'--exclude-standard',
'-z',
]);
if (untracked.status !== 0) {
fail('Failed to read untracked files.', untracked.stderr);
}
const files = [
...parseNullSeparated(trackedChanged.stdout),
...parseNullSeparated(untracked.stdout),
]
.filter(isFormattable)
.filter((file, index, array) => array.indexOf(file) === index);
if (files.length === 0) {
process.exit(0);
}
const format = run('pnpm', ['exec', 'oxfmt', '--write', ...files]);
writeOutput(format.stdout, process.stdout);
writeOutput(format.stderr, process.stderr);
if (format.status !== 0) {
if (isNoTargetError(format)) {
process.exit(0);
}
process.exit(format.status ?? 1);
}