-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathindex.js
101 lines (81 loc) · 2.4 KB
/
index.js
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
import path from 'node:path';
import {Transform} from 'node:stream';
import {Buffer} from 'node:buffer';
import process from 'node:process';
import PluginError from 'plugin-error';
import prettier from 'prettier';
export default function plugin(options = {}) {
return new Transform({
objectMode: true,
async transform(file, encoding, callback) {
if (file.isNull()) {
return callback(null, file);
}
if (file.isStream()) {
return callback(new PluginError('gulp-prettier', 'Streaming not supported'));
}
const config = await prettier.resolveConfig(file.path, options);
const fileOptions = {...config, ...options, filepath: file.path};
const unformattedCode = file.contents.toString('utf8');
try {
const formattedCode = await prettier.format(unformattedCode, fileOptions);
if (formattedCode !== unformattedCode) {
file.isPrettier = true;
file.contents = Buffer.from(formattedCode);
}
this.push(file);
} catch (error) {
this.emit(
'error',
new PluginError('gulp-prettier', error, {fileName: file.path}),
);
}
callback();
},
});
}
plugin.check = function (options = {}) {
const unformattedFiles = [];
return new Transform({
objectMode: true,
async transform(file, encoding, callback) {
if (file.isNull()) {
return callback(null, file);
}
if (file.isStream()) {
return callback(
new PluginError('gulp-prettier', 'Streaming not supported'),
);
}
const config = await prettier.resolveConfig(file.path, options);
const fileOptions = {...config, ...options, filepath: file.path};
const unformattedCode = file.contents.toString('utf8');
try {
const isFormatted = await prettier.check(unformattedCode, fileOptions);
if (!isFormatted) {
const filename = path
.relative(process.cwd(), file.path)
.replaceAll('\\', '/');
unformattedFiles.push(filename);
}
this.push(file);
} catch (error) {
this.emit(
'error',
new PluginError('gulp-prettier', error, {fileName: file.path}),
);
}
callback();
},
flush(callback) {
if (unformattedFiles.length > 0) {
const header
= 'Code style issues found in the following file(s). Forgot to run Prettier?';
const body = unformattedFiles.join('\n');
const message = `${header}\n${body}`;
this.emit('error', new PluginError('gulp-prettier', message));
}
callback();
},
});
};