-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathscript.image-lint.js
More file actions
179 lines (162 loc) · 5.98 KB
/
script.image-lint.js
File metadata and controls
179 lines (162 loc) · 5.98 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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
const fs = require('node:fs');
const path = require('node:path');
const sharp = require('sharp');
const weblog = require('webpack-log');
const ENV = require('./app.env');
const UTILS = require('./webpack.utils');
const config = require('./.imagelintrc');
const imageminConfig = require('./imagemin.config');
const logger = weblog({ name: 'image-lint' });
const lintIgnore = UTILS.readIgnoreFile('./.imagelintignore');
const VERBOSE = ENV.ARGV.verbose;
const metadataAsync = async (filename) => {
let metadata;
const result = {};
try {
metadata = await sharp(filename).metadata();
} catch (error) {
logger.error(filename, error);
return null;
}
const imageStat = await sharp(filename).stats();
const fileStat = fs.statSync(filename);
result.isOpaque = imageStat.isOpaque;
result.hasAlpha = metadata.hasAlpha;
result.size = fileStat.size;
result.extension = path.extname(filename).replace('.', '');
result.width = parseInt(metadata.width, 10);
result.height = parseInt(metadata.height, 10);
result.quality = parseInt(metadata.quality, 10);
result.format = metadata.format === 'jpeg' ? 'jpg' : metadata.format;
result.space = metadata.space;
return result;
};
const LINT_RULES = [
{
name: 'size',
maxwidth: config.maxwidth,
maxheight: config.maxheight,
fn(metadata) {
if (metadata.format === 'svg') {
return false;
}
if (metadata.width > this.maxwidth || metadata.height > this.maxheight) {
return `Image size ${metadata.width}x${metadata.height} is not less than ${this.maxwidth}x${this.maxheight}.`;
}
return false;
},
},
{
name: 'format',
fn(metadata) {
if (metadata.format.toLowerCase() !== metadata.extension.toLowerCase()) {
return 'Invalid image format and extension.';
}
return false;
},
},
{
name: 'space',
allowed: config.colorspace,
fn(metadata) {
if (!this.allowed.includes(metadata.space)) {
return `The color space of this image is ${metadata.space}. It must be ${JSON.stringify(this.allowed)}.`;
}
return false;
},
},
{
name: 'jpeg',
options: { ...imageminConfig.jpeg.options, ...config.jpeg },
async fn(metadata, filename) {
if (metadata.format === 'png' && metadata.isOpaque) {
const jpeg = await sharp(filename).jpeg(this.options).toBuffer();
const png = await sharp(filename).png(imageminConfig.png.options).toBuffer();
if (jpeg.length < png.length) {
const convertSource = UTILS.slash(path.relative(__dirname, filename));
const convertTarget = convertSource.replace('.png', '.jpg');
return [
`JPEG (${jpeg.length} bytes) better than PNG (${png.length} bytes).`,
`Use JPG instead, please run: \`magick convert ${convertSource} ${convertTarget}\`.`,
].join('\n');
}
}
return false;
},
},
{
name: 'png',
options: { ...imageminConfig.png.options, ...config.png },
async fn(metadata, filename) {
if (metadata.format === 'jpg') {
const png = await sharp(filename).png(this.options).toBuffer();
const jpeg = await sharp(filename).jpeg(imageminConfig.jpeg.options).toBuffer();
if (png.length < jpeg.length) {
const convertSource = UTILS.slash(path.relative(__dirname, filename));
const convertTarget = convertSource.replace('.jpg', '.png');
return [
`PNG (${png.length} bytes) better than JPEG (${jpeg.length} bytes).`,
`Use PNG instead, please run: \`magick convert ${convertSource} ${convertTarget}\`.`,
].join('\n');
}
}
return false;
},
},
];
const patterns = [...UTILS.processArgs._];
const files = UTILS.globArraySync(patterns.length > 0 ? patterns : [`${ENV.SOURCE_PATH}/**/*.{jpg,jpeg,png,svg,gif}`], {
ignore: [`${ENV.OUTPUT_PATH}/**/*.{jpg,jpeg,png,svg,gif}`],
nodir: true,
});
logger.info(`${files.length} files\n`);
const statMessages = { ignored: 0, skipped: 0, error: 0 };
const increaseStat = (type) => {
if (type in statMessages) statMessages[type] += 1;
else statMessages[type] = 1;
};
const promises = files.map(async (resourcePath) => {
const relativePath = UTILS.slash(path.relative(ENV.SOURCE_PATH, resourcePath));
if (lintIgnore.ignores(relativePath)) {
increaseStat('ignored');
if (VERBOSE) {
logger.info(`${relativePath}: ignored`);
}
return Promise.resolve(relativePath);
}
const metadata = await metadataAsync(resourcePath);
if (!metadata) {
logger.error(`${relativePath}: cannot read metadata`);
increaseStat('error');
process.exitCode = 1;
return Promise.resolve(relativePath);
}
const lintErrors = (
await Promise.all(
LINT_RULES.map(async (rule) => {
const lintError = await rule.fn(metadata, resourcePath);
return lintError ? [lintError] : [];
}),
)
).flat();
if (lintErrors.length > 0) {
lintErrors.forEach((lintError) => {
logger.error(`${relativePath}: ${lintError}`);
});
console.log('');
increaseStat('error');
process.exitCode = 1;
} else {
increaseStat('skipped');
if (VERBOSE) {
logger.info(`skipped ${relativePath}`);
}
}
return metadata;
});
Promise.all(promises)
.then(() => {
console.log('');
return logger.info('stats:', statMessages);
})
.catch((error) => logger.error(error));