-
Notifications
You must be signed in to change notification settings - Fork 149
/
hublint
executable file
·870 lines (706 loc) · 29.8 KB
/
hublint
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
#!/usr/bin/env python3
import argparse
import base64
import collections
import enum
import json
import sys
import textwrap
import time
import tomllib
from http import HTTPMethod
import jsonschema
import requests
import yaml
RED = ''
GREEN = ''
YELLOW = ''
BLUE = ''
RESET = ''
UNDERLINE = ''
BOL = '\r'
ERASETOEOL = '\033[0K'
# TODO:
# --file-only to check only the modified files
# (if an item has the file path, it's checked, otherwise it's skipped)
# --item-only to check only the specified items, with a glob pattern
# tests
# publish comment on PR
# markdown report: error and warning must keep track of the item (proper class!)
# review linter names, descriptions and defaults
# separate index linters (to run in CI) from the others, which can be run before committing (with an out-of-date index)
# - linter name prefix?
# - separate config section?
# - flag to skip them?
isatty = sys.stdout.isatty
def init_colors(force):
global RED, GREEN, YELLOW, BLUE, RESET, UNDERLINE
if force == 'always' or (force == 'auto' and isatty()):
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
RESET = '\033[0m'
UNDERLINE = '\033[4m'
# tweaked from https://github.com/yaml/pyyaml/issues/456
class TrackingLoader(yaml.SafeLoader):
def __init__(self, stream):
super().__init__(stream)
self.locations = {}
def compose_node(self, parent, index):
# Get the start position before composing the node
start_line, start_column = self.line, self.column
node = super().compose_node(parent, index)
# Attach the start position to the node itself
node._myloader_start_location = (start_line, start_column)
return node
def construct_object(self, node, deep=False):
# Construct the object first
obj = super().construct_object(node, deep=deep)
key = id(obj)
# Use the start location attached to the node
if hasattr(node, '_myloader_start_location'):
self.locations[key] = node._myloader_start_location
else:
self.locations[key] = None
return obj
@classmethod
def load(cls, stream):
loader = cls(stream)
try:
return loader.get_single_data(), loader.locations
finally:
loader.dispose()
class Index:
def __init__(self, content, enabled_linters):
# self._index = json.loads(content)
self._index, self._yaml_locations = TrackingLoader.load(content)
self.hubtypes = list(self._index.keys())
# cache for http requests, by method and url
self._http_cache = {}
# some linter may skip some checks if they are covered by others
self.enabled_linters = enabled_linters
# eager creation of items, so we can store stuff if needed
self._items = []
for hubtype, content in self._index.items():
for key, spec in content.items():
self._items.append(Item(hubtype, key, spec))
def __iter__(self):
yield from self._items
def locate(self, ob):
# TODO: return file path too
return self._yaml_locations.get(id(ob))
def proxy(self, method, url):
"""
Return a cached request, if it exists
"""
try:
return self._http_cache[(url, method)]
except KeyError:
r = requests.request(method, url)
self._http_cache[(url, method)] = r
return r
class Severity(enum.StrEnum):
WARNING = "warning"
ERROR = "error"
class Issue:
def __init__(self, linter, message, severity, location=None):
self.linter = linter
self.message = message
self.location = location
self._reported_severity = severity
# set by the Item after the Issue is created
self.item = None
@property
def severity(self):
# the severity can be ERROR only if the linter is in error mode
if self.linter.error:
return self._reported_severity
return Severity.WARNING
# TODO: __str__ ?
class Item:
def __init__(self, hubtype, key, spec):
self.hubtype = hubtype
self.key = key
self._spec = spec
self._issues = []
def __str__(self):
return f"{self.hubtype}:{self.key}"
def validate(self, linters):
for linter in linters:
for issue in linter(self):
issue.item = self
self._issues.append(issue)
def yaml_content(self):
try:
pth = self._spec['path']
except KeyError:
return ""
try:
with open(pth) as file:
return file.read()
except FileNotFoundError:
return ""
# XXX: loading documents can have errors, how to handle them?
def yaml_docs(self):
content = self.yaml_content()
if not content:
return
for doc in yaml.safe_load_all(content):
yield doc
def data_urls(self):
for doc in self.yaml_docs():
data = doc.get("data", [])
for data in data:
if 'source_url' in data:
yield data['source_url']
class Linter:
def __init__(self):
# XXX: this is mandatory
self.index = None
cls = self.__class__.__name__
if not hasattr(self, "name"):
raise ValueError(f"Linter {cls} must have a name")
if not hasattr(self, "description"):
raise ValueError(f"Linter {cls} must have a description")
if not hasattr(self, "enabled"):
raise ValueError(f"Linter {cls} must have a default 'enabled' attribute")
if not hasattr(self, "error"):
raise ValueError(f"Linter {cls} must have a default 'error' attribute")
if not hasattr(self, "__call__"):
raise ValueError(f"Linter {cls} must have a __call__ method")
def err(self, message, ob=None):
location = None
if ob:
location = self.index.locate(ob)
return Issue(self, message, Severity.ERROR, location)
def warn(self, message, ob=None):
location = None
if ob:
location = self.index.locate(ob)
return Issue(self, message, Severity.WARNING, location)
# yeah, it's a joke/example
class NotLinux(Linter):
name = "not-linux"
description = "Item name must not contain 'linux'"
enabled = False
error = False
def __call__(self, item):
if 'linux' in item.key:
yield self.err(f"Name contains 'linux': {item.key}",
self.index._index[item.hubtype][item.key])
class OnlyCollectionHaveDependencies(Linter):
name = "only-collection-have-dependencies"
description = "Only collections can have dependencies"
enabled = True
error = True
def __call__(self, item):
if item.hubtype == "collections":
return
for typ in self.index.hubtypes:
deps = item._spec.get(typ, [])
if deps:
yield self.err(f"Item declares dependencies but it's not a collection: {typ}={deps}",
self.index._index[item.hubtype][item.key][typ])
class EmptyDependencies(Linter):
name = "empty-dependencies"
description = "An item (collection) contains an explicit empty dependency (ex. parsers=[])"
enabled = True
error = False
def __call__(self, item):
for typ in self.index.hubtypes:
if item._spec.get(typ) == []:
yield self.err(f"Empty dependency: {typ}=[]",
self.index._index[item.hubtype][item.key][typ])
class OneDocumentPerYAMLFile(Linter):
name = "one-document-per-yaml-file"
description = "Each YAML file must contain only one document"
enabled = False
error = False
def __call__(self, item):
names = [doc.get("name") for doc in item.yaml_docs()]
if len(names) > 1:
yield self.err(f"File {item._spec['path']} contains more than one document: {names}")
class MissingAuthor(Linter):
name = "missing-author"
description = "Each item must have an author field"
enabled = True
error = True
def __call__(self, item):
if not item._spec.get("author"):
yield self.err("Missing 'author' field",
self.index._index[item.hubtype][item.key])
class MissingItemFile(Linter):
name = "missing-item-file"
description = "The item file is missing"
enabled = True
error = True
def __call__(self, item):
try:
with open(item._spec['path']):
pass
except FileNotFoundError:
yield self.err(f"File '{item._spec['path']}' does not exist")
except KeyError:
yield self.err("Missing 'path' field",
self.index._index[item.hubtype][item.key])
class MissingDependencies(Linter):
name = "missing-dependencies"
description = "An item declares a dependency that does not exist"
enabled = True
error = True
def __call__(self, item):
for typ in self.index.hubtypes:
for dep_idx, dep in enumerate(item._spec.get(typ, [])):
if dep not in self.index._index.get(typ, {}):
yield self.err(f"Dependency '{typ}:{dep}' does not exist",
self.index._index[item.hubtype][item.key][typ][dep_idx])
class BadPath(Linter):
name = "bad-path"
description = "The path must match the item type, stage (if it exists) and name"
enabled = True
error = False
def __call__(self, item):
stage = item._spec.get("stage")
basedir = f"{item.hubtype}/{stage}" if stage else item.hubtype
expected_paths = [
f"{basedir}/{item.key}.yml",
f"{basedir}/{item.key}.yaml",
]
pth = item._spec.get("path")
if pth not in expected_paths:
ob = self.index._index[item.hubtype][item.key]
if 'path' in ob:
ob = ob['path']
yield self.err(f"Path '{pth}' does not match item type/stage/name (must be one of: {expected_paths})",
ob)
class MissingPath(Linter):
name = "missing-path"
description = "Each item must have a path field"
enabled = True
error = True
def __call__(self, item):
if not item._spec.get("path"):
yield self.err("Missing 'path' field",
self.index._index[item.hubtype][item.key])
class AuthorMatchkey(Linter):
name = "author-match-key"
description = "The author field must match the item key"
enabled = True
error = True
def __call__(self, item):
author = item._spec.get("author", "")
if not item.key.startswith(author + '/'):
ob = self.index._index[item.hubtype][item.key]
if 'author' in ob:
ob = ob['author']
yield self.err(f"Author field '{author}' does not match the item key '{item.key}'",
ob)
class DocumentWithoutName(Linter):
name = "document-without-name"
description = "Each section of a YAML file must have a name (only scenarios)"
enabled = True
error = True
# XXX: we could make linters configurable from the toml file
config = {'hubtypes': ['scenarios']}
def __call__(self, item):
if item.hubtype not in self.config['hubtypes']:
return
for doc in item.yaml_docs():
if not doc.get("name"):
yield self.err(f"YAML document without name: {item._spec['path']}")
class DocumentNameMatchingItem(Linter):
name = "document-name-matching-item"
description = "The name of the document must match the item name (only scenarios+appsec-configs)"
enabled = False
error = False
config = {'hubtypes': ['scenarios', 'appsec-configs']}
def __call__(self, item):
if item.hubtype not in self.config['hubtypes']:
return
for doc in item.yaml_docs():
if doc.get("name") == item.key:
return
yield self.err(f"YAML file {item._spec.get('path')} does not have a document named: {item.key}")
class ItemSchema(Linter):
name = "item-schema"
description = "Validate item files against their YAML schema"
enabled = False
error = False
config = {
'collections': {
'url': 'https://raw.githubusercontent.com/crowdsecurity/crowdsec-yaml-schemas/main/collection_schema.yaml',
},
'parsers': {
'url': 'https://raw.githubusercontent.com/crowdsecurity/crowdsec-yaml-schemas/main/parser_schema.yaml',
},
'scenarios': {
'url': 'https://raw.githubusercontent.com/crowdsecurity/crowdsec-yaml-schemas/main/scenario_schema.yaml',
},
'postoverflows': {
'url': 'https://raw.githubusercontent.com/crowdsecurity/crowdsec-yaml-schemas/main/parser_schema.yaml',
},
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._schemas = {}
def __call__(self, item):
if item.hubtype not in self.config:
return
if item.hubtype not in self._schemas:
try:
yaml_schema = requests.get(self.config[item.hubtype]['url']).text
self._schemas[item.hubtype] = yaml.safe_load(yaml_schema)
except requests.RequestException as e:
yield self.err(f"Failed to fetch schema for {item.hubtype}: {e}")
return
schema = self._schemas[item.hubtype]
for doc in item.yaml_docs():
try:
jsonschema.validate(doc, schema)
except jsonschema.ValidationError as e:
yield self.err(f"File {item._spec.get('path')} does not match the schema: {e.message}")
class DataFilesExist(Linter):
name = "data-files-exist"
description = "Check the source_url of the data files declared in the item"
enabled = False
error = True
def __call__(self, item):
for url in item.data_urls():
try:
if isatty():
print(f"Checking {url}{ERASETOEOL}{BOL}", end="")
try:
r = self.index.proxy(HTTPMethod.HEAD, url)
r.raise_for_status()
except requests.HTTPError as e:
yield self.err(f"HTTP error for data file {url}: {e}")
continue
except requests.RequestException as e:
yield self.err(f"Failed to fetch data file {url}: {e}")
class DataFilesLastModified(Linter):
"""
This is implemented as a separate linter to allow for a warning instead of an error
"""
name = "data-files-last-modified"
description = "Check the last-modified header of the data files declared in the item"
enabled = False
error = False
def __call__(self, item):
for url in item.data_urls():
try:
if isatty():
print(f"Checking {url}{ERASETOEOL}{BOL}", end="")
r = self.index.proxy(HTTPMethod.HEAD, url)
r.raise_for_status()
if not r.headers.get('last-modified'):
yield self.err(f"Data file {url} does not have a 'last-modified' header")
except requests.RequestException as e:
# if the other linter is enabled, we don't report the error here
if DataFilesExist.name in self.index.enabled_linters:
yield self.err(f"Failed to fetch data file {url}: {e}")
class NoDebugMode(Linter):
name = "no-debug-mode"
description = "The item must not be in debug mode"
enabled = True
error = True
def __call__(self, item):
for doc in item.yaml_docs():
if doc.get("debug"):
# TODO: add location (needs file name support if it's other than the index file)
yield self.err(f"Item file {item._spec.get('path')} in debug mode")
class ContentMatchFile(Linter):
name = "content-match-file"
description = "The content of the item must match the file"
enabled = True
error = True
def __call__(self, item):
# TODO: handle file or field not present
from_file = item.yaml_content()
from_file = from_file.encode('utf-8')
from_file = base64.b64encode(from_file).decode('utf-8')
from_field = item._spec.get('content')
if from_field != from_file:
yield self.err(f"Content field does not match the file: {item._spec.get('path')}")
# --------------------------------------------------------------------- #
# validate configuration and create linters
def linters_from_config(config):
cfg_linters = config.get("linters", {})
# create a default configuration for all linters
for linter_class in Linter.__subclasses__():
# see if the class can be instantiated, or defaults are missing
linter_class()
if linter_class.name not in cfg_linters:
cfg_linters[linter_class.name] = {}
for linter_name, linter_cfg in cfg_linters.items():
for linter_class in Linter.__subclasses__():
# TODO: check for duplicates
if linter_class.name == linter_name:
linter = linter_class()
if linter_cfg.get("enabled") is not None:
linter.enabled = linter_cfg.get("enabled")
if linter_cfg.get("error") is not None:
linter.error = linter_cfg.get("error")
# XXX: default config for _each_ linter is not written to the TOML file
if linter_cfg.get("config") is not None:
linter.config = linter_cfg.get("config")
yield linter
break
else:
raise ValueError(f"Unknown linter: {linter_name}")
class TTYReporter:
spinner = ["▹▹▹▹▹", "▸▹▹▹▹", "▹▸▹▹▹", "▹▹▸▹▹", "▹▹▹▸▹", "▹▹▹▹▸"]
def __init__(self, no_warnings, show_location, print_ok=False):
self.no_warnings = no_warnings
self.show_location = show_location
# leave feedback for successful checks too?
self.print_ok = print_ok
def item(self, item):
pass
def update_status(self, idx, tot, item):
wheel = self.spinner[idx % len(self.spinner)]
if isatty():
print(f" {wheel} [{idx}/{tot}] {item}{ERASETOEOL}{BOL}", end="")
def item_feedback(self, item, index, index_file):
print_feedback = False
if any(i.severity == Severity.ERROR for i in item._issues):
check = RED + '✗'
print_feedback = True
elif any(i.severity == Severity.WARNING for i in item._issues):
check = YELLOW + '⚠'
print_feedback = True
else:
check = GREEN + '✓'
if not isatty():
print_feedback = False
if print_feedback or self.print_ok:
print(f" {check}{RESET} {item}{ERASETOEOL}", end="")
if self.print_ok:
print()
else:
print(BOL, end="")
if item._issues:
if print_feedback or self.print_ok:
print("")
for issue in item._issues:
file = index_file.name
if issue.location and self.show_location:
location = f" {file}:{issue.location[0]+1}:{issue.location[1]+1}:"
else:
location = ""
sev = RED if issue.severity == Severity.ERROR else YELLOW
print(f"{sev}{issue.linter.name}:{RESET}{location} {issue.message}")
class MarkDownReporter:
def __init__(self, outfile):
self.outfile = outfile
def write_report(self, index, enabled_linters):
if not self.outfile:
return
self.outfile.write(self.report(index, enabled_linters))
def report(self, index, enabled_linters):
linters_desc = {linter.name: linter.description for linter in enabled_linters}
errors = [i for item in index for i in item._issues if i.severity == Severity.ERROR]
warnings = [i for item in index for i in item._issues if i.severity == Severity.WARNING]
report = [
"# Hublint Validation Report",
"",
f" Checked {len(enabled_linters)} linters: {len(errors)} errors, {len(warnings)} warnings",
"",
]
item_per_type = collections.defaultdict(list)
for item in index:
if not item._issues:
continue
item_per_type[item.hubtype].append(item)
report.append("Issues were found by the following linters.")
report.append("")
failed_linters = set(i.linter.name for i in errors + warnings)
for linter in failed_linters:
report.append(f"## {linter}")
report.append(f" {linters_desc[linter]}")
for hubtype, items in item_per_type.items():
for item in items:
report.append(f"### {hubtype}:{item.key}")
for issue in item._issues:
if issue.severity == Severity.ERROR:
report.append(f" - :x: {issue.linter.name}: {issue.message}")
elif issue.severity == Severity.WARNING:
report.append(f" - :warning: {issue.linter.name}: {issue.message}")
return '\n'.join(report)
def run_linters(index_file, enabled_linters, no_warnings, show_location, markdown, quick):
ttyrep = TTYReporter(no_warnings, show_location)
mdrep = MarkDownReporter(markdown)
t0 = time.time()
try:
content = index_file.read()
index = Index(content, enabled_linters=enabled_linters)
except json.JSONDecodeError as e:
print(f"Error parsing JSON: {e}", file=sys.stderr)
sys.exit(1)
all_items = list(index)
tot = len(all_items)
tot_warnings = 0
tot_errors = 0
errors_by_linter = collections.defaultdict(int)
warnings_by_linter = collections.defaultdict(int)
# XXX: clean this mess
for linter in enabled_linters:
linter.index = index
for idx, item in enumerate(all_items):
ttyrep.update_status(idx, tot, item)
item.validate(enabled_linters)
ttyrep.item_feedback(item, index, index_file)
errors = [i for i in item._issues if i.severity == Severity.ERROR]
tot_errors += len(errors)
for e in errors:
errors_by_linter[e.linter.name] += 1
warnings = [i for i in item._issues if i.severity == Severity.WARNING]
for w in warnings:
warnings_by_linter[w.linter.name] += 1
tot_warnings += len(warnings)
if not quick and isatty():
# fake delay to show the cute spinner
time.sleep(0.01)
# but why? here's why.
#
# Psychological Perspective
#
# Cognitive Processing Time: Users need time to process the
# information presented on the screen. An artificial pause can
# ensure that users have adequate time to read and understand
# the output before the application proceeds to the next step.
# This is especially crucial for complex outputs or instructions
# that require user attention and comprehension.
#
# Reduced Cognitive Load: Rapidly updating the screen with new
# information can overwhelm users, leading to a higher cognitive
# load. By introducing a pause, the application allows the
# user's cognitive processes to catch up with the information
# flow, reducing the risk of information overload.
#
# User Experience and Satisfaction: A pause can contribute to a
# more pleasant user experience by making the interaction feel
# less rushed and more deliberate. This pacing can make the
# application feel more responsive to the user's need for time
# to think and make decisions, potentially increasing overall
# user satisfaction.
#
# Anticipation and Engagement: Strategic pauses can create a
# sense of anticipation, making the interaction more engaging.
# In scenarios where the application performs a complex task, a
# brief pause before displaying the result can enhance the
# perceived value of the outcome.
#
# Other practical reasons can be provided on request.
# More importantly, it allows the developer to make the application faster in a new version.
elapsed = time.time() - t0
print(f"Checked {tot} items: {tot_warnings} warnings, {tot_errors} errors in {elapsed:.2}s{ERASETOEOL}")
print()
if len(errors_by_linter) > 0:
print("Errors by linter:")
for linter, count in sorted(errors_by_linter.items()):
print(f" {linter}: {count}")
if len(warnings_by_linter) > 0:
print("Warnings by linter:")
for linter, count in sorted(warnings_by_linter.items()):
print(f" {linter}: {count}")
mdrep.write_report(index, enabled_linters)
return tot_errors
def read_config(config_file=None):
try:
return tomllib.load(config_file)
except tomllib.TOMLDecodeError as e:
print(f"Error parsing TOML: {e}", file=sys.stderr)
sys.exit(1)
def print_linters(linters):
init_colors('auto')
print("Available linters:")
for linter in linters:
enabled = f"{GREEN}✓{RESET}" if linter.enabled else f"{RED}✗{RESET}"
print(f" {enabled} {linter.name}: {linter.description}")
if linter.enabled:
if linter.error:
print(" error")
else:
print(" warning")
def add_config_argument(parser):
parser.add_argument('--config', default='.hublint.toml', type=argparse.FileType('rb'),
help='The configuration file')
def print_default_config():
linters = list(Linter.__subclasses__())
for linter in linters:
print(f'# {linter.description}')
print(f"[linters.{linter.name}]")
print(f"enabled = {linter.enabled.__str__().lower()}")
print(f"error = {linter.error.__str__().lower()}")
print("")
def main(argv):
parser = argparse.ArgumentParser(description='Validate hub index files',
formatter_class=argparse.RawTextHelpFormatter,
epilog=textwrap.dedent("""
Example:
# generate the initial configuration
hublint defaults > .hublint.toml
# validate an index file
hublint check --index .index.json
"""))
subparsers = parser.add_subparsers(dest='command')
parser_linters = subparsers.add_parser('linters', help='Show all the available linters')
add_config_argument(parser_linters)
parser_check = subparsers.add_parser('check', help='Validate an index file')
parser_check.add_argument('--index', default='.index.json', type=argparse.FileType(),
help='The index file to validate')
parser_check.add_argument('--color', choices=['always', 'never', 'auto'], default='auto',
help='Force colored output')
parser_check.add_argument('--no-warning-details', action='store_true',
help='Do not show warning details (still, count them)')
parser_check.add_argument('--show-location', action='store_true',
help='Show the location of the error/warning')
parser_check.add_argument('--markdown', type=argparse.FileType('w'),
help='Generate a markdown report')
parser_check.add_argument('--quick', action='store_true', help='Quick mode (default when stdout is redirected)')
parser_check.add_argument('--lint-only', type=str, nargs='+', help='Run only the specified linters')
# XXX: --debug option, for logger and to keep stack trace on CTRL+C
add_config_argument(parser_check)
subparsers.add_parser('defaults', help='Show the default configuration',
epilog=textwrap.dedent("""
Example:
#generate an initial configuration file
hublint defaults > .hublint.toml
"""))
args = parser.parse_args()
if args.command not in [None, 'defaults']:
print(f"Using config: {args.config.name}")
config = read_config(args.config)
all_linters = list(linters_from_config(config))
if args.command == "linters":
print_linters(all_linters)
sys.exit(0)
elif args.command == "check":
init_colors(args.color)
print(f"Validating: '{args.index.name}'")
print()
for linter in args.lint_only or []:
if linter not in [linter.name for linter in all_linters]:
print(f"Unknown linter: {linter}", file=sys.stderr)
sys.exit(1)
for linter in all_linters:
if args.lint_only:
linter.enabled = linter.name in args.lint_only
tot_errors = run_linters(args.index, [linter for linter in all_linters if linter.enabled],
no_warnings=args.no_warning_details,
show_location=args.show_location,
markdown=args.markdown,
quick=args.quick)
sys.exit(tot_errors > 0)
elif args.command == "defaults":
print_default_config()
sys.exit(0)
else:
parser.print_help()
sys.exit(1)
if __name__ == "__main__":
try:
main(sys.argv)
except KeyboardInterrupt:
sys.exit(1)