UNPKG

2.99 kBJavaScriptView Raw
1/* eslint-disable prefer-template,newline-per-chained-call,complexity */
2'use strict';
3
4const path = require('path');
5const fs = require('fs');
6
7require('string.fromcodepoint');
8require('string.prototype.codepointat');
9
10function getMetadataService(options = {}) {
11 let usedUnicodes = [];
12
13 // Default options
14 options.prependUnicode = !!options.prependUnicode;
15 options.startUnicode =
16 'number' === typeof options.startUnicode ? options.startUnicode : 0xea01;
17 options.log = options.log || console.log; // eslint-disable-line
18 options.err = options.err || console.err; // eslint-disable-line
19
20 // Throw on old options usage
21 if ('undefined' !== typeof options.appendUnicode) {
22 throw new Error(
23 'The "appendUnicode" option was renamed "prependUnicode".' +
24 ' See https://github.com/nfroidure/gulp-svgicons2svgfont/issues/33'
25 );
26 }
27
28 return function getMetadataFromFile(file, cb) {
29 const basename = path.basename(file);
30 const metadata = {
31 path: file,
32 name: '',
33 unicode: [],
34 renamed: false,
35 };
36 const matches = basename.match(/^(?:((?:u[0-9a-f]{4,6},?)+)-)?(.+)\.svg$/i);
37
38 metadata.name =
39 matches && matches[2] ? matches[2] : 'icon' + options.startUnicode;
40 if (matches && matches[1]) {
41 metadata.unicode = matches[1].split(',').map(match => {
42 match = match.substr(1);
43 return match
44 .split('u')
45 .map(code => String.fromCodePoint(parseInt(code, 16)))
46 .join('');
47 });
48 if (-1 !== usedUnicodes.indexOf(metadata.unicode[0])) {
49 cb(
50 new Error(
51 'The unicode codepoint of the glyph ' +
52 metadata.name +
53 ' seems to be already used by another glyph.'
54 )
55 );
56 return;
57 }
58 usedUnicodes.push(...metadata.unicode);
59 } else {
60 do {
61 metadata.unicode[0] = String.fromCodePoint(options.startUnicode++);
62 } while (usedUnicodes.includes(metadata.unicode[0]));
63 usedUnicodes.push(metadata.unicode[0]);
64 if (options.prependUnicode) {
65 metadata.renamed = true;
66 metadata.path = path.join(
67 path.dirname(file),
68 'u' +
69 metadata.unicode[0]
70 .codePointAt(0)
71 .toString(16)
72 .toUpperCase() +
73 '-' +
74 basename
75 );
76 fs.rename(file, metadata.path, err => {
77 if (err) {
78 cb(
79 new Error(
80 'Could not save codepoint: ' +
81 'u' +
82 metadata.unicode[0]
83 .codePointAt(0)
84 .toString(16)
85 .toUpperCase() +
86 ' for ' +
87 basename
88 )
89 );
90 return;
91 }
92 cb(null, metadata);
93 });
94 }
95 }
96 if (!metadata.renamed) {
97 setImmediate(() => cb(null, metadata));
98 }
99 };
100}
101
102module.exports = getMetadataService;