-
-
Notifications
You must be signed in to change notification settings - Fork 78
/
Copy pathDeployCommand.php
279 lines (243 loc) · 10.7 KB
/
DeployCommand.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
<?php
/*
* This file is part of the DevShop package.
*
* (c) Jon Pugh <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace DevShop\Component\Deploy;
use Composer\Composer;
use Composer\Config;
use DevShop\Component\Common\ComposerRepositoryAwareTrait;
use DevShop\Component\Common\GitRepository;
use Robo\Common\OutputAwareTrait;
use Symfony\Component\Console\Command\Command as BaseCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
/**
* GitSplitConsoleCommand runs splitsh-lite script.
*
* @author Jon Pugh <[email protected]>
*/
class DeployCommand extends BaseCommand
{
use ComposerRepositoryAwareTrait;
/**
* @var SymfonyStyle
*/
private $io;
/**
* @var string Store the initial working directory at startup time
*/
private $initialWorkingDirectory;
/**
* {@inheritdoc}
*/
protected function configure()
{
$this
->setName('deploy')
->setDescription(
'Run the deploy stages for this application, contingent on environment configuration and .'
)
->setHelp(
<<<'EOF'
The <info>%command.name%</info> runs the commands defined in a project's composer.json:extras.deploy.stages
EOF
);
$this
->addOption(
'option',
'o',
InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY,
"Set deploy options in the format NAME=VALUE."
);
$this
->addOption(
'working-dir',
'd',
InputOption::VALUE_REQUIRED,
'If specified, use the given directory as working directory.'
);
// Add CLI options for default stages.
foreach ([false, true] as $skip) {
$i = 0;
foreach (DeployStages::getStages() as $stage_name => $description) {
$i++;
$this
->addOption(
$skip
? "skip-$stage_name"
: $stage_name
,
null,
InputOption::VALUE_NONE,
$skip
? "Skip Stage $i: $stage_name: $description"
: "Stage $i: $stage_name: $description"
);
}
}
}
/**
* {@inheritdoc}
*/
public function initialize(InputInterface $input, OutputInterface $output)
{
// Prepare object.
$this->io = new SymfonyStyle($input, $output);
$this->setComposerConfig();
// switch working dir
if (empty($this->initialWorkingDirectory) && $newWorkDir = $this->getNewWorkingDir($input)) {
$oldWorkingDir = getcwd();
chdir($newWorkDir);
$this->initialWorkingDirectory = $newWorkDir;
$this->io->writeln('Changed CWD to ' . getcwd());
}
// Set repository from the current working directory.
try {
$this->setRepository(GitRepository::open(getcwd()));
}
catch (\InvalidArgumentException $e) {
$this->io->error("Unable to load git working copy. " . $e->getMessage());
exit(1);
}
// Load the stages from the current composer project.
if ($this->io->isVerbose()) {
$this->io->section('Initializing Deploy Command');
$verbose_rows[] = ['PWD', getenv('PWD')];
$verbose_rows[] = [
'Repository Root',
$this->getRepository()->getRepositoryPath(),
];
$verbose_rows[] = [
'Composer Project',
$this->getComposerConfig()->name(),
];
$this->io->table(['Debug Information'], $verbose_rows);
}
}
/**
* @param InputInterface $input
* @throws \RuntimeException
* @return string
*/
private function getNewWorkingDir(InputInterface $input)
{
$workingDir = $input->getParameterOption(array('--working-dir', '-d'));
if (false !== $workingDir && !is_dir($workingDir)) {
throw new \RuntimeException('Invalid working directory specified, '.$workingDir.' does not exist.');
}
return $workingDir;
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->io->title('Deploy');
// @TODO: Convert to use the Deploy class to load config from anywhere.
// @TODO: Create common DeployTemplates so every project does not need extras.deploy.stages
if (empty($this->getComposerConfig()->extra()->deploy)) {
// @TODO: Allow Fail or Warn
$this->io->warning(
"No 'extra.deploy' section found in composer.json in directory " . $this->composerPath
);
}
else {
// @TODO: Create a simple config class so stage commands can be loaded from many places.
$deploy_extra_config = $this->getComposerConfig()->extra()->deploy;
// Create Deploy class.
$deploy = new Deploy(null, $this->getRepository());
// Pass all options as deploy options.
foreach ($input->getOption('option') as $option) {
[$name, $value] = explode('=', $option);
$deploy->setOption($name, $value);
}
// Load all possible deploy stages
$deploy_plan = [];
$skipped_stages = [];
// Load built in stage "git", but allow extra config to override it.
$command = !empty($deploy_extra_config->stages->git)? $deploy_extra_config->stages->git: null;
// @TODO: Move this logic to the Deploy Class.
foreach (DeployStages::getStages() as $stage_name => $description) {
// Check if --stage is set and --skip-stage is not and stage exists in "$deploy_extra_config";
if ((Deploy::isDefaultStage($stage_name) || $input->getOption($stage_name)) && !$input->getOption("skip-{$stage_name}") && (!empty($deploy_extra_config->stages->{$stage_name}) || $stage_name == 'git')) {
// If this is the git state, use the DeployStageGit class.
if ($stage_name == 'git') {
$deploy->stages['git'] = new DeployStageGit(null, $command, $this->getRepository(), $deploy);
$deploy_plan['git'] = ['git', $deploy->stages['git']->getCommand()];
}
else {
$deploy->stages[$stage_name] = new DeployStage($stage_name, $deploy_extra_config->stages->{$stage_name}, $this->getRepository(), $deploy, $this->composerPath);
$deploy_plan[$stage_name] = [$stage_name, $deploy->stages[$stage_name]->getCommand()];
}
}
// Messages on why stage was skipped.
// Because: --skip-stage was used
elseif (Deploy::isDefaultStage($stage_name) && $input->getOption("skip-{$stage_name}")) {
$deploy_plan[$stage_name] = ["<fg=black>$stage_name</>", "<fg=black>Stage skipped: --skip-{$stage_name} option was used.</>"];
$skipped_stages[$stage_name] = $stage_name;
}
// Because: Stage is not default and --stage option was not set.
elseif (!Deploy::isDefaultStage($stage_name) && !$input->getOption($stage_name)) {
$deploy_plan[$stage_name] = ["<fg=black>$stage_name</>", "<fg=black>Stage skipped: '{$stage_name}' is not a default stage and --{$stage_name} option was not used.</>"];
}
// Because: Specific stage was not found in config.
elseif (empty($deploy_extra_config->stages->{$stage_name})){
$deploy_plan[$stage_name] = ["<fg=black>$stage_name</>", "<fg=black>Stage skipped: '{$stage_name}' stage command was not found in extras.deploy.stages.{$stage_name}.</>"];
}
}
$remote = $this->getRepository()->getCurrentRemote();
$this->io->section('Deploy Plan');
$this->io->table([], [
['Remote', $remote['origin']['fetch']],
['Composer Project Path', getcwd()],
['Git Repo Path', $this->getRepository()->getRepositoryPath()],
['Git Branch', $this->getRepository()->getCurrentBranch()],
['Local Commit', $this->getRepository()->getLocalSha()],
['Remote Commit', $this->getRepository()->getRemoteSha()],
['Merge Base', $this->getRepository()->getMergeSha()],
]);
switch ($this->getRepository()->remoteTrackingState()) {
case GitRepository::REMOTE_TRACKING_STATE_BEHIND:
$this->io->note('Remote git repo has new commits.');
break;
case GitRepository::REMOTE_TRACKING_STATE_AHEAD:
if ($deploy->getOption('git_reset')) {
$this->io->warning('Local git repo has commits not pushed to the remote and the git_reset option was passed, so the working copy will be reset to the origin. Unpushed commits may be lost! Run "git push" in the repo path or "git reflog" to view all commits.');
}
else {
$this->io->warning('Local git repo has commits not pushed to the remote. The deployment will abort. Run "git push" or use deploy command option "--option=git_reset=1" to force the repo back to the remote SHA or "--skip-git" to skip the git stage and run the rest of the deploy.');
}
break;
}
$this->io->table(['Stages'], $deploy_plan);
if (!empty($skipped_stages)) {
$count = count($skipped_stages);
$skipped_stages = implode(', ', $skipped_stages);
$plural = $count == 0 || $count > 1? 'stages': 'stage';
$this->io->note("Skipping $count default $plural: $skipped_stages");
}
if (empty($deploy->stages)) {
$this->io->warning("There were no stages to run.");
}
else {
// Confirm plan before executing.
if ($input->isInteractive()) {
if (!$this->io->confirm('Execute Deploy Plan? Press [enter] to continue, [n] or [CTRL+C] to cancel.', true)) {
$this->io->text('Deploy Cancelled');
return 1;
}
}
$deploy->runStages();
}
return 0;
}
return 1;
}
}