/
CliRunner.php
246 lines (197 loc) · 6.76 KB
/
CliRunner.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
<?php
/**
* FTP Deployment
*
* Copyright (c) 2009 David Grudl (https://davidgrudl.com)
*/
namespace Deployment;
/**
* Run Forrest run!
*/
class CliRunner
{
/** @var array */
public $defaults = [
'local' => '',
'passivemode' => true,
'ignore' => '',
'allowdelete' => true,
'purge' => '',
'before' => '',
'afterupload' => '',
'after' => '',
'preprocess' => true,
];
/** @var string[] */
public $ignoreMasks = ['*.bak', '.svn', '.git*', 'Thumbs.db', '.DS_Store', '.idea'];
/** @var Logger */
private $logger;
/** @var string */
private $configFile;
/** @var string test|generate|null */
private $mode;
/** @var array[] */
private $batches = [];
/** @var resource */
private $lock;
/** @return int|null */
public function run()
{
$this->logger = new Logger('php://memory');
$this->setupPhp();
$config = $this->loadConfig();
if (!$config) {
return 1;
}
$this->logger = new Logger($config['log']);
$this->logger->useColors = (bool) $config['colors'];
$this->logger->showProgress = (bool) $config['progress'];
if (!is_dir($tempDir = $config['tempdir'])) {
$this->logger->log("Creating temporary directory $tempDir");
mkdir($tempDir, 0777, true);
}
$time = time();
$this->logger->log('Started at ' . date('[Y/m/d H:i]'));
$this->logger->log("Config file is $this->configFile");
foreach ($this->batches as $name => $batch) {
$this->logger->log("\nDeploying $name");
$deployment = $this->createDeployer($batch);
$deployment->tempDir = $tempDir;
if ($this->mode === 'generate') {
$this->logger->log('Scanning files');
$localPaths = $deployment->collectPaths();
$this->logger->log('Saved ' . $deployment->writeDeploymentFile($localPaths));
continue;
}
if ($deployment->testMode) {
$this->logger->log('Test mode', 'lime');
} else {
$this->logger->log('Live mode', 'aqua');
}
if (!$deployment->allowDelete) {
$this->logger->log('Deleting disabled');
}
$deployment->deploy();
}
$time = time() - $time;
$this->logger->log("\nFinished at " . date('[Y/m/d H:i]') . " (in $time seconds)", 'lime');
}
/** @return Deployer */
private function createDeployer($config)
{
if (empty($config['remote']) || !($urlParts = parse_url($config['remote'])) || !isset($urlParts['scheme'], $urlParts['host'])) {
throw new \Exception("Missing or invalid 'remote' URL in config.");
}
if (isset($config['user'])) {
$urlParts['user'] = urlencode($config['user']);
}
if (isset($config['password'])) {
$urlParts['pass'] = urlencode($config['password']);
}
$server = $urlParts['scheme'] === 'sftp'
? new SshServer($urlParts)
: new FtpServer($urlParts, (bool) $config['passivemode']);
if (!preg_match('#/|\\\\|[a-z]:#iA', $config['local'])) {
$config['local'] = dirname($this->configFile) . '/' . $config['local'];
}
$deployment = new Deployer($server, $config['local'], $this->logger);
if ($config['preprocess']) {
$deployment->preprocessMasks = $config['preprocess'] == 1 ? ['*.js', '*.css'] : self::toArray($config['preprocess']); // intentionally ==
$preprocessor = new Preprocessor($this->logger);
$deployment->addFilter('js', [$preprocessor, 'expandApacheImports']);
$deployment->addFilter('js', [$preprocessor, 'compressJs'], true);
$deployment->addFilter('css', [$preprocessor, 'expandApacheImports']);
$deployment->addFilter('css', [$preprocessor, 'expandCssImports']);
$deployment->addFilter('css', [$preprocessor, 'compressCss'], true);
}
$deployment->ignoreMasks = array_merge($this->ignoreMasks, self::toArray($config['ignore']));
$deployment->deploymentFile = empty($config['deploymentfile']) ? $deployment->deploymentFile : $config['deploymentfile'];
$deployment->allowDelete = $config['allowdelete'];
$deployment->toPurge = self::toArray($config['purge'], true);
$deployment->runBefore = self::toArray($config['before'], true);
$deployment->runAfterUpload = self::toArray($config['afterupload'], true);
$deployment->runAfter = self::toArray($config['after'], true);
$deployment->testMode = !empty($config['test']) || $this->mode === 'test';
$server->filePermissions = empty($config['filepermissions']) ? null : octdec($config['filepermissions']);
$server->dirPermissions = empty($config['dirpermissions']) ? null : octdec($config['dirpermissions']);
return $deployment;
}
/** @return void */
private function setupPhp()
{
set_time_limit(0);
date_default_timezone_set('Europe/Prague');
set_error_handler(function ($severity, $message, $file, $line) {
if (($severity & error_reporting()) === $severity) {
$this->logger->log("Error: $message in $file on $line", 'red');
exit(1);
}
return false;
});
set_exception_handler(function ($e) {
$this->logger->log("Error: {$e->getMessage()}\n\n$e", 'red');
exit(1);
});
}
/** @return array */
private function loadConfig()
{
$cmd = new CommandLine(<<<'XX'
FTP deployment v2.7
-------------------
Usage:
deployment <config_file> [-t | --test]
Options:
-t | --test Run in test-mode.
--generate Only generates deployment file.
--no-progress Hide the progress indicators.
XX
, [
'config' => [CommandLine::REALPATH => true],
]);
if ($cmd->isEmpty()) {
$cmd->help();
return;
}
$options = $cmd->parse();
$this->mode = $options['--generate'] ? 'generate' : ($options['--test'] ? 'test' : null);
$this->configFile = $options['config'];
if (!flock($this->lock = fopen($options['config'], 'r'), LOCK_EX | LOCK_NB)) {
throw new \Exception('It seems that you are in the middle of another deployment.');
}
$config = $this->loadConfigFile($options['config']);
if (!$config) {
throw new \Exception('Missing config.');
}
$this->batches = isset($config['remote']) && is_string($config['remote'])
? ['' => $config]
: array_filter($config, 'is_array');
foreach ($this->batches as &$batch) {
$batch = array_change_key_case($batch, CASE_LOWER) + $this->defaults;
}
$config = array_change_key_case($config, CASE_LOWER) + [
'log' => preg_replace('#\.\w+$#', '.log', $this->configFile),
'tempdir' => sys_get_temp_dir() . '/deployment',
'progress' => true,
'colors' => (PHP_SAPI === 'cli' && ((function_exists('posix_isatty') && posix_isatty(STDOUT))
|| getenv('ConEmuANSI') === 'ON' || getenv('ANSICON') !== false)),
];
$config['progress'] = $options['--no-progress'] ? false : $config['progress'];
return $config;
}
protected function loadConfigFile($file)
{
if (pathinfo($file, PATHINFO_EXTENSION) == 'php') {
return include $file;
} else {
return parse_ini_file($file, true);
}
}
/** @return array */
public static function toArray($val, $lines = false)
{
return is_array($val)
? array_filter($val)
: preg_split($lines ? '#\s*\n\s*#' : '#\s+#', $val, -1, PREG_SPLIT_NO_EMPTY);
}
}