UNPKG

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