Completed
Push — master ( 3c513e...852a18 )
by Alexander
03:56
created

Connector::_getSvnInfoEntryPath()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 12
ccs 5
cts 5
cp 1
rs 9.4285
cc 2
eloc 5
nc 2
nop 1
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 47
	public function __construct(
86
		ConfigEditor $config_editor,
87
		IProcessFactory $process_factory,
88
		ConsoleIO $io,
89
		CacheManager $cache_manager
90
	) {
91 47
		$this->_configEditor = $config_editor;
92 47
		$this->_processFactory = $process_factory;
93 47
		$this->_io = $io;
94 47
		$this->_cacheManager = $cache_manager;
95
96 47
		$cache_duration = $this->_configEditor->get('repository-connector.last-revision-cache-duration');
97
98 47
		if ( (string)$cache_duration === '' || substr($cache_duration, 0, 1) === '0' ) {
99 4
			$cache_duration = null;
100 4
		}
101
102 47
		$this->_lastRevisionCacheDuration = $cache_duration;
103
104 47
		$this->prepareSvnCommand();
105 47
	}
106
107
	/**
108
	 * Prepares static part of svn command to be used across the script.
109
	 *
110
	 * @return void
111
	 */
112 47
	protected function prepareSvnCommand()
113
	{
114 47
		$username = $this->_configEditor->get('repository-connector.username');
115 47
		$password = $this->_configEditor->get('repository-connector.password');
116
117 47
		$this->_svnCommand .= ' --non-interactive';
118
119 47
		if ( $username ) {
120 12
			$this->_svnCommand .= ' --username ' . $username;
121 12
		}
122
123 47
		if ( $password ) {
124 12
			$this->_svnCommand .= ' --password ' . $password;
125 12
		}
126 47
	}
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
	 * Detects ref from given path.
249
	 *
250
	 * @param string $path Path to a file.
251
	 *
252
	 * @return string|boolean
253
	 */
254 6
	public function getRefByPath($path)
255
	{
256 6
		if ( preg_match('#^.*?/(trunk|branches/[^/]*|tags/[^/]*|releases/[^/]*).*$#', $path, $regs) ) {
257 5
			return $regs[1];
258
		}
259
260 1
		return false;
261
	}
262
263
	/**
264
	 * Returns URL of the working copy.
265
	 *
266
	 * @param string $wc_path Working copy path.
267
	 *
268
	 * @return string
269
	 * @throws RepositoryCommandException When repository command failed to execute.
270
	 */
271 7
	public function getWorkingCopyUrl($wc_path)
272
	{
273 7
		if ( $this->isUrl($wc_path) ) {
274 1
			return $wc_path;
275
		}
276
277
		try {
278 6
			$wc_url = (string)$this->_getSvnInfoEntry($wc_path)->url;
279
		}
280 6
		catch ( RepositoryCommandException $e ) {
281 3
			if ( $e->getCode() == RepositoryCommandException::SVN_ERR_WC_UPGRADE_REQUIRED ) {
282 2
				$message = explode(PHP_EOL, $e->getMessage());
283
284 2
				$this->_io->writeln(array('', '<error>' . end($message) . '</error>', ''));
285
286 2
				if ( $this->_io->askConfirmation('Run "svn upgrade"', false) ) {
287 1
					$this->getCommand('upgrade', '{' . $wc_path . '}')->runLive();
288
289 1
					return $this->getWorkingCopyUrl($wc_path);
290
				}
291 1
			}
292
293 2
			throw $e;
294
		}
295
296 3
		return $wc_url;
297
	}
298
299
	/**
300
	 * Returns last changed revision on path/url.
301
	 *
302
	 * @param string $path_or_url    Path or url.
303
	 * @param mixed  $cache_duration Cache duration.
304
	 *
305
	 * @return integer
306
	 */
307 7
	public function getLastRevision($path_or_url, $cache_duration = null)
308
	{
309
		// Cache "svn info" commands to remote urls, not the working copy.
310 7
		if ( !isset($cache_duration) && $this->isUrl($path_or_url) ) {
311 5
			$cache_duration = $this->_lastRevisionCacheDuration;
312 5
		}
313
314 7
		$svn_info = $this->withCache($cache_duration)->_getSvnInfoEntry($path_or_url);
315
316 7
		return (int)$svn_info->commit['revision'];
317
	}
318
319
	/**
320
	 * Determines if given path is in fact an url.
321
	 *
322
	 * @param string $path Path.
323
	 *
324
	 * @return boolean
325
	 */
326 15
	public function isUrl($path)
327
	{
328 15
		return strpos($path, '://') !== false;
329
	}
330
331
	/**
332
	 * Returns project url (container for "trunk/branches/tags/releases" folders).
333
	 *
334
	 * @param string $repository_url Repository url.
335
	 *
336
	 * @return string
337
	 */
338 9
	public function getProjectUrl($repository_url)
339
	{
340 9
		if ( preg_match('#^(.*?)/(trunk|branches|tags|releases).*$#', $repository_url, $regs) ) {
341 8
			return $regs[1];
342
		}
343
344 1
		return $repository_url;
345
	}
346
347
	/**
348
	 * Returns "svn info" entry for path or url.
349
	 *
350
	 * @param string $path_or_url Path or url.
351
	 *
352
	 * @return \SimpleXMLElement
353
	 * @throws \LogicException When unexpected 'svn info' results retrieved.
354
	 */
355 16
	private function _getSvnInfoEntry($path_or_url)
356
	{
357 16
		$svn_info = $this->getCommand('info', '--xml {' . $path_or_url . '}')->run();
358
359
		// When getting remote "svn info", then path is last folder only.
360 14
		if ( basename($this->_getSvnInfoEntryPath($svn_info->entry)) != basename($path_or_url) ) {
361 1
			throw new \LogicException('The directory "' . $path_or_url . '" not found in "svn info" command results.');
362
		}
363
364 13
		return $svn_info->entry;
365
	}
366
367
	/**
368
	 * Returns path of "svn info" entry.
369
	 *
370
	 * @param \SimpleXMLElement $svn_info_entry The "entry" node of "svn info" command.
371
	 *
372
	 * @return string
373
	 */
374 14
	private function _getSvnInfoEntryPath(\SimpleXMLElement $svn_info_entry)
375
	{
376
		// SVN 1.7+.
377 14
		$path = (string)$svn_info_entry->{'wc-info'}->{'wcroot-abspath'};
378
379 14
		if ( $path ) {
380 1
			return $path;
381
		}
382
383
		// SVN 1.6-.
384 13
		return (string)$svn_info_entry['path'];
385
	}
386
387
	/**
388
	 * Returns revision, when path was added to repository.
389
	 *
390
	 * @param string $url Url.
391
	 *
392
	 * @return integer
393
	 * @throws \InvalidArgumentException When not an url was given.
394
	 */
395
	public function getFirstRevision($url)
396
	{
397
		if ( !$this->isUrl($url) ) {
398
			throw new \InvalidArgumentException('The repository URL "' . $url . '" is invalid.');
399
		}
400
401
		$log = $this->withCache('1 year')->getCommand('log', ' -r 1:HEAD --limit 1 --xml {' . $url . '}')->run();
402
403
		return (int)$log->logentry['revision'];
404
	}
405
406
	/**
407
	 * Returns conflicts in working copy.
408
	 *
409
	 * @param string $wc_path Working copy path.
410
	 *
411
	 * @return array
412
	 */
413
	public function getWorkingCopyConflicts($wc_path)
414
	{
415
		$ret = array();
416
417
		foreach ( $this->getWorkingCopyStatus($wc_path) as $path => $status ) {
418
			if ( $status['item'] == 'conflicted' || $status['props'] == 'conflicted' || $status['tree-conflicted'] ) {
419
				$ret[] = $path;
420
			}
421
		}
422
423
		return $ret;
424
	}
425
426
	/**
427
	 * Returns compact working copy status.
428
	 *
429
	 * @param string  $wc_path          Working copy path.
430
	 * @param boolean $with_unversioned With unversioned.
431
	 *
432
	 * @return string
433
	 */
434
	public function getCompactWorkingCopyStatus($wc_path, $with_unversioned = true)
435
	{
436
		$ret = array();
437
438
		foreach ( $this->getWorkingCopyStatus($wc_path) as $path => $status ) {
439
			if ( !$with_unversioned && $status['item'] == self::STATUS_UNVERSIONED ) {
440
				continue;
441
			}
442
443
			$line = $this->getShortItemStatus($status['item']) . $this->getShortPropertiesStatus($status['props']);
444
			$line .= '   ' . $path;
445
446
			$ret[] = $line;
447
		}
448
449
		return implode(PHP_EOL, $ret);
450
	}
451
452
	/**
453
	 * Returns short item status.
454
	 *
455
	 * @param string $status Status.
456
	 *
457
	 * @return string
458
	 * @throws \InvalidArgumentException When unknown status given.
459
	 */
460
	protected function getShortItemStatus($status)
461
	{
462
		$status_map = array(
463
			'added' => 'A',
464
			'conflicted' => 'C',
465
			'deleted' => 'D',
466
			'external' => 'X',
467
			'ignored' => 'I',
468
			// 'incomplete' => '',
469
			// 'merged' => '',
470
			'missing' => '!',
471
			'modified' => 'M',
472
			'none' => ' ',
473
			'normal' => '_',
474
			// 'obstructed' => '',
475
			'replaced' => 'R',
476
			'unversioned' => '?',
477
		);
478
479
		if ( !isset($status_map[$status]) ) {
480
			throw new \InvalidArgumentException('The "' . $status . '" item status is unknown.');
481
		}
482
483
		return $status_map[$status];
484
	}
485
486
	/**
487
	 * Returns short item status.
488
	 *
489
	 * @param string $status Status.
490
	 *
491
	 * @return string
492
	 * @throws \InvalidArgumentException When unknown status given.
493
	 */
494
	protected function getShortPropertiesStatus($status)
495
	{
496
		$status_map = array(
497
			'conflicted' => 'C',
498
			'modified' => 'M',
499
			'normal' => '_',
500
			'none' => ' ',
501
		);
502
503
		if ( !isset($status_map[$status]) ) {
504
			throw new \InvalidArgumentException('The "' . $status . '" properties status is unknown.');
505
		}
506
507
		return $status_map[$status];
508
	}
509
510
	/**
511
	 * Returns working copy status.
512
	 *
513
	 * @param string $wc_path Working copy path.
514
	 *
515
	 * @return array
516
	 */
517
	protected function getWorkingCopyStatus($wc_path)
518
	{
519
		$ret = array();
520
		$status = $this->getCommand('status', '--xml {' . $wc_path . '}')->run();
521
522
		foreach ( $status->target as $target ) {
523
			if ( (string)$target['path'] !== $wc_path ) {
524
				continue;
525
			}
526
527
			foreach ( $target as $entry ) {
528
				$path = (string)$entry['path'];
529
530
				if ( $path === $wc_path ) {
531
					$path = '.';
532
				}
533
				else {
534
					$path = str_replace($wc_path . '/', '', $path);
535
				}
536
537
				$ret[$path] = array(
538
					'item' => (string)$entry->{'wc-status'}['item'],
539
					'props' => (string)$entry->{'wc-status'}['props'],
540
					'tree-conflicted' => (string)$entry->{'wc-status'}['tree-conflicted'] === 'true',
541
				);
542
			}
543
		}
544
545
		return $ret;
546
	}
547
548
	/**
549
	 * Determines if working copy contains mixed revisions.
550
	 *
551
	 * @param string $wc_path Working copy path.
552
	 *
553
	 * @return array
554
	 */
555
	public function isMixedRevisionWorkingCopy($wc_path)
556
	{
557
		$revisions = array();
558
		$status = $this->getCommand('status', '--xml --verbose {' . $wc_path . '}')->run();
559
560
		foreach ( $status->target as $target ) {
561
			if ( (string)$target['path'] !== $wc_path ) {
562
				continue;
563
			}
564
565
			foreach ( $target as $entry ) {
566
				$item_status = (string)$entry->{'wc-status'}['item'];
567
568
				if ( $item_status !== self::STATUS_UNVERSIONED ) {
569
					$revision = (int)$entry->{'wc-status'}['revision'];
570
					$revisions[$revision] = true;
571
				}
572
			}
573
		}
574
575
		return count($revisions) > 1;
576
	}
577
578
	/**
579
	 * Determines if there is a working copy on a given path.
580
	 *
581
	 * @param string $path Path.
582
	 *
583
	 * @return boolean
584
	 * @throws \InvalidArgumentException When path isn't found.
585
	 * @throws RepositoryCommandException When repository command failed to execute.
586
	 */
1 ignored issue
show
Coding Style introduced by
Expected 1 @throws tag(s) in function comment; 2 found
Loading history...
587
	public function isWorkingCopy($path)
588
	{
589
		if ( $this->isUrl($path) || !file_exists($path) || !is_dir($path) ) {
590
			throw new \InvalidArgumentException('Path "' . $path . '" not found or isn\'t a directory.');
591
		}
592
593
		try {
594
			$wc_url = $this->getWorkingCopyUrl($path);
595
		}
596
		catch ( RepositoryCommandException $e ) {
597
			if ( $e->getCode() == RepositoryCommandException::SVN_ERR_WC_NOT_WORKING_COPY ) {
598
				return false;
599
			}
600
601
			throw $e;
602
		}
603
604
		return $wc_url != '';
605
	}
606
607
}
608