forked from oppia/oppia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pre_commit_linter.py
1931 lines (1682 loc) · 73.7 KB
/
pre_commit_linter.py
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding: utf-8
#
# Copyright 2014 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Pre-commit script for Oppia.
This script lints Python and JavaScript code, and prints a
list of lint errors to the terminal. If the directory path is passed,
it will lint all Python and JavaScript files in that directory; otherwise,
it will only lint files that have been touched in this commit.
This script ignores all filepaths contained within .eslintignore.
IMPORTANT NOTES:
1. Before running this script, you must install third-party dependencies by
running
bash scripts/start.sh
at least once.
=====================
CUSTOMIZATION OPTIONS
=====================
1. To lint only files that have been touched in this commit
python scripts/pre_commit_linter.py
2. To lint all files in the folder or to lint just a specific file
python scripts/pre_commit_linter.py --path filepath
3. To lint a specific list of files (*.js/*.py only). Separate files by spaces
python scripts/pre_commit_linter.py --files file_1 file_2 ... file_n
Note that the root folder MUST be named 'oppia'.
"""
# Pylint has issues with the import order of argparse.
# pylint: disable=wrong-import-order
import HTMLParser
import StringIO
import argparse
import ast
import contextlib
import fnmatch
import multiprocessing
import os
import re
import subprocess
import sys
import threading
import time
import docstrings_checker # pylint: disable=relative-import
# pylint: enable=wrong-import-order
_PARSER = argparse.ArgumentParser()
_EXCLUSIVE_GROUP = _PARSER.add_mutually_exclusive_group()
_EXCLUSIVE_GROUP.add_argument(
'--path',
help='path to the directory with files to be linted',
action='store')
_EXCLUSIVE_GROUP.add_argument(
'--files',
nargs='+',
help='specific files to be linted. Space separated list',
action='store')
BAD_PATTERNS = {
'__author__': {
'message': 'Please remove author tags from this file.',
'excluded_files': (),
'excluded_dirs': ()},
'datetime.datetime.now()': {
'message': 'Please use datetime.datetime.utcnow() instead of'
'datetime.datetime.now().',
'excluded_files': (),
'excluded_dirs': ()},
'\t': {
'message': 'Please use spaces instead of tabs.',
'excluded_files': (),
'excluded_dirs': (
'assets/i18n/', 'core/tests/build_sources/assets/')},
'\r': {
'message': 'Please make sure all files only have LF endings (no CRLF).',
'excluded_files': (),
'excluded_dirs': ()},
'<<<<<<<': {
'message': 'Please fully resolve existing merge conflicts.',
'excluded_files': (),
'excluded_dirs': ()},
'>>>>>>>': {
'message': 'Please fully resolve existing merge conflicts.',
'excluded_files': (),
'excluded_dirs': ()},
'glyphicon': {
'message': 'Please use equivalent material-icons '
'instead of glyphicons.',
'excluded_files': (),
'excluded_dirs': ()}
}
BAD_PATTERNS_JS_REGEXP = [
{
'regexp': r'\b(browser.explore)\(',
'message': 'In tests, please do not use browser.explore().',
'excluded_files': (),
'excluded_dirs': ()
},
{
'regexp': r'\b(browser.pause)\(',
'message': 'In tests, please do not use browser.pause().',
'excluded_files': (),
'excluded_dirs': ()
},
{
'regexp': r'\b(browser.sleep)\(',
'message': 'In tests, please do not use browser.sleep().',
'excluded_files': (),
'excluded_dirs': ()
},
{
'regexp': r'\b(browser.waitForAngular)\(',
'message': 'In tests, please do not use browser.waitForAngular().',
'excluded_files': (),
'excluded_dirs': ()
},
{
'regexp': r'\b(ddescribe|fdescribe)\(',
'message': 'In tests, please use \'describe\' instead of \'ddescribe\''
'or \'fdescribe\'',
'excluded_files': (),
'excluded_dirs': ()
},
{
'regexp': r'\b(iit|fit)\(',
'message': 'In tests, please use \'it\' instead of \'iit\' or \'fit\'',
'excluded_files': (),
'excluded_dirs': ()
},
{
'regexp': r'templateUrl: \'',
'message': 'The directives must be directly referenced.',
'excluded_files': (
'core/templates/dev/head/pages/exploration_player/'
'FeedbackPopupDirective.js'
),
'excluded_dirs': (
'extensions/answer_summarizers/',
'extensions/classifiers/',
'extensions/dependencies/',
'extensions/value_generators/',
'extensions/visualizations/')
},
{
'regexp': r'\$parent',
'message': 'Please do not access parent properties ' +
'using $parent. Use the scope object' +
'for this purpose.',
'excluded_files': (),
'excluded_dirs': ()
}
]
BAD_LINE_PATTERNS_HTML_REGEXP = [
{
'regexp': r'text\/ng-template',
'message': 'The directives must be directly referenced.',
'excluded_files': (),
'excluded_dirs': (
'extensions/answer_summarizers/',
'extensions/classifiers/',
'extensions/objects/',
'extensions/value_generators/')
},
{
'regexp': r'[ \t]+$',
'message': 'There should not be any trailing whitespaces.',
'excluded_files': (),
'excluded_dirs': ()
}
]
BAD_PATTERNS_PYTHON_REGEXP = [
{
'regexp': r'print ',
'message': 'Please do not use print statement.',
'excluded_files': (
'core/tests/test_utils.py',
'core/tests/performance_framework/perf_domain.py'),
'excluded_dirs': ('scripts/',)
},
{
'regexp': r'# pylint:\s*disable=[A-Z][0-9]{4}',
'message': 'Please remove pylint exclusion if it is unnecessary, or '
'make it human readable with a sentence instead of an id. '
'The id-to-message list can be seen '
'here->http://pylint-messages.wikidot.com/all-codes',
'excluded_files': (),
'excluded_dirs': ()
},
{
'regexp': r'self.assertEquals\(',
'message': 'Please do not use self.assertEquals method. ' +
'This method has been deprecated. Instead use ' +
'self.assertEqual method.',
'excluded_files': (),
'excluded_dirs': ()
}
]
REQUIRED_STRINGS_CONSTANTS = {
'DEV_MODE: true': {
'message': 'Please set the DEV_MODE variable in constants.js'
'to true before committing.',
'excluded_files': ()
}
}
ALLOWED_TERMINATING_PUNCTUATIONS = ['.', '?', '}', ']', ')']
EXCLUDED_PHRASES = [
'utf', 'pylint:', 'http://', 'https://', 'scripts/', 'extract_node']
EXCLUDED_PATHS = (
'third_party/*', 'build/*', '.git/*', '*.pyc', 'CHANGELOG',
'integrations/*', 'integrations_dev/*', '*.svg', '*.gif',
'*.png', '*.zip', '*.ico', '*.jpg', '*.min.js',
'assets/scripts/*', 'core/tests/data/*', 'core/tests/build_sources/*',
'*.mp3', '*.mp4')
GENERATED_FILE_PATHS = (
'extensions/interactions/LogicProof/static/js/generatedDefaultData.js',
'extensions/interactions/LogicProof/static/js/generatedParser.js',
'core/templates/dev/head/expressions/ExpressionParserService.js')
CONFIG_FILE_PATHS = (
'core/tests/.browserstack.env.example',
'core/tests/protractor.conf.js',
'core/tests/karma.conf.js',
'core/templates/dev/head/mathjaxConfig.js',
'assets/constants.js',
'assets/rich_text_components_definitions.js')
if not os.getcwd().endswith('oppia'):
print ''
print 'ERROR Please run this script from the oppia root directory.'
_PARENT_DIR = os.path.abspath(os.path.join(os.getcwd(), os.pardir))
_PYLINT_PATH = os.path.join(_PARENT_DIR, 'oppia_tools', 'pylint-1.9.3')
if not os.path.exists(_PYLINT_PATH):
print ''
print 'ERROR Please run start.sh first to install pylint '
print ' and its dependencies.'
sys.exit(1)
_PATHS_TO_INSERT = [
_PYLINT_PATH,
os.getcwd(),
os.path.join(
_PARENT_DIR, 'oppia_tools', 'google_appengine_1.9.67',
'google_appengine', 'lib', 'webapp2-2.3'),
os.path.join(
_PARENT_DIR, 'oppia_tools', 'google_appengine_1.9.67',
'google_appengine', 'lib', 'yaml-3.10'),
os.path.join(
_PARENT_DIR, 'oppia_tools', 'google_appengine_1.9.67',
'google_appengine', 'lib', 'jinja2-2.6'),
os.path.join(
_PARENT_DIR, 'oppia_tools', 'google_appengine_1.9.67',
'google_appengine'),
os.path.join(_PARENT_DIR, 'oppia_tools', 'webtest-1.4.2'),
os.path.join(_PARENT_DIR, 'oppia_tools', 'browsermob-proxy-0.7.1'),
os.path.join(_PARENT_DIR, 'oppia_tools', 'esprima-4.0.1'),
os.path.join(_PARENT_DIR, 'oppia_tools', 'pycodestyle-2.3.1'),
os.path.join(_PARENT_DIR, 'oppia_tools', 'pylint-quotes-0.1.9'),
os.path.join(_PARENT_DIR, 'oppia_tools', 'selenium-2.53.2'),
os.path.join(_PARENT_DIR, 'oppia_tools', 'PIL-1.1.7'),
os.path.join('third_party', 'gae-pipeline-1.9.17.0'),
os.path.join('third_party', 'bleach-1.2.2'),
os.path.join('third_party', 'beautifulsoup4-4.6.0'),
os.path.join('third_party', 'gae-mapreduce-1.9.17.0'),
os.path.join('third_party', 'mutagen-1.38'),
os.path.join('third_party', 'gae-cloud-storage-1.9.15.0'),
]
for path in _PATHS_TO_INSERT:
sys.path.insert(0, path)
# pylint: disable=wrong-import-order
# pylint: disable=wrong-import-position
import isort # isort:skip
import pycodestyle # isort:skip
import esprima # isort:skip
from pylint import lint # isort:skip
# pylint: enable=wrong-import-order
# pylint: enable=wrong-import-position
_MESSAGE_TYPE_SUCCESS = 'SUCCESS'
_MESSAGE_TYPE_FAILED = 'FAILED'
_TARGET_STDOUT = StringIO.StringIO()
class FileCache(object):
"""Provides thread-safe access to cached file content."""
_CACHE_DATA_DICT = {}
_CACHE_LOCK_DICT = {}
_CACHE_LOCK_DICT_LOCK = threading.Lock()
@classmethod
def read(cls, filename, mode='r'):
"""Returns the data read from the file.
Args:
filename: str. The file name from which data is to be read.
mode: str. The mode in which the file is to be opened.
Returns:
str. The data read from the file.
"""
return cls._get_data(filename, mode)[0]
@classmethod
def readlines(cls, filename, mode='r'):
"""Returns the tuple containing data line by line as read from the
file.
Args:
filename: str. The file name from which data is to be read.
mode: str. The mode in which the file is to be opened.
Returns:
tuple(str). The tuple containing data line by line as read from the
file.
"""
return cls._get_data(filename, mode)[1]
@classmethod
def _get_cache_lock(cls, key):
"""Returns the cache lock corresponding to the given key.
Args:
key: str. The key corresponding to which the cache lock is to be
found.
Returns:
str. The cache lock corresponding to the given key.
"""
if key not in cls._CACHE_LOCK_DICT:
with cls._CACHE_LOCK_DICT_LOCK:
if key not in cls._CACHE_LOCK_DICT:
cls._CACHE_LOCK_DICT[key] = threading.Lock()
return cls._CACHE_LOCK_DICT[key]
@classmethod
def _get_data(cls, filename, mode):
"""Returns the collected data from the file corresponding to the given
filename.
Args:
filename: str. The file name from which data is to be read.
mode: str. The mode in which the file is to be opened.
Returns:
tuple(str, tuple(str)). The tuple containing data read from the file
as first element and tuple containing the text line by line as
second element.
"""
key = (filename, mode)
if key not in cls._CACHE_DATA_DICT:
with cls._get_cache_lock(key):
if key not in cls._CACHE_DATA_DICT:
with open(filename, mode) as f:
lines = f.readlines()
cls._CACHE_DATA_DICT[key] = (''.join(lines), tuple(lines))
return cls._CACHE_DATA_DICT[key]
def _is_filename_excluded_for_bad_patterns_check(pattern, filename):
"""Checks if file is excluded from the bad patterns check.
Args:
pattern: str. The pattern to be checked against.
filename: str. Name of the file.
Returns:
bool: Whether to exclude the given file from this
particular pattern check.
"""
return (any(filename.startswith(bad_pattern)
for bad_pattern in BAD_PATTERNS[pattern]['excluded_dirs'])
or filename in BAD_PATTERNS[pattern]['excluded_files'])
def _get_changed_filenames():
"""Returns a list of modified files (both staged and unstaged)
Returns:
a list of filenames of modified files.
"""
unstaged_files = subprocess.check_output([
'git', 'diff', '--name-only',
'--diff-filter=ACM']).splitlines()
staged_files = subprocess.check_output([
'git', 'diff', '--cached', '--name-only',
'--diff-filter=ACM']).splitlines()
return unstaged_files + staged_files
def _get_all_files_in_directory(dir_path, excluded_glob_patterns):
"""Recursively collects all files in directory and
subdirectories of specified path.
Args:
dir_path: str. Path to the folder to be linted.
excluded_glob_patterns: set(str). Set of all glob patterns
to be excluded.
Returns:
a list of files in directory and subdirectories without excluded files.
"""
files_in_directory = []
for _dir, _, files in os.walk(dir_path):
for file_name in files:
filename = os.path.relpath(
os.path.join(_dir, file_name), os.getcwd())
if not any([fnmatch.fnmatch(filename, gp) for gp in
excluded_glob_patterns]):
files_in_directory.append(filename)
return files_in_directory
@contextlib.contextmanager
def _redirect_stdout(new_target):
"""Redirect stdout to the new target.
Args:
new_target: TextIOWrapper. The new target to which stdout is redirected.
Yields:
TextIOWrapper. The new target.
"""
old_target = sys.stdout
sys.stdout = new_target
try:
yield new_target
finally:
sys.stdout = old_target
def _lint_css_files(
node_path, stylelint_path, config_path, files_to_lint, stdout, result):
"""Prints a list of lint errors in the given list of CSS files.
Args:
node_path: str. Path to the node binary.
stylelint_path: str. Path to the Stylelint binary.
config_path: str. Path to the configuration file.
files_to_lint: list(str). A list of filepaths to lint.
stdout: multiprocessing.Queue. A queue to store Stylelint outputs.
result: multiprocessing.Queue. A queue to put results of test.
"""
start_time = time.time()
num_files_with_errors = 0
num_css_files = len(files_to_lint)
if not files_to_lint:
result.put('')
print 'There are no CSS files to lint.'
return
print 'Total css files: ', num_css_files
stylelint_cmd_args = [
node_path, stylelint_path, '--config=' + config_path]
result_list = []
for _, filename in enumerate(files_to_lint):
print 'Linting: ', filename
proc_args = stylelint_cmd_args + [filename]
proc = subprocess.Popen(
proc_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
linter_stdout, linter_stderr = proc.communicate()
if linter_stderr:
print 'LINTER FAILED'
print linter_stderr
sys.exit(1)
if linter_stdout:
num_files_with_errors += 1
result_list.append(linter_stdout)
print linter_stdout
stdout.put(linter_stdout)
if num_files_with_errors:
for error in result_list:
result.put(error)
result.put('%s %s CSS file' % (
_MESSAGE_TYPE_FAILED, num_files_with_errors))
else:
result.put('%s %s CSS file linted (%.1f secs)' % (
_MESSAGE_TYPE_SUCCESS, num_css_files, time.time() - start_time))
print 'CSS linting finished.'
def _lint_js_files(
node_path, eslint_path, files_to_lint, stdout, result):
"""Prints a list of lint errors in the given list of JavaScript files.
Args:
node_path: str. Path to the node binary.
eslint_path: str. Path to the ESLint binary.
files_to_lint: list(str). A list of filepaths to lint.
stdout: multiprocessing.Queue. A queue to store ESLint outputs.
result: multiprocessing.Queue. A queue to put results of test.
"""
start_time = time.time()
num_files_with_errors = 0
num_js_files = len(files_to_lint)
if not files_to_lint:
result.put('')
print 'There are no JavaScript files to lint.'
return
print 'Total js files: ', num_js_files
eslint_cmd_args = [node_path, eslint_path, '--quiet']
result_list = []
for _, filename in enumerate(files_to_lint):
print 'Linting: ', filename
proc_args = eslint_cmd_args + [filename]
proc = subprocess.Popen(
proc_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
linter_stdout, linter_stderr = proc.communicate()
if linter_stderr:
print 'LINTER FAILED'
print linter_stderr
sys.exit(1)
if linter_stdout:
num_files_with_errors += 1
result_list.append(linter_stdout)
stdout.put(linter_stdout)
if num_files_with_errors:
for error in result_list:
result.put(error)
result.put('%s %s JavaScript files' % (
_MESSAGE_TYPE_FAILED, num_files_with_errors))
else:
result.put('%s %s JavaScript files linted (%.1f secs)' % (
_MESSAGE_TYPE_SUCCESS, num_js_files, time.time() - start_time))
print 'Js linting finished.'
def _lint_py_files(config_pylint, config_pycodestyle, files_to_lint, result):
"""Prints a list of lint errors in the given list of Python files.
Args:
config_pylint: str. Path to the .pylintrc file.
config_pycodestyle: str. Path to the tox.ini file.
files_to_lint: list(str). A list of filepaths to lint.
result: multiprocessing.Queue. A queue to put results of test.
"""
start_time = time.time()
are_there_errors = False
num_py_files = len(files_to_lint)
if not files_to_lint:
result.put('')
print 'There are no Python files to lint.'
return
print 'Linting %s Python files' % num_py_files
_batch_size = 50
current_batch_start_index = 0
while current_batch_start_index < len(files_to_lint):
# Note that this index is an exclusive upper bound -- i.e., the current
# batch of files ranges from 'start_index' to 'end_index - 1'.
current_batch_end_index = min(
current_batch_start_index + _batch_size, len(files_to_lint))
current_files_to_lint = files_to_lint[
current_batch_start_index: current_batch_end_index]
print 'Linting Python files %s to %s...' % (
current_batch_start_index + 1, current_batch_end_index)
with _redirect_stdout(_TARGET_STDOUT):
# This line invokes Pylint and prints its output
# to the target stdout.
pylinter = lint.Run(
current_files_to_lint + [config_pylint],
exit=False).linter
# These lines invoke Pycodestyle and print its output
# to the target stdout.
style_guide = pycodestyle.StyleGuide(config_file=config_pycodestyle)
pycodestyle_report = style_guide.check_files(
paths=current_files_to_lint)
if pylinter.msg_status != 0 or pycodestyle_report.get_count() != 0:
result.put(_TARGET_STDOUT.getvalue())
are_there_errors = True
current_batch_start_index = current_batch_end_index
if are_there_errors:
result.put('%s Python linting failed' % _MESSAGE_TYPE_FAILED)
else:
result.put('%s %s Python files linted (%.1f secs)' % (
_MESSAGE_TYPE_SUCCESS, num_py_files, time.time() - start_time))
print 'Python linting finished.'
def _lint_html_files(all_files):
"""This function is used to check HTML files for linting errors."""
parent_dir = os.path.abspath(os.path.join(os.getcwd(), os.pardir))
node_path = os.path.join(
parent_dir, 'oppia_tools', 'node-6.9.1', 'bin', 'node')
htmllint_path = os.path.join(
parent_dir, 'node_modules', 'htmllint-cli', 'bin', 'cli.js')
error_summary = []
total_error_count = 0
summary_messages = []
htmllint_cmd_args = [node_path, htmllint_path, '--rc=.htmllintrc']
html_files_to_lint = [
filename for filename in all_files if filename.endswith('.html')]
print 'Starting HTML linter...'
print '----------------------------------------'
print ''
for filename in html_files_to_lint:
proc_args = htmllint_cmd_args + [filename]
print 'Linting %s file' % filename
with _redirect_stdout(_TARGET_STDOUT):
proc = subprocess.Popen(
proc_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
linter_stdout, _ = proc.communicate()
# This line splits the output of the linter and extracts digits
# from it. The digits are stored in a list. The second last digit
# in the list represents the number of errors in the file.
error_count = (
[int(s) for s in linter_stdout.split() if s.isdigit()][-2])
if error_count:
error_summary.append(error_count)
print linter_stdout
with _redirect_stdout(_TARGET_STDOUT):
print '----------------------------------------'
for error_count in error_summary:
total_error_count += error_count
total_files_checked = len(html_files_to_lint)
if total_error_count:
print '(%s files checked, %s errors found)' % (
total_files_checked, total_error_count)
summary_message = '%s HTML linting failed' % (
_MESSAGE_TYPE_FAILED)
summary_messages.append(summary_message)
else:
summary_message = '%s HTML linting passed' % (
_MESSAGE_TYPE_SUCCESS)
summary_messages.append(summary_message)
print ''
print summary_message
print 'HTML linting finished.'
print ''
return summary_messages
def _get_all_files():
"""This function is used to check if this script is ran from
root directory and to return a list of all the files for linting and
pattern checks.
"""
eslintignore_path = os.path.join(os.getcwd(), '.eslintignore')
parsed_args = _PARSER.parse_args()
if parsed_args.path:
input_path = os.path.join(os.getcwd(), parsed_args.path)
if not os.path.exists(input_path):
print 'Could not locate file or directory %s. Exiting.' % input_path
print '----------------------------------------'
sys.exit(1)
if os.path.isfile(input_path):
all_files = [input_path]
else:
excluded_glob_patterns = FileCache.readlines(eslintignore_path)
all_files = _get_all_files_in_directory(
input_path, excluded_glob_patterns)
elif parsed_args.files:
valid_filepaths = []
invalid_filepaths = []
for f in parsed_args.files:
if os.path.isfile(f):
valid_filepaths.append(f)
else:
invalid_filepaths.append(f)
if invalid_filepaths:
print ('The following file(s) do not exist: %s\n'
'Exiting.' % invalid_filepaths)
sys.exit(1)
all_files = valid_filepaths
else:
all_files = _get_changed_filenames()
all_files = [
filename for filename in all_files if not
any(fnmatch.fnmatch(filename, pattern) for pattern in EXCLUDED_PATHS)]
return all_files
def _pre_commit_linter(all_files):
"""This function is used to check if node-eslint dependencies are installed
and pass ESLint binary path.
"""
print 'Starting linter...'
pylintrc_path = os.path.join(os.getcwd(), '.pylintrc')
config_pylint = '--rcfile=%s' % pylintrc_path
config_pycodestyle = os.path.join(os.getcwd(), 'tox.ini')
parent_dir = os.path.abspath(os.path.join(os.getcwd(), os.pardir))
node_path = os.path.join(
parent_dir, 'oppia_tools', 'node-6.9.1', 'bin', 'node')
eslint_path = os.path.join(
parent_dir, 'node_modules', 'eslint', 'bin', 'eslint.js')
stylelint_path = os.path.join(
parent_dir, 'node_modules', 'stylelint', 'bin', 'stylelint.js')
config_path_for_css_in_html = os.path.join(
parent_dir, 'oppia', '.stylelintrc')
config_path_for_oppia_css = os.path.join(
parent_dir, 'oppia', 'core', 'templates', 'dev', 'head',
'css', '.stylelintrc')
if not (os.path.exists(eslint_path) and os.path.exists(stylelint_path)):
print ''
print 'ERROR Please run start.sh first to install node-eslint '
print ' or node-stylelint and its dependencies.'
sys.exit(1)
js_files_to_lint = [
filename for filename in all_files if filename.endswith('.js')]
py_files_to_lint = [
filename for filename in all_files if filename.endswith('.py')]
html_files_to_lint_for_css = [
filename for filename in all_files if filename.endswith('.html')]
css_files_to_lint = [
filename for filename in all_files if filename.endswith('oppia.css')]
css_in_html_result = multiprocessing.Queue()
css_in_html_stdout = multiprocessing.Queue()
linting_processes = []
linting_processes.append(multiprocessing.Process(
target=_lint_css_files, args=(
node_path,
stylelint_path,
config_path_for_css_in_html,
html_files_to_lint_for_css, css_in_html_stdout,
css_in_html_result)))
css_result = multiprocessing.Queue()
css_stdout = multiprocessing.Queue()
linting_processes.append(multiprocessing.Process(
target=_lint_css_files, args=(
node_path,
stylelint_path,
config_path_for_oppia_css,
css_files_to_lint, css_stdout,
css_result)))
js_result = multiprocessing.Queue()
js_stdout = multiprocessing.Queue()
linting_processes.append(multiprocessing.Process(
target=_lint_js_files, args=(
node_path, eslint_path, js_files_to_lint,
js_stdout, js_result)))
py_result = multiprocessing.Queue()
linting_processes.append(multiprocessing.Process(
target=_lint_py_files,
args=(config_pylint, config_pycodestyle, py_files_to_lint, py_result)))
print 'Starting CSS, Javascript and Python Linting'
print '----------------------------------------'
for process in linting_processes:
process.daemon = False
process.start()
file_groups_to_lint = [
html_files_to_lint_for_css, css_files_to_lint,
js_files_to_lint, py_files_to_lint]
number_of_files_to_lint = sum(
len(file_group) for file_group in file_groups_to_lint)
timeout_multiplier = 2000
for file_group, process in zip(file_groups_to_lint, linting_processes):
# try..except block is needed to catch ZeroDivisionError
# when there are no CSS, HTML, JavaScript and Python files to lint.
try:
# Require timeout parameter to prevent against endless
# waiting for the linting function to return.
process.join(timeout=(
timeout_multiplier * len(file_group) / number_of_files_to_lint))
except ZeroDivisionError:
break
js_messages = []
while not js_stdout.empty():
js_messages.append(js_stdout.get())
print ''
print '\n'.join(js_messages)
summary_messages = []
result_queues = [
css_in_html_result, css_result,
js_result, py_result]
for result_queue in result_queues:
while not result_queue.empty():
summary_messages.append(result_queue.get())
with _redirect_stdout(_TARGET_STDOUT):
print '\n'.join(summary_messages)
print ''
return summary_messages
def _check_newline_character(all_files):
"""This function is used to check that each file
ends with a single newline character.
"""
print 'Starting newline-at-EOF checks'
print '----------------------------------------'
errors_found = 0
files_checked = 0
summary_messages = []
all_files = [
filename for filename in all_files if not
any(fnmatch.fnmatch(filename, pattern)
for pattern in EXCLUDED_PATHS) and not filename.endswith('.py')]
with _redirect_stdout(_TARGET_STDOUT):
for filename in all_files:
content = FileCache.read(filename, mode='rb')
files_checked += 1
if len(content) == 1:
errors_found += 1
print '%s --> Error: Only one character in file.' % filename
elif len(content) >= 2 and not re.match(r'[^\n]\n', content[-2:]):
errors_found += 1
print (
'%s --> Please ensure that this file ends with exactly one '
'newline char.' % filename)
print ''
if errors_found:
summary_message = '%s Newline character checks failed' % (
_MESSAGE_TYPE_FAILED)
summary_messages.append(summary_message)
else:
summary_message = '%s Newline character checks passed' % (
_MESSAGE_TYPE_SUCCESS)
summary_messages.append(summary_message)
print ''
if files_checked:
print '(%s files checked, %s errors found)\n%s' % (
files_checked, errors_found, summary_message)
else:
print 'There are no files to be checked.'
return summary_messages
def _check_bad_pattern_in_file(filename, content, pattern):
"""Detects whether the given pattern is present in the file.
Args:
filename: str. Name of the file.
content: str. Contents of the file.
pattern: dict. (regexp(regex pattern) : pattern to match,
message(str) : message to show if pattern matches,
excluded_files(tuple(str)) : files to be excluded from matching,
excluded_dirs(tuple(str)) : directories to be excluded from
matching).
Object containing details for the pattern to be checked.
Returns:
bool. True if there is bad pattern else false.
"""
regexp = pattern['regexp']
if not (any(filename.startswith(excluded_dir)
for excluded_dir in pattern['excluded_dirs'])
or filename in pattern['excluded_files']):
bad_pattern_count = 0
for line_num, line in enumerate(content.split('\n'), 1):
if line.endswith('disable-bad-pattern-check'):
continue
if re.search(regexp, line):
print '%s --> Line %s: %s' % (
filename, line_num, pattern['message'])
print ''
bad_pattern_count += 1
if bad_pattern_count:
return True
return False
def _check_bad_patterns(all_files):
"""This function is used for detecting bad patterns."""
print 'Starting Pattern Checks'
print '----------------------------------------'
total_files_checked = 0
total_error_count = 0
summary_messages = []
all_files = [
filename for filename in all_files if not (
filename.endswith('pre_commit_linter.py') or
any(
fnmatch.fnmatch(filename, pattern)
for pattern in EXCLUDED_PATHS)
)]
failed = False
with _redirect_stdout(_TARGET_STDOUT):
for filename in all_files:
content = FileCache.read(filename)
total_files_checked += 1
for pattern in BAD_PATTERNS:
if (pattern in content and
not _is_filename_excluded_for_bad_patterns_check(
pattern, filename)):
failed = True
print '%s --> %s' % (
filename, BAD_PATTERNS[pattern]['message'])
print ''
total_error_count += 1
if filename.endswith('.js'):
for regexp in BAD_PATTERNS_JS_REGEXP:
if _check_bad_pattern_in_file(filename, content, regexp):
failed = True
total_error_count += 1
if filename.endswith('.html'):
for regexp in BAD_LINE_PATTERNS_HTML_REGEXP:
if _check_bad_pattern_in_file(filename, content, regexp):
failed = True
total_error_count += 1
if filename.endswith('.py'):
for regexp in BAD_PATTERNS_PYTHON_REGEXP:
if _check_bad_pattern_in_file(filename, content, regexp):
failed = True
total_error_count += 1
if filename == 'constants.js':
for pattern in REQUIRED_STRINGS_CONSTANTS:
if pattern not in content:
failed = True
print '%s --> %s' % (
filename,
REQUIRED_STRINGS_CONSTANTS[pattern]['message'])
print ''
total_error_count += 1
if failed:
summary_message = '%s Pattern checks failed' % _MESSAGE_TYPE_FAILED
summary_messages.append(summary_message)
else:
summary_message = '%s Pattern checks passed' % _MESSAGE_TYPE_SUCCESS
summary_messages.append(summary_message)