Failed Conditions
Push — master ( b6d550...8c6be2 )
by Alexander
01:57
created

MergeCommand::execute()   C

Complexity

Conditions 14
Paths 34

Size

Total Lines 67
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 210

Importance

Changes 7
Bugs 0 Features 0
Metric Value
eloc 41
c 7
b 0
f 0
dl 0
loc 67
ccs 0
cts 43
cp 0
rs 6.2666
cc 14
nc 34
nop 2
crap 210

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * This file is part of the SVN-Buddy library.
4
 * For the full copyright and license information, please view
5
 * the LICENSE file that was distributed with this source code.
6
 *
7
 * @copyright Alexander Obuhovich <[email protected]>
8
 * @link      https://github.com/console-helpers/svn-buddy
9
 */
10
11
namespace ConsoleHelpers\SVNBuddy\Command;
12
13
14
use ConsoleHelpers\SVNBuddy\Config\AbstractConfigSetting;
15
use ConsoleHelpers\SVNBuddy\Config\ArrayConfigSetting;
16
use ConsoleHelpers\SVNBuddy\Config\ChoiceConfigSetting;
17
use ConsoleHelpers\SVNBuddy\Config\StringConfigSetting;
18
use ConsoleHelpers\ConsoleKit\Exception\CommandException;
19
use ConsoleHelpers\SVNBuddy\Exception\RepositoryCommandException;
20
use ConsoleHelpers\SVNBuddy\Helper\OutputHelper;
21
use ConsoleHelpers\SVNBuddy\MergeSourceDetector\AbstractMergeSourceDetector;
22
use ConsoleHelpers\SVNBuddy\Repository\Connector\UrlResolver;
23
use ConsoleHelpers\SVNBuddy\Repository\Parser\RevisionListParser;
24
use ConsoleHelpers\SVNBuddy\Repository\WorkingCopyConflictTracker;
25
use Stecman\Component\Symfony\Console\BashCompletion\CompletionContext;
26
use Symfony\Component\Console\Helper\Table;
27
use Symfony\Component\Console\Input\InputArgument;
28
use Symfony\Component\Console\Input\InputInterface;
29
use Symfony\Component\Console\Input\InputOption;
30
use Symfony\Component\Console\Output\OutputInterface;
31
32
class MergeCommand extends AbstractCommand implements IAggregatorAwareCommand, IConfigAwareCommand
33
{
34
35
	const SETTING_MERGE_SOURCE_URL = 'merge.source-url';
36
37
	const SETTING_MERGE_RECENT_CONFLICTS = 'merge.recent-conflicts';
38
39
	const SETTING_MERGE_AUTO_COMMIT = 'merge.auto-commit';
40
41
	const REVISION_ALL = 'all';
42
43
	/**
44
	 * Merge source detector.
45
	 *
46
	 * @var AbstractMergeSourceDetector
47
	 */
48
	private $_mergeSourceDetector;
49
50
	/**
51
	 * Revision list parser.
52
	 *
53
	 * @var RevisionListParser
54
	 */
55
	private $_revisionListParser;
56
57
	/**
58
	 * Usable revisions (either to be merged OR to be unmerged).
59
	 *
60
	 * @var array
61
	 */
62
	private $_usableRevisions = array();
63
64
	/**
65
	 * Url resolver.
66
	 *
67
	 * @var UrlResolver
68
	 */
69
	private $_urlResolver;
70
71
	/**
72
	 * Working copy conflict tracker.
73
	 *
74
	 * @var WorkingCopyConflictTracker
75
	 */
76
	private $_workingCopyConflictTracker;
77
78
	/**
79
	 * Prepare dependencies.
80
	 *
81
	 * @return void
82
	 */
83
	protected function prepareDependencies()
84
	{
85
		parent::prepareDependencies();
86
87
		$container = $this->getContainer();
88
89
		$this->_mergeSourceDetector = $container['merge_source_detector'];
90
		$this->_revisionListParser = $container['revision_list_parser'];
91
		$this->_urlResolver = $container['repository_url_resolver'];
92
		$this->_workingCopyConflictTracker = $container['working_copy_conflict_tracker'];
93
	}
94
95
	/**
96
	 * {@inheritdoc}
97
	 */
98
	protected function configure()
99
	{
100
		$this
101
			->setName('merge')
102
			->setDescription('Merge changes from another project or ref within same project into a working copy')
103
			->addArgument(
104
				'path',
105
				InputArgument::OPTIONAL,
106
				'Working copy path',
107
				'.'
108
			)
109
			->addOption(
110
				'source-url',
111
				null,
112
				InputOption::VALUE_REQUIRED,
113
				'Merge source url (absolute or relative) or ref name, e.g. <comment>branches/branch-name</comment>'
114
			)
115
			->addOption(
116
				'revisions',
117
				'r',
118
				InputOption::VALUE_REQUIRED,
119
				'List of revision(-s) and/or revision range(-s) to merge, e.g. <comment>53324</comment>, <comment>1224-4433</comment> or <comment>all</comment>'
120
			)
121
			->addOption(
122
				'exclude-revisions',
123
				null,
124
				InputOption::VALUE_REQUIRED,
125
				'List of revision(-s) and/or revision range(-s) not to merge, e.g. <comment>53324</comment>, <comment>1224-4433</comment>'
126
			)
127
			->addOption(
128
				'bugs',
129
				'b',
130
				InputOption::VALUE_REQUIRED,
131
				'List of bug(-s) to merge, e.g. <comment>JRA-1234</comment>, <comment>43644</comment>'
132
			)
133
			->addOption(
134
				'exclude-bugs',
135
				null,
136
				InputOption::VALUE_REQUIRED,
137
				'List of bug(-s) not to merge, e.g. <comment>JRA-1234</comment>, <comment>43644</comment>'
138
			)
139
			->addOption(
140
				'no-merges',
141
				null,
142
				InputOption::VALUE_NONE,
143
				'Hide merge revisions'
144
			)
145
			->addOption(
146
				'with-full-message',
147
				'f',
148
				InputOption::VALUE_NONE,
149
				'Shows non-truncated commit messages'
150
			)
151
			->addOption(
152
				'with-details',
153
				'd',
154
				InputOption::VALUE_NONE,
155
				'Shows detailed revision information, e.g. paths affected'
156
			)
157
			->addOption(
158
				'with-summary',
159
				's',
160
				InputOption::VALUE_NONE,
161
				'Shows number of added/changed/removed paths in the revision'
162
			)
163
			->addOption(
164
				'update-revision',
165
				null,
166
				InputOption::VALUE_REQUIRED,
167
				'Update working copy to given revision before performing a merge'
168
			)
169
			->addOption(
170
				'auto-commit',
171
				null,
172
				InputOption::VALUE_REQUIRED,
173
				'Automatically perform commit on successful merge, e.g. <comment>yes</comment> or <comment>no</comment>'
174
			)
175
			->addOption(
176
				'record-only',
177
				null,
178
				InputOption::VALUE_NONE,
179
				'Mark revisions as merged without actually merging them'
180
			)
181
			->addOption(
182
				'reverse',
183
				null,
184
				InputOption::VALUE_NONE,
185
				'Rollback previously merged revisions'
186
			)
187
			->addOption(
188
				'aggregate',
189
				'a',
190
				InputOption::VALUE_NONE,
191
				'Aggregate displayed revisions by bugs'
192
			);
193
194
		parent::configure();
195
	}
196
197
	/**
198
	 * Return possible values for the named option
199
	 *
200
	 * @param string            $optionName Option name.
201
	 * @param CompletionContext $context    Completion context.
202
	 *
203
	 * @return array
204
	 */
205
	public function completeOptionValues($optionName, CompletionContext $context)
206
	{
207
		$ret = parent::completeOptionValues($optionName, $context);
208
209
		if ( $optionName === 'revisions' ) {
210
			return array('all');
211
		}
212
213
		if ( $optionName === 'source-url' ) {
214
			return $this->getAllRefs();
215
		}
216
217
		if ( $optionName === 'auto-commit' ) {
218
			return array('yes', 'no');
219
		}
220
221
		return $ret;
222
	}
223
224
	/**
225
	 * {@inheritdoc}
226
	 *
227
	 * @throws CommandException When everything is merged.
228
	 * @throws CommandException When manually specified revisions are already merged.
229
	 * @throws CommandException When bugs from "--bugs" option are not found.
230
	 */
231
	protected function execute(InputInterface $input, OutputInterface $output)
232
	{
233
		$bugs = $this->getList($this->io->getOption('bugs'));
0 ignored issues
show
Bug introduced by
It seems like $this->io->getOption('bugs') can also be of type string[]; however, parameter $string of ConsoleHelpers\SVNBuddy\...tractCommand::getList() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

233
		$bugs = $this->getList(/** @scrutinizer ignore-type */ $this->io->getOption('bugs'));
Loading history...
234
		$revisions = $this->getList($this->io->getOption('revisions'));
235
236
		$wc_path = $this->getWorkingCopyPath();
237
238
		$this->ensureLatestWorkingCopy($wc_path);
239
240
		$source_url = $this->getSourceUrl($wc_path);
241
		$this->printSourceAndTarget($source_url, $wc_path);
242
		$this->_usableRevisions = $this->getUsableRevisions($source_url, $wc_path);
243
244
		if ( ($bugs || $revisions) && !$this->_usableRevisions ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->_usableRevisions of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
Bug Best Practice introduced by
The expression $bugs of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
Bug Best Practice introduced by
The expression $revisions of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
245
			throw new CommandException(\sprintf(
246
				'Nothing to %s.',
247
				$this->isReverseMerge() ? 'reverse-merge' : 'merge'
248
			));
249
		}
250
251
		$this->ensureWorkingCopyWithoutConflicts($source_url, $wc_path);
252
253
		if ( $this->shouldUseAll($revisions) ) {
254
			$revisions = $this->filterMergeableRevisions($this->_usableRevisions, $source_url);
255
		}
256
		else {
257
			if ( $revisions ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $revisions of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
258
				$revisions = $this->getDirectRevisions($revisions, $source_url);
259
			}
260
261
			if ( $bugs ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $bugs of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
262
				$revisions_from_bugs = $this->getRevisionLog($source_url)->find('bugs', $bugs);
263
264
				if ( !$revisions_from_bugs ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $revisions_from_bugs of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
265
					throw new CommandException('Specified bugs aren\'t mentioned in any of revisions');
266
				}
267
268
				$revisions = array_merge($revisions, $revisions_from_bugs);
269
			}
270
271
			$revisions = $this->filterMergeableRevisions($revisions, $source_url);
272
273
			if ( $revisions ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $revisions of type integer[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
274
				$revisions = array_intersect($revisions, $this->_usableRevisions);
275
276
				if ( !$revisions ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $revisions of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
277
					throw new CommandException(\sprintf(
278
						'Requested revisions are %s',
279
						$this->isReverseMerge() ? 'not yet merged' : 'already merged'
280
					));
281
				}
282
			}
283
		}
284
285
		if ( $revisions ) {
286
			$this->performMerge($source_url, $wc_path, $revisions);
287
		}
288
		elseif ( $this->_usableRevisions ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->_usableRevisions of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
289
			$this->runOtherCommand('log', array(
290
				'path' => $source_url,
291
				'--revisions' => implode(',', $this->_usableRevisions),
292
				'--no-merges' => $this->io->getOption('no-merges'),
293
				'--with-full-message' => $this->io->getOption('with-full-message'),
294
				'--with-details' => $this->io->getOption('with-details'),
295
				'--with-summary' => $this->io->getOption('with-summary'),
296
				'--aggregate' => $this->io->getOption('aggregate'),
297
				'--with-merge-oracle' => true,
298
			));
299
		}
300
	}
301
302
	/**
303
	 * Filters mergeable revision list.
304
	 *
305
	 * @param array  $revisions  Revisions.
306
	 * @param string $source_url Source URL.
307
	 *
308
	 * @return integer[]
309
	 * @throws CommandException When bugs from "--exclude-bugs" option are not found.
310
	 */
311
	protected function filterMergeableRevisions(array $revisions, $source_url)
312
	{
313
		$exclude_bugs = $this->getList($this->io->getOption('exclude-bugs'));
0 ignored issues
show
Bug introduced by
It seems like $this->io->getOption('exclude-bugs') can also be of type string[]; however, parameter $string of ConsoleHelpers\SVNBuddy\...tractCommand::getList() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

313
		$exclude_bugs = $this->getList(/** @scrutinizer ignore-type */ $this->io->getOption('exclude-bugs'));
Loading history...
314
		$exclude_revisions = $this->getList($this->io->getOption('exclude-revisions'));
315
316
		if ( $exclude_revisions ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $exclude_revisions of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
317
			$revisions = array_diff(
318
				$revisions,
319
				$this->getDirectRevisions($exclude_revisions, $source_url)
320
			);
321
		}
322
323
		if ( $exclude_bugs ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $exclude_bugs of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
324
			$exclude_revisions_from_bugs = $this->getRevisionLog($source_url)->find('bugs', $exclude_bugs);
325
326
			if ( !$exclude_revisions_from_bugs ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $exclude_revisions_from_bugs of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
327
				throw new CommandException('Specified exclude-bugs aren\'t mentioned in any of revisions');
328
			}
329
330
			$revisions = array_diff($revisions, $exclude_revisions_from_bugs);
331
		}
332
333
		if ( $this->io->getOption('no-merges') ) {
334
			$revisions = array_diff($revisions, $this->getRevisionLog($source_url)->find('merges', 'all_merges'));
335
		}
336
337
		return $revisions;
338
	}
339
340
	/**
341
	 * Determines if all usable revisions should be processed.
342
	 *
343
	 * @param array $revisions Revisions.
344
	 *
345
	 * @return boolean
346
	 */
347
	protected function shouldUseAll(array $revisions)
348
	{
349
		return $revisions === array(self::REVISION_ALL);
350
	}
351
352
	/**
353
	 * Ensures, that working copy is up to date.
354
	 *
355
	 * @param string $wc_path Working copy path.
356
	 *
357
	 * @return void
358
	 */
359
	protected function ensureLatestWorkingCopy($wc_path)
360
	{
361
		$this->io->write(' * Working Copy Status ... ');
362
		$update_revision = $this->io->getOption('update-revision');
363
364
		if ( $this->repositoryConnector->getWorkingCopyMissing($wc_path) ) {
365
			$this->io->writeln('<error>Locally deleted files found</error>');
366
			$this->updateWorkingCopy($wc_path, $update_revision);
367
368
			return;
369
		}
370
371
		$working_copy_revisions = $this->repositoryConnector->getWorkingCopyRevisions($wc_path);
372
373
		if ( count($working_copy_revisions) > 1 ) {
374
			$this->io->writeln(
375
				'<error>Mixed revisions: ' . implode(', ', $working_copy_revisions) . '</error>'
376
			);
377
			$this->updateWorkingCopy($wc_path, $update_revision);
378
379
			return;
380
		}
381
382
		$update_revision = $this->getWorkingCopyUpdateRevision($wc_path);
383
384
		if ( isset($update_revision) ) {
385
			$this->io->writeln('<error>Not at ' . $update_revision . ' revision</error>');
386
			$this->updateWorkingCopy($wc_path, $update_revision);
387
388
			return;
389
		}
390
391
		$this->io->writeln('<info>Up to date</info>');
392
	}
393
394
	/**
395
	 * Returns revision, that working copy needs to be updated to.
396
	 *
397
	 * @param string $wc_path Working copy path.
398
	 *
399
	 * @return integer|null
400
	 */
401
	protected function getWorkingCopyUpdateRevision($wc_path)
402
	{
403
		$update_revision = $this->io->getOption('update-revision');
404
		$actual_revision = $this->repositoryConnector->getLastRevision($wc_path);
405
406
		if ( isset($update_revision) ) {
407
			if ( is_numeric($update_revision) ) {
408
				return (int)$update_revision === (int)$actual_revision ? null : $update_revision;
0 ignored issues
show
Bug Best Practice introduced by
The expression return (int)$update_revi...null : $update_revision also could return the type string which is incompatible with the documented return type integer|null.
Loading history...
409
			}
410
411
			return $update_revision;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $update_revision returns the type boolean|string|string[] which is incompatible with the documented return type integer|null.
Loading history...
412
		}
413
414
		$repository_revision = $this->repositoryConnector->getLastRevision(
415
			$this->repositoryConnector->getWorkingCopyUrl($wc_path)
416
		);
417
418
		return $repository_revision > $actual_revision ? $repository_revision : null;
419
	}
420
421
	/**
422
	 * Updates working copy.
423
	 *
424
	 * @param string     $wc_path  Working copy path.
425
	 * @param mixed|null $revision Revision.
426
	 *
427
	 * @return void
428
	 */
429
	protected function updateWorkingCopy($wc_path, $revision = null)
430
	{
431
		$arguments = array('path' => $wc_path, '--ignore-externals' => true);
432
433
		if ( isset($revision) ) {
434
			$arguments['--revision'] = $revision;
435
		}
436
437
		$this->runOtherCommand('update', $arguments);
438
	}
439
440
	/**
441
	 * Returns source url for merge.
442
	 *
443
	 * @param string $wc_path Working copy path.
444
	 *
445
	 * @return string
446
	 * @throws CommandException When source path is invalid.
447
	 */
448
	protected function getSourceUrl($wc_path)
449
	{
450
		$source_url = $this->io->getOption('source-url');
451
452
		if ( $source_url === null ) {
453
			$source_url = $this->getSetting(self::SETTING_MERGE_SOURCE_URL);
454
		}
455
		elseif ( !$this->repositoryConnector->isUrl($source_url) ) {
0 ignored issues
show
Bug introduced by
It seems like $source_url can also be of type string[]; however, parameter $path of ConsoleHelpers\SVNBuddy\...ctor\Connector::isUrl() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

455
		elseif ( !$this->repositoryConnector->isUrl(/** @scrutinizer ignore-type */ $source_url) ) {
Loading history...
456
			$wc_url = $this->repositoryConnector->getWorkingCopyUrl($wc_path);
457
			$source_url = $this->_urlResolver->resolve($wc_url, $source_url);
0 ignored issues
show
Bug introduced by
It seems like $source_url can also be of type string[]; however, parameter $url_to_resolve of ConsoleHelpers\SVNBuddy\...\UrlResolver::resolve() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

457
			$source_url = $this->_urlResolver->resolve($wc_url, /** @scrutinizer ignore-type */ $source_url);
Loading history...
458
		}
459
460
		if ( !$source_url ) {
461
			$wc_url = $this->repositoryConnector->getWorkingCopyUrl($wc_path);
462
			$source_url = $this->_mergeSourceDetector->detect($wc_url);
463
464
			if ( $source_url ) {
465
				$this->setSetting(self::SETTING_MERGE_SOURCE_URL, $source_url);
466
			}
467
		}
468
469
		if ( !$source_url ) {
470
			$wc_url = $this->repositoryConnector->getWorkingCopyUrl($wc_path);
471
			$error_msg = 'Unable to guess "--source-url" option value. Please specify it manually.' . PHP_EOL;
472
			$error_msg .= 'Working Copy URL: ' . $wc_url . '.';
473
			throw new CommandException($error_msg);
474
		}
475
476
		return $source_url;
477
	}
478
479
	/**
480
	 * Prints information about merge source & target.
481
	 *
482
	 * @param string $source_url Merge source: url.
483
	 * @param string $wc_path    Merge target: working copy path.
484
	 *
485
	 * @return void
486
	 */
487
	protected function printSourceAndTarget($source_url, $wc_path)
488
	{
489
		$relative_source_url = $this->repositoryConnector->getRelativePath($source_url);
490
		$relative_target_url = $this->repositoryConnector->getRelativePath($wc_path);
491
492
		$this->io->writeln(' * Merge Source ... <info>' . $relative_source_url . '</info>');
493
		$this->io->writeln(' * Merge Target ... <info>' . $relative_target_url . '</info>');
494
	}
495
496
	/**
497
	 * Ensures, that there are some usable revisions.
498
	 *
499
	 * @param string $source_url Merge source: url.
500
	 * @param string $wc_path    Merge target: working copy path.
501
	 *
502
	 * @return array
503
	 */
504
	protected function getUsableRevisions($source_url, $wc_path)
505
	{
506
		// Avoid missing revision query progress bar overwriting following output.
507
		$revision_log = $this->getRevisionLog($source_url);
508
509
		$this->io->write(sprintf(
510
			' * Upcoming %s Status ... ',
511
			$this->isReverseMerge() ? 'Reverse-merge' : 'Merge'
512
		));
513
		$usable_revisions = $this->calculateUsableRevisions($source_url, $wc_path);
514
515
		if ( $usable_revisions ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $usable_revisions of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
516
			$usable_bugs = $revision_log->getBugsFromRevisions($usable_revisions);
517
			$error_msg = '<error>%d revision(-s) or %d bug(-s) %s</error>';
518
			$this->io->writeln(sprintf(
519
				$error_msg,
520
				count($usable_revisions),
521
				count($usable_bugs),
522
				$this->isReverseMerge() ? 'merged' : 'not merged'
523
			));
524
		}
525
		else {
526
			$this->io->writeln('<info>Up to date</info>');
527
		}
528
529
		return $usable_revisions;
530
	}
531
532
	/**
533
	 * Returns usable revisions.
534
	 *
535
	 * @param string $source_url Merge source: url.
536
	 * @param string $wc_path    Merge target: working copy path.
537
	 *
538
	 * @return array
539
	 */
540
	protected function calculateUsableRevisions($source_url, $wc_path)
541
	{
542
		$command = $this->repositoryConnector->getCommand(
543
			'mergeinfo',
544
			sprintf(
545
				'--show-revs %s {%s} {%s}',
546
				$this->isReverseMerge() ? 'merged' : 'eligible',
547
				$source_url,
548
				$wc_path
549
			)
550
		);
551
552
		$merge_info = $this->repositoryConnector->getProperty('svn:mergeinfo', $wc_path);
553
554
		$cache_invalidator = array(
555
			'source:' . $this->repositoryConnector->getLastRevision($source_url),
556
			'merged_hash:' . crc32($merge_info),
557
		);
558
		$command->setCacheInvalidator(implode(';', $cache_invalidator));
559
560
		$merge_info = $command->run();
561
		$merge_info = explode(PHP_EOL, $merge_info);
562
563
		foreach ( $merge_info as $index => $revision ) {
564
			$merge_info[$index] = ltrim($revision, 'r');
565
		}
566
567
		return array_filter($merge_info);
568
	}
569
570
	/**
571
	 * Parses information from "svn:mergeinfo" property.
572
	 *
573
	 * @param string $source_path Merge source: path in repository.
574
	 * @param string $wc_path     Merge target: working copy path.
575
	 *
576
	 * @return array
577
	 */
578
	protected function getMergedRevisions($source_path, $wc_path)
579
	{
580
		$merge_info = $this->repositoryConnector->getProperty('svn:mergeinfo', $wc_path);
581
		$merge_info = array_filter(explode("\n", $merge_info));
582
583
		foreach ( $merge_info as $merge_info_line ) {
584
			list($path, $revisions) = explode(':', $merge_info_line, 2);
585
586
			if ( $path === $source_path ) {
587
				return $this->_revisionListParser->expandRanges(explode(',', $revisions));
588
			}
589
		}
590
591
		return array();
592
	}
593
594
	/**
595
	 * Validates revisions to actually exist.
596
	 *
597
	 * @param array  $revisions      Revisions.
598
	 * @param string $repository_url Repository url.
599
	 *
600
	 * @return array
601
	 * @throws CommandException When revision doesn't exist.
602
	 */
603
	protected function getDirectRevisions(array $revisions, $repository_url)
604
	{
605
		$revision_log = $this->getRevisionLog($repository_url);
606
607
		try {
608
			$revisions = $this->_revisionListParser->expandRanges($revisions);
609
			$revision_log->getRevisionsData('summary', $revisions);
610
		}
611
		catch ( \InvalidArgumentException $e ) {
612
			throw new CommandException($e->getMessage());
613
		}
614
615
		return $revisions;
616
	}
617
618
	/**
619
	 * Performs merge.
620
	 *
621
	 * @param string $source_url Merge source: url.
622
	 * @param string $wc_path    Merge target: working copy path.
623
	 * @param array  $revisions  Revisions to merge.
624
	 *
625
	 * @return void
626
	 */
627
	protected function performMerge($source_url, $wc_path, array $revisions)
628
	{
629
		if ( $this->isReverseMerge() ) {
630
			rsort($revisions, SORT_NUMERIC);
631
		}
632
		else {
633
			sort($revisions, SORT_NUMERIC);
634
		}
635
636
		$revision_count = count($revisions);
637
638
		$used_revision_count = 0;
639
		$used_revisions = $this->repositoryConnector->getMergedRevisionChanges($wc_path, !$this->isReverseMerge());
640
641
		if ( $used_revisions ) {
642
			$used_revisions = call_user_func_array('array_merge', $used_revisions);
643
			$used_revision_count = count($used_revisions);
644
			$revision_count += $used_revision_count;
645
		}
646
647
		$param_string_beginning = '-c ';
648
		$param_string_ending = '{' . $source_url . '} {' . $wc_path . '}';
649
650
		if ( $this->isReverseMerge() ) {
651
			$param_string_beginning .= '-';
652
		}
653
654
		if ( $this->io->getOption('record-only') ) {
655
			$param_string_ending = '--record-only ' . $param_string_ending;
656
		}
657
658
		$revision_log = $this->getRevisionLog($source_url);
659
		$revisions_data = $revision_log->getRevisionsData('summary', $revisions);
660
661
		$revision_title_mask = $this->getRevisionTitle($source_url);
662
663
		foreach ( $revisions as $index => $revision ) {
664
			$command = $this->repositoryConnector->getCommand(
665
				'merge',
666
				$param_string_beginning . $revision . ' ' . $param_string_ending
667
			);
668
669
			$progress_bar = $this->createMergeProgressBar($used_revision_count + $index + 1, $revision_count);
670
671
			// 1. Add revision link with a progress bar.
672
			$merge_heading = PHP_EOL . '<fg=white;options=bold>';
673
			$merge_heading .= '--- $1 ' . \str_replace('{revision}', $revision, $revision_title_mask);
674
			$merge_heading .= " into '$2' " . $progress_bar . ':</>';
675
676
			// 2. Add a commit message.
677
			$commit_message = trim($revisions_data[$revision]['msg']);
678
			$commit_message = wordwrap($commit_message, 68); // FIXME: Not UTF-8 safe solution.
679
			$merge_heading .= PHP_EOL . $commit_message;
680
			$merge_heading .= PHP_EOL;
681
			$merge_heading .= PHP_EOL . '<fg=white;options=bold>Changed Paths:</>';
682
683
			$command->runLive(array(
684
				$wc_path => '.',
685
				'/--- (Merging|Reverse-merging) r' . $revision . " into '([^']*)':/" => $merge_heading,
686
			));
687
688
			$this->_usableRevisions = array_diff($this->_usableRevisions, array($revision));
689
			$this->ensureWorkingCopyWithoutConflicts($source_url, $wc_path, $revision);
690
		}
691
692
		$this->performCommit();
693
	}
694
695
	/**
696
	 * Returns revision title.
697
	 *
698
	 * @param string $source_url Merge source: url.
699
	 *
700
	 * @return string
701
	 */
702
	protected function getRevisionTitle($source_url)
703
	{
704
		$link_style = 'fg=white;options=bold,underscore';
705
706
		try {
707
			$arcanist_config = \json_decode(
708
				$this->repositoryConnector->getFileContent($source_url . '/.arcconfig', 'HEAD'),
0 ignored issues
show
Bug introduced by
'HEAD' of type string is incompatible with the type integer expected by parameter $revision of ConsoleHelpers\SVNBuddy\...ector::getFileContent(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

708
				$this->repositoryConnector->getFileContent($source_url . '/.arcconfig', /** @scrutinizer ignore-type */ 'HEAD'),
Loading history...
709
				true
710
			);
711
		}
712
		catch ( RepositoryCommandException $e ) {
713
			// Phabricator integration is not configured.
714
			return '<' . $link_style . '>{revision}</> revision';
715
		}
716
717
		// Phabricator integration is not configured correctly.
718
		if ( !\is_array($arcanist_config)
719
			|| !isset($arcanist_config['repository.callsign'], $arcanist_config['phabricator.uri'])
720
		) {
721
			return '<' . $link_style . '>{revision}</> revision';
722
		}
723
724
		// Phabricator integration is configured properly.
725
		$revision_title = $arcanist_config['phabricator.uri'];
726
		$revision_title .= 'r' . $arcanist_config['repository.callsign'] . '{revision}';
727
728
		return '<' . $link_style . '>' . $revision_title . '</>';
729
	}
730
731
	/**
732
	 * Create merge progress bar.
733
	 *
734
	 * @param integer $current Current.
735
	 * @param integer $total   Total.
736
	 *
737
	 * @return string
738
	 */
739
	protected function createMergeProgressBar($current, $total)
740
	{
741
		$total_length = 28;
742
		$percent_used = floor(($current / $total) * 100);
743
		$length_used = floor(($total_length * $percent_used) / 100);
744
		$length_free = $total_length - $length_used;
745
746
		$ret = $length_used > 0 ? str_repeat('=', $length_used - 1) : '';
0 ignored issues
show
Bug introduced by
$length_used - 1 of type double is incompatible with the type integer expected by parameter $times of str_repeat(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

746
		$ret = $length_used > 0 ? str_repeat('=', /** @scrutinizer ignore-type */ $length_used - 1) : '';
Loading history...
747
		$ret .= '>' . str_repeat('-', $length_free);
748
749
		return '[' . $ret . '] ' . $percent_used . '% (' . $current . ' of ' . $total . ')';
750
	}
751
752
	/**
753
	 * Ensures, that there are no unresolved conflicts in working copy.
754
	 *
755
	 * @param string  $source_url                 Source url.
756
	 * @param string  $wc_path                    Working copy path.
757
	 * @param integer $largest_suggested_revision Largest revision, that is suggested in error message.
758
	 *
759
	 * @return void
760
	 * @throws CommandException When merge conflicts detected.
761
	 */
762
	protected function ensureWorkingCopyWithoutConflicts($source_url, $wc_path, $largest_suggested_revision = null)
763
	{
764
		$this->io->write(' * Previous Merge Status ... ');
765
766
		$conflicts = $this->_workingCopyConflictTracker->getNewConflicts($wc_path);
767
768
		if ( !$conflicts ) {
769
			$this->io->writeln('<info>Successful</info>');
770
771
			return;
772
		}
773
774
		$this->_workingCopyConflictTracker->add($wc_path);
775
		$this->io->writeln('<error>' . count($conflicts) . ' conflict(-s)</error>');
776
777
		$table = new Table($this->io->getOutput());
778
779
		if ( $largest_suggested_revision ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $largest_suggested_revision of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
780
			$table->setHeaders(array(
781
				'Path',
782
				'Associated Revisions (before ' . $largest_suggested_revision . ')',
783
			));
784
		}
785
		else {
786
			$table->setHeaders(array(
787
				'Path',
788
				'Associated Revisions',
789
			));
790
		}
791
792
		$revision_log = $this->getRevisionLog($source_url);
793
		$source_path = $this->repositoryConnector->getRelativePath($source_url) . '/';
794
795
		/** @var OutputHelper $output_helper */
796
		$output_helper = $this->getHelper('output');
797
798
		foreach ( $conflicts as $conflict_path ) {
799
			$path_revisions = $revision_log->find('paths', $source_path . $conflict_path);
800
			$path_revisions = array_intersect($this->_usableRevisions, $path_revisions);
801
802
			if ( $path_revisions && isset($largest_suggested_revision) ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $path_revisions of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
803
				$path_revisions = $this->limitRevisions($path_revisions, $largest_suggested_revision);
804
			}
805
806
			$table->addRow(array(
807
				$conflict_path,
808
				$path_revisions ? $output_helper->formatArray($path_revisions, 4) : '-',
809
			));
810
		}
811
812
		$table->render();
813
814
		throw new CommandException('Working copy contains unresolved merge conflicts.');
815
	}
816
817
	/**
818
	 * Returns revisions not larger, then given one.
819
	 *
820
	 * @param array   $revisions    Revisions.
821
	 * @param integer $max_revision Maximal revision.
822
	 *
823
	 * @return array
824
	 */
825
	protected function limitRevisions(array $revisions, $max_revision)
826
	{
827
		$ret = array();
828
829
		foreach ( $revisions as $revision ) {
830
			if ( $revision < $max_revision ) {
831
				$ret[] = $revision;
832
			}
833
		}
834
835
		return $ret;
836
	}
837
838
	/**
839
	 * Performs commit unless user doesn't want it.
840
	 *
841
	 * @return void
842
	 */
843
	protected function performCommit()
844
	{
845
		$auto_commit = $this->io->getOption('auto-commit');
846
847
		if ( $auto_commit !== null ) {
848
			$auto_commit = $auto_commit === 'yes';
849
		}
850
		else {
851
			$auto_commit = (boolean)$this->getSetting(self::SETTING_MERGE_AUTO_COMMIT);
852
		}
853
854
		if ( $auto_commit ) {
855
			$this->io->writeln(array('', 'Commencing automatic commit after merge ...'));
856
			$this->runOtherCommand('commit');
857
		}
858
	}
859
860
	/**
861
	 * Returns list of config settings.
862
	 *
863
	 * @return AbstractConfigSetting[]
864
	 */
865
	public function getConfigSettings()
866
	{
867
		return array(
868
			new StringConfigSetting(self::SETTING_MERGE_SOURCE_URL, ''),
869
			new ArrayConfigSetting(self::SETTING_MERGE_RECENT_CONFLICTS, array()),
870
			new ChoiceConfigSetting(
871
				self::SETTING_MERGE_AUTO_COMMIT,
872
				array(1 => 'Yes', 0 => 'No'),
873
				1
874
			),
875
		);
876
	}
877
878
	/**
879
	 * Returns option names, that makes sense to use in aggregation mode.
880
	 *
881
	 * @return array
882
	 */
883
	public function getAggregatedOptions()
884
	{
885
		return array('with-full-message', 'with-details', 'with-summary');
886
	}
887
888
	/**
889
	 * Determines if merge should be done in opposite direction (unmerge).
890
	 *
891
	 * @return boolean
892
	 */
893
	protected function isReverseMerge()
894
	{
895
		return $this->io->getOption('reverse');
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->io->getOption('reverse') also could return the type string|string[] which is incompatible with the documented return type boolean.
Loading history...
896
	}
897
898
}
899