File size: 6,758 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const execSync = require( 'child_process' ).execSync;
const spawnSync = require( 'child_process' ).spawnSync;
const existsSync = require( 'fs' ).existsSync;
const path = require( 'path' );
const chalk = require( 'chalk' );
const _ = require( 'lodash' );

const phpcsPath = getPathForCommand( 'phpcs' );
const phpcbfPath = getPathForCommand( 'phpcbf' );

function quotedPath( pathToQuote ) {
	if ( pathToQuote.includes( ' ' ) ) {
		return `"${ pathToQuote }"`;
	}
	return pathToQuote;
}

console.log(
	'\nBy contributing to this project, you license the materials you contribute ' +
		'under the GNU General Public License v2 (or later). All materials must have ' +
		'GPLv2 compatible licenses — see docs/CONTRIBUTING.md for details.\n\n'
);

// Make quick pass over config files on every change
require( './validate-config-keys' );

/**
 * Parses the output of a git diff command into file paths.
 * @param   {string} command Command to run. Expects output like `git diff --name-only […]`
 * @returns {Array}          Paths output from git command
 */
function parseGitDiffToPathArray( command ) {
	return execSync( command, { encoding: 'utf8' } )
		.split( '\n' )
		.map( ( name ) => name.trim() )
		.filter( ( name ) => /(?:\.json|\.[jt]sx?|\.scss|\.php)$/.test( name ) );
}

function getPathForCommand( command ) {
	/**
	 * Only look for locally installed commands (phpcs, phpcbf). The reason for this is that we also require
	 * a number of dependencies, such as WordPress Coding Standards, which we cannot guarantee are installed
	 * system-wide, and system-wide installs of phpcs and phpcbf cannot find our local copies of those dependencies.
	 *
	 * If we cannot find these commands, we ask the user to run `composer install`, which will install all commands
	 * and dependencies locally.
	 * @see printPhpcsDocs
	 */
	const path_to_command = path.join( __dirname, '..', 'vendor', 'bin', command );
	return _.trim( path_to_command );
}
function linterFailure() {
	console.log(
		chalk.red( 'COMMIT ABORTED:' ),
		'The linter reported some problems. ' +
			'If you are aware of them and it is OK, ' +
			'repeat the commit command with --no-verify to avoid this check.'
	);
	process.exit( 1 );
}

function printPhpcsDocs() {
	console.log(
		chalk.red( 'COMMIT ABORTED:' ),
		'Working with PHP files in this repository requires the PHP Code Sniffer and its dependencies to be installed. Make sure you have composer installed on your machine and from the root of this repository, run `composer install`.'
	);
	process.exit( 1 );
}

function phpcsInstalled() {
	if ( existsSync( phpcsPath ) && existsSync( phpcbfPath ) ) {
		return true;
	}
	return false;
}

// determine if PHPCS is available
const phpcs = phpcsInstalled();

// grab a list of all the files staged to commit
const files = parseGitDiffToPathArray( 'git diff --cached --name-only --diff-filter=ACM' );

// grab a list of all the files with changes in the working copy.
// This list may have overlaps with the staged list if files are
// partially staged...
const dirtyFiles = new Set( parseGitDiffToPathArray( 'git diff --name-only --diff-filter=ACM' ) );

// we don't want to format any files that are partially staged or unstaged
dirtyFiles.forEach( ( file ) =>
	console.log(
		chalk.red( `${ file } will not be auto-formatted because it has unstaged changes.` )
	)
);

// Remove all the dirty files from the set to format
const toFormat = files.filter( ( file ) => ! dirtyFiles.has( file ) );

// Split the set to format into things to format with stylelint and things to format with prettier.
// We avoid prettier on sass files because of outstanding bugs in how prettier handles
// single line comments. We also split on PHP files for PHPCS handling.
const {
	toPrettify = [],
	toStylelintfix = [],
	toPHPCBF = [],
} = _.groupBy( toFormat, ( file ) => {
	switch ( true ) {
		case file.endsWith( '.scss' ):
			return 'toStylelintfix';
		case file.endsWith( '.php' ):
			return 'toPHPCBF';
		default:
			return 'toPrettify';
	}
} );

// Format JavaScript and TypeScript files with prettier, then re-stage them. Swallow the output.
toPrettify.forEach( ( file ) => console.log( `Prettier formatting staged file: ${ file }` ) );
if ( toPrettify.length ) {
	// chunk this up into multiple runs if we have a lot of files to avoid E2BIG
	_.forEach( _.chunk( toPrettify, 500 ), ( chunk ) => {
		execSync(
			`./node_modules/.bin/prettier --ignore-path .eslintignore --write ${ chunk.join( ' ' ) }`
		);
		execSync( `git add ${ chunk.join( ' ' ) }` );
	} );
}

// Format the sass files with stylelint and then re-stage them. Swallow the output.
toStylelintfix.forEach( ( file ) => console.log( `stylelint formatting staged file: ${ file }` ) );
if ( toStylelintfix.length ) {
	spawnSync( `./node_modules/.bin/stylelint --fix ${ toStylelintfix.join( ' ' ) }` );
	execSync( `git add ${ toStylelintfix.join( ' ' ) }` );
}

// Format the PHP files with PHPCBF and then re-stage them. Swallow the output.
toPHPCBF.forEach( ( file ) => console.log( `PHPCBF formatting staged file: ${ file }` ) );
if ( toPHPCBF.length ) {
	if ( phpcs ) {
		try {
			execSync(
				`${ quotedPath( phpcbfPath ) } --standard=apps/phpcs.xml ${ toPHPCBF.join( ' ' ) }`
			);
		} catch ( error ) {
			// PHPCBF returns a `0` or `1` exit code on success, and `2` on failures. ¯\_(ツ)_/¯
			// https://github.com/squizlabs/PHP_CodeSniffer/blob/HEAD/src/Runner.php#L210
			if ( 2 === error.status ) {
				linterFailure();
			}
		}
		execSync( `git add ${ toPHPCBF.join( ' ' ) }` );
	} else {
		printPhpcsDocs();
	}
}

// Now run the linters over everything staged to commit (excepting JSON), even if they are partially staged
const {
	toEslint = [],
	toStylelint = [],
	toPHPCS = [],
} = _.groupBy(
	files.filter( ( file ) => ! file.endsWith( '.json' ) ),
	( file ) => {
		switch ( true ) {
			case file.endsWith( '.scss' ):
				return 'toStylelint';
			case file.endsWith( '.php' ):
				return 'toPHPCS';
			default:
				return 'toEslint';
		}
	}
);

// first stylelint
if ( toStylelint.length ) {
	const lintResult = spawnSync( './node_modules/.bin/stylelint', [ ...toStylelint ], {
		shell: true,
		stdio: 'inherit',
	} );

	if ( lintResult.status ) {
		linterFailure();
	}
}

// then eslint
if ( toEslint.length ) {
	const lintResult = spawnSync( './node_modules/.bin/eslint', [ '--quiet', ...toEslint ], {
		shell: true,
		stdio: 'inherit',
	} );

	if ( lintResult.status ) {
		linterFailure();
	}
}

// and finally PHPCS
if ( toPHPCS.length ) {
	if ( phpcs ) {
		const lintResult = spawnSync(
			quotedPath( phpcsPath ),
			[ '--standard=apps/phpcs.xml', ...toPHPCS ],
			{
				shell: true,
				stdio: 'inherit',
			}
		);

		if ( lintResult.status ) {
			linterFailure();
		}
	} else {
		printPhpcsDocs();
	}
}