UNPKG

1.72 kBJavaScriptView Raw
1var unyield = require('unyield')
2var thunkify = require('thunkify')
3
4/**
5 * Given a thunk `fn`, return a thunk of it that returns `undefined` instead of
6 * an error. Useful for, say, `fs.stat()`.
7 */
8
9var safe = function (fn) {
10 return unyield(function * () {
11 try {
12 var result = yield fn.apply(this, arguments)
13 return result
14 } catch (e) {
15 return
16 }
17 })
18}
19
20var stat = safe(thunkify(require('fs').stat))
21
22/**
23 * Given two objects, return a list of keys in `new` that values are changed in
24 * `old`. Also, propagate the new keys into `old`.
25 *
26 * var old = {
27 * 'index.html': 'abc'
28 * 'script.js': 'def'
29 * }
30 *
31 * var neww = {
32 * 'index.html': 'xyz'
33 * 'script.js': 'def'
34 * }
35 *
36 * diffHashes(old, new)
37 * => [ 'index.html' ]
38 */
39
40exports.diffHashes = function (old, neww) {
41 var updated = []
42
43 Object.keys(neww).forEach(function (key) {
44 if (!old[key] || old[key] !== neww[key]) {
45 updated.push(key)
46 }
47 old[key] = neww[key]
48 })
49
50 return updated
51}
52
53/**
54 * Given a list of files `paths`, return only the files; weed out any
55 * directories or whatnot.
56 */
57
58exports.filterFiles = unyield(function * (cwd, paths) {
59 var stats = yield paths.map(function (path) {
60 return stat(require('path').join(cwd, path))
61 })
62
63 var result = paths.filter(function (path, idx) {
64 if (stats[idx] && stats[idx].isFile()) return true
65 })
66
67 return result
68})
69
70var ASSET_EXPR = /\.(css|js|html|jpe?g|png|gif|woff2?|otf|svg)$/
71
72/*
73 * Check if a file is a web asset. Things like `.map` should be stripped,
74 * because these will cause unintentional livereloads.
75 */
76
77exports.isAsset = function (filename) {
78 return ASSET_EXPR.test(filename)
79}