Failed Conditions
Push — master ( bd53b9...8854a5 )
by Alexander
02:50
created

Connector::getCommand()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 17
ccs 12
cts 12
cp 1
rs 9.4285
cc 2
eloc 10
nc 2
nop 2
crap 2
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\Repository\Connector;
12
13
14
use ConsoleHelpers\ConsoleKit\ConsoleIO;
15
use ConsoleHelpers\SVNBuddy\Cache\CacheManager;
16
use ConsoleHelpers\ConsoleKit\Config\ConfigEditor;
17
use ConsoleHelpers\SVNBuddy\Exception\RepositoryCommandException;
18
use ConsoleHelpers\SVNBuddy\Process\IProcessFactory;
19
20
/**
21
 * Executes command on the repository.
22
 */
23
class Connector
24
{
25
26
	const STATUS_UNVERSIONED = 'unversioned';
27
28
	/**
29
	 * Reference to configuration.
30
	 *
31
	 * @var ConfigEditor
32
	 */
33
	private $_configEditor;
34
35
	/**
36
	 * Process factory.
37
	 *
38
	 * @var IProcessFactory
39
	 */
40
	private $_processFactory;
41
42
	/**
43
	 * Console IO.
44
	 *
45
	 * @var ConsoleIO
46
	 */
47
	private $_io;
48
49
	/**
50
	 * Cache manager.
51
	 *
52
	 * @var CacheManager
53
	 */
54
	private $_cacheManager;
55
56
	/**
57
	 * Path to an svn command.
58
	 *
59
	 * @var string
60
	 */
61
	private $_svnCommand = 'svn';
62
63
	/**
64
	 * Cache duration for next invoked command.
65
	 *
66
	 * @var mixed
67
	 */
68
	private $_nextCommandCacheDuration = null;
69
70
	/**
71
	 * Whatever to cache last repository revision or not.
72
	 *
73
	 * @var mixed
74
	 */
75
	private $_lastRevisionCacheDuration = null;
76
77
	/**
78
	 * Creates repository connector.
79
	 *
80
	 * @param ConfigEditor    $config_editor   ConfigEditor.
81
	 * @param IProcessFactory $process_factory Process factory.
82
	 * @param ConsoleIO       $io              Console IO.
83
	 * @param CacheManager    $cache_manager   Cache manager.
84
	 */
85 41
	public function __construct(
86
		ConfigEditor $config_editor,
87
		IProcessFactory $process_factory,
88
		ConsoleIO $io,
89
		CacheManager $cache_manager
90
	) {
91 41
		$this->_configEditor = $config_editor;
92 41
		$this->_processFactory = $process_factory;
93 41
		$this->_io = $io;
94 41
		$this->_cacheManager = $cache_manager;
95
96 41
		$cache_duration = $this->_configEditor->get('repository-connector.last-revision-cache-duration');
97
98 41
		if ( (string)$cache_duration === '' || substr($cache_duration, 0, 1) === '0' ) {
99 4
			$cache_duration = null;
100 4
		}
101
102 41
		$this->_lastRevisionCacheDuration = $cache_duration;
103
104 41
		$this->prepareSvnCommand();
105 41
	}
106
107
	/**
108
	 * Prepares static part of svn command to be used across the script.
109
	 *
110
	 * @return void
111
	 */
112 41
	protected function prepareSvnCommand()
113
	{
114 41
		$username = $this->_configEditor->get('repository-connector.username');
115 41
		$password = $this->_configEditor->get('repository-connector.password');
116
117 41
		$this->_svnCommand .= ' --non-interactive';
118
119 41
		if ( $username ) {
120 12
			$this->_svnCommand .= ' --username ' . $username;
121 12
		}
122
123 41
		if ( $password ) {
124 12
			$this->_svnCommand .= ' --password ' . $password;
125 12
		}
126 41
	}
127
128
	/**
129
	 * Builds a command.
130
	 *
131
	 * @param string      $sub_command  Sub command.
132
	 * @param string|null $param_string Parameter string.
133
	 *
134
	 * @return Command
135
	 */
136 29
	public function getCommand($sub_command, $param_string = null)
137
	{
138 29
		$command_line = $this->buildCommand($sub_command, $param_string);
139
140 28
		$command = new Command(
141 28
			$this->_processFactory->createProcess($command_line, 1200),
142 28
			$this->_io,
143 28
			$this->_cacheManager
144 28
		);
145
146 28
		if ( isset($this->_nextCommandCacheDuration) ) {
147 5
			$command->setCacheDuration($this->_nextCommandCacheDuration);
148 5
			$this->_nextCommandCacheDuration = null;
149 5
		}
150
151 28
		return $command;
152
	}
153
154
	/**
155
	 * Builds command from given arguments.
156
	 *
157
	 * @param string $sub_command  Command.
158
	 * @param string $param_string Parameter string.
159
	 *
160
	 * @return string
161
	 * @throws \InvalidArgumentException When command contains spaces.
162
	 */
163 29
	protected function buildCommand($sub_command, $param_string = null)
164
	{
165 29
		if ( strpos($sub_command, ' ') !== false ) {
166 1
			throw new \InvalidArgumentException('The "' . $sub_command . '" sub-command contains spaces.');
167
		}
168
169 28
		$command_line = $this->_svnCommand;
170
171 28
		if ( !empty($sub_command) ) {
172 23
			$command_line .= ' ' . $sub_command;
173 23
		}
174
175 28
		if ( !empty($param_string) ) {
176 26
			$command_line .= ' ' . $param_string;
177 26
		}
178
179 28
		$command_line = preg_replace_callback(
180 28
			'/\{([^\}]*)\}/',
181 28
			function (array $matches) {
182 20
				return escapeshellarg($matches[1]);
183 28
			},
184
			$command_line
185 28
		);
186
187 28
		return $command_line;
188
	}
189
190
	/**
191
	 * Sets cache configuration for next created command.
192
	 *
193
	 * @param mixed $cache_duration Cache duration.
194
	 *
195
	 * @return self
196
	 */
197 11
	public function withCache($cache_duration)
198
	{
199 11
		$this->_nextCommandCacheDuration = $cache_duration;
200
201 11
		return $this;
202
	}
203
204
	/**
205
	 * Returns property value.
206
	 *
207
	 * @param string $name        Property name.
208
	 * @param string $path_or_url Path to get property from.
209
	 * @param mixed  $revision    Revision.
210
	 *
211
	 * @return string
212
	 */
213 2
	public function getProperty($name, $path_or_url, $revision = null)
214
	{
215 2
		$param_string = $name . ' {' . $path_or_url . '}';
216
217 2
		if ( isset($revision) ) {
218 1
			$param_string .= ' --revision ' . $revision;
219 1
		}
220
221 2
		return $this->getCommand('propget', $param_string)->run();
222
	}
223
224
	/**
225
	 * Returns relative path of given path/url to the root of the repository.
226
	 *
227
	 * @param string $path_or_url    Path or url.
228
	 * @param mixed  $cache_duration Cache duration.
229
	 *
230
	 * @return string
231
	 */
232 3
	public function getRelativePath($path_or_url, $cache_duration = null)
233
	{
234
		// Cache "svn info" commands to remote urls, not the working copy.
235 3
		if ( !isset($cache_duration) && $this->isUrl($path_or_url) ) {
236 1
			$cache_duration = '1 year';
237 1
		}
238
239 3
		$svn_info = $this->withCache($cache_duration)->_getSvnInfoEntry($path_or_url);
240
241 3
		$wc_url = (string)$svn_info->url;
242 3
		$repository_root_url = (string)$svn_info->repository->root;
243
244 3
		return preg_replace('/^' . preg_quote($repository_root_url, '/') . '/', '', $wc_url, 1);
245
	}
246
247
	/**
248
	 * Returns URL of the working copy.
249
	 *
250
	 * @param string $wc_path Working copy path.
251
	 *
252
	 * @return string
253
	 * @throws RepositoryCommandException When repository command failed to execute.
254
	 */
255 7
	public function getWorkingCopyUrl($wc_path)
256
	{
257 7
		if ( $this->isUrl($wc_path) ) {
258 1
			return $wc_path;
259
		}
260
261
		try {
262 6
			$wc_url = (string)$this->_getSvnInfoEntry($wc_path)->url;
263
		}
264 6
		catch ( RepositoryCommandException $e ) {
265 3
			if ( $e->getCode() == RepositoryCommandException::SVN_ERR_WC_UPGRADE_REQUIRED ) {
266 2
				$message = explode(PHP_EOL, $e->getMessage());
267
268 2
				$this->_io->writeln(array('', '<error>' . end($message) . '</error>', ''));
269
270 2
				if ( $this->_io->askConfirmation('Run "svn upgrade"', false) ) {
271 1
					$this->getCommand('upgrade', '{' . $wc_path . '}')->runLive();
272
273 1
					return $this->getWorkingCopyUrl($wc_path);
274
				}
275 1
			}
276
277 2
			throw $e;
278
		}
279
280 3
		return $wc_url;
281
	}
282
283
	/**
284
	 * Returns last changed revision on path/url.
285
	 *
286
	 * @param string $path_or_url    Path or url.
287
	 * @param mixed  $cache_duration Cache duration.
288
	 *
289
	 * @return integer
290
	 */
291 7
	public function getLastRevision($path_or_url, $cache_duration = null)
292
	{
293
		// Cache "svn info" commands to remote urls, not the working copy.
294 7
		if ( !isset($cache_duration) && $this->isUrl($path_or_url) ) {
295 5
			$cache_duration = $this->_lastRevisionCacheDuration;
296 5
		}
297
298 7
		$svn_info = $this->withCache($cache_duration)->_getSvnInfoEntry($path_or_url);
299
300 7
		return (int)$svn_info->commit['revision'];
301
	}
302
303
	/**
304
	 * Determines if given path is in fact an url.
305
	 *
306
	 * @param string $path Path.
307
	 *
308
	 * @return boolean
309
	 */
310 15
	public function isUrl($path)
311
	{
312 15
		return strpos($path, '://') !== false;
313
	}
314
315
	/**
316
	 * Returns project url (container for "trunk/branches/tags/releases" folders).
317
	 *
318
	 * @param string $repository_url Repository url.
319
	 *
320
	 * @return string
321
	 */
322 9
	public function getProjectUrl($repository_url)
323
	{
324 9
		if ( preg_match('#^(.*?)/(trunk|branches|tags|releases).*$#', $repository_url, $regs) ) {
325 8
			return $regs[1];
326
		}
327
328 1
		return $repository_url;
329
	}
330
331
	/**
332
	 * Returns "svn info" entry for path or url.
333
	 *
334
	 * @param string $path_or_url Path or url.
335
	 *
336
	 * @return \SimpleXMLElement
337
	 * @throws \LogicException When unexpected 'svn info' results retrieved.
338
	 */
339 16
	private function _getSvnInfoEntry($path_or_url)
340
	{
341 16
		$svn_info = $this->getCommand('info', '--xml {' . $path_or_url . '}')->run();
342
343
		// When getting remote "svn info", then path is last folder only.
344 14
		if ( basename($this->_getSvnInfoEntryPath($svn_info->entry)) != basename($path_or_url) ) {
345 1
			throw new \LogicException('The directory "' . $path_or_url . '" not found in "svn info" command results.');
346
		}
347
348 13
		return $svn_info->entry;
349
	}
350
351
	/**
352
	 * Returns path of "svn info" entry.
353
	 *
354
	 * @param \SimpleXMLElement $svn_info_entry The "entry" node of "svn info" command.
355
	 *
356
	 * @return string
357
	 */
358 14
	private function _getSvnInfoEntryPath(\SimpleXMLElement $svn_info_entry)
359
	{
360
		// SVN 1.7+.
361 14
		$path = (string)$svn_info_entry->{'wc-info'}->{'wcroot-abspath'};
362
363 14
		if ( $path ) {
364 1
			return $path;
365
		}
366
367
		// SVN 1.6-.
368 13
		return (string)$svn_info_entry['path'];
369
	}
370
371
	/**
372
	 * Returns revision, when path was added to repository.
373
	 *
374
	 * @param string $url Url.
375
	 *
376
	 * @return integer
377
	 * @throws \InvalidArgumentException When not an url was given.
378
	 */
379
	public function getFirstRevision($url)
380
	{
381
		if ( !$this->isUrl($url) ) {
382
			throw new \InvalidArgumentException('The repository URL "' . $url . '" is invalid.');
383
		}
384
385
		$log = $this->withCache('1 year')->getCommand('log', ' -r 1:HEAD --limit 1 --xml {' . $url . '}')->run();
386
387
		return (int)$log->logentry['revision'];
388
	}
389
390
	/**
391
	 * Returns conflicts in working copy.
392
	 *
393
	 * @param string $wc_path Working copy path.
394
	 *
395
	 * @return array
396
	 */
397
	public function getWorkingCopyConflicts($wc_path)
398
	{
399
		$ret = array();
400
401
		foreach ( $this->getWorkingCopyStatus($wc_path) as $path => $status ) {
402
			if ( $status['item'] == 'conflicted' || $status['props'] == 'conflicted' || $status['tree-conflicted'] ) {
403
				$ret[] = $path;
404
			}
405
		}
406
407
		return $ret;
408
	}
409
410
	/**
411
	 * Returns compact working copy status.
412
	 *
413
	 * @param string  $wc_path          Working copy path.
414
	 * @param boolean $with_unversioned With unversioned.
415
	 *
416
	 * @return string
417
	 */
418
	public function getCompactWorkingCopyStatus($wc_path, $with_unversioned = true)
419
	{
420
		$ret = array();
421
422
		foreach ( $this->getWorkingCopyStatus($wc_path) as $path => $status ) {
423
			if ( !$with_unversioned && $status['item'] == self::STATUS_UNVERSIONED ) {
424
				continue;
425
			}
426
427
			$line = $this->getShortItemStatus($status['item']) . $this->getShortPropertiesStatus($status['props']);
428
			$line .= '   ' . $path;
429
430
			$ret[] = $line;
431
		}
432
433
		return implode(PHP_EOL, $ret);
434
	}
435
436
	/**
437
	 * Returns short item status.
438
	 *
439
	 * @param string $status Status.
440
	 *
441
	 * @return string
442
	 * @throws \InvalidArgumentException When unknown status given.
443
	 */
444
	protected function getShortItemStatus($status)
445
	{
446
		$status_map = array(
447
			'added' => 'A',
448
			'conflicted' => 'C',
449
			'deleted' => 'D',
450
			'external' => 'X',
451
			'ignored' => 'I',
452
			// 'incomplete' => '',
453
			// 'merged' => '',
454
			'missing' => '!',
455
			'modified' => 'M',
456
			'none' => ' ',
457
			'normal' => '_',
458
			// 'obstructed' => '',
459
			'replaced' => 'R',
460
			'unversioned' => '?',
461
		);
462
463
		if ( !isset($status_map[$status]) ) {
464
			throw new \InvalidArgumentException('The "' . $status . '" item status is unknown.');
465
		}
466
467
		return $status_map[$status];
468
	}
469
470
	/**
471
	 * Returns short item status.
472
	 *
473
	 * @param string $status Status.
474
	 *
475
	 * @return string
476
	 * @throws \InvalidArgumentException When unknown status given.
477
	 */
478
	protected function getShortPropertiesStatus($status)
479
	{
480
		$status_map = array(
481
			'conflicted' => 'C',
482
			'modified' => 'M',
483
			'normal' => '_',
484
			'none' => ' ',
485
		);
486
487
		if ( !isset($status_map[$status]) ) {
488
			throw new \InvalidArgumentException('The "' . $status . '" properties status is unknown.');
489
		}
490
491
		return $status_map[$status];
492
	}
493
494
	/**
495
	 * Returns working copy status.
496
	 *
497
	 * @param string $wc_path Working copy path.
498
	 *
499
	 * @return array
500
	 */
501
	protected function getWorkingCopyStatus($wc_path)
502
	{
503
		$ret = array();
504
		$status = $this->getCommand('status', '--xml {' . $wc_path . '}')->run();
505
506
		foreach ( $status->target as $target ) {
507
			if ( (string)$target['path'] !== $wc_path ) {
508
				continue;
509
			}
510
511
			foreach ( $target as $entry ) {
512
				$path = (string)$entry['path'];
513
514
				if ( $path === $wc_path ) {
515
					$path = '.';
516
				}
517
				else {
518
					$path = str_replace($wc_path . '/', '', $path);
519
				}
520
521
				$ret[$path] = array(
522
					'item' => (string)$entry->{'wc-status'}['item'],
523
					'props' => (string)$entry->{'wc-status'}['props'],
524
					'tree-conflicted' => (string)$entry->{'wc-status'}['tree-conflicted'] === 'true',
525
				);
526
			}
527
		}
528
529
		return $ret;
530
	}
531
532
	/**
533
	 * Determines if working copy contains mixed revisions.
534
	 *
535
	 * @param string $wc_path Working copy path.
536
	 *
537
	 * @return array
538
	 */
539
	public function isMixedRevisionWorkingCopy($wc_path)
540
	{
541
		$revisions = array();
542
		$status = $this->getCommand('status', '--xml --verbose {' . $wc_path . '}')->run();
543
544
		foreach ( $status->target as $target ) {
545
			if ( (string)$target['path'] !== $wc_path ) {
546
				continue;
547
			}
548
549
			foreach ( $target as $entry ) {
550
				$item_status = (string)$entry->{'wc-status'}['item'];
551
552
				if ( $item_status !== self::STATUS_UNVERSIONED ) {
553
					$revision = (int)$entry->{'wc-status'}['revision'];
554
					$revisions[$revision] = true;
555
				}
556
			}
557
		}
558
559
		return count($revisions) > 1;
560
	}
561
562
	/**
563
	 * Determines if there is a working copy on a given path.
564
	 *
565
	 * @param string $path Path.
566
	 *
567
	 * @return boolean
568
	 * @throws \InvalidArgumentException When path isn't found.
569
	 * @throws RepositoryCommandException When repository command failed to execute.
570
	 */
1 ignored issue
show
Coding Style introduced by
Expected 1 @throws tag(s) in function comment; 2 found
Loading history...
571
	public function isWorkingCopy($path)
572
	{
573
		if ( $this->isUrl($path) || !file_exists($path) || !is_dir($path) ) {
574
			throw new \InvalidArgumentException('Path "' . $path . '" not found or isn\'t a directory.');
575
		}
576
577
		try {
578
			$wc_url = $this->getWorkingCopyUrl($path);
579
		}
580
		catch ( RepositoryCommandException $e ) {
581
			if ( $e->getCode() == RepositoryCommandException::SVN_ERR_WC_NOT_WORKING_COPY ) {
582
				return false;
583
			}
584
585
			throw $e;
586
		}
587
588
		return $wc_url != '';
589
	}
590
591
}
592