1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Exec.php |
4
|
|
|
* |
5
|
|
|
* @package ProjectVersioner |
6
|
|
|
* @subpackage Reader |
7
|
|
|
*/ |
8
|
|
|
|
9
|
|
|
namespace Naneau\ProjectVersioner\Reader\Git; |
10
|
|
|
|
11
|
|
|
use Naneau\ProjectVersioner\ReaderInterface; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* Exec |
15
|
|
|
* |
16
|
|
|
* Base class for exec based git reading |
17
|
|
|
* |
18
|
|
|
* @category Naneau |
19
|
|
|
* @package ProjectVersioner |
20
|
|
|
* @subpackage Reader |
21
|
|
|
*/ |
22
|
|
|
abstract class Exec implements ReaderInterface |
23
|
|
|
{ |
24
|
|
|
/** |
25
|
|
|
* {@inheritDoc} |
26
|
|
|
**/ |
27
|
|
|
public function canRead($directory) |
28
|
|
|
{ |
29
|
|
|
return $this->canExec( |
30
|
|
|
$this->getCommandForDirectory($directory), |
31
|
|
|
$directory |
32
|
|
|
); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* {@inheritDoc} |
37
|
|
|
**/ |
38
|
|
|
public function read($directory) |
39
|
|
|
{ |
40
|
|
|
return $this->exec( |
41
|
|
|
$this->getCommandForDirectory($directory) |
42
|
|
|
); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* Get the command for a directory |
47
|
|
|
* |
48
|
|
|
* @param string $directory |
49
|
|
|
* @return string |
50
|
|
|
**/ |
51
|
|
|
abstract protected function getCommandForDirectory($directory); |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* Can a git command be executed? |
55
|
|
|
* |
56
|
|
|
* @param string $command |
57
|
|
|
* @param string $directory |
58
|
|
|
* @return void |
59
|
|
|
**/ |
60
|
|
|
private function canExec($command, $directory) |
61
|
|
|
{ |
62
|
|
|
// We rely on exec, so it needs to exist |
63
|
|
|
if (!function_exists('exec')) { |
64
|
|
|
return false; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
// (Cheap) check for git directory |
68
|
|
|
if (!is_dir($directory . '/.git')) { |
69
|
|
|
return false; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
// Try to exec() |
73
|
|
|
$output = array(); |
74
|
|
|
$return = 0; |
75
|
|
|
@exec($command, $output, $return); |
|
|
|
|
76
|
|
|
|
77
|
|
|
// Check return code |
78
|
|
|
return $return === 0; |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
/** |
82
|
|
|
* Execute a git command and return first line of output |
83
|
|
|
* |
84
|
|
|
* @param string $command |
85
|
|
|
* @return string |
86
|
|
|
**/ |
87
|
|
|
private function exec($command) |
88
|
|
|
{ |
89
|
|
|
$output = array(); |
90
|
|
|
$return = 0; |
91
|
|
|
|
92
|
|
|
// Try to find last commit hash |
93
|
|
|
@exec($command, $output, $return); |
|
|
|
|
94
|
|
|
|
95
|
|
|
// Make sure it worked |
96
|
|
|
if ($return !== 0) { |
97
|
|
|
throw new RuntimeException(sprintf( |
98
|
|
|
'Can not parse version from git using %s', |
99
|
|
|
$command |
100
|
|
|
)); |
101
|
|
|
} |
102
|
|
|
|
103
|
|
|
// Return first line of output |
104
|
|
|
return $output[0]; |
105
|
|
|
} |
106
|
|
|
} |
107
|
|
|
|
If you suppress an error, we recommend checking for the error condition explicitly: