-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
83 lines (72 loc) · 1.92 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
'use strict'
const PLUGIN_NAME = 'gulp-if-any-newer'
const log = require('fancy-log')
const PluginError = require('plugin-error')
const through = require('through2')
const glob = require('glob')
const fs = require('fs')
const path = require('path')
function getMinModTime (dir, filter) {
var minModTime = Number.MAX_SAFE_INTEGER
var files = glob.sync(filter, {cwd: dir, absolute: true, nodir: true})
for (let i = 0; i < files.length; ++i) {
let stats = fs.statSync(files[i])
minModTime = Math.min(stats.mtime, minModTime)
}
return minModTime
}
const gulpIfAnyNewer = (dest, opts) =>
{
if (!dest) {
throw new PluginError(PLUGIN_NAME, '"dest" required')
}
opts = Object.assign({
cwd: process.cwd(),
filter: '**/*',
debug: false
}, opts)
const destAbs = path.resolve(opts.cwd, dest)
const destMinModTime = getMinModTime(destAbs, opts.filter)
let buffer = []
let open = destMinModTime === Number.MAX_SAFE_INTEGER
return through.obj(function (chunk, enc, callback) {
if (!open) {
let srcPath = chunk.path
let stats = fs.statSync(srcPath)
if (stats.mtime > destMinModTime) {
open = true
if (opts.debug) {
log(srcPath, 'newer than any in ', dest + '/' + opts.filter, ', opened buffer')
}
}
}
if (!open) {
if (opts.debug) {
log('Buffered', chunk.path)
}
buffer.push(chunk)
} else {
if (buffer.length > 0) {
if (opts.debug) {
log('Flushing buffer...')
}
for (let i = 0; i < buffer.length; ++i) {
if (opts.debug) {
log('Forwarded', buffer[i].path)
}
this.push(buffer[i])
}
buffer = []
if (opts.debug) {
log('Buffer flushed')
}
}
if (opts.debug) {
log('Forwarded', chunk.path)
}
this.push(chunk)
}
callback()
})
}
module.exports = gulpIfAnyNewer