-
Notifications
You must be signed in to change notification settings - Fork 6
/
init.coffee
executable file
·1060 lines (946 loc) · 43.8 KB
/
init.coffee
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
# This file contains all the logic of the linter-mypy.
# Import every required libraries.
{CompositeDisposable} = require 'atom'
helpers = require 'atom-linter'
fs = require 'fs'
os = require 'os'
path = require 'path'
NamedRegexp = require('named-js-regexp')
md5 = require('md5')
# Define every available settings.
## Those settings are also documented in the README file.
module.exports =
config:
executablePath:
title: 'Python Executable Path'
type: 'string'
default: 'python3'
description: '''Semicolon separated list of paths to Python.
The optionals `$PROJECT_PATH` and `$PROJECT_NAME` variables can be used to resolve the path
dynamically depending of the current project. For example:
`/home/user/.virtualenvs/$PROJECT_NAME/bin/python;python3`.
'''
order: 1
pythonPath:
type: 'string'
default: ''
description: '''PYTHONPATH environment variable to use, is a colon-separated list of directories
<br /><strong>Note:</strong> Use a dot to add the directory containing the file being linted.
The optionals `$PROJECT_PATH` and `$PROJECT_NAME` variables can be used to resolve the path
dynamically depending of the current project.
'''
order: 2
mypyNotifyInternalError:
type: 'boolean'
default: true
description: 'Pop-up a detailed error if a Mypy Internal error occurs'
order: 3
ignoreFiles:
type: 'string'
default: ''
description: 'Regex pattern of filenames to ignore, e.g.: "test.+"'
order: 4
lintTrigger:
title: 'Lint Trigger'
type: 'string'
default: 'LintOnFileSave'
enum: [
{value: 'LintOnFileSave', description: 'Lint on file save'}
{value: 'LintAsYouType', description: 'Lint as you type'}
]
description: "Specify the lint trigger"
order: 5
mypyIncremental:
type: 'boolean'
default: true
description: 'Use <a href="http://mypy.readthedocs.io/en/latest/command_line.html#incremental">Mypy experimental incremental analysis</a> to improve lint process time.'
order: 6
mypyIncrementalCacheFolderPath:
title: 'Mypy Incremental Cache Folder Path'
type: 'string'
default: ''
description: '''Path to an existing folder where Mypy can use to cache data.
The optionals `$PROJECT_PATH` and `$PROJECT_NAME` variables can be used to resolve the path
dynamically depending of the current project.<br />For example: `$PROJECT_PATH/mypy_cache`.
<br/><strong>Note:</strong><ul>
<li>If `/dev/null` is provided, no cache will be use.</li>
<li>If no path is provided, folders under the OS temp folder will be use.</li>
<li>If a path is provided, and the folder exists, then it will be use.</li>
<li>If a dot is provided, the default behavior of MyPy will be use (a .mypy_cache folder next to the file being linted)</li>
</ul>
'''
order: 7
mypyPath:
type: 'string'
default: ''
description: '''<a href="http://mypy.readthedocs.io/en/latest/command_line.html#how-imports-are-found">MYPYPATH</a> environment variable to use, is a colon-separated list of directories
<br /><strong>Note:</strong> Use a dot to add the directory containing the file being linted.
The optionals `$PROJECT_PATH` and `$PROJECT_NAME` variables can be used to resolve the path
dynamically depending of the current project. For example:
`$PROJECT_PATH/stubs`.
'''
order: 8
mypyIniFile:
title: 'Mypy Config File'
type: 'string'
default: ''
description: '''Path to a <a href="http://mypy.readthedocs.io/en/latest/config_file.html"> mypy configuration file (mypy.ini or setup.cfg)</a>.
The optionals variables `$PROJECT_PATH` and `$PROJECT_NAME` can be used to resolve the path
dynamically depending of the current project. For example:
`$PROJECT_PATH/mypy.ini`. <strong>If a file is being found at the given path then it will be <a href="https://mypy.readthedocs.io/en/latest/command_line.html#cmdoption-mypy-config-file">provided to mypy</a> and all the below settings will be ignore.</strong>
'''
order: 9
warnUnreachable:
type: 'boolean'
default: true
description: 'Warn about statements or expressions inferred to be unreachable or redundant'
order: 10
noImplicitReexport:
type: 'boolean'
default: true
description: 'Treat imports as private unless aliased'
order: 11
followImports:
type: 'string'
default: 'silent'
enum: [
{value: 'normal', description: 'Normal. Follow imports normally and type check all top level code'}
{value: 'silent', description: 'Silent. Follow imports normally, but suppress any error messages.'}
{value: 'skip', description: 'Skip. Don’t follow imports.'}
{value: 'error', description: 'Error. The same behavior as skip but not quite as silent.'}
]
description: '''Should mypy analysis <a href="http://mypy.readthedocs.io/en/latest/command_line.html#follow-imports">follow imports</a>'''
order: 12
namespacePackages:
type: 'boolean'
default: true
description: 'Support namespace packages (PEP 420, __init__.py-less'
order: 13
disallowUntypedCalls:
type: 'boolean'
default: true
description: 'Disallow calling functions without type annotations from functions with type annotations'
order: 14
disallowUntypedDefs:
type: 'boolean'
default: true
description: 'Disallow defining functions without type annotations or with incomplete type annotations'
order: 15
disallowUntypedGlobals:
type: 'boolean'
default: true
description: 'toplevel errors about missing annotations'
order: 16
disallowRedefinition:
type: 'boolean'
default: true
description: 'Disallow unconditional variable redefinition with a new type'
order: 17
strictEquality:
type: 'boolean'
default: true
description: 'Prohibit equality, identity, and container checks for non-overlapping types'
order: 18
disallowIncompleteDefs:
type: 'boolean'
default: true
description: 'Disallow defining functions with incomplete type annotations'
order: 19
checkUntypedDefs:
type: 'boolean'
default: true
description: 'Type check the interior of functions without type annotations'
order: 20
warnIncompleteStub:
type: 'boolean'
default: true
description: 'Warn if missing type annotation in typeshed, only relevant with --check-untyped-defs enabled'
order: 21
disallowUntypedDecorators:
type: 'boolean'
default: true
description: 'Disallow decorating typed functions with untyped decorators'
order: 22
warnRedundantCasts:
type: 'boolean'
default: true
description: 'Warn about casting an expression to its inferred type'
order: 23
warnNoReturn:
type: 'boolean'
default: true
description: 'Warn about functions that end without returning'
order: 24
warnReturnAny:
type: 'boolean'
default: true
description: 'Warn about returning values of type Any from non-Any typed functions'
order: 25
disallowSubclassingAny:
type: 'boolean'
default: true
description: 'Disallow subclassing values of type "Any" when defining classes'
order: 26
disallowAnyUnimported:
type: 'boolean'
default: true
description: 'Disallows usage of types that come from unfollowed imports'
order: 27
disallowAnyExpr:
type: 'boolean'
default: true
description: 'Disallows all expressions in the module that have type Any'
order: 28
disallowAnyDecorated:
type: 'boolean'
default: true
description: 'Disallows functions that have Any in their signature after decorator transformation'
order: 29
disallowAnyExplicit:
type: 'boolean'
default: true
description: 'Disallows explicit Any in type positions'
order: 30
disallowAnyGenerics:
type: 'boolean'
default: true
description: 'Disallows usage of generic types that do not specify explicit type parameters'
order: 31
warnUnusedIgnores:
type: 'boolean'
default: true
description: "Warn about unneeded '# type: ignore' comments"
order: 32
warnUnusedConfigs:
type: 'boolean'
default: true
description: "Warn about unnused '[mypy-<pattern>]' config sections"
order: 33
warnMissingImports:
type: 'boolean'
default: true
description: "Warn about imports of missing modules"
order: 34
strictOptional:
type: 'boolean'
default: true
description: "Enable experimental strict Optional checks"
order: 35
noImplicitOptional:
type: 'boolean'
default: true
description: "Don't assume arguments with default values of None are Optional"
order: 36
theOSTempFolder: undefined
removeFromDisk: (p_path) ->
if p_path
if fs.existsSync(p_path)
stat = fs.statSync p_path
if stat.isDirectory()
# Remove Directory content
for item in fs.readdirSync p_path
@removeFromDisk path.join(p_path, item)
fs.rmdirSync p_path
else
# Remove File
fs.unlinkSync p_path
activate: ->
require('atom-package-deps').install('linter-mypy')
# Create a temporary folder which will exists for the lifetime of the linter-mypy session.
fs.mkdtemp path.join(os.tmpdir(), "atom_linter-mypy_"), (err, folder) =>
if err
# Bah it's not that bad... it will just not use incremental analysis even if requested by the user in the settings.
else
@theOSTempFolder = folder
#Listen and reload any settings changes to prevent having to restart Atom.
@subscriptions = new CompositeDisposable
@subscriptions.add atom.config.observe 'linter-mypy.executablePath',
(executablePath) =>
@executablePath = executablePath
@subscriptions.add atom.config.observe 'linter-mypy.pythonPath',
(pythonPath) =>
@pythonPath = pythonPath
@subscriptions.add atom.config.observe 'linter-mypy.mypyIncremental',
(mypyIncremental) =>
@mypyIncremental = mypyIncremental
@subscriptions.add atom.config.observe 'linter-mypy.mypyIncrementalCacheFolderPath',
(mypyIncrementalCacheFolderPath) =>
@mypyIncrementalCacheFolderPath = mypyIncrementalCacheFolderPath
@subscriptions.add atom.config.observe 'linter-mypy.mypyNotifyInternalError',
(mypyNotifyInternalError) =>
@mypyNotifyInternalError = mypyNotifyInternalError
@subscriptions.add atom.config.observe 'linter-mypy.ignoreFiles',
(ignoreFiles) =>
@ignoreFiles = ignoreFiles
@subscriptions.add atom.config.observe 'linter-mypy.mypyIniFile',
(mypyConfigFile) =>
@mypyConfigFile = mypyConfigFile
@subscriptions.add atom.config.observe 'linter-mypy.disallowUntypedCalls',
(disallowUntypedCalls) =>
@disallowUntypedCalls = disallowUntypedCalls
@subscriptions.add atom.config.observe 'linter-mypy.disallowUntypedGlobals',
(disallowUntypedGlobals) =>
@disallowUntypedGlobals = disallowUntypedGlobals
@subscriptions.add atom.config.observe 'linter-mypy.disallowRedefinition',
(disallowRedefinition) =>
@disallowRedefinition = disallowRedefinition
@subscriptions.add atom.config.observe 'linter-mypy.strictEquality',
(strictEquality) =>
@strictEquality = strictEquality
@subscriptions.add atom.config.observe 'linter-mypy.disallowUntypedDefs',
(disallowUntypedDefs) =>
@disallowUntypedDefs = disallowUntypedDefs
@subscriptions.add atom.config.observe 'linter-mypy.checkUntypedDefs',
(checkUntypedDefs) =>
@checkUntypedDefs = checkUntypedDefs
@subscriptions.add atom.config.observe 'linter-mypy.warnIncompleteStub',
(warnIncompleteStub) =>
@warnIncompleteStub = warnIncompleteStub
@subscriptions.add atom.config.observe 'linter-mypy.warnRedundantCasts',
(warnRedundantCasts) =>
@warnRedundantCasts = warnRedundantCasts
@subscriptions.add atom.config.observe 'linter-mypy.warnNoReturn',
(warnNoReturn) =>
@warnNoReturn = warnNoReturn
@subscriptions.add atom.config.observe 'linter-mypy.warnReturnAny',
(warnReturnAny) =>
@warnReturnAny = warnReturnAny
@subscriptions.add atom.config.observe 'linter-mypy.disallowSubclassingAny',
(disallowSubclassingAny) =>
@disallowSubclassingAny = disallowSubclassingAny
@subscriptions.add atom.config.observe 'linter-mypy.disallowAnyUnimported',
(disallowAnyUnimported) =>
@disallowAnyUnimported = disallowAnyUnimported
@subscriptions.add atom.config.observe 'linter-mypy.disallowAnyExpr',
(disallowAnyExpr) =>
@disallowAnyExpr = disallowAnyExpr
@subscriptions.add atom.config.observe 'linter-mypy.disallowAnyDecorated',
(disallowAnyDecorated) =>
@disallowAnyDecorated = disallowAnyDecorated
@subscriptions.add atom.config.observe 'linter-mypy.disallowAnyExplicit',
(disallowAnyExplicit) =>
@disallowAnyExplicit = disallowAnyExplicit
@subscriptions.add atom.config.observe 'linter-mypy.disallowAnyGenerics',
(disallowAnyGenerics) =>
@disallowAnyGenerics = disallowAnyGenerics
@subscriptions.add atom.config.observe 'linter-mypy.warnUnusedIgnores',
(warnUnusedIgnores) =>
@warnUnusedIgnores = warnUnusedIgnores
@subscriptions.add atom.config.observe 'linter-mypy.warnUnreachable',
(warnUnreachable) =>
@warnUnreachable = warnUnreachable
@subscriptions.add atom.config.observe 'linter-mypy.noImplicitReexport',
(noImplicitReexport) =>
@noImplicitReexport = noImplicitReexport
@subscriptions.add atom.config.observe 'linter-mypy.warnMissingImports',
(warnMissingImports) =>
@warnMissingImports = warnMissingImports
@subscriptions.add atom.config.observe 'linter-mypy.strictOptional',
(strictOptional) =>
@strictOptional = strictOptional
@subscriptions.add atom.config.observe 'linter-mypy.noImplicitOptional',
(noImplicitOptional) =>
@noImplicitOptional = noImplicitOptional
@subscriptions.add atom.config.observe 'linter-mypy.warnUnusedConfigs',
(warnUnusedConfigs) =>
@warnUnusedConfigs = warnUnusedConfigs
@subscriptions.add atom.config.observe 'linter-mypy.disallowIncompleteDefs',
(disallowIncompleteDefs) =>
@disallowIncompleteDefs = disallowIncompleteDefs
@subscriptions.add atom.config.observe 'linter-mypy.disallowUntypedDecorators',
(disallowUntypedDecorators) =>
@disallowUntypedDecorators = disallowUntypedDecorators
@subscriptions.add atom.config.observe 'linter-mypy.followImports',
(followImports) =>
@followImports = followImports
@subscriptions.add atom.config.observe 'linter-mypy.namespacePackages',
(namespacePackages) =>
@namespacePackages = namespacePackages
@subscriptions.add atom.config.observe 'linter-mypy.mypyPath',
(mypyPath) =>
@mypyPath = mypyPath
deactivate: ->
# Clean up the OS temp files created on the hard drive
@removeFromDisk(@theOSTempFolder)
# Unsubscribe any registered atom's event.
if @subscriptions
@subscriptions.dispose()
getMypyCommandLine: (filePath, filePathShadow)->
# Get the command line arguments to lint a given file path.
params = []
## Use the python module mypy
params.push("-m")
params.push("mypy")
## Useless feature for linter-mypy use case.
params.push("--hide-error-context")
params.push("--no-error-summary")
params.push("--no-pretty")
params.push("--no-color-output")
## Useful info for the user.
params.push("--show-error-codes")
## We want column number so that we can know where to underline.
params.push("--show-column-numbers")
## We want a stable output format which is independent of cwd.
params.push("--show-absolute-path")
## In case a Mypy INTERNAL ERROR is encountered, print the stacktrace to ease bug reporting.
params.push("--show-traceback")
if filePath != filePathShadow
params.push("--shadow-file")
params.push(filePath)
params.push(filePathShadow)
# Cache Strategy #0: Do not use cache folder at all
# Cache Strategy #1: Use a unique cache folder for each file under OS temp
# Cache Strategy #2: Use default MyPy behavior of creating a ".mypy_cache" folder next to the file
# Cache Strategy #3: Use the user provided cache folder
#
# Fallback hierarchy:
# (#2|#3) -> #1 -> #0
v_cacheFolder = undefined
if @mypyIncremental
# Use mypy incremental
params.push("--incremental")
v_cacheFolder = @resolvePath @mypyIncrementalCacheFolderPath, filePath
if ("/dev/null" == v_cacheFolder) || ("nul" == v_cacheFolder)
v_cacheFolder = undefined
else
if "" == v_cacheFolder
else if "." == v_cacheFolder
# We need to explicitely compute the .mypy_cache folder path next to the file being linted
# since by default mypy creates it in the CWD
# but linter-mypy sets CWD to the root of the hard drive... (due to a bug in Mypy)
# Therefore it would either pollute the root or mostly silently fail to create the folder.
v_cacheFolder = path.join path.dirname(filePath), ".mypy_cache"
# Make sure the cache folder exists & create it if needed
try
fs.mkdirSync(v_cacheFolder)
catch err
if "EEXIST" == err.code
else
# Bah it's not that bad... We fallback to Strategy #1.
v_cacheFolder = ""
# Make sure the cache folder exists
if fs.existsSync(v_cacheFolder)
stat = fs.statSync v_cacheFolder
if stat.isDirectory()
else
#We fallback to Strategy #1 if the directory does not already exist
v_cacheFolder = ""
else
#We fallback to Strategy #1 if the directory does not already exist
v_cacheFolder = ""
if "" == v_cacheFolder
if @theOSTempFolder
v_cacheFolder = path.join(@theOSTempFolder, md5(filePath))
try
fs.mkdirSync(v_cacheFolder)
catch err
if "EEXIST" == err.code then
else
# Bah it's not that bad... We fallback to Strategy #0.
v_cacheFolder = undefined
else
# Bah it's not that bad... We fallback to Strategy #0.
v_cacheFolder = undefined
else
params.push("--no-incremental")
# Note: At this point, v_cacheFolder is either a path to an existing folder or undefined
if v_cacheFolder
else
# Do not create any cache file anywhere.
switch os.platform()
when "win32"
v_cacheFolder = "nul"
#when "linux"
#when "darwin"
else
v_cacheFolder = "/dev/null"
params.push("--cache-dir")
params.push(v_cacheFolder)
configPath = @resolvePath @mypyConfigFile, filePath
if (fs.existsSync configPath)
# Use the provided mypy configuration file.
params.push("--config-file")
params.push(configPath)
else
# Add the parameters base on user selected settings.
params.push("--follow-imports")
params.push(@followImports)
if (@warnUnreachable)
params.push("--warn-unreachable")
else
params.push("--no-warn-unreachable")
if (@noImplicitReexport)
params.push("--no-implicit-reexport")
else
params.push("--implicit-reexport")
if (@namespacePackages)
params.push("--namespace-packages")
else
params.push("--no-namespace-packages")
if (@disallowUntypedGlobals)
params.push("--disallow-untyped-globals")
else
params.push("--allow-untyped-globals")
if (@disallowRedefinition)
params.push("--disallow-redefinition")
else
params.push("--allow-redefinition")
if (@strictEquality)
params.push("--strict-equality")
else
params.push("--no-strict-equality")
if (@disallowUntypedCalls)
params.push("--disallow-untyped-calls")
else
params.push("--allow-untyped-calls")
if (@disallowUntypedDefs)
params.push("--disallow-untyped-defs")
else
params.push("--allow-untyped-defs")
if (@checkUntypedDefs)
params.push("--check-untyped-defs")
else
params.push("--no-check-untyped-defs")
if (@warnIncompleteStub)
params.push("--warn-incomplete-stub")
else
params.push("--no-warn-incomplete-stub")
if (@warnRedundantCasts)
params.push("--warn-redundant-casts")
else
params.push("--no-warn-redundant-casts")
if (@warnNoReturn)
params.push("--warn-no-return")
else
params.push("--no-warn-no-return")
if (@warnReturnAny)
params.push("--warn-return-any")
else
params.push("--no-warn-return-any")
if (@disallowSubclassingAny)
params.push("--disallow-subclassing-any")
else
params.push("--allow-subclassing-any")
if (@disallowAnyUnimported)
params.push("--disallow-any-unimported")
if (@disallowAnyExpr)
params.push("--disallow-any-expr")
if (@disallowAnyDecorated)
params.push("--disallow-any-decorated")
if (@disallowAnyExplicit)
params.push("--disallow-any-explicit")
if (@disallowAnyGenerics)
params.push("--disallow-any-generics")
else
params.push("--allow-any-generics")
if (@warnUnusedIgnores)
params.push("--warn-unused-ignores")
else
params.push("--no-warn-unused-ignores")
if (!@warnMissingImports)#Note: the boolean flag value is inversed since the parameter meaning is inversed.
params.push("--ignore-missing-imports")
if (@strictOptional)
params.push("--strict-optional")
else
params.push("--no-strict-optional")
if (@noImplicitOptional)
params.push("--no-implicit-optional")
else
params.push("--implicit-optional")
if (@warnUnusedConfigs)
params.push("--warn-unused-configs")
else
params.push("--no-warn-unused-configs")
if (@disallowIncompleteDefs)
params.push("--disallow-incomplete-defs")
else
params.push("--allow-incomplete-defs")
if (@disallowUntypedDecorators)
params.push("--disallow-untyped-decorators")
else
params.push("--allow-untyped-decorators")
# Provide the filename to lint.
params.push(filePath)
return params
lintPath: (filePath, filePathShadow) ->
# This is the entry point for Lint requests for a given file.
options = { stream: 'both', ignoreExitCode: true, env: Object.create(process.env), timeout: Infinity }
# Set the PYTHONPATH as requested
##Initialize the environment variable PYTHONPATH
if !(options.env["PYTHONPATH"])?
options.env["PYTHONPATH"] = ''
##Prepend user setting defined PYTHONPATH to current system env PYTHONPATH
if @pythonPath?
pythonPathResolved = @resolvePath @pythonPath, filePath
options.env["PYTHONPATH"] = path.delimiter + pythonPathResolved + path.delimiter + options.env["PYTHONPATH"] + path.delimiter
##Clean all repeated path separator
options.env["PYTHONPATH"] = options.env["PYTHONPATH"].replace(new RegExp(path.delimiter + "+","g"), path.delimiter)
##Strip not necessary separator
options.env["PYTHONPATH"] = options.env["PYTHONPATH"].replace(new RegExp("^" + path.delimiter + "+|" + path.delimiter + "+$","g"), '')
# Set the MYPYPATH as requested
##Initialize the environment variable MYPYPATH
if !(options.env["MYPYPATH"])?
options.env["MYPYPATH"] = ''
##Prepend user setting defined MYPYPATH to current system env MYPYPATH
if @mypyPath?
mypyPathResolved = @resolvePath @mypyPath, filePath
options.env["MYPYPATH"] = path.delimiter + mypyPathResolved + path.delimiter + options.env["MYPYPATH"] + path.delimiter
##Add current folder of the file being linted to MYPYPATH
options.env["MYPYPATH"] = options.env["MYPYPATH"].replace(new RegExp(path.delimiter + "\\." + path.delimiter, "g"), path.delimiter + path.dirname(filePath) + path.delimiter)
##Clean all repeated path separator
options.env["MYPYPATH"] = options.env["MYPYPATH"].replace(new RegExp(path.delimiter + "+","g"), path.delimiter)
##Strip not necessary separator
options.env["MYPYPATH"] = options.env["MYPYPATH"].replace(new RegExp("^" + path.delimiter + "+|" + path.delimiter + "+$","g"), '')
executablePath = @resolveMultiPaths @executablePath, filePath
params = @getMypyCommandLine(filePath, filePathShadow)
configFileIndex = params.lastIndexOf("--config-file") + 1
if 0 < configFileIndex
# A configuration file is being use, therefore run the command with the cwd set to the folder containing the configuration file
# PRO:
# * It allows relative path defined in the configuration file to be valid.
# CONS:
# * It may be affected by the mypy bug #2974
#
# * But at this point if it is affected than linter-mypy did more than it should to try workaround MyPy issues, Mypy should:
# 1- Should better handle config file by considering relative path base on the config file path and not base on cwd.
# AND/OR
# 2 - Fix mypy bug #2974
# Linter-mypy users could as a last resort workaround to not use config file.
options.cwd = path.dirname(params[configFileIndex])
else
# Run the command with the cwd set to the file system root of where the file being linted is located.
# This has the advantage that:
# * It always works fine, it is not affected by the mypy bug #2974 (should therefore never run with cwd set to the directory of the file being linted)
# Extract the file system root.
options.cwd = path.parse(filePath).root
mypyNotifyInternalError = @mypyNotifyInternalError
# We call the mypy process and parse its output.
## For debug: ## alert(executablePath + " " + params.join(" "))
# https://github.com/steelbrain/exec
return helpers.exec(executablePath, params, options).then (({stdout, stderr, exitCode}) ->
## For debug: ## alert(stderr)
## For debug: ## alert(stdout)
# The goal of this method is to return an array of string where each string is a valid warning in the format: "FILEPATH:LINENO:COLNO:MESSAGE"
result = []
# Each line of the mypy output may be a potential warning so we create an array of string containing each line of the output.
# We split the text using the new line as a separator and handle any OS kind of new lines.
lines = stdout.split(/\r\n|\r|\n/g)
# For each line (aka warnings) we filter out those which are not wanted else we append it to the final list of warnings to reports.
# Note: The final report must contain the full path to the file so that Atom can find the file.
for key, val of lines
result.push(val)
if "" != stderr
# Well, Well, Well... something went wrong.
# Instead of crashing or giving cryptic error message, let's try to be user friendly.
if stderr.match /^.+\:\sNo\s\[mypy\]\ssection\sin\sconfig\sfile$/gi
###
The Problem: The error is about a mypy.ini file not in the good format.
The Context: At this point everything is fine a valid mypy launch was done using a found mypy.ini file.
The Conclusion: the user must only make sure to either not use mypy configuration file or have it in the good format.
The Solution: Let's:
1- Inform the user about the situation with a pop-up.
2- Offer him a link to change the setting.
###
notification = atom.notifications.addWarning(
"The mypy configuration file does not contains a [mypy] section as it should.<br />Either correct the configuration file or adjust the mypy configuration path setting of linter-mypy.",
{
buttons: [
{
text: "Adjust the linter-mypy setting",
onDidClick: ->
atom.workspace.open("atom://config/packages/linter-mypy")
notification.dismiss()
}
],
dismissable: true,
}
)
else if (0 <= stderr.indexOf("usage: mypy"))
###
The Problem: The error is about an incorrect usage of mypy parameters.
The Context: At this point a call to mypy was effectively done, there are three options
1- The mypy command line interface has change and the project should be updated accordingly
- But We have a spec to detect mypy command line interface change, so this option is probably not what is the real cause of the problem, anyway the user would not have much possibility to recover anyway.
2- The executablePath provided in the settings is not pointing to python but directly to the mypy executable as it was required prior to linter-mypy v2.0.0
3- The version of mypy is older than the one linter-mypy expect.
The Conclusion: It may be the executablePath which is pointing to mypy instead of Python but it is most likely an outdated mypy installation.
The Solution: Let's:
1- Inform the user about the situation with a pop-up.
2- Display the command line to update mypy.
3- Offer him a link to change the setting.
###
notification = atom.notifications.addWarning(
"MyPy does not understand the provided parameters. Make sure the latest mypy version is installed using the following command line:<br/><br/><em>" + executablePath + " -m pip install -U mypy</em>",
{
buttons: [
{
text: "Adjust the linter-mypy setting",
onDidClick: ->
atom.workspace.open("atom://config/packages/linter-mypy")
notification.dismiss()
}
],
dismissable: true,
}
)
else if (0 <= stderr.indexOf("No module named mypy"))
###
The Problem: The error is about the absence of the mypy module in the python installation.
The Context: Mypy has to be installed manually and it is base on the error message not installed in the python installation provided in the executable path setting.
The Conclusion: It is most likely the user which haven't installed the module, but it is also possible that the user has more than one python installation on his system and didn't provide the good one in the settings.
The Solution: Let's:
1- Inform the user about the situation with a pop-up
2- Show him an example of command line to install mypy
* Using the resolved executablePath to build the example will highlight to the user which python installation is being used for users which may have more than one on their system.
###
atom.notifications.addWarning("The python package <strong>mypy</strong> does not seem to be installed. Install it with:<br /><br /><em>" + executablePath + " -m pip install mypy</em>")
else if (0 <= stderr.indexOf("The typed_ast package is not installed"))
###
The Problem: The error is about the absence of the typed_ast module in the python installation.
The Context: Mypy requires the module typed_ast which has to be installed manually and it is base on the error message not installed in the python installation provided in the executable path setting.
The Conclusion: It is most likely the user which haven't installed the module, but it is also possible that the user has more than one python installation on his system and didn't provide the good one in the settings.
The Solution: Let's:
1- Inform the user about the situation with a pop-up
2- Show him an example of command line to install typed_ast
* Using the resolved executablePath to build the example will highlight to the user which python installation is being used for users which may have more than one on their system.
###
atom.notifications.addWarning("The python package <strong>typed-ast</strong> does not seem to be installed and is required by Mypy. Install it with:<br /><br /><em>" + executablePath + " -m pip install -U typed-ast</em>")
else if (0 <= stderr.indexOf("AssertionError: Neither id, path nor source given"))
###
The Problem: When Mypy encouters a relative import from a toplevel, it crashes with an assert Stacktrace.
The Context: Mypy has a recorded bug #2974.
The Conclusion: We can't do much, other than not crashing ourself with annoying pop-ups.
The Solution: Let's:
1- Inform the user about the situation with a lint error
###
return [[filePath + ":0:0: error: MypyBug2974"]]
else if (0 <= stderr.indexOf(": error: INTERNAL ERROR --"))
###
The Problem: Mypy has an internal bug.
The Context: linter-mypy did a good job but Mypy has a bug.
The Conclusion: We can't do much, other than not crashing ourself with annoying pop-ups.
The Solution: Let's:
1- Inform the user about the situation with a lint error
2- Display the stacktrace in the pop-up to help bug reporting
3- Offer to deactivate internal error related pop-up to at least allow the user to keep linter-mypy activated so other files which are not affected by the bug can still be linted.
###
if (mypyNotifyInternalError)
notification = atom.notifications.addError("Mypy version " + /.*version: (.*)/.exec(stderr)[1] + " INTERNAL ERROR",
{
detail: stdout,
description: "Please report a bug at https://github.com/python/mypy/issues",
dismissable: true,
buttons: [
{
text: "Deactivate Mypy INTERNAL ERROR pop-ups",
onDidClick: ->
atom.config.set('linter-mypy.mypyNotifyInternalError', false)
notification.dismiss()
},
{
text: "Close",
onDidClick: ->
notification.dismiss()
}
],
})
return [[filePath + ":0:0: error: INTERNAL MYPY ERROR"]]
else
###
The Problem: Something unknown went wrong.
The Context: Many known possible error were managed in a user friendly manner, but this error is not.
The Conclusion: Not much can be done.
The Solution: Since it is an unknown error let's keep the error message intact
1- Inform the user about the situation with an error pop-up containing the full error message, hopefully he will provide a bug report with this information so that it can be better handle.
###
atom.notifications.addError(stderr)
# Return the result.
return [result]
), (err) ->
if ('ENOENT' == err.code)
###
The Problem: The error is about a process spawn which failed
The Context: At this point the only process we launched was Python using the provided path in the setting @executablePath
The Conclusion: The provided executable path is therefore probably incorrect
The Solution: Let's:
1- Inform the user about the situation with a pop-up.
2- Offer him a link to change the setting.
###
notification = atom.notifications.addWarning(
"The executable of <strong>" + executablePath + "</strong> was not found.<br />Either install <a href='https://www.python.org/downloads/'>python</a> or adjust the executable path setting of linter-mypy.",
{
buttons: [
{
text: "Adjust the linter-mypy setting",
onDidClick: ->
atom.workspace.open("atom://config/packages/linter-mypy")
notification.dismiss()
}
],
dismissable: true,
}
)
else
# An unknown bad thing occured.
atom.notifications.addError(err.message)
#Something went wrong there is therefore no mypy warnings to report.
return [err.message]
parseMessages: (output) ->
# Parse the pre-processed mypy warnings output and isolate:
# - file = The file path to the file being linted.
# - line = The line number where the warning is.
# - col = The column where the warning is within the line.
# - message = The warning text.
# Declare regex which extract information about the lint details.
regexLine = new NamedRegexp("^(?<file>([A-Z]:)?[^:]+)[:](?<line>\\d+):(?:(?<col>\\d+):)? (?<severity>[a-z]+): (?<message>.+)")
# Prepare an array of all the warnings to report.
result = []
for msg, idx in output[0]
if "" == msg
continue
v_CurrMessageRaw = regexLine.execGroups(msg)
if v_CurrMessageRaw
else
#Ignore this output line, it is not in the expected warning format.
continue
[projectPath, ...] = atom.project.relativizePath(v_CurrMessageRaw.file)
if not projectPath
#Ignore this warning since it is about a file which is not part of any currently opened projects.
continue
# At this point every messages will be reported, we won't filter them
# But we will improve them a little to make them more helpful.
#Prepare the lint characteristics.
theSeverity = 'warning'
if v_CurrMessageRaw.severity == "error"
theSeverity = 'warning'
else if v_CurrMessageRaw.severity == "note"
theSeverity = "info"
theDescription = ""
theMessage = v_CurrMessageRaw.message
theUrl = ""
theStartLine = parseInt(v_CurrMessageRaw.line, 10) - 1
theStartCol = parseInt(v_CurrMessageRaw.col, 10) - 1
if theStartLine
if theStartLine < 0
theStartLine = 0
else
# Can this occur?
theStartLine = 0
if 0 == theStartCol
theStartCol += 1
else if theStartCol
theStartCol += 1
else
# May occur if the start column is not provided by Mypy
theStartCol = 0
#HACK: Work around since mypy only provide the start column of the error, we have to use heuristics for the end column of the warning, without this workaround the warning would not be underline.
theEndLine = theStartLine
theEndCol = theStartCol
if 0 < theStartCol
#Rational: The underline is off by one character.
theStartCol -= 1
theEndCol -= 1
#Rational: Since mypy points to something it must at least be one character long.
theEndCol += 1
# Use specialized heuristic base on the lint message...
if ("Revealed type is '" == theMessage.substr(0, 18))
#Rational: Since we know the method name is "reveal_type", we can underline its length.
#Rational: Since we know it is a method call we can underline its opening parenthesis.
theStartCol -= 10 + 1 + 1
theEndCol -= 1
theSeverity = 'info'
else if "MypyBug2974" == theMessage#Rational: Mypy Internal Bug
theSeverity = 'error'
theMessage = "Top-level module cannot use a relative import"
theDescription = "Mypy does not support relative import in top-level module, mypy process aborted for this file"
theUrl = "https://github.com/python/mypy/issues/2974"
else if "INTERNAL MYPY ERROR" == theMessage
theSeverity = 'error'
theMessage = "INTERNAL MYPY ERROR"
theDescription = "Mypy crashed"
theUrl = "https://github.com/python/mypy/issues/"
else if "invalid syntax [syntax]" == theMessage
theSeverity = 'error'
#Rational: We can't really know where in the line the invalid syntax is, so let's underline the whole line.
theStartCol = 0
else if "inconsistent use of tabs and spaces in indentation [syntax]" == theMessage
theSeverity = 'error'
#Rational: Indentation is obviously at the start of the line.
theStartCol = 0
else if "unindent does not match any outer indentation level [syntax]" == theMessage
theSeverity = 'error'
#Rational: Indentation is obviously at the start of the line.
theStartCol = 0
else if theMessage in ["unexpected unindent [syntax]", "expected an indented block [syntax]"] # There are two variant of the message (Starting from Python version 3.8 the message changed slightly)
theSeverity = 'error'
#Rational: Indentation is obviously at the start of the line.
theStartCol = 0
else
# Use regex...
regexHeuristic = new NamedRegexp("^Argument . to .(?<name>.+). has incompatible type ..+.; expected ..+.$")
rawMatch = regexHeuristic.execGroups(v_CurrMessageRaw.message)
if rawMatch
#Rational: Since we know the method name we can underline its length.
theEndCol += 0 * (rawMatch.name.length - 1)
else
regexHeuristic = new NamedRegexp("^Name '(?<name>.+)' is not defined \\[name-defined\\]$")
rawMatch = regexHeuristic.execGroups(v_CurrMessageRaw.message)
if rawMatch
theSeverity = 'error'
#Rational: Since we know the method name we can underline its length.
theEndCol += rawMatch.name.length - 1
#TODO: Put more heuristic