-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwatchdog
executable file
·687 lines (607 loc) · 22.4 KB
/
watchdog
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
#!/usr/bin/php
<?php
// signal handling
declare(ticks = 1);
// include the CLI helper
require_once('inc/cli');
/**
* A PHP class implementing inotify which watches for changes to files in
* any given number of directories specified in the input. It will not
* recursively check directories, so you must implicitely specify each directory
* you want watched.
*/
class Watchdog {
const PAUSE_MS = 500000;
const MODE_BLOCKING = 1;
const MODE_NONBLOCKING = 0;
/**
* A full list of valid events. The events marked with an asterisk (*) can
* occur for files in watched directories. This is overkill, as currently
* we're only supporting IN_MODIFY and it's not editable.
*
* @var array
*/
protected $_validEvents = array(
IN_ACCESS, // File was accessed (read) (*)
IN_MODIFY, // File was modified (*)
IN_ATTRIB, // Metadata changed (e.g. permissions, mtime, etc.) (*)
IN_CLOSE_WRITE, // File opened for writing was closed (*)
IN_CLOSE_NOWRITE, // File not opened for writing was closed (*)
IN_OPEN, // File was opened (*)
IN_MOVED_TO, // File moved into watched directory (*)
IN_MOVED_FROM, // File moved out of watched directory (*)
IN_CREATE, // File or directory created in watched directory (*)
IN_DELETE, // File or directory deleted in watched directory (*)
IN_DELETE_SELF, // Watched file or directory was deleted
IN_MOVE_SELF, // Watch file or directory was moved
IN_CLOSE, // Equals to IN_CLOSE_WRITE | IN_CLOSE_NOWRITE
IN_MOVE, // Equals to IN_MOVED_FROM | IN_MOVED_TO
IN_ALL_EVENTS, // Bitmask of all the above constants
IN_UNMOUNT, // File system containing watched object was unmounted
IN_Q_OVERFLOW, // Event queue overflowed (wd is -1 for this event)
IN_IGNORED, // Watch was removed (explicitly by inotify_rm_watch() or because file was removed or filesystem unmounted
IN_ISDIR, // Subject of this event is a directory
IN_ONLYDIR, // Only watch pathname if it is a directory (Since Linux 2.6.15)
IN_DONT_FOLLOW, // Do not dereference pathname if it is a symlink (Since Linux 2.6.15)
IN_MASK_ADD, // Add events to watch mask for this pathname if it already exists (instead of replacing mask).
IN_ONESHOT // Monitor pathname for one event, then remove from watch list
);
/**
* The list of watched file extensions.
*
* @var array
*/
protected $_watchedFileExtensions = array();
/**
* The list of ignored files.
*
* @var array
*/
protected $_ignoredFiles = array();
/**
* Contains an array of all watched files/directories.
*
* @var array
*/
protected $_watched = array();
/**
* A reverse lookup to find a directory path based on the descriptor.
*
* @var array
*/
protected $_pathLookup = array();
/**
* An instance of inotify.
*
* @var resource
*/
protected $_inotify;
/**
* Whether or not we're minifying/compressing the output.
*
* @var bool
*/
protected $_minify = false;
/**
* Default constructor.
*
* @access public
* @param array $directories
* @param array $fileExtensions
* @param bool $minify
* @param array $ignoredFiles
* @return void
*/
public function __construct(
$directories = array(),
$fileExtensions = array(),
$minify = false,
$ignoredFiles = array()
)
{
// initial validation
if (empty($fileExtensions)) {
die('You must watch at least one of the following file extensions: sass, scss, less, styl');
}
// store the watched file extensions
$this->_watchedFileExtensions = $fileExtensions;
// store any ignored files
$this->_ignoredFiles = $ignoredFiles;
// store minify flag
$this->_minify = $minify;
// initialize an inotify instance
$this->_inotify = inotify_init();
// don't block the stream
stream_set_blocking($this->_inotify, self::MODE_NONBLOCKING);
// watch files within specific directories (on modify)
foreach ($directories as $inFile => $outFile) {
if (!is_numeric($inFile)) {
// represents the inFile directory, need to map to output directory
$this->add($inFile, $outFile);
} else {
// represents both the inFile and outFile directory
$this->add($outFile, NULL);
}
}
// update any and all watched files/dirs on startup
$this->update();
// alert
@system('notify-send Watchdog "Watchdog is now actively monitoring for changes to the following file extensions: ' . "\n\n" . implode(', ', $fileExtensions) . '"');
// initialize the watchdog
$this->init();
}
/**
* Handles updating/compiling watched files and/or directories of files.
*
* @access public
* @return void
*/
public function update()
{
foreach ($this->_watched as $inputPath => $info) {
// only trigger on files/dirs with modify flag
if ($info['events'] != IN_MODIFY) {
continue;
}
// skip if not readable
if (!is_readable($inputPath)) {
continue;
}
// determine if directory or file
if (is_dir($inputPath)) {
$iterator = new DirectoryIterator($inputPath);
foreach ($iterator as $fileInfo) {
if ($fileInfo->isDot() || $fileInfo->isDir()) {
continue;
}
// get the full path to the file
if ($fileInfo->isFile()) {
// get some file info
$filename = $fileInfo->getFilename();
$filepath = $fileInfo->getPathname();
$ext = $fileInfo->getExtension();
// check if ignored
if (!$this->_fileIsIgnored($filename)) {
// check if we actually need to do anything with the file
if (in_array($ext, $this->_watchedFileExtensions)) {
// determine the directory
$dirpath = dirname($inputPath);
$dirpath = rtrim($dirpath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
// check for an output path for the file
$outputPath = $this->_getOutputPathByDescriptor($info['descriptor']);
// notify of detected change
echo '[' . date('m.d.Y H:i:s') . '] Forced compile on: ' . $filepath . PHP_EOL;
// perform the update on the command line and display result to STDOUT
$output = $this->_executeCmd($filepath, $dirpath, $ext, $outputPath);
if (!empty($output)) {
echo $output . PHP_EOL;
}
}
}
}
}
} else if (is_file($inputPath)) {
// determine the filename
$filename = basename($inputPath);
// check if we actually need to do anything with the file
$ext = strtolower(substr($filename, strrpos($filename, '.') + 1));
if (in_array($ext, $this->_watchedFileExtensions)) {
// determine the directory
$dirpath = dirname($inputPath);
$dirpath = rtrim($dirpath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
// check for an output path for the file
$outputPath = $this->_getOutputPathByDescriptor($info['descriptor']);
// notify of detected change
echo '[' . date('m.d.Y H:i:s') . '] Forced compile on: ' . $filepath . PHP_EOL;
// perform the update on the command line and display result to STDOUT
$output = $this->_executeCmd($inputPath, $dirpath, $ext, $outputPath);
if (!empty($output)) {
echo $output . PHP_EOL;
}
}
}
}
}
/**
* Continuous watching.
*
* @access public
* @return void
*/
public function init()
{
pcntl_signal(SIGTERM, array(&$this, "signal_handler"));
pcntl_signal(SIGINT, array(&$this, "signal_handler"));
// begin the watchdog
while(1) {
// watch
$this->watch();
// pause before checking again
usleep(self::PAUSE_MS);
}
}
/**
* Perform the actual check for file changes.
*
* @access public
* @return void
*/
public function watch()
{
// check for any changes
$events = $this->read();
if (!empty($events)) {
// ensure we don't have duplicate events (it happens...)
$events = $this->_array_unique($events);
// iterate over events
foreach ($events as $e) {
// handle the event
$filename = $e['name'];
// check if filename is excluded
if ($this->_fileIsIgnored($filename)) {
continue 2;
}
// check if we actually need to do anything with the file
$ext = strtolower(substr($filename, strrpos($filename, '.') + 1));
if (in_array($ext, $this->_watchedFileExtensions)) {
// generate the full input path to the file
$dirpath =
rtrim($this->_pathLookup[$e['wd']], DIRECTORY_SEPARATOR) .
DIRECTORY_SEPARATOR;
$filepath = $dirpath . $filename;
// check for an output path for the file
$outputPath = $this->_getOutputPathByDescriptor($e['wd']);
// notify of detected change
echo '[' . date('m.d.Y H:i:s') . '] Change detected in: ' . $filepath . PHP_EOL;
$msg = "A change was detected in file:\n$filepath\n\nRe-compiled.";
@system('notify-send Watchdog "' . $msg . '"');
// perform the update on the command line and display result to STDOUT
$output = $this->_executeCmd($filepath, $dirpath, $ext, $outputPath);
if (!empty($output)) {
echo $output . PHP_EOL;
}
}
}
}
}
/**
* Add a new file/folder to watch. The return value is a unique (inotify
* instance wide) watch descriptor.
*
* @access public
* @param string $inputPath
* @param mixed $outputPath
* @param array $events A masked integer of all events
*
*/
public function add($inputPath, $outputPath = NULL, $events = IN_MODIFY)
{
// check if we need to first remove a matching path
if (isset($this->_watched[$inputPath])) {
$this->remove($inputPath);
}
// add the new watch
$descriptor = inotify_add_watch($this->_inotify, $inputPath, $events);
// create the array
$info = array(
'events' => $events,
'descriptor' => $descriptor
);
// create a reverse lookup on the descriptor
$this->_pathLookup[$descriptor] = $inputPath;
// create a lookup for the output path
$this->_outputPathLookup[$descriptor] = $outputPath;
// add to watched list
$this->_watched[$inputPath] = $info;
}
/**
* Removes an inotify watch.
*
* @access public
* @param string $path
* @return mixed
*/
public function remove($path)
{
if (isset($this->_watched[$path])) {
if (inotify_rm_watch($this->_inotify, $this->_watched[$path]['descriptor'])) {
unset($this->_pathLookup[ $this->_watched[$path]['descriptor'] ]);
unset($this->_outputPathLookup[ $this->_watched[$path]['descriptor'] ]);
unset($this->_watched[$path]);
return true;
}
}
return false;
}
/**
* Remove all inotify watches.
*
* @access public
* @return void
*/
public function removeAll()
{
foreach ($this->_watched as $path => $watch) {
if (inotify_rm_watch($this->_inotify, $watch['descriptor'])) {
unset($this->_pathLookup[ $watch['descriptor'] ]);
unset($this->_watched[$path]);
}
}
}
/**
* Read events from an inotify instance. Returns an array of inotify events
* or FALSE if no events was pending and inotify_instance is non-blocking.
* Each event is an array with the following keys:
*
* - wd is a watch descriptor returned by inotify_add_watch()
* - mask is a bit mask of events
* - cookie is a unique id to connect related events (e.g. IN_MOVE_FROM and IN_MOVE_TO)
* - name is the name of a file (e.g. if a file was modified in a watched directory)
*
* @access public
* @return mixed
*/
public function read()
{
return inotify_read($this->_inotify);
}
/**
* Retrieves the number of pending events.
*
* @access public
* @return int
*/
public function getPendingEventsCount()
{
return inotify_queue_len($this->_inotify);
}
/**
* Handle the signals. Gracefully removes all inotify watches before closing.
*
* @access public
* @param int $signal
*/
public function signal_handler($signal)
{
switch($signal) {
case SIGTERM:
$this->removeAll();
echo 'Caught the signal SIGTERM. Now exiting.' . PHP_EOL;
exit;
case SIGKILL:
$this->removeAll();
print 'Caught the signal SIGKILL. Now exiting.' . PHP_EOL;
exit;
case SIGINT:
$this->removeAll();
print 'Caught the signal SIGINT. Now exiting.' . PHP_EOL;
exit;
}
}
/**
* Determine the command for generating/compiling output.
*
* @access public
* @param string $inFile
* @param string $outputDir
* @param string $fileExt
* @param string $outputFile
* @return void
*/
protected function _executeCmd($inFile, $outputDir, $fileExt, $outputFile = NULL)
{
switch ($fileExt) {
case 'sass':
case 'scss':
return $this->_executeSassCmd($inFile, $outputDir, $fileExt, $outputFile);
break;
case 'less':
return $this->_executeLessCmd($inFile, $outputDir, $fileExt, $outputFile);
break;
case 'styl':
return $this->_executeStylusCmd($inFile, $outputDir, $fileExt, $outputFile);
break;
case 'haml':
return $this->_executeHamlCmd($inFile, $outputDir, $fileExt, $outputFile);
break;
case 'jade':
return $this->_executeJadeCmd($inFile, $outputDir, $fileExt, $outputFile);
break;
}
return false;
}
/**
* Execute the SASS command for generating output. As a side note, SASS
* can output styles of nested (default), compact, compressed, or expanded.
* We currently only handle one case.
*
* @access public
* @param string $inFile
* @param string $path
* @param string $ext
* @return void
*/
protected function _executeSassCmd($inFile, $path, $ext, $outFile = NULL)
{
// generate the outfile name
$outFile = $this->_generateOutFile($inFile, $outFile, $ext);
// create the command
if ($this->_minify) {
$cmd = 'sass -I ' . $path . ' --style compressed ' . $inFile . ' ' . $outFile;
} else {
$cmd = 'sass -I ' . $path . ' ' . $inFile . ' ' . $outFile;
}
// execute the command and display output
return shell_exec($cmd);
}
/**
* Execute the LESS command for generating output. Note that the include
* path needs to be relative to the directory that lessc is executing in.
*
* @access public
* @param string $inFile
* @param string $path
* @param string $ext
* @return void
*/
protected function _executeLessCmd($inFile, $path, $ext, $outFile = NULL)
{
// generate the outfile name
$outFile = $this->_generateOutFile($inFile, $outFile, $ext);
// create the command
if ($this->_minify) {
$cmd = 'lessc -x --include-path="' . $path . '" ' . $inFile . ' > ' . $outFile;
} else {
$cmd = 'lessc --include-path="' . $path . '" ' . $inFile . ' > ' . $outFile;
}
// execute the command and display output
return shell_exec($cmd);
}
/**
* Execute the Stylus command for generating output. More documentation on
* CLI arguments for stylus are available at:
*
* http://learnboost.github.com/stylus/docs/executable.html
*
* @access public
* @param string $inFile
* @param string $path
* @param string $ext
* @return void
*/
protected function _executeStylusCmd($inFile, $path, $ext, $outFile = NULL)
{
// generate the outfile name
$outFile = $this->_generateOutFile($inFile, $outFile, $ext);
// create the command
if ($this->_minify) {
$cmd = 'stylus -c -I ' . $path . ' < ' . $inFile . ' > ' . $outFile;
} else {
$cmd = 'stylus -I ' . $path . ' < ' . $inFile . ' > ' . $outFile;
}
// execute the command and display output
return shell_exec($cmd);
}
/**
* Execute the HAML command for generating output. More documentation on
* CLI arguments for HAML are available at:
*
* http://haml-lang.com/docs/yardoc/file.HAML_REFERENCE.html
*
* @access public
* @param string $inFile
* @param string $path
* @param string $ext
* @return void
*/
protected function _executeHamlCmd($inFile, $path, $ext, $outFile = NULL)
{
// generate the outfile name
$outFile = $this->_generateOutFile($inFile, $outFile, $ext);
// create the command
if ($this->_minify) {
$cmd = 'haml --format html5 --style ugly -I ' . $path . ' ' . $inFile . ' ' . $outFile;
} else {
$cmd = 'haml --format html5 -I ' . $path . ' ' . $inFile . ' ' . $outFile;
}
// execute the command and display output
return shell_exec($cmd);
}
/**
* Execute the Jade command for generating output. More documentation on
* CLI arguments for Jade are available at:
*
* http://haml-lang.com/docs/yardoc/file.HAML_REFERENCE.html
*
* @access public
* @param string $inFile
* @param string $path
* @param string $ext
* @return void
*/
protected function _executeJadeCmd($inFile, $path, $ext, $outFile = NULL)
{
// generate the outfile name
$outFile = $this->_generateOutFile($inFile, $outFile, $ext);
// create the command
if ($this->_minify) {
$cmd = 'jade -p ' . $path . ' < ' . $inFile . ' > ' . $outFile;
} else {
$cmd = 'jade -p ' . $path . ' < ' . $inFile . ' > ' . $outFile;
}
// execute the command and display output
return shell_exec($cmd);
}
/**
* Given a full path to a file, return the same file with a
* CSS extension.
*
* @access protected
* @param string $inFile
* @param string $outPath
* @param string $ext
* @return string
*/
protected function _generateOutFile($inFile, $outPath, $ext)
{
if (!empty($outPath)) {
$inFile = basename($inFile);
return
rtrim($outPath, DIRECTORY_SEPARATOR)
. DIRECTORY_SEPARATOR
. substr($inFile, 0, strpos($inFile, '.'))
. '.css';
}
return substr($inFile, 0, strpos($inFile, '.')) . '.css';
}
/**
* Checks if the filename is in the list of ignored files.
*
* @access protected
* @param string $filename
* @return bool
*/
protected function _fileIsIgnored($filename)
{
// check if filename is excluded
foreach ($this->_ignoredFiles as $ignoredFile) {
if ($filename === $ignoredFile) {
return true;
}
}
return false;
}
/**
* De-dupe a multi-dimensional array.
*
* @access protected
* @param array $arr
* @return array
*/
protected function _array_unique($arr) {
return array_map(
'unserialize',
array_unique(array_map('serialize', $arr))
);
}
/**
* Given a file descriptor from the watched files, retrieve the output
* path for where we want to compile the file to.
*
* @access protected
* @param mixed $descriptor
* @return mixed
*/
protected function _getOutputPathByDescriptor($descriptor)
{
$outputPath = NULL;
if (!empty($this->_outputPathLookup[$descriptor])) {
$outputPath =
rtrim($this->_outputPathLookup[$descriptor], DIRECTORY_SEPARATOR) .
DIRECTORY_SEPARATOR;
}
return $outputPath;
}
}
// load the watchdog
$watchdog = new Watchdog($directoryWatch, $fileExtensions, $minified, $ignoredFiles);