-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpre-commit
319 lines (262 loc) · 8.91 KB
/
pre-commit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
#!/usr/bin/php
<?php
require __DIR__ . '/../../vendor/autoload.php';
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Process\ProcessBuilder;
use Symfony\Component\Console\Application;
class CodeQualityTool extends Application
{
const PHP_FILES = '/(\.php)$/';
const PHP_FILES_IN_SRC = '/^src\/(.*)(\.php)$/';
const PHP_FILES_IN_CLASSES = '/^classes\/(.*)(\.php)$/';
/**
* @var OutputInterface
*/
private $output;
/**
* @var InputInterface
*/
private $input;
/**
* @var array
*/
private $forbiddenDebugCodes = [
// Prevent committing 'debugger' commands in JS:
'js/coffee' => [
'filePattern' => '\.(js|coffee)(\..+)?$',
'forbidden' => ['debugger'],
],
// Prevent committing some common debugging stuff in PHP files:
'php' => [
'filePattern' => '\.(php|phtml)(\..+)?$',
'forbidden' => [
'var_dump',
'ladybug_dump',
'print_r',
'if\ \(true\ \|\|',
'if\ \(false\ \&\&',
'if\ \(true\)',
'if\ \(false\)',
],
],
'twig' => [
'filePattern' => '\.(html\.twig)$',
'forbidden' => [
'dump',
],
],
// Prevent committing unresolved merge conflicts anywhere:
'global' => [
'filePattern' => '.*',
'forbidden' => ['\<\<\<\<', '\>\>\>\>',],
],
];
/**
* @var array
*/
private $linters = [
// Run jshint on all committed JS files:
'js' => [
'filePattern' => '/(src\/js\/[a-zA-Z0-9-]*\.js)/',
'command' => '/usr/local/bin/jshint',
'arguments' => null,
],
// Run php linting on all committed PHP files:
'php' => [
'filePattern' => '/\.php/',
'command' => '/usr/bin/php',
'arguments' => '-l',
],
];
public function __construct()
{
parent::__construct('Code Quality Tool', '1.0.0');
}
/**
* @param InputInterface $input
* @param OutputInterface $output
*/
public function doRun(InputInterface $input, OutputInterface $output)
{
$this->input = $input;
$this->output = $output;
$output->writeln('<fg=white;options=bold;bg=red>Intaro Code Quality Tool</fg=white;options=bold;bg=red>');
$output->writeln('<info>Fetching files</info>');
$files = $this->extractCommitedFiles();
$output->writeln('<info>Running lint</info>');
$result = $this->lint($files);
if ($result) {
throw new Exception('There are some ' . $result .' syntax errors!');
}
$output->writeln(sprintf(
'<info>Checking for forgotten debugs or unresolved merge conflicts in %s</info>',
implode(', ', array_keys($this->forbiddenDebugCodes))
));
if (!$this->checkDebugCode()) {
throw new Exception(sprintf('There is forgotten debug code or an unresolved merge conflict!'));
}
$output->writeln('<info>Good job dude!</info>');
}
private function checkComposer($files)
{
$composerJsonDetected = false;
$composerLockDetected = false;
foreach ($files as $file) {
if ($file === 'composer.json') {
$composerJsonDetected = true;
}
if ($file === 'composer.lock') {
$composerLockDetected = true;
}
}
if ($composerJsonDetected && !$composerLockDetected) {
throw new Exception('composer.lock must be commited if composer.json is modified!');
}
}
private function extractCommitedFiles()
{
$output = array();
$rc = 0;
exec('git rev-parse --verify HEAD 2> /dev/null', $output, $rc);
$against = '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
if ($rc == 0) {
$against = 'HEAD';
}
exec("git diff-index --cached --name-status $against | egrep '^(A|M)' | awk '{print $2;}'", $output);
return $output;
}
private function lint($files)
{
$failure = false;
foreach ($this->linters as $language => $config) {
foreach ($files as $file) {
if (!preg_match($config['filePattern'], $file)) {
continue;
}
$processBuilder = new ProcessBuilder(array($config['command'], $config['arguments'], $file));
$process = $processBuilder->getProcess();
$process->run();
if (!$process->isSuccessful()) {
$this->output->writeln($file);
if ($language == 'js') {
$this->output->writeln(sprintf('<error>Errors: %s</error>', $process->getOutput()));
} else {
$this->output->writeln(sprintf('<error>Errors: %s</error>', $process->getErrorOutput()));
}
$failure = $language;
}
}
}
return $failure;
}
private function codeStyle(array $files)
{
$succeed = true;
foreach ($files as $file) {
$phpFile = preg_match(self::PHP_FILES, $file);
if (!$phpFile) {
continue;
}
$fixers = 'contrib';
$processBuilder = new ProcessBuilder(array(
'php',
__DIR__ . '/../../vendor/bin/php-cs-fixer',
'--dry-run',
'--level=psr2',
'--verbose',
'fix',
$file,
));
$processBuilder->setWorkingDirectory(getcwd());
$phpCsFixer = $processBuilder->getProcess();
$phpCsFixer->run();
if (!$phpCsFixer->isSuccessful()) {
$this->output->writeln(sprintf('<error>%s</error>', trim($phpCsFixer->getOutput())));
if ($succeed) {
$succeed = false;
}
}
}
return $succeed;
}
private function codeStylePsr(array $files)
{
$succeed = true;
$needle = self::PHP_FILES_IN_SRC;
foreach ($files as $file) {
if (!preg_match($needle, $file)) {
continue;
}
$processBuilder = new ProcessBuilder(array('php', __DIR__ . '/../../vendor/bin/phpcs', '--encoding=utf-8', '--standard=PSR2', $file));
$processBuilder->setWorkingDirectory(getcwd());
$phpCsFixer = $processBuilder->getProcess();
$phpCsFixer->run();
if (!$phpCsFixer->isSuccessful()) {
$this->output->writeln(sprintf('<error>%s</error>', trim($phpCsFixer->getOutput())));
if ($succeed) {
$succeed = false;
}
}
}
return $succeed;
}
private function checkDebugCode()
{
$succeed = true;
foreach ($this->forbiddenDebugCodes as $data) {
$response = $this->findDebugCode($data['forbidden'], $data['filePattern']);
if ($response['statusCode'] == 1) {
$this->output->writeln(
sprintf(
'<error>%s</error>',
implode(PHP_EOL, $response['output'])
)
);
$succeed = false;
}
}
return $succeed;
}
/**
* @param array $forbidden
* @param string $filePattern
*
* @return array [int 'statusCode', array 'outputRows']
*/
private function findDebugCode(array $forbidden, $filePattern)
{
$response = ['statusCode' => 0];
foreach ($forbidden as $snippet) {
if ($response['statusCode'] == 1) {
return $response;
}
$script = sprintf(
"git diff --cached --name-only | \
grep -E '%s' | \
GREP_COLOR='4;5;37;41' xargs grep --color --with-filename -n %s \
&& echo 'COMMIT REJECTED Found %s references. \
Please remove them before commiting' && exit 1",
$filePattern,
$snippet,
$snippet
);
exec($script, $response['output'], $response['statusCode']);
}
return $response;
}
/**
* @return bool
*/
private function runPHPUnit()
{
$output = shell_exec(__DIR__.'/../../vendor/bin/phpunit');
if (preg_match('/FAILURES|Fatal/' , $output)) {
$this->output->writeln(sprintf('<error>%s</error>', trim($output)));
return false;
}
return true;
}
}
$console = new CodeQualityTool();
$console->run();