Passed
Pull Request — master (#146)
by Alexander
09:03
created

MergeCommand::performCommit()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

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

244
		$bugs = $this->getList(/** @scrutinizer ignore-type */ $this->io->getOption('bugs'));
Loading history...
245
		$revisions = $this->getList($this->io->getOption('revisions'));
246
247
		$wc_path = $this->getWorkingCopyPath();
248
249
		$this->ensureLatestWorkingCopy($wc_path);
250
251
		$source_url = $this->getSourceUrl($wc_path);
252
		$this->printSourceAndTarget($source_url, $wc_path);
253
		$this->_usableRevisions = $this->getUsableRevisions($source_url, $wc_path);
254
255
		if ( ($bugs || $revisions) && !$this->_usableRevisions ) {
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...
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 $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...
256
			throw new CommandException(\sprintf(
257
				'Nothing to %s.',
258
				$this->isReverseMerge() ? 'reverse-merge' : 'merge'
259
			));
260
		}
261
262
		$this->ensureWorkingCopyWithoutConflicts($source_url, $wc_path);
263
264
		if ( $this->shouldUseAll($revisions) ) {
265
			$revisions = $this->filterMergeableRevisions($this->_usableRevisions, $source_url);
266
		}
267
		else {
268
			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...
269
				$revisions = $this->getDirectRevisions($revisions, $source_url);
270
			}
271
272
			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...
273
				$revisions_from_bugs = $this->getRevisionLog($source_url)->find('bugs', $bugs);
274
275
				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...
276
					throw new CommandException('Specified bugs aren\'t mentioned in any of revisions');
277
				}
278
279
				$revisions = array_merge($revisions, $revisions_from_bugs);
280
			}
281
282
			$revisions = $this->filterMergeableRevisions($revisions, $source_url);
283
284
			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...
285
				$revisions = array_intersect($revisions, $this->_usableRevisions);
286
287
				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...
288
					throw new CommandException(\sprintf(
289
						'Requested revisions are %s',
290
						$this->isReverseMerge() ? 'not yet merged' : 'already merged'
291
					));
292
				}
293
			}
294
		}
295
296
		if ( $revisions ) {
297
			if ( $this->io->getOption('preview') ) {
298
				// Display mergeable revisions according to user-specified filters.
299
				$this->printRevisions($source_url, $revisions);
300
			}
301
			else {
302
				// Perform merge using user-specified filters.
303
				$this->performMerge($source_url, $wc_path, $revisions);
304
			}
305
		}
306
		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...
307
			// Display all mergeable revisions, because user haven't specified any revisions for merging.
308
			$this->printRevisions($source_url, $this->_usableRevisions);
309
		}
310
	}
311
312
	/**
313
	 * Filters mergeable revision list.
314
	 *
315
	 * @param array  $revisions  Revisions.
316
	 * @param string $source_url Source URL.
317
	 *
318
	 * @return integer[]
319
	 * @throws CommandException When bugs from "--exclude-bugs" option are not found.
320
	 */
321
	protected function filterMergeableRevisions(array $revisions, $source_url)
322
	{
323
		$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

323
		$exclude_bugs = $this->getList(/** @scrutinizer ignore-type */ $this->io->getOption('exclude-bugs'));
Loading history...
324
		$exclude_revisions = $this->getList($this->io->getOption('exclude-revisions'));
325
326
		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...
327
			$revisions = array_diff(
328
				$revisions,
329
				$this->getDirectRevisions($exclude_revisions, $source_url)
330
			);
331
		}
332
333
		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...
334
			$exclude_revisions_from_bugs = $this->getRevisionLog($source_url)->find('bugs', $exclude_bugs);
335
336
			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...
337
				throw new CommandException('Specified exclude-bugs aren\'t mentioned in any of revisions');
338
			}
339
340
			$revisions = array_diff($revisions, $exclude_revisions_from_bugs);
341
		}
342
343
		if ( $this->io->getOption('merges') ) {
344
			$revisions = array_intersect($revisions, $this->getRevisionLog($source_url)->find('merges', 'all_merges'));
345
		}
