|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Hyde\Framework\Actions\PreBuildTasks; |
|
6
|
|
|
|
|
7
|
|
|
use Hyde\Hyde; |
|
8
|
|
|
use Hyde\Facades\Config; |
|
9
|
|
|
use Hyde\Facades\Filesystem; |
|
10
|
|
|
use Hyde\Support\Filesystem\MediaFile; |
|
11
|
|
|
use Hyde\Framework\Features\BuildTasks\PreBuildTask; |
|
12
|
|
|
|
|
13
|
|
|
use function basename; |
|
14
|
|
|
use function in_array; |
|
15
|
|
|
use function sprintf; |
|
16
|
|
|
|
|
17
|
|
|
class CleanSiteDirectory extends PreBuildTask |
|
18
|
|
|
{ |
|
19
|
|
|
protected static string $message = 'Removing all files from build directory'; |
|
20
|
|
|
|
|
21
|
|
|
public function handle(): void |
|
22
|
|
|
{ |
|
23
|
|
|
if ($this->isItSafeToCleanOutputDirectory()) { |
|
24
|
|
|
Filesystem::unlink(Filesystem::findFiles(Hyde::sitePath(), ['html', 'json'])->all()); |
|
|
|
|
|
|
25
|
|
|
Filesystem::cleanDirectory(MediaFile::outputPath()); |
|
26
|
|
|
} |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
public function printFinishMessage(): void |
|
30
|
|
|
{ |
|
31
|
|
|
$this->newLine(); |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
protected function isItSafeToCleanOutputDirectory(): bool |
|
35
|
|
|
{ |
|
36
|
|
|
if (! $this->isOutputDirectoryWhitelisted() && ! $this->askIfUnsafeDirectoryShouldBeEmptied()) { |
|
37
|
|
|
$this->info('Output directory will not be emptied.'); |
|
38
|
|
|
|
|
39
|
|
|
return false; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
return true; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
protected function isOutputDirectoryWhitelisted(): bool |
|
46
|
|
|
{ |
|
47
|
|
|
return in_array(basename(Hyde::sitePath()), $this->safeOutputDirectories()); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
protected function askIfUnsafeDirectoryShouldBeEmptied(): bool |
|
51
|
|
|
{ |
|
52
|
|
|
return $this->confirm(sprintf( |
|
53
|
|
|
'The configured output directory (%s) is potentially unsafe to empty. '. |
|
54
|
|
|
'Are you sure you want to continue?', |
|
55
|
|
|
Hyde::getOutputDirectory() |
|
|
|
|
|
|
56
|
|
|
)); |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
/** @return array<string> */ |
|
60
|
|
|
protected function safeOutputDirectories(): array |
|
61
|
|
|
{ |
|
62
|
|
|
/** @var array<string> $directories */ |
|
63
|
|
|
$directories = Config::getArray('hyde.safe_output_directories', ['_site', 'docs', 'build']); |
|
64
|
|
|
|
|
65
|
|
|
return $directories; |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|