Skip to content

Commit 832222d

Browse files
committed
Filters: New GitStaged filter
With the new file added in this commit, a new filter becomes available which can be used in a pre-commit git hook, as in: `phpcs --filter=gitstaged` ... to only examine the files which you are about to commit.
1 parent 4d88439 commit 832222d

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

package.xml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,7 @@ http://pear.php.net/dtd/package-2.0.xsd">
127127
<file baseinstalldir="PHP/CodeSniffer" name="ExactMatch.php" role="php" />
128128
<file baseinstalldir="PHP/CodeSniffer" name="Filter.php" role="php" />
129129
<file baseinstalldir="PHP/CodeSniffer" name="GitModified.php" role="php" />
130+
<file baseinstalldir="PHP/CodeSniffer" name="GitStaged.php" role="php" />
130131
</dir>
131132
<dir name="Generators">
132133
<file baseinstalldir="PHP/CodeSniffer" name="Generator.php" role="php" />

src/Filters/GitStaged.php

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
<?php
2+
/**
3+
* A filter to only include files that have been staged for commit in a Git repository.
4+
*
5+
* This filter is the ideal companion for your pre-commit git hook.
6+
*
7+
* @author Juliette Reinders Folmer <phpcs_nospam@adviesenzo.nl>
8+
* @copyright 2018 Juliette Reinders Folmer. All rights reserved.
9+
* @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
10+
*/
11+
12+
namespace PHP_CodeSniffer\Filters;
13+
14+
use PHP_CodeSniffer\Util;
15+
16+
class GitStaged extends ExactMatch
17+
{
18+
19+
20+
/**
21+
* Get a list of blacklisted file paths.
22+
*
23+
* @return array
24+
*/
25+
protected function getBlacklist()
26+
{
27+
return [];
28+
29+
}//end getBlacklist()
30+
31+
32+
/**
33+
* Get a list of whitelisted file paths.
34+
*
35+
* @return array
36+
*/
37+
protected function getWhitelist()
38+
{
39+
$modified = [];
40+
41+
$cmd = 'git diff --cached --name-only -- '.escapeshellarg($this->basedir);
42+
$output = [];
43+
exec($cmd, $output);
44+
45+
$basedir = $this->basedir;
46+
if (is_dir($basedir) === false) {
47+
$basedir = dirname($basedir);
48+
}
49+
50+
foreach ($output as $path) {
51+
$path = Util\Common::realpath($path);
52+
do {
53+
$modified[$path] = true;
54+
$path = dirname($path);
55+
} while ($path !== $basedir);
56+
}
57+
58+
return $modified;
59+
60+
}//end getWhitelist()
61+
62+
63+
}//end class

0 commit comments

Comments
 (0)