Gitter migration: Setup redirects (rollout pt. 3)
[gitter.git] / build-scripts / extract-urls.js
blob4d4043711d1f3eb004f5d4c6db69a0b770e90bcd
1 'use strict';
3 var postcss = require('postcss');
4 var fs = require('fs');
5 var path = require('path');
6 var reduceFunctionCall = require('reduce-function-call');
7 var url = require('url');
9 function extractUrls(input, basePath) {
10 var resources = {};
12 function getFileName(value) {
13 var u = url.parse(value);
14 if (u.protocol || u.hostname) return value;
16 value = u.pathname;
18 if (value.indexOf('.') === 0) {
19 var inputRelativeDir = path.dirname(path.relative(basePath, input));
20 var relativeToPublicFilePath = path.join(inputRelativeDir, value);
21 return path.join('public', relativeToPublicFilePath);
24 return value;
27 var css = postcss.parse(fs.readFileSync(input));
29 css.eachDecl(function(decl) {
30 if (!decl.value) return;
32 if (decl.prop !== 'src' || decl.parent.name !== 'font-face') return;
34 if (!decl.parent.decls) return;
36 var d = decl.parent.decls.filter(function(d) {
37 return d.prop === 'src' && d.parent.name === 'font-face';
38 });
40 if (!d.length) return;
42 // var hasTtf = d.filter(function(x) {
43 // return x.value.indexOf('.ttf') >= 0;
44 // });
46 // if(hasTtf.length) {
47 // decl.parent.decls = hasTtf;
48 // }
49 });
51 css.eachDecl(function(decl) {
52 if (!decl.value) return;
54 var urls = [];
56 reduceFunctionCall(decl.value, 'url', function(value) {
57 var m = /^['"]([^'"]*)['"]$/.exec(value);
58 if (m) value = m[1];
60 value = getFileName(value);
62 urls.push(value);
63 });
65 if (decl.prop === 'src' && decl.parent.name === 'font-face') {
66 // If there are multiple fonts, choose the ttf
67 var ttfs = urls.filter(function(v) {
68 return /\.ttf/.test(v);
69 });
71 if (ttfs.length > 0) {
72 urls = ttfs;
76 urls.forEach(function(value) {
77 resources[value] = true;
78 });
79 });
81 return Object.keys(resources);
84 module.exports = extractUrls;