-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
270 lines (220 loc) · 7.33 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
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
const path = require("path");
const fs = require("fs");
const src = path.resolve(__dirname, "../../..", "src");
const node_modules = path.resolve(__dirname, "../..");
// const src = "./example/src";
// const node_modules = "./example/node_modules";
const iconTypes = [
{ prefix: "fas", libary: "solid", type: "" },
{ prefix: "far", libary: "regular", type: "" },
{ prefix: "fal", libary: "light", type: "" },
{ prefix: "fab", libary: "brands", type: "" },
{ prefix: "fad", libary: "duotone", type: "" },
{ prefix: "fat", libary: "thin", type: "" },
];
const prefixes = /fas|far|fal|fab|fad|fat/;
const faModule = "@fortawesome";
const outputFolder = `${src}/plugins`;
const outputFile = `${outputFolder}/fontawesome-autogen.js`;
const componentCheck =
/[Vue\.component\("]([a-z0-9-]+)["],[ ]{0,1}FontAwesomeIcon\)/g;
const componentName = getComponentName();
// console.log(componentName);
// Edit this per requirements
const matches = [
/(?<=icon:\s"+)fa.*?(?=",)/g, // Get icons within props or data
/(?<=default:\s"+)fa.*?(?=",)/g, // Get default icon values within props
///(?<=<fa\s+icon="+).*?(?=")/g // Get icons within components
// /icon=['"]([a-z-]+)['"]|:icon=\"\[['"](fa[a-z])['"],.*['"]([a-z-]+)['"]\]/g,
new RegExp(
`<(?:fa|${componentName})\\s+icon=['"]([a-z-]+)['"]|<${componentName}\\s+:icon=['"]\\[['"](fa[a-z])['"],[ ]{0,1}['"]([a-z-]+)['"]\\]|<FontAwesomeIcon\\s+icon=['"]([a-z-]+)['"]|<FontAwesomeIcon\\s+icon={\\[['"](fa[a-z])['"],[ ]{0,1}['"]([a-z-]+)['"]\\]}`,
"g"
),
];
String.prototype.replaceAt = function (index, replacement) {
return (
this.substr(0, index) +
replacement +
this.substr(index + replacement.length)
);
};
String.prototype.removeAt = function removeAt(index) {
return this.slice(0, index) + this.slice(index + 1);
};
function getLibraries() {
const libs = { pro: [], free: [] };
const pathing = `${node_modules}${path.sep}${faModule}`;
// Get all installed libraries
for (const name of fs.readdirSync(pathing)) {
if (!fs.lstatSync(`${pathing}${path.sep}${name}`).isDirectory()) continue;
const lib = name.match(/(?=pro-|free-).*?(?=-svg-icons)/g);
if (lib === null) continue;
const libSpl = lib[0].split("-");
libs[libSpl[0]].push(libSpl[1]);
}
// Take only pro libraries instead of free ones
const filtered = [];
for (const [key, value] of Object.entries(libs)) {
for (const val of value) {
if (!filtered.map((e) => e.split("-")[1]).includes(val)) {
filtered.push(`${key}-${val}`);
}
}
}
// Populate them into our libs object
// the reason this is in its own loop is because the prior loop will fill the array out of order, it doesn't matter much anyway
for (const l of filtered) {
const spl = l.split("-");
const index = iconTypes.indexOf(iconTypes.find((e) => e.libary === spl[1]));
iconTypes[index].type = spl[0];
}
}
var files = [];
function getFiles(path) {
// Recursive ((!))
for (const name of fs.readdirSync(path)) {
const entry = `${path}/${name}`;
fs.lstatSync(entry).isDirectory() ? getFiles(entry) : files.push(entry);
}
// Filter all non-vue files
files = files.filter(
(file) =>
file.indexOf(".vue") > -1 ||
file.indexOf(".jsx") > -1 ||
file.indexOf(".js") > -1 ||
file.indexOf(".tsx") > -1 ||
file.indexOf(".ts") > -1
);
}
function getComponentName() {
var files = [];
getfiles(src);
function getfiles(path) {
// Recursive ((!))
for (const name of fs.readdirSync(path)) {
const entry = `${path}/${name}`;
fs.lstatSync(entry).isDirectory() ? getfiles(entry) : files.push(entry);
}
// Filter all non-vue files
files = files.filter((file) => file.indexOf(".js") > -1);
}
for (const f of files) {
const file = fs.readFileSync(f);
const compo = componentCheck.exec(file);
if (compo === null) return "font-awesome-icon";
return compo[1];
}
}
function getIcons(files) {
const icons = [];
for (const f of files) {
const file = fs.readFileSync(f);
for (const r of matches) {
// console.log(r);
while (null != (icon = r.exec(file))) {
// console.log(icon);
icon = icon.filter((e) => e != null);
icon.shift();
if (!prefixes.test(icon)) {
icon = "fas-" + icon;
} else if (icon.length == 1) {
icon = icon[0];
} else if (icon.length == 2) {
icon = icon[0] + "-" + icon[1];
}
icons.push(icon);
}
}
}
// Distinct values (Remove duplicates)
return [...new Set(icons)];
}
function sortIcons(icons) {
const ficons = [];
for (const icon of icons) {
const spl = icon.split("-");
// fa(r|s|l|b|d)
const prefix = spl[0];
// thumbs-up -> fathumbs-up
let iconName = `fa${spl.slice(1).join("-")}`;
// fathumbs-up -> faThumbs-up
iconName = iconName.replaceAt(2, iconName[2].toUpperCase());
// faThumbs-up
while (true) {
let pos = iconName.indexOf("-");
if (pos === -1) break;
// faThumbs-up -> faThumbs-Up -> faThumbsUp
iconName = iconName
.replaceAt(pos + 1, iconName[pos + 1].toUpperCase())
.removeAt(pos);
}
ficons.push({ prefix: prefix, icon: iconName });
}
return ficons;
}
function getListing(sortedIcons) {
let result = `// Auto generated @ ${new Date()}`;
// Filter out icons from not installed libraries
sortedIcons = sortedIcons.filter(
(el) => iconTypes.find((e) => e.prefix === el.prefix).type !== ""
);
for (const type of iconTypes) {
if (sortedIcons.filter((el) => el.prefix === type.prefix).length === 0)
continue; // ignore unused libraries
result += `\n\n//${type.prefix}\nimport {\n${sortedIcons
.filter((el) => el.prefix === type.prefix)
.map((e) => `\t${e.icon} as ${e.prefix}${e.icon.slice(2)}`)
.join(",\n")}\n} from '${faModule}/${type.type}-${
type.libary
}-svg-icons';`;
}
return (result += `\n\nimport { library } from "@fortawesome/fontawesome-svg-core";\nlibrary.add(\n${sortedIcons
.map((e) => `\t${e.prefix}${e.icon.slice(2)}`)
.join(",\n")}\n);`);
}
const t0 = Date.now();
// Fetch installed libraries and only prioritize pro versions if even free ones are installed
getLibraries();
// Find all vue files within folders
getFiles(src);
// console.log(files);
// parse icons within found files
const icons = getIcons(files);
// console.log(icons);
// Fix up icon list
const sortedIcons = sortIcons(icons);
// Generate code
const listing = getListing(sortedIcons);
const previousListing = [
...new Set(
[
...(fs.existsSync(outputFile) && fs.readFileSync(outputFile))
.toString()
.matchAll(/fa[a-z][A-Z]\w+/g),
].map(([icon]) => icon)
),
].sort();
const currentListing = [
...new Set(
[...listing.toString().matchAll(/fa[a-z][A-Z]\w+/g)].map(([icon]) => icon)
),
].sort();
if (JSON.stringify(previousListing) === JSON.stringify(currentListing)) {
console.log(
`- Fontawesome treeshaking list already up-to-date. (took ${
Date.now() - t0
} ms)`
);
return;
} else {
// Write to file
fs.mkdir(outputFolder, { recursive: true }, (err) => {
if (err) throw err;
fs.writeFile(outputFile, listing, function (err) {
if (err) return console.log(err);
console.log(
`- Fontawesome treeshaking list generated. (took ${Date.now() - t0} ms)`
);
});
});
}