-
Notifications
You must be signed in to change notification settings - Fork 2
/
less-watch
executable file
·71 lines (67 loc) · 2.35 KB
/
less-watch
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
#!/usr/bin/env /usr/local/bin/node
var fs = require('fs'),
path = require('path'),
child_process = require('child_process'),
glob = require('glob'),
winston = require('winston'),
watched_filepaths = [],
config_path = path.join(process.env.HOME, '.less-watch'),
logfile = path.join(process.env.HOME, 'Library', 'Logs', 'less-watch.log')
logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)(),
new (winston.transports.File)({ filename: logfile })
]
});
function reload() {
logger.info(watched_filepaths.length ? "Reloading" : "Loading");
watched_filepaths.forEach(function(filepath) {
fs.unwatchFile(filepath);
});
watched_filepaths = [];
// "restart" is a special action keyword
watch(config_path, 'restart');
fs.readFile(config_path, 'utf8', function (err, data) {
if (err) throw err;
data.split(/\n+/g).forEach(function(line) {
var parts = line.split(/\s*:\s*/g);
if (parts[0] && parts[1])
watch(parts[0], parts[1]);
});
});
}
function watch(globpath, action) {
glob(globpath, function(err, filepaths) {
// for single files, filepaths will just be one file: the exact match
filepaths.forEach(function(filepath) {
// for each file, decide on its command
var ext = filepath.match(/(\.\w+)?$/)[1],
command = action.
replace(/\{file\}/g, filepath).
replace(/\{basename\}/g, path.basename(filepath, ext)).
replace(/\{dirname\}/g, path.dirname(filepath));
// save the filepath so that we can unwatch it easily when reloading, and start the watch
watched_filepaths.push(filepath);
fs.watchFile(filepath, {interval: 250}, function(curr, prev) {
// ignore simple accesses
if (curr.mtime.valueOf() != prev.mtime.valueOf() || curr.ctime.valueOf() != prev.ctime.valueOf()) {
if (command === 'restart') {
reload();
}
else {
logger.warn('> ' + filepath + ' changed.');
logger.warn('$ ' + command);
child_process.exec(command, function (error, stdout, stderr) {
logger.info('stdout: ' + stdout);
logger.info('stderr: ' + stderr);
if (error !== null) {
logger.error('exec error: ' + error);
}
});
}
}
});
});
});
}
reload();