-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathWatcher.php
426 lines (321 loc) · 14.3 KB
/
Watcher.php
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
<?php
/*!
* Watcher Class
*
* Copyright (c) 2013-2014 Dave Olsen, http://dmolsen.com
* Licensed under the MIT license
*
* Watches the source/ dir for any changes so those changes can be automagically
* moved to the public/ dir. Watches static files, patterns, and data files
*
* This is not the most efficient implementation of a directory watch but I hope
* it's the most platform agnostic.
*
*/
namespace PatternLab;
use \PatternLab\Annotations;
use \PatternLab\Builder;
use \PatternLab\Config;
use \PatternLab\Console;
use \PatternLab\Data;
use \PatternLab\Dispatcher;
use \PatternLab\FileUtil;
use \PatternLab\InstallerUtil;
use \PatternLab\PatternData;
use \PatternLab\Util;
use \PatternLab\Timer;
use \Symfony\Component\Filesystem\Filesystem;
use \Symfony\Component\Filesystem\Exception\IOExceptionInterface;
class Watcher extends Builder {
/**
* Use the Builder __construct to gather the config variables
*/
public function __construct($config = array()) {
// construct the parent
parent::__construct($config);
$this->options = array();
}
/**
* Watch the source/ directory for any changes to existing files. Will run forever if given the chance.
* @param {Boolean} decide if the reload server should be turned on
* @param {Boolean} decide if static files like CSS and JS should be moved
*/
public function watch($options = array()) {
// double-checks options was properly set
if (empty($options)) {
Console::writeError("need to pass options to generate...");
}
// set default attributes
$moveStatic = (isset($options["moveStatic"])) ? $options["moveStatic"] : true;
$noCacheBuster = (isset($options["noCacheBuster"])) ? $options["noCacheBuster"] : false;
// make sure a copy of the given options are saved for using when running generate
$this->options = $options;
// set-up the Dispatcher
$dispatcherInstance = Dispatcher::getInstance();
$dispatcherInstance->dispatch("watcher.start");
if ($noCacheBuster) {
Config::setOption("cacheBuster",0);
}
$c = false; // track that one loop through the pattern file listing has completed
$o = new \stdClass(); // create an object to hold the properties
$cp = new \stdClass(); // create an object to hold a clone of $o
$o->patterns = new \stdClass();
Console::writeLine("watching your site for changes...");
// default vars
$publicDir = Config::getOption("publicDir");
$sourceDir = Config::getOption("sourceDir");
$patternSourceDir = Config::getOption("patternSourceDir");
$ignoreExts = Config::getOption("ie");
$ignoreDirs = Config::getOption("id");
$patternExt = Config::getOption("patternExtension");
// build the file extensions based on the rules
$fileExtensions = array();
$patternRules = PatternData::getRules();
foreach ($patternRules as $patternRule) {
$extensions = $patternRule->getProp("extProp");
if (strpos($extensions,"&&") !== false) {
$extensions = explode("&&",$extensions);
} else if (strpos($extensions,"||") !== false) {
$extensions = explode("||",$extensions);
} else {
$extensions = array($extensions);
}
foreach ($extensions as $extension) {
if (!in_array($extension, $fileExtensions)) {
$fileExtensions[] = $extension;
}
}
}
// run forever
while (true) {
// clone the patterns so they can be checked in case something gets deleted
$cp = clone $o->patterns;
// iterate over the patterns & related data and regenerate the entire site if they've changed
$patternObjects = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($patternSourceDir), \RecursiveIteratorIterator::SELF_FIRST);
// make sure dots are skipped
$patternObjects->setFlags(\FilesystemIterator::SKIP_DOTS);
foreach($patternObjects as $name => $object) {
// clean-up the file name and make sure it's not one of the pattern lab files or to be ignored
$fileName = str_replace($patternSourceDir.DIRECTORY_SEPARATOR,"",$name);
$fileNameClean = str_replace(DIRECTORY_SEPARATOR."_",DIRECTORY_SEPARATOR,$fileName);
if ($object->isFile() && in_array($object->getExtension(), $fileExtensions)) {
// make sure this isn't a hidden pattern
$patternParts = explode(DIRECTORY_SEPARATOR,$fileName);
$pattern = isset($patternParts[2]) ? $patternParts[2] : $patternParts[1];
// make sure the pattern still exists in source just in case it's been deleted during the iteration
if (file_exists($name)) {
$mt = $object->getMTime();
if (isset($o->patterns->$fileName) && ($o->patterns->$fileName != $mt)) {
$o->patterns->$fileName = $mt;
$this->updateSite($fileName,"changed");
} else if (!isset($o->patterns->$fileName) && $c) {
$o->patterns->$fileName = $mt;
$this->updateSite($fileName,"added");
if ($object->getExtension() == $patternExt) {
$patternSrcPath = str_replace(".".$patternExt,"",$fileName);
$patternDestPath = str_replace("/","-",$patternSrcPath);
$render = ($pattern[0] != "_") ? true : false;
$this->patternPaths[$patternParts[0]][$pattern] = array("patternSrcPath" => $patternSrcPath, "patternDestPath" => $patternDestPath, "render" => $render);
}
} else if (!isset($o->patterns->$fileName)) {
$o->patterns->$fileName = $mt;
}
if ($c && isset($o->patterns->$fileName)) {
unset($cp->$fileName);
}
} else {
// the file was removed during the iteration so remove references to the item
unset($o->patterns->$fileName);
unset($cp->$fileName);
unset($this->patternPaths[$patternParts[0]][$pattern]);
$this->updateSite($fileName,"removed");
}
}
}
// make sure old entries are deleted
// will throw "pattern not found" errors if an entire directory is removed at once but that shouldn't be a big deal
if ($c) {
foreach($cp as $fileName => $mt) {
unset($o->patterns->$fileName);
$patternParts = explode(DIRECTORY_SEPARATOR,$fileName);
$pattern = isset($patternParts[2]) ? $patternParts[2] : $patternParts[1];
unset($this->patternPaths[$patternParts[0]][$pattern]);
$this->updateSite($fileName,"removed");
}
}
// iterate over annotations, data, meta and any other _ dirs
$watchDirs = glob($sourceDir.DIRECTORY_SEPARATOR."_*",GLOB_ONLYDIR);
foreach ($watchDirs as $watchDir) {
if ($watchDir != $patternSourceDir) {
// iterate over the data files and regenerate the entire site if they've changed
$objects = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($watchDir), \RecursiveIteratorIterator::SELF_FIRST);
// make sure dots are skipped
$objects->setFlags(\FilesystemIterator::SKIP_DOTS);
foreach($objects as $name => $object) {
$fileName = str_replace($sourceDir.DIRECTORY_SEPARATOR,"",$name);
$mt = $object->getMTime();
if (!isset($o->$fileName)) {
$o->$fileName = $mt;
if ($c) {
$this->updateSite($fileName,"added");
}
} else if ($o->$fileName != $mt) {
$o->$fileName = $mt;
if ($c) {
$this->updateSite($fileName,"changed");
}
}
}
}
}
// iterate over all of the other files in the source directory and move them if their modified time has changed
if ($moveStatic) {
$objects = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($sourceDir.DIRECTORY_SEPARATOR), \RecursiveIteratorIterator::SELF_FIRST);
// make sure dots are skipped
$objects->setFlags(\FilesystemIterator::SKIP_DOTS);
foreach($objects as $name => $object) {
// clean-up the file name and make sure it's not one of the pattern lab files or to be ignored
$fileName = str_replace($sourceDir.DIRECTORY_SEPARATOR,"",$name);
if (($fileName[0] != "_") && (!in_array($object->getExtension(),$ignoreExts)) && (!in_array($object->getFilename(),$ignoreDirs))) {
// catch directories that have the ignored dir in their path
$ignoreDir = FileUtil::ignoreDir($fileName);
// check to see if it's a new directory
if (!$ignoreDir && $object->isDir() && !isset($o->$fileName) && !is_dir($publicDir."/".$fileName)) {
mkdir($publicDir."/".$fileName);
$o->$fileName = "dir created"; // placeholder
Console::writeLine($fileName."/ directory was created...");
}
// check to see if it's a new file or a file that has changed
if (file_exists($name)) {
$mt = $object->getMTime();
if (!$ignoreDir && $object->isFile() && !isset($o->$fileName) && !file_exists($publicDir."/".$fileName)) {
$o->$fileName = $mt;
FileUtil::moveStaticFile($fileName,"added");
if ($object->getExtension() == "css") {
$this->updateSite($fileName,"changed",0); // make sure the site is updated for MQ reasons
}
} else if (!$ignoreDir && $object->isFile() && isset($o->$fileName) && ($o->$fileName != $mt)) {
$o->$fileName = $mt;
FileUtil::moveStaticFile($fileName,"changed");
if ($object->getExtension() == "css") {
$this->updateSite($fileName,"changed",0); // make sure the site is updated for MQ reasons
}
} else if (!isset($o->fileName)) {
$o->$fileName = $mt;
}
} else {
unset($o->$fileName);
}
}
}
}
$c = true;
// taking out the garbage. basically killing mustache after each run.
if (gc_enabled()) gc_collect_cycles();
// pause for .05 seconds to give the CPU a rest
usleep(50000);
}
}
/**
* Updates the Pattern Lab Website and prints the appropriate message
* @param {String} file name to included in the message
* @param {String} a switch for decided which message isn't printed
*
* @return {String} the final message
*/
private function updateSite($fileName,$message,$verbose = true) {
$watchMessage = "";
if ($verbose) {
if ($message == "added") {
$watchMessage = "<warning>".$fileName." was added to Pattern Lab. reload the website to see this change in the navigation...</warning>";
} elseif ($message == "removed") {
$watchMessage = "<warning>".$fileName." was removed from Pattern Lab. reload the website to see this change reflected in the navigation...</warning>";
} elseif ($message == "hidden") {
$watchMessage = "<warning>".$fileName." was hidden from Pattern Lab. reload the website to see this change reflected in the navigation...</warning>";
} else {
$watchMessage = "<info>".$fileName." changed...</info>";
}
}
$options = $this->options;
$options["watchVerbose"] = $verbose;
$options["watchMessage"] = $watchMessage;
$options["moveStatic"] = false;
// clear the various data stores for re-population
Data::clear();
PatternData::clear();
Annotations::clear();
$g = new Generator();
try {
$g->generate($options);
} catch (\Exception $e) {
Console::writeWarning("Failed on update to ".$fileName);
Console::writeWarning($e->getMessage());
} catch (\Throwable $e) {
Console::writeWarning("Failed on update to ".$fileName);
Console::writeWarning($e->getMessage());
}
}
protected function starterKitPathPrompt() {
// need to figure this out long-term
InstallerUtil::$isInteractive = true;
$input = Console::promptInput("Tell me the path to the starterkit you want to watch.","e.g. vendor/pattern-lab/starterkit-mustache-demo/dist","baz",false);
// set-up the full starterkit path
$starterKitPath = Config::getOption("baseDir").$input;
if (!is_dir($starterKitPath)) {
Console::writeWarning("that doesn't seem to be a real directory. let's try again...");
$starterKitPath = $this->starterKitPathPrompt();
}
return $starterKitPath;
}
public function watchStarterKit() {
// default vars
$starterKitPath = $this->starterKitPathPrompt();
$sourceDir = Config::getOption("sourceDir");
$fs = new Filesystem();
$c = false; // track that one loop through the pattern file listing has completed
$o = new \stdClass(); // create an object to hold the properties
$cp = new \stdClass(); // create an object to hold a clone of $o
$o->patterns = new \stdClass();
Console::writeLine("watching your starterkit for changes...");
// run forever
while (true) {
// clone the patterns so they can be checked in case something gets deleted
$cp = clone $o->patterns;
$objects = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($starterKitPath), \RecursiveIteratorIterator::SELF_FIRST);
// make sure dots are skipped
$objects->setFlags(\FilesystemIterator::SKIP_DOTS);
foreach ($objects as $name => $object) {
// clean-up the file name and make sure it's not one of the pattern lab files or to be ignored
$fileName = str_replace($starterKitPath.DIRECTORY_SEPARATOR,"",$name);
// check to see if it's a new directory
if ($object->isDir() && !isset($o->$fileName) && !is_dir($starterKitPath."/".$fileName)) {
mkdir($sourceDir."/".$fileName);
$o->$fileName = "dir created"; // placeholder
Console::writeLine($fileName."/ directory was created...");
}
// check to see if it's a new file or a file that has changed
if (file_exists($name)) {
$mt = $object->getMTime();
if ($object->isFile() && !isset($o->$fileName) && !file_exists($sourceDir.DIRECTORY_SEPARATOR.$fileName)) {
$o->$fileName = $mt;
$fs->copy($starterKitPath.DIRECTORY_SEPARATOR.$fileName,$sourceDir.DIRECTORY_SEPARATOR.$fileName);
Console::writeInfo($fileName." added...");
} else if ($object->isFile() && isset($o->$fileName) && ($o->$fileName != $mt)) {
$o->$fileName = $mt;
$fs->copy($starterKitPath.DIRECTORY_SEPARATOR.$fileName,$sourceDir.DIRECTORY_SEPARATOR.$fileName);
Console::writeInfo($fileName." changed...");
} else if (!isset($o->fileName)) {
$o->$fileName = $mt;
}
} else {
unset($o->$fileName);
}
}
$c = true;
// taking out the garbage. basically killing mustache after each run.
if (gc_enabled()) gc_collect_cycles();
// pause for .05 seconds to give the CPU a rest
usleep(50000);
}
}
}