346
		elseif ( $this->io->getOption('no-merges') ) {
347
			$revisions = array_diff($revisions, $this->getRevisionLog($source_url)->find('merges', 'all_merges'));
348
		}
349
350
		return $revisions;
351
	}
352
353
	/**
354
	 * Determines if all usable revisions should be processed.
355
	 *
356
	 * @param array $revisions Revisions.
357
	 *
358
	 * @return boolean
359
	 */
360
	protected function shouldUseAll(array $revisions)
361
	{
362
		return $revisions === array(self::REVISION_ALL);
363
	}
364
365
	/**
366
	 * Ensures, that working copy is up to date.
367
	 *
368
	 * @param string $wc_path Working copy path.
369
	 *
370
	 * @return void
371
	 */
372
	protected function ensureLatestWorkingCopy($wc_path)
373
	{
374
		$this->io->write(' * Working Copy Status ... ');
375
		$update_revision = $this->io->getOption('update-revision');
376
377
		if ( $this->repositoryConnector->getWorkingCopyMissing($wc_path) ) {
378
			$this->io->writeln('<error>Locally deleted files found</error>');
379
			$this->updateWorkingCopy($wc_path, $update_revision);
380
381
			return;
382
		}
383
384
		$working_copy_revisions = $this->repositoryConnector->getWorkingCopyRevisions($wc_path);
385
386
		if ( count($working_copy_revisions) > 1 ) {
387
			$this->io->writeln(
388
				'<error>Mixed revisions: ' . implode(', ', $working_copy_revisions) . '</error>'
389
			);
390
			$this->updateWorkingCopy($wc_path, $update_revision);
391
392
			return;
393
		}
394
395
		$update_revision = $this->getWorkingCopyUpdateRevision($wc_path);
396
397
		if ( isset($update_revision) ) {
398
			$this->io->writeln('<error>Not at ' . $update_revision . ' revision</error>');
399
			$this->updateWorkingCopy($wc_path, $update_revision);
400
401
			return;
402
		}
403
404
		$this->io->writeln('<info>Up to date</info>');
405
	}
406
407
	/**
408
	 * Returns revision, that working copy needs to be updated to.
409
	 *
410
	 * @param string $wc_path Working copy path.
411
	 *
412
	 * @return integer|null
413
	 */
414
	protected function getWorkingCopyUpdateRevision($wc_path)
415
	{
416
		$update_revision = $this->io->getOption('update-revision');
417
		$actual_revision = $this->repositoryConnector->getLastRevision($wc_path);
418
419
		if ( isset($update_revision) ) {
420
			if ( is_numeric($update_revision) ) {
421
				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...
422
			}
423
424
			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...
425
		}
426
427
		$repository_revision = $this->repositoryConnector->getLastRevision(
428
			$this->repositoryConnector->getWorkingCopyUrl($wc_path)
429
		);
430
431
		return $repository_revision > $actual_revision ? $repository_revision : null;
432
	}
433
434
	/**
435
	 * Updates working copy.
436
	 *
437
	 * @param string     $wc_path  Working copy path.
438
	 * @param mixed|null $revision Revision.
439
	 *
440
	 * @return void
441
	 */
442
	protected function updateWorkingCopy($wc_path, $revision = null)
443
	{
444
		$arguments = array('path' => $wc_path, '--ignore-externals' => true);
445
446
		if ( isset($revision) ) {
447
			$arguments['--revision'] = $revision;
448
		}
449
450
		$this->runOtherCommand('update', $arguments);
451
	}
452
453
	/**
454
	 * Returns source url for merge.
455
	 *
456
	 * @param string $wc_path Working copy path.
457
	 *
458
	 * @return string
459
	 * @throws CommandException When source path is invalid.
460
	 */
461
	protected function getSourceUrl($wc_path)
