summaryrefslogtreecommitdiff
path: root/vendor/oojs/oojs-ui/build/tasks/typos.js
blob: 6c0bb4eea0e41eb1ce9bce7363820fed528baeec (plain)
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
/*!
 * Check files from 'src' for typos; fail if any are found.
 */

/*jshint node:true */
module.exports = function ( grunt ) {

	grunt.registerMultiTask( 'typos', function () {
		var typosData, typosCSRegExp, typosCIRegExp, file,
			options = this.options( {
				typos: 'typos.json'
			} ),
			files = this.filesSrc,
			fileCount = files.length,
			typosJSON = grunt.file.read( options.typos ),
			typoCount = 0,
			ok = true;

		try {
			typosData = JSON.parse( typosJSON );
		} catch ( e ) {
			grunt.log.error( 'Could not parse ' + options.typos + ': ' + e );
		}

		typosData.caseSensitive = typosData.caseSensitive || [];
		typosData.caseInsensitive = typosData.caseInsensitive || [];

		typoCount += typosData.caseSensitive.length + typosData.caseInsensitive.length;

		function patternMap( typo ) {
			return typo[ 0 ];
		}

		if ( typosData.caseSensitive.length ) {
			typosCSRegExp = new RegExp(
				'(' + typosData.caseSensitive.map( patternMap ).join( '|' )  + ')', 'g'
			);
		}

		if ( typosData.caseInsensitive.length ) {
			typosCIRegExp = new RegExp(
				'(' + typosData.caseInsensitive.map( patternMap ).join( '|' )  + ')', 'gi'
			);
		}

		function findTypo( line, lineNumber, filepath, typos, flags ) {
			// Check each pattern to find the replacement
			typos.forEach( function ( typo ) {
				var replace,
					pattern = new RegExp( typo[ 0 ], flags ),
					matches = line.match( pattern );

				if ( matches ) {
					ok = false;
					replace = matches[ 0 ].replace( pattern, typo[ 1 ], flags );
					grunt.log.error(
						'File "' + filepath + '" contains typo "' + matches[ 0 ] + '" on line ' + lineNumber +
						', did you mean "' + replace + '"?'
					);
				}
			} );
		}

		files.forEach( function ( filepath ) {
			if ( grunt.file.isDir( filepath ) ) {
				fileCount--;
				return;
			}
			file = grunt.file.read( filepath );
			file.split( '\n' ).forEach( function ( line, lineNumber ) {
				// Check for any typos on the line with group expressions
				if ( typosCSRegExp && typosCSRegExp.test( line ) ) {
					findTypo( line, lineNumber, filepath, typosData.caseSensitive, 'g' );
				}
				if ( typosCIRegExp && typosCIRegExp.test( line ) ) {
					findTypo( line, lineNumber, filepath, typosData.caseInsensitive, 'gi' );
				}
			} );
		} );

		if ( !ok ) {
			return false;
		}

		grunt.log.ok( 'No typos found; ' +
			fileCount + ' file' + ( fileCount !== 1 ? 's' : '' ) + ' checked for ' +
			typoCount + ' typo' + ( typoCount !== 1 ? 's' : '' ) + '.' );
	} );
};