Serve::setupWatcher()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 7
nc 2
nop 1
dl 0
loc 10
rs 10
c 1
b 0
f 0
1
<?php
2
3
/**
4
 * This file is part of Cecil.
5
 *
6
 * (c) Arnaud Ligny <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Cecil\Command;
15
16
use Cecil\Exception\RuntimeException;
17
use Cecil\Util;
18
use Joli\JoliNotif\DefaultNotifier;
19
use Symfony\Component\Console\Input\InputArgument;
20
use Symfony\Component\Console\Input\InputInterface;
21
use Symfony\Component\Console\Input\InputOption;
22
use Symfony\Component\Console\Output\OutputInterface;
23
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
24
use Symfony\Component\Finder\Finder;
25
use Symfony\Component\Process\Exception\ProcessFailedException;
26
use Symfony\Component\Process\PhpExecutableFinder;
27
use Symfony\Component\Process\Process;
28
use Yosymfony\ResourceWatcher\Crc32ContentHash;
29
use Yosymfony\ResourceWatcher\ResourceCacheMemory;
30
use Yosymfony\ResourceWatcher\ResourceWatcher;
31
32
/**
33
 * Serve command.
34
 *
35
 * This command starts the built-in web server with live reloading capabilities.
36
 * It allows users to serve their website locally and automatically rebuild it when changes are detected.
37
 * It also supports opening the web browser automatically and includes options for drafts, optimization, and more.
38
 */
39
class Serve extends AbstractCommand
40
{
41
    /** @var boolean */
42
    protected $watcherEnabled;
43
44
    /**
45
     * {@inheritdoc}
46
     */
47
    protected function configure()
48
    {
49
        $this
50
            ->setName('serve')
51
            ->setDescription('Starts the built-in server')
52
            ->setDefinition([
53
                new InputArgument('path', InputArgument::OPTIONAL, 'Use the given path as working directory'),
54
                new InputOption('open', 'o', InputOption::VALUE_NONE, 'Open web browser automatically'),
55
                new InputOption('host', null, InputOption::VALUE_REQUIRED, 'Server host', 'localhost'),
56
                new InputOption('port', null, InputOption::VALUE_REQUIRED, 'Server port', '8000'),
57
                new InputOption('watch', 'w', InputOption::VALUE_NEGATABLE, 'Enable (or disable --no-watch) changes watcher (enabled by default)', true),
58
                new InputOption('drafts', 'd', InputOption::VALUE_NONE, 'Include drafts'),
59
                new InputOption('optimize', null, InputOption::VALUE_NEGATABLE, 'Enable (or disable --no-optimize) optimization of generated files'),
60
                new InputOption('config', 'c', InputOption::VALUE_REQUIRED, 'Set the path to extra config files (comma-separated)'),
61
                new InputOption('clear-cache', null, InputOption::VALUE_OPTIONAL, 'Clear cache before build (optional cache key as regular expression)', false),
62
                new InputOption('page', 'p', InputOption::VALUE_REQUIRED, 'Build a specific page'),
63
                new InputOption('no-ignore-vcs', null, InputOption::VALUE_NONE, 'Changes watcher must not ignore VCS directories'),
64
                new InputOption('metrics', 'm', InputOption::VALUE_NONE, 'Show build metrics (duration and memory) of each step'),
65
                new InputOption('timeout', null, InputOption::VALUE_REQUIRED, 'Sets the process timeout (max. runtime) in seconds', 7200), // default is 2 hours
66
                new InputOption('notif', null, InputOption::VALUE_NONE, 'Send desktop notification on server start'),
67
            ])
68
            ->setHelp(
69
                <<<'EOF'
70
The <info>%command.name%</> command starts the live-reloading-built-in web server.
71
72
  <info>%command.full_name%</>
73
  <info>%command.full_name% path/to/the/working/directory</>
74
  <info>%command.full_name% --open</>
75
  <info>%command.full_name% --drafts</>
76
  <info>%command.full_name% --no-watch</>
77
78
You can use a custom host and port by using the <info>--host</info> and <info>--port</info> options:
79
80
  <info>%command.full_name% --host=127.0.0.1 --port=8080</>
81
82
To build the website with an extra configuration file, you can use the <info>--config</info> option.
83
This is useful during local development to <comment>override some settings</comment> without modifying the main configuration:
84
85
  <info>%command.full_name% --config=config/dev.yml</>
86
87
To start the server with changes watcher <comment>not ignoring VCS</comment> directories, run:
88
89
  <info>%command.full_name% --no-ignore-vcs</>
90
91
To define the process <comment>timeout</comment> (in seconds), run:
92
93
  <info>%command.full_name% --timeout=7200</>
94
95
Send a desktop <comment>notification</comment> on server start, run:
96
97
  <info>%command.full_name% --notif</>
98
EOF
99
            );
100
    }
101
102
    /**
103
     * {@inheritdoc}
104
     *
105
     * @throws RuntimeException
106
     */
107
    protected function execute(InputInterface $input, OutputInterface $output): int
108
    {
109
        $open = $input->getOption('open');
110
        $host = $input->getOption('host');
111
        $port = $input->getOption('port');
112
        $drafts = $input->getOption('drafts');
113
        $optimize = $input->getOption('optimize');
114
        $clearcache = $input->getOption('clear-cache');
115
        $page = $input->getOption('page');
116
        $noignorevcs = $input->getOption('no-ignore-vcs');
117
        $metrics = $input->getOption('metrics');
118
        $timeout = $input->getOption('timeout');
119
        $verbose = $input->getOption('verbose');
120
121
        $resourceWatcher = null;
122
        $this->watcherEnabled = $input->getOption('watch');
123
124
        // checks if PHP executable is available
125
        $phpFinder = new PhpExecutableFinder();
126
        $php = $phpFinder->find();
127
        if ($php === false) {
128
            throw new RuntimeException('Unable to find a local PHP executable.');
129
        }
130
131
        // setup server
132
        $this->setUpServer();
133
        $command = \sprintf(
134
            '"%s" -S %s:%d -t "%s" "%s"',
135
            $php,
136
            $host,
137
            $port,
138
            Util::joinFile($this->getPath(), self::SERVE_OUTPUT),
139
            Util::joinFile($this->getPath(), self::TMP_DIR, 'router.php')
140
        );
141
        $process = Process::fromShellCommandline($command);
142
143
        // setup build process
144
        $buildProcessArguments = [
145
            $php,
146
            $_SERVER['argv'][0],
147
        ];
148
        $buildProcessArguments[] = 'build';
149
        $buildProcessArguments[] = $this->getPath();
150
        if (!empty($this->getConfigFiles())) {
151
            $buildProcessArguments[] = '--config';
152
            $buildProcessArguments[] = implode(',', $this->getConfigFiles());
153
        }
154
        if ($drafts) {
155
            $buildProcessArguments[] = '--drafts';
156
        }
157
        if ($optimize === true) {
158
            $buildProcessArguments[] = '--optimize';
159
        }
160
        if ($optimize === false) {
161
            $buildProcessArguments[] = '--no-optimize';
162
        }
163
        if ($clearcache === null) {
164
            $buildProcessArguments[] = '--clear-cache';
165
        }
166
        if (!empty($clearcache)) {
167
            $buildProcessArguments[] = '--clear-cache';
168
            $buildProcessArguments[] = $clearcache;
169
        }
170
        if ($verbose) {
171
            $buildProcessArguments[] = '-' . str_repeat('v', $_SERVER['SHELL_VERBOSITY']);
172
        }
173
        if (!empty($page)) {
174
            $buildProcessArguments[] = '--page';
175
            $buildProcessArguments[] = $page;
176
        }
177
        if (!empty($metrics)) {
178
            $buildProcessArguments[] = '--metrics';
179
        }
180
        $buildProcessArguments[] = '--baseurl';
181
        $buildProcessArguments[] = "http://$host:$port/";
182
        $buildProcessArguments[] = '--output';
183
        $buildProcessArguments[] = self::SERVE_OUTPUT;
184
        $buildProcess = new Process(
185
            $buildProcessArguments,
186
            null,
187
            ['BOX_REQUIREMENT_CHECKER' => '0'] // prevents double check (build then serve)
188
        );
189
        $buildProcess->setTty(Process::isTtySupported());
190
        $buildProcess->setPty(Process::isPtySupported());
191
        $buildProcess->setTimeout((float) $timeout);
192
        $processOutputCallback = function ($type, $buffer) use ($output) {
193
            $output->write($buffer, false, OutputInterface::OUTPUT_RAW);
194
        };
195
196
        // builds before serve
197
        $output->writeln(\sprintf('<comment>Build process: %s</comment>', implode(' ', $buildProcessArguments)), OutputInterface::VERBOSITY_DEBUG);
198
        $buildProcess->run($processOutputCallback);
199
        if ($buildProcess->isSuccessful()) {
200
            $this->buildSuccessActions($output);
201
        }
202
        if ($buildProcess->getExitCode() !== 0) {
203
            $this->tearDownServer();
204
205
            return 1;
206
        }
207
208
        // handles serve process
209
        if (!$process->isStarted()) {
210
            $messageSuffix = '';
211
            // setup resource watcher
212
            if ($this->watcherEnabled) {
213
                $resourceWatcher = $this->setupWatcher($noignorevcs);
214
                $resourceWatcher->initialize();
215
                $messageSuffix = ' with changes watcher';
216
            }
217
            // starts server
218
            try {
219
                if (\function_exists('\pcntl_signal')) {
220
                    pcntl_async_signals(true);
221
                    pcntl_signal(SIGINT, [$this, 'tearDownServer']);
222
                    pcntl_signal(SIGTERM, [$this, 'tearDownServer']);
223
                }
224
                $output->writeln(\sprintf('<comment>Server process: %s</comment>', $command), OutputInterface::VERBOSITY_DEBUG);
225
                $output->writeln(\sprintf('Starting server%s (<href=http://%s:%d>http://%s:%d</>) 🚀', $messageSuffix, $host, $port, $host, $port));
226
                $process->start(function ($type, $buffer) {
227
                    if ($type === Process::ERR) {
228
                        error_log($buffer, 3, Util::joinFile($this->getPath(), self::TMP_DIR, 'errors.log'));
229
                    }
230
                });
231
                // notification
232
                if ($input->getOption('notif')) {
233
                    $notifier = new DefaultNotifier();
234
                    $this->notification->setBody('Starting server 🚀');
235
                    $this->notification->addOption('url', \sprintf('http://%s:%s', $host, $port));
236
                    $notifier->send($this->notification);
237
                }
238
                if ($open) {
239
                    $output->writeln('Opening web browser...');
240
                    Util\Platform::openBrowser(\sprintf('http://%s:%s', $host, $port));
241
                }
242
                while ($process->isRunning()) {
243
                    sleep(1); // wait for server is ready
244
                    if (!fsockopen($host, (int) $port)) {
245
                        $output->writeln('<info>Server is not ready.</info>');
246
247
                        return 1;
248
                    }
249
                    if ($this->watcherEnabled && $resourceWatcher instanceof ResourceWatcher) {
250
                        $watcher = $resourceWatcher->findChanges();
251
                        if ($watcher->hasChanges()) {
252
                            $output->writeln('<comment>Changes detected.</comment>');
253
                            // prints deleted/new/updated files in debug mode
254
                            if (\count($watcher->getDeletedFiles()) > 0) {
255
                                $output->writeln('<comment>Deleted files:</comment>', OutputInterface::VERBOSITY_DEBUG);
256
                                foreach ($watcher->getDeletedFiles() as $file) {
257
                                    $output->writeln("<comment>- $file</comment>", OutputInterface::VERBOSITY_DEBUG);
258
                                }
259
                            }
260
                            if (\count($watcher->getNewFiles()) > 0) {
261
                                $output->writeln('<comment>New files:</comment>', OutputInterface::VERBOSITY_DEBUG);
262
                                foreach ($watcher->getNewFiles() as $file) {
263
                                    $output->writeln("<comment>- $file</comment>", OutputInterface::VERBOSITY_DEBUG);
264
                                }
265
                            }
266
                            if (\count($watcher->getUpdatedFiles()) > 0) {
267
                                $output->writeln('<comment>Updated files:</comment>', OutputInterface::VERBOSITY_DEBUG);
268
                                foreach ($watcher->getUpdatedFiles() as $file) {
269
                                    $output->writeln("<comment>- $file</comment>", OutputInterface::VERBOSITY_DEBUG);
270
                                }
271
                            }
272
                            $output->writeln('');
273
                            // re-builds
274
                            $buildProcess->run($processOutputCallback);
275
                            if ($buildProcess->isSuccessful()) {
276
                                $this->buildSuccessActions($output);
277
                            }
278
                            $output->writeln('<info>Server is runnning...</info>');
279
                        }
280
                    }
281
                }
282
                if ($process->getExitCode() > 0) {
283
                    $output->writeln(\sprintf('<comment>%s</comment>', trim($process->getErrorOutput())));
284
                }
285
            } catch (ProcessFailedException $e) {
286
                $this->tearDownServer();
287
288
                throw new RuntimeException(\sprintf($e->getMessage()));
289
            }
290
        }
291
292
        return 0;
293
    }
294
295
    /**
296
     * Build success actions.
297
     */
298
    private function buildSuccessActions(OutputInterface $output): void
299
    {
300
        // writes `changes.flag` file
301
        if ($this->watcherEnabled) {
302
            Util\File::getFS()->dumpFile(Util::joinFile($this->getPath(), self::TMP_DIR, 'changes.flag'), time());
303
        }
304
        // writes `headers.ini` file
305
        $headers = $this->getBuilder()->getConfig()->get('server.headers');
306
        if (is_iterable($headers)) {
307
            $output->writeln('Writing headers file...');
308
            Util\File::getFS()->remove(Util::joinFile($this->getPath(), self::TMP_DIR, 'headers.ini'));
309
            foreach ($headers as $entry) {
310
                Util\File::getFS()->appendToFile(Util::joinFile($this->getPath(), self::TMP_DIR, 'headers.ini'), "[{$entry['path']}]\n");
311
                foreach ($entry['headers'] ?? [] as $header) {
312
                    Util\File::getFS()->appendToFile(Util::joinFile($this->getPath(), self::TMP_DIR, 'headers.ini'), "{$header['key']} = \"{$header['value']}\"\n");
313
                }
314
            }
315
        }
316
    }
317
318
    /**
319
     * Sets up the watcher.
320
     */
321
    private function setupWatcher(bool $noignorevcs = false): ResourceWatcher
322
    {
323
        $finder = new Finder();
324
        $finder->files()
325
            ->in($this->getPath())
326
            ->exclude((string) $this->getBuilder()->getConfig()->get('output.dir'));
327
        if (file_exists(Util::joinFile($this->getPath(), '.gitignore')) && $noignorevcs === false) {
328
            $finder->ignoreVCSIgnored(true);
329
        }
330
        return new ResourceWatcher(new ResourceCacheMemory(), $finder, new Crc32ContentHash());
331
    }
332
333
    /**
334
     * Prepares server's files.
335
     *
336
     * @throws RuntimeException
337
     */
338
    private function setUpServer(): void
339
    {
340
        try {
341
            // copying router
342
            Util\File::getFS()->copy(
343
                $this->rootPath . '/resources/server/router.php',
344
                Util::joinFile($this->getPath(), self::TMP_DIR, 'router.php'),
345
                true
346
            );
347
            // copying livereload JS for watcher
348
            $livereloadJs = Util::joinFile($this->getPath(), self::TMP_DIR, 'livereload.js');
349
            if (is_file($livereloadJs)) {
350
                Util\File::getFS()->remove($livereloadJs);
351
            }
352
            if ($this->watcherEnabled) {
353
                Util\File::getFS()->copy(
354
                    $this->rootPath . '/resources/server/livereload.js',
355
                    $livereloadJs,
356
                    true
357
                );
358
            }
359
        } catch (IOExceptionInterface $e) {
360
            throw new RuntimeException(\sprintf('An error occurred while copying server\'s files to "%s".', $e->getPath()));
361
        }
362
        if (!is_file(Util::joinFile($this->getPath(), self::TMP_DIR, 'router.php'))) {
363
            throw new RuntimeException(\sprintf('Router not found: "%s".', Util::joinFile(self::TMP_DIR, 'router.php')));
364
        }
365
    }
366
367
    /**
368
     * Removes temporary directory.
369
     *
370
     * @throws RuntimeException
371
     */
372
    public function tearDownServer(): void
373
    {
374
        $this->output->writeln('');
375
        $this->output->writeln('<info>Server stopped.</info>');
376
377
        try {
378
            Util\File::getFS()->remove(Util::joinFile($this->getPath(), self::TMP_DIR));
379
        } catch (IOExceptionInterface $e) {
380
            throw new RuntimeException($e->getMessage());
381
        }
382
    }
383
}
384