462
	{
463
		$source_url = $this->io->getOption('source-url');
464
465
		if ( $source_url === null ) {
466
			$source_url = $this->getSetting(self::SETTING_MERGE_SOURCE_URL);
467
		}
468
		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

468
		elseif ( !$this->repositoryConnector->isUrl(/** @scrutinizer ignore-type */ $source_url) ) {
Loading history...
469
			$wc_url = $this->repositoryConnector->getWorkingCopyUrl($wc_path);
470
			$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

470
			$source_url = $this->_urlResolver->resolve($wc_url, /** @scrutinizer ignore-type */ $source_url);
Loading history...
471
		}
472
473
		if ( !$source_url ) {
474
			$wc_url = $this->repositoryConnector->getWorkingCopyUrl($wc_path);
475
			$source_url = $this->_mergeSourceDetector->detect($wc_url);
476
477
			if ( $source_url ) {
478
				$this->setSetting(self::SETTING_MERGE_SOURCE_URL, $source_url);
479
			}
480
		}
481
482
		if ( !$source_url ) {
483
			$wc_url = $this->repositoryConnector->getWorkingCopyUrl($wc_path);
484
			$error_msg = 'Unable to guess "--source-url" option value. Please specify it manually.' . PHP_EOL;
485
			$error_msg .= 'Working Copy URL: ' . $wc_url . '.';
486
			throw new CommandException($error_msg);
487
		}
488
489
		return $source_url;
490
	}
491
492
	/**
493
	 * Prints information about merge source & target.
494
	 *
495
	 * @param string $source_url Merge source: url.
496
	 * @param string $wc_path    Merge target: working copy path.
497
	 *
498
	 * @return void
499
	 */
500
	protected function printSourceAndTarget($source_url, $wc_path)
501
	{
502
		$relative_source_url = $this->repositoryConnector->getRelativePath($source_url);
503
		$relative_target_url = $this->repositoryConnector->getRelativePath($wc_path);
504
505
		$this->io->writeln(' * Merge Source ... <info>' . $relative_source_url . '</info>');
506
		$this->io->writeln(' * Merge Target ... <info>' . $relative_target_url . '</info>');
507
	}
508
509
	/**
510
	 * Ensures, that there are some usable revisions.
511
	 *
512
	 * @param string $source_url Merge source: url.
513
	 * @param string $wc_path    Merge target: working copy path.
514
	 *
515
	 * @return array
516
	 */
517
	protected function getUsableRevisions($source_url, $wc_path)
518
	{
519
		// Avoid missing revision query progress bar overwriting following output.
520
		$revision_log = $this->getRevisionLog($source_url);
521
522
		$this->io->write(sprintf(
523
			' * Upcoming %s Status (no filters) ... ',
524
			$this->isReverseMerge() ? 'Reverse-merge' : 'Merge'
525
		));
526
		$usable_revisions = $this->calculateUsableRevisions($source_url, $wc_path);
527
528
		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...
529
			$usable_bugs = $revision_log->getBugsFromRevisions($usable_revisions);
530
			$error_msg = '<error>%d revision(-s) or %d bug(-s) %s</error>';
531
			$this->io->writeln(sprintf(
532
				$error_msg,
533
				count($usable_revisions),
534
				count($usable_bugs),
535
				$this->isReverseMerge() ? 'merged' : 'not merged'
536
			));
537
		}
538
		else {
539
			$this->io->writeln('<info>Up to date</info>');
540
		}
541
542
		return $usable_revisions;
543
	}
544
545
	/**
546
	 * Returns usable revisions.
547
	 *
548
	 * @param string $source_url Merge source: url.
549
	 * @param string $wc_path    Merge target: working copy path.
550
	 *
551
	 * @return array
552
	 */
553
	protected function calculateUsableRevisions($source_url, $wc_path)
554
	{
555
		$command = $this->repositoryConnector->getCommand(
556
			'mergeinfo',
557
			array(
558
				'--show-revs',
559
				$this->isReverseMerge() ? 'merged' : 'eligible',
560
				$source_url,
561
				$wc_path,
562
			)
563
		);
564
565
		$merge_info = $this->repositoryConnector->getProperty('svn:mergeinfo', $wc_path);
566
567
		$cache_invalidator = array(
568
			'source:' . $this->repositoryConnector->getLastRevision($source_url),
569
			'merged_hash:' . crc32($merge_info),
570
		);
571
		$command->setCacheInvalidator(implode(';', $cache_invalidator));
572
573
		$merge_info = $command->run();
574
		$merge_info = explode(PHP_EOL, $merge_info);
575
576
		foreach ( $merge_info as $index => $revision ) {
577
			$merge_info[$index] = ltrim($revision, 'r');
578
		}
579
580
		return array_filter($merge_info);
581
	}
582
583
	/**
584
	 * Parses information from "svn:mergeinfo" property.
585
	 *
586
	 * @param string $source_path Merge source: path in repository.
587
	 * @param string $wc_path     Merge target: working copy path.
588
	 *
589
	 * @return array
590
	 */
591
	protected function getMergedRevisions($source_path, $wc_path)
592
	{
593
		$merge_info = $this->repositoryConnector->getProperty('svn:mergeinfo', $wc_path);
594
		$merge_info = array_filter(explode("\n", $merge_info));
595
596
		foreach ( $merge_info as $merge_info_line ) {
597
			list($path, $revisions) = explode(':', $merge_info_line, 2);
598
599
			if ( $path === $source_path ) {
600
				return $this->_revisionListParser->expandRanges(explode(',', $revisions));
601
			}
602
		}
603
604
		return array();
605
	}
606
607
	/**
608
	 * Validates revisions to actually exist.
609
	 *
610
	 * @param array  $revisions      Revisions.
611
	 * @param string $repository_url Repository url.
612
	 *
613
	 * @return array
614
	 * @throws CommandException When revision doesn't exist.
615
	 */
616
	protected function getDirectRevisions(array $revisions, $repository_url)
617
	{
618
		$revision_log = $this->getRevisionLog($repository_url);
619
620
		try {
621
			$revisions = $this->_revisionListParser->expandRanges($revisions);
622
			$revision_log->getRevisionsData('summary', $revisions);
623
		}
624
		catch ( \InvalidArgumentException $e ) {
625
			throw new CommandException($e->getMessage());
626
		}
627
628
		return $revisions;
629
	}
630
631
	/**
632
	 * Performs merge.
633
	 *
634
	 * @param string $source_url Merge source: url.
635
	 * @param string $wc_path    Merge target: working copy path.
636
	 * @param array  $revisions  Revisions to merge.
637
	 *
638
	 * @return void
639
	 */
640
	protected function performMerge($source_url, $wc_path, array $revisions)
641
	{
642
		if ( $this->isReverseMerge() ) {
643
			rsort($revisions, SORT_NUMERIC);
644
		}
645
		else {
646
			sort($revisions, SORT_NUMERIC);
647
		}
648
649
		$revision_count = count($revisions);
650
651
		$used_revision_count = 0;
652
		$used_revisions = $this->repositoryConnector->getMergedRevisionChanges($wc_path, !$this->isReverseMerge());
653
654
		if ( $used_revisions ) {
655
			$used_revisions = call_user_func_array('array_merge', $used_revisions);
656
			$used_revision_count = count($used_revisions);
657
			$revision_count += $used_revision_count;
658
		}
659
660
		$revision_log = $this->getRevisionLog($source_url);
661
		$revisions_data = $revision_log->getRevisionsData('summary', $revisions);
662
663
		$revision_title_mask = $revision_log->getRevisionURLBuilder()->getMask('fg=white;options=bold,underscore');
664
665
		// Added " revision" text, when URL wasn't detected.
666
		if ( strpos($revision_title_mask, '://') === false ) {
667
			$revision_title_mask .= ' revision';
668
		}
669
670
		$merge_command_arguments = $this->getMergeCommandArguments($source_url, $wc_path);
671
672
		foreach ( $revisions as $index => $revision ) {
673
			$command_arguments = str_replace('{revision}', $revision, $merge_command_arguments);
674
			$command = $this->repositoryConnector->getCommand('merge', $command_arguments);
675
676
			$progress_bar = $this->createMergeProgressBar($used_revision_count + $index + 1, $revision_count);
677
678
			// 1. Add revision link with a progress bar.
679
			$merge_heading = PHP_EOL . '<fg=white;options=bold>';
680
			$merge_heading .= '--- $1 ' . \str_replace('{revision}', $revision, $revision_title_mask);
681
			$merge_heading .= " into '$2' " . $progress_bar . ':</>';
682
683
			// 2. Add a commit message.
684
			$commit_message = trim($revisions_data[$revision]['msg']);
685
			$commit_message = wordwrap($commit_message, 68); // FIXME: Not UTF-8 safe solution.
686
			$merge_heading .= PHP_EOL . $commit_message;
687
			$merge_heading .= PHP_EOL;
688
			$merge_heading .= PHP_EOL . '<fg=white;options=bold>Changed Paths:</>';
689
690
			$command->runLive(array(
691
				$wc_path => '.',
692
				'/--- (Merging|Reverse-merging) r' . $revision . " into '([^']*)':/" => $merge_heading,
693
			));
694
695
			$this->_usableRevisions = array_diff($this->_usableRevisions, array($revision));
696
			$this->ensureWorkingCopyWithoutConflicts($source_url, $wc_path, $revision);
697
		}
698
699
		$this->performCommit();
700
	}
701
702
	/**
703
	 * Returns merge command arguments.
704
	 *
705
	 * @param string $source_url Merge source: url.
706
	 * @param string $wc_path    Merge target: working copy path.
707
	 *
708
	 * @return array
709
	 */
710
	protected function getMergeCommandArguments($source_url, $wc_path)
711
	{
712
		$ret = array(
713
			'-c',
714
			$this->isReverseMerge() ? '-{revision}' : '{revision}',
715
		);
716
717
		if ( $this->io->getOption('record-only') ) {
718
			$ret[] = '--record-only';
719
		}
720
721
		$ret[] = $source_url;
722
		$ret[] = $wc_path;
723
724
		return $ret;
725
	}
726
727
	/**
728
	 * Create merge progress bar.
729
	 *
730
	 * @param integer $current Current.
731
	 * @param integer $total   Total.
732
	 *
733
	 * @return string
734
	 */
735
	protected function createMergeProgressBar($current, $total)
736
	{
737
		$total_length = 28;
738
		$percent_used = floor(($current / $total) * 100);
739
		$length_used = floor(($total_length * $percent_used) / 100);
740
		$length_free = $total_length - $length_used;
741
742
		$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

742
		$ret = $length_used > 0 ? str_repeat('=', /** @scrutinizer ignore-type */ $length_used - 1) : '';
Loading history...
743
		$ret .= '>' . str_repeat('-', $length_free);
744
745
		return '[' . $ret . '] ' . $percent_used . '% (' . $current . ' of ' . $total . ')';
746
	}
747
748
	/**
749
	 * Ensures, that there are no unresolved conflicts in working copy.
750
	 *
751
	 * @param string  $source_url                 Source url.
752
	 * @param string  $wc_path                    Working copy path.
753
	 * @param integer $largest_suggested_revision Largest revision, that is suggested in error message.
754
	 *
755
	 * @return void
756
	 * @throws CommandException When merge conflicts detected.
757
	 */
758
	protected function ensureWorkingCopyWithoutConflicts($source_url, $wc_path, $largest_suggested_revision = null)
759
	{
760
		$this->io->write(' * Previous Merge Status ... ');
761
762
		$conflicts = $this->_workingCopyConflictTracker->getNewConflicts($wc_path);
763
764
		if ( !$conflicts ) {
765
			$this->io->writeln('<info>Successful</info>');
766
767
			return;
768
		}
769
770
		$this->_workingCopyConflictTracker->add($wc_path);
771
		$this->io->writeln('<error>' . count($conflicts) . ' conflict(-s)</error>');
772
773
		$table = new Table($this->io->getOutput());
774
775
		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...
776
			$table->setHeaders(array(
777
				'Path',
778
				'Associated Revisions (before ' . $largest_suggested_revision . ')',
779
			));
780
		}
781
		else {
782
			$table->setHeaders(array(
783
				'Path',
784
				'Associated Revisions',
785
			));
786
		}
787
788
		$revision_log = $this->getRevisionLog($source_url);
789
		$source_path = $this->repositoryConnector->getRelativePath($source_url) . '/';
790
791
		/** @var OutputHelper $output_helper */
792
		$output_helper = $this->getHelper('output');
793
794
		foreach ( $conflicts as $conflict_path ) {
795
			$path_revisions = $revision_log->find('paths', $source_path . $conflict_path);
796
			$path_revisions = array_intersect($this->_usableRevisions, $path_revisions);
797
798
			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...
799
				$path_revisions = $this->limitRevisions($path_revisions, $largest_suggested_revision);
800
			}
801
802
			$table->addRow(array(
803
				$conflict_path,
804
				$path_revisions ? $output_helper->formatArray($path_revisions, 4) : '-',
805
			));
806
		}
807
808
		$table->render();
809
810
		throw new CommandException('Working copy contains unresolved merge conflicts.');
811
	}
812
813
	/**
814
	 * Returns revisions not larger, then given one.
815
	 *
816
	 * @param array   $revisions    Revisions.
817
	 * @param integer $max_revision Maximal revision.
818
	 *
819
	 * @return array
820
	 */
821
	protected function limitRevisions(array $revisions, $max_revision)
822
	{
823
		$ret = array();
824
825
		foreach ( $revisions as $revision ) {
826
			if ( $revision < $max_revision ) {
827
				$ret[] = $revision;
828
			}
829
		}
830
831
		return $ret;
832
	}
833
834
	/**
835
	 * Performs commit unless user doesn't want it.
836
	 *
837
	 * @return void
838
	 */
839
	protected function performCommit()
840
	{
841
		$auto_commit = $this->io->getOption('auto-commit');
842
843
		if ( $auto_commit !== null ) {
844
			$auto_commit = $auto_commit === 'yes';
845
		}
846
		else {
847
			$auto_commit = (boolean)$this->getSetting(self::SETTING_MERGE_AUTO_COMMIT);
848
		}
849
850
		if ( $auto_commit ) {
851
			$this->io->writeln(array('', 'Commencing automatic commit after merge ...'));
852
			$this->runOtherCommand('commit');
853
		}
854
	}
855
856
	/**
857
	 * Prints revisions.
858
	 *
859
	 * @param string $source_url Merge source: url.
860
	 * @param array  $revisions  Revisions.
861
	 *
862
	 * @return void
863
	 */
864
	protected function printRevisions($source_url, array $revisions)
865
	{
866
		$this->runOtherCommand('log', array(
867
			'path' => $source_url,
868
			'--revisions' => implode(',', $revisions),
869
			'--merges' => $this->io->getOption('merges'),
870
			'--no-merges' => $this->io->getOption('no-merges'),
871
			'--with-full-message' => $this->io->getOption('with-full-message'),
872
			'--with-details' => $this->io->getOption('with-details'),
873
			'--with-summary' => $this->io->getOption('with-summary'),
874
			'--aggregate' => $this->io->getOption('aggregate'),
875
			'--with-merge-oracle' => true,
876
		));
877
	}
878
879
	/**
880
	 * Returns list of config settings.
881
	 *
882
	 * @return AbstractConfigSetting[]
883
	 */
884
	public function getConfigSettings()
885
	{
886
		return array(
887
			new StringConfigSetting(self::SETTING_MERGE_SOURCE_URL, ''),
888
			new ArrayConfigSetting(self::SETTING_MERGE_RECENT_CONFLICTS, array()),
889
			new ChoiceConfigSetting(
890
				self::SETTING_MERGE_AUTO_COMMIT,
891
				array(1 => 'Yes', 0 => 'No'),
892
				1
893
			),
894
		);
895
	}
896
897
	/**
898
	 * Returns option names, that makes sense to use in aggregation mode.
899
	 *
900
	 * @return array
901
	 */
902
	public function getAggregatedOptions()
903
	{
904
		return array('with-full-message', 'with-details', 'with-summary');
905
	}
906
907
	/**
908
	 * Determines if merge should be done in opposite direction (unmerge).
909
	 *
910
	 * @return boolean
911
	 */
912
	protected function isReverseMerge()
913
	{
914
		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...
915
	}
916
917
}
918