-
-
Notifications
You must be signed in to change notification settings - Fork 238
/
build.py
3423 lines (3242 loc) · 139 KB
/
build.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
# !/usr/bin/env python3
"""
Automatically generate source code ,descriptive files Dockerfiles and documentation
"""
# pylint: disable=import-error
import json
import logging
import os
import re
import shutil
import subprocess
import sys
from datetime import date, datetime
from shutil import copyfile, which
from typing import Any
from urllib import parse as parse_urllib
import git
import jsonschema
import markdown
import megalinter
import requests
import terminaltables
import webpreview
import yaml
from bs4 import BeautifulSoup
from giturlparse import parse
from megalinter import config, utils
from megalinter.constants import (
DEFAULT_DOCKERFILE_APK_PACKAGES,
DEFAULT_RELEASE,
DEFAULT_REPORT_FOLDER_NAME,
ML_DOC_URL_BASE,
ML_DOCKER_IMAGE,
ML_DOCKER_IMAGE_LEGACY,
ML_DOCKER_IMAGE_LEGACY_V5,
ML_REPO,
ML_REPO_URL,
)
from requests.adapters import HTTPAdapter
from urllib3.util import Retry
from webpreview import web_preview
RELEASE = "--release" in sys.argv
UPDATE_STATS = "--stats" in sys.argv or RELEASE is True
UPDATE_DOC = "--doc" in sys.argv or RELEASE is True
UPDATE_DEPENDENTS = "--dependents" in sys.argv
UPDATE_CHANGELOG = "--changelog" in sys.argv
IS_LATEST = "--latest" in sys.argv
DELETE_DOCKERFILES = "--delete-dockerfiles" in sys.argv
DELETE_TEST_CLASSES = "--delete-test-classes" in sys.argv
# Release args management
if RELEASE is True:
RELEASE_TAG = sys.argv[sys.argv.index("--release") + 1]
if "v" not in RELEASE_TAG:
RELEASE_TAG = "v" + RELEASE_TAG
VERSION = RELEASE_TAG.replace("v", "")
VERSION_V = "v" + VERSION
elif "--version" in sys.argv:
VERSION = sys.argv[sys.argv.index("--version") + 1].replace("v", "")
VERSION_V = "v" + VERSION
else:
VERSION = "beta"
VERSION_V = VERSION
# latest management
if IS_LATEST is True:
VERSION_URL_SEGMENT = "latest"
else:
VERSION_URL_SEGMENT = VERSION
MKDOCS_URL_ROOT = ML_DOC_URL_BASE + VERSION_URL_SEGMENT
BRANCH = "main"
URL_ROOT = ML_REPO_URL + "/tree/" + BRANCH
URL_RAW_ROOT = ML_REPO_URL + "/raw/" + BRANCH
TEMPLATES_URL_ROOT = URL_ROOT + "/TEMPLATES"
DOCS_URL_ROOT = URL_ROOT + "/docs"
DOCS_URL_DESCRIPTORS_ROOT = DOCS_URL_ROOT + "/descriptors"
DOCS_URL_FLAVORS_ROOT = DOCS_URL_ROOT + "/flavors"
DOCS_URL_RAW_ROOT = URL_RAW_ROOT + "/docs"
REPO_HOME = os.path.dirname(os.path.abspath(__file__)) + os.path.sep + ".."
REPO_ICONS = REPO_HOME + "/docs/assets/icons"
REPO_IMAGES = REPO_HOME + "/docs/assets/images"
VERSIONS_FILE = REPO_HOME + "/.automation/generated/linter-versions.json"
LICENSES_FILE = REPO_HOME + "/.automation/generated/linter-licenses.json"
USERS_FILE = REPO_HOME + "/.automation/generated/megalinter-users.json"
HELPS_FILE = REPO_HOME + "/.automation/generated/linter-helps.json"
LINKS_PREVIEW_FILE = REPO_HOME + "/.automation/generated/linter-links-previews.json"
DOCKER_STATS_FILE = REPO_HOME + "/.automation/generated/flavors-stats.json"
PLUGINS_FILE = REPO_HOME + "/.automation/plugins.yml"
FLAVORS_DIR = REPO_HOME + "/flavors"
LINTERS_DIR = REPO_HOME + "/linters"
GLOBAL_FLAVORS_FILE = REPO_HOME + "/megalinter/descriptors/all_flavors.json"
BASE_SHIELD_IMAGE_LINK = "https://img.shields.io/docker/image-size"
BASE_SHIELD_COUNT_LINK = "https://img.shields.io/docker/pulls"
DESCRIPTOR_JSON_SCHEMA = (
f"{REPO_HOME}/megalinter/descriptors/schemas/megalinter-descriptor.jsonschema.json"
)
CONFIG_JSON_SCHEMA = f"{REPO_HOME}/megalinter/descriptors/schemas/megalinter-configuration.jsonschema.json"
OWN_MEGALINTER_CONFIG_FILE = f"{REPO_HOME}/.mega-linter.yml"
IDE_LIST = {
"atom": {"label": "Atom", "url": "https://atom.io/"},
"brackets": {"label": "Brackets", "url": "https://brackets.io/"},
"eclipse": {"label": "Eclipse", "url": "https://www.eclipse.org/"},
"emacs": {"label": "Emacs", "url": "https://www.gnu.org/software/emacs/"},
"idea": {
"label": "IDEA",
"url": "https://www.jetbrains.com/products.html#type=ide",
},
"sublime": {"label": "Sublime Text", "url": "https://www.sublimetext.com/"},
"vim": {"label": "vim", "url": "https://www.vim.org/"},
"vscode": {"label": "Visual Studio Code", "url": "https://code.visualstudio.com/"},
}
DEPRECATED_LINTERS = [
"CREDENTIALS_SECRETLINT", # Removed in v6
"DOCKERFILE_DOCKERFILELINT", # Removed in v6
"GIT_GIT_DIFF", # Removed in v6
"PHP_BUILTIN", # Removed in v6
"KUBERNETES_KUBEVAL", # Removed in v7
"REPOSITORY_GOODCHECK", # Removed in v7
"SPELL_MISSPELL", # Removed in v7
"TERRAFORM_CHECKOV", # Removed in v7
"TERRAFORM_KICS", # Removed in v7
"CSS_SCSSLINT", # Removed in v8
"OPENAPI_SPECTRAL", # Removed in v8
"SQL_SQL_LINT", # Removed in v8
]
DESCRIPTORS_FOR_BUILD_CACHE = None
# Generate one Dockerfile by MegaLinter flavor
def generate_all_flavors():
flavors = megalinter.flavor_factory.list_megalinter_flavors()
for flavor, flavor_info in flavors.items():
generate_flavor(flavor, flavor_info)
update_mkdocs_and_workflow_yml_with_flavors()
if UPDATE_STATS is True:
try:
update_docker_pulls_counter()
except requests.exceptions.ConnectionError as e:
logging.warning(
"Connection error - Unable to update docker pull counters: " + str(e)
)
except Exception as e:
logging.warning("Unable to update docker pull counters: " + str(e))
# Automatically generate Dockerfile , action.yml and upgrade all_flavors.json
def generate_flavor(flavor, flavor_info):
descriptor_and_linters = []
flavor_descriptors = []
flavor_linters = []
# Get install instructions at descriptor level
descriptor_files = megalinter.linter_factory.list_descriptor_files()
for descriptor_file in descriptor_files:
with open(descriptor_file, "r", encoding="utf-8") as f:
descriptor = yaml.safe_load(f)
if (
match_flavor(descriptor, flavor, flavor_info) is True
and "install" in descriptor
):
descriptor_and_linters += [descriptor]
flavor_descriptors += [descriptor["descriptor_id"]]
# Get install instructions at linter level
linters = megalinter.linter_factory.list_all_linters(({"request_id": "build"}))
requires_docker = False
for linter in linters:
if match_flavor(vars(linter), flavor, flavor_info) is True:
descriptor_and_linters += [vars(linter)]
flavor_linters += [linter.name]
if linter.cli_docker_image is not None:
requires_docker = True
# Initialize Dockerfile
if flavor == "all":
dockerfile = f"{REPO_HOME}/Dockerfile"
if RELEASE is True:
image_release = RELEASE_TAG
action_yml = f"""# Automatically {'@'}generated by build.py
name: "MegaLinter"
author: "Nicolas Vuillamy"
description: "Combine all available linters to automatically validate your sources without configuration !"
outputs:
has_updated_sources:
description: "0 if no source file has been updated, 1 if source files has been updated"
runs:
using: "docker"
image: "docker://{ML_DOCKER_IMAGE}:{image_release}"
args:
- "-v"
- "/var/run/docker.sock:/var/run/docker.sock:rw"
branding:
icon: "check"
color: "green"
"""
main_action_yml = "action.yml"
with open(main_action_yml, "w", encoding="utf-8") as file:
file.write(action_yml)
logging.info(f"Updated {main_action_yml}")
else:
# Flavor json
flavor_file = f"{FLAVORS_DIR}/{flavor}/flavor.json"
if os.path.isfile(flavor_file):
with open(flavor_file, "r", encoding="utf-8") as json_file:
flavor_info = json.load(json_file)
flavor_info["descriptors"] = flavor_descriptors
flavor_info["linters"] = flavor_linters
os.makedirs(os.path.dirname(flavor_file), exist_ok=True)
with open(flavor_file, "w", encoding="utf-8") as outfile:
json.dump(flavor_info, outfile, indent=4, sort_keys=True)
outfile.write("\n")
# Write in global flavors files
with open(GLOBAL_FLAVORS_FILE, "r", encoding="utf-8") as json_file:
global_flavors = json.load(json_file)
global_flavors[flavor] = flavor_info
with open(GLOBAL_FLAVORS_FILE, "w", encoding="utf-8") as outfile:
json.dump(global_flavors, outfile, indent=4, sort_keys=True)
outfile.write("\n")
# Flavored dockerfile
dockerfile = f"{FLAVORS_DIR}/{flavor}/Dockerfile"
if not os.path.isdir(os.path.dirname(dockerfile)):
os.makedirs(os.path.dirname(dockerfile), exist_ok=True)
copyfile(f"{REPO_HOME}/Dockerfile", dockerfile)
flavor_label = flavor_info["label"]
comment = f"# MEGALINTER FLAVOR [{flavor}]: {flavor_label}"
with open(dockerfile, "r+", encoding="utf-8") as f:
first_line = f.readline().rstrip()
if first_line.startswith("# syntax="):
comment = f"{first_line}\n{comment}"
else:
f.seek(0)
content = f.read()
f.seek(0)
f.truncate()
f.write(f"{comment}\n{content}")
# Generate action.yml
if RELEASE is True:
image_release = RELEASE_TAG
else:
image_release = DEFAULT_RELEASE
flavor_x = f"[{flavor} flavor]"
action_yml = f""" # Automatically {'@'}generated by build.py
name: "MegaLinter"
author: "Nicolas Vuillamy"
description: "{flavor_x} Combine all available linters to automatically validate your sources without configuration !"
outputs:
has_updated_sources:
description: "0 if no source file has been updated, 1 if source files has been updated"
runs:
using: "docker"
image: "docker://{ML_DOCKER_IMAGE}-{flavor}:{image_release}"
args:
- "-v"
- "/var/run/docker.sock:/var/run/docker.sock:rw"
branding:
icon: "check"
color: "green"
"""
flavor_action_yml = f"{FLAVORS_DIR}/{flavor}/action.yml"
with open(flavor_action_yml, "w", encoding="utf-8") as file:
file.write(action_yml)
logging.info(f"Updated {flavor_action_yml}")
extra_lines = [
"COPY entrypoint.sh /entrypoint.sh",
"RUN chmod +x entrypoint.sh",
'ENTRYPOINT ["/bin/bash", "/entrypoint.sh"]',
]
build_dockerfile(
dockerfile,
descriptor_and_linters,
requires_docker,
flavor,
extra_lines,
{"cargo": ["sarif-fmt"]},
)
def build_dockerfile(
dockerfile,
descriptor_and_linters,
requires_docker,
flavor,
extra_lines,
extra_packages=None,
):
if extra_packages is None:
extra_packages = {}
# Gather all dockerfile commands
docker_from = []
docker_arg = []
docker_copy = []
docker_other = []
all_dockerfile_items = []
apk_packages = DEFAULT_DOCKERFILE_APK_PACKAGES.copy()
npm_packages = []
pip_packages = []
pipvenv_packages = {}
gem_packages = []
cargo_packages = [] if "cargo" not in extra_packages else extra_packages["cargo"]
is_docker_other_run = False
# Manage docker
if requires_docker is True:
apk_packages += ["docker", "openrc"]
docker_other += [
"RUN rc-update add docker boot && (rc-service docker start || true)"
]
is_docker_other_run = True
for item in descriptor_and_linters:
if "install" not in item:
item["install"] = {}
# Collect Dockerfile items
if "dockerfile" in item["install"]:
item_label = item.get("linter_name", item.get("descriptor_id", ""))
docker_other += [f"# {item_label} installation"]
for dockerfile_item in item["install"]["dockerfile"]:
# FROM
if dockerfile_item.startswith("FROM"):
if dockerfile_item in all_dockerfile_items:
dockerfile_item = (
"# Next FROM line commented because already managed by another linter\n"
"# " + "\n# ".join(dockerfile_item.splitlines())
)
docker_from += [dockerfile_item]
# ARG
elif dockerfile_item.startswith("ARG") or (
len(dockerfile_item.splitlines()) > 1
and dockerfile_item.splitlines()[0].startswith("# renovate: ")
and dockerfile_item.splitlines()[1].startswith("ARG")
):
docker_arg += [dockerfile_item]
# COPY
elif dockerfile_item.startswith("COPY"):
if dockerfile_item in all_dockerfile_items:
dockerfile_item = (
"# Next COPY line commented because already managed by another linter\n"
"# " + "\n# ".join(dockerfile_item.splitlines())
)
docker_copy += [dockerfile_item]
docker_other += [
"# Managed with "
+ "\n# ".join(dockerfile_item.splitlines())
]
# Already used item
elif (
dockerfile_item in all_dockerfile_items
or dockerfile_item.replace(
"RUN ", "RUN --mount=type=secret,id=GITHUB_TOKEN "
)
in all_dockerfile_items
):
dockerfile_item = (
"# Next line commented because already managed by another linter\n"
"# " + "\n# ".join(dockerfile_item.splitlines())
)
docker_other += [dockerfile_item]
# RUN (standalone with GITHUB_TOKEN)
elif (
dockerfile_item.startswith("RUN")
and "GITHUB_TOKEN" in dockerfile_item
):
dockerfile_item_cmd = dockerfile_item.replace(
"RUN ", "RUN --mount=type=secret,id=GITHUB_TOKEN "
)
docker_other += [dockerfile_item_cmd]
is_docker_other_run = False
# RUN (start)
elif dockerfile_item.startswith("RUN") and is_docker_other_run is False:
docker_other += [dockerfile_item]
is_docker_other_run = True
# RUN (append)
elif dockerfile_item.startswith("RUN") and is_docker_other_run is True:
dockerfile_item_cmd = dockerfile_item.replace("RUN", " &&")
# Add \ in previous instruction line
for index, prev_instruction_line in reversed(
list(enumerate(docker_other))
):
if (
prev_instruction_line.strip() != ""
and not prev_instruction_line.startswith("#")
):
# Remove last char if \n
prev_instruction_line = (
prev_instruction_line
if not prev_instruction_line.endswith("\n")
else prev_instruction_line[:-1]
)
docker_other[index] = prev_instruction_line + " \\"
break
docker_other += [dockerfile_item_cmd]
# Other
else:
is_docker_other_run = False
docker_other += [dockerfile_item]
all_dockerfile_items += [dockerfile_item]
docker_other += ["#"]
# Collect python packages
if "apk" in item["install"]:
apk_packages += item["install"]["apk"]
# Collect npm packages
if "npm" in item["install"]:
npm_packages += item["install"]["npm"]
# Collect python for venvs
if "linter_name" in item and "pip" in item["install"]:
pipvenv_packages[item["linter_name"]] = item["install"]["pip"]
# Collect python packages
if "pip" in item["install"]:
pip_packages += item["install"]["pip"]
# Collect ruby packages
if "gem" in item["install"]:
gem_packages += item["install"]["gem"]
# Collect cargo packages (rust)
if "cargo" in item["install"]:
cargo_packages += item["install"]["cargo"]
# Add node install if node packages are here
if len(npm_packages) > 0:
apk_packages += ["npm", "nodejs-current", "yarn"]
# Add ruby apk packages if gem packages are here
if len(gem_packages) > 0:
apk_packages += ["ruby", "ruby-dev", "ruby-bundler", "ruby-rdoc"]
# Separate args used in FROM instructions from others
all_from_instructions = "\n".join(list(dict.fromkeys(docker_from)))
docker_arg_top = []
docker_arg_main = []
for docker_arg_item in docker_arg:
match = re.match(
r"(?:# renovate: .*\n)?ARG\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*=?\s*",
docker_arg_item,
)
arg_name = match.group(1)
if arg_name in all_from_instructions:
docker_arg_top += [docker_arg_item]
else:
docker_arg_main += [docker_arg_item]
# Replace between tags in Dockerfile
# Commands
replace_in_file(
dockerfile,
"#FROM__START",
"#FROM__END",
"\n".join(list(dict.fromkeys(docker_from))),
)
replace_in_file(
dockerfile,
"#ARGTOP__START",
"#ARGTOP__END",
"\n".join(list(dict.fromkeys(docker_arg_top))),
)
replace_in_file(
dockerfile,
"#ARG__START",
"#ARG__END",
"\n".join(list(dict.fromkeys(docker_arg_main))),
)
replace_in_file(
dockerfile,
"#COPY__START",
"#COPY__END",
"\n".join(docker_copy),
)
replace_in_file(
dockerfile,
"#OTHER__START",
"#OTHER__END",
"\n".join(docker_other),
)
# apk packages
apk_install_command = ""
if len(apk_packages) > 0:
apk_install_command = (
"RUN apk add --no-cache \\\n "
+ " \\\n ".join(list(dict.fromkeys(apk_packages)))
+ " \\\n && git config --global core.autocrlf true"
)
replace_in_file(dockerfile, "#APK__START", "#APK__END", apk_install_command)
# cargo packages
cargo_install_command = ""
keep_rustup = False
if len(cargo_packages) > 0:
rust_commands = []
if "clippy" in cargo_packages:
cargo_packages.remove("clippy")
rust_commands += ["rustup component add clippy"]
keep_rustup = True
# Only COMPILER_ONLY in descriptors just to have rust toolchain in the Dockerfile
if all(p == "COMPILER_ONLY" for p in cargo_packages):
rust_commands += [
'echo "No cargo package to install, we just need rust for dependencies"'
]
keep_rustup = True
# Cargo packages to install minus empty package
elif len(cargo_packages) > 0:
cargo_packages = [
p for p in cargo_packages if p != "COMPILER_ONLY"
] # remove empty string packages
cargo_cmd = "cargo install --force --locked " + " ".join(
list(dict.fromkeys(cargo_packages))
)
rust_commands += [cargo_cmd]
rustup_cargo_cmd = " && ".join(rust_commands)
cargo_install_command = (
"RUN curl https://sh.rustup.rs -sSf |"
+ " sh -s -- -y --profile minimal --default-toolchain stable \\\n"
+ ' && export PATH="/root/.cargo/bin:${PATH}" \\\n'
+ f" && {rustup_cargo_cmd} \\\n"
+ " && rm -rf /root/.cargo/registry /root/.cargo/git "
+ "/root/.cache/sccache"
+ (" /root/.rustup" if keep_rustup is False else "")
+ "\n"
+ 'ENV PATH="/root/.cargo/bin:${PATH}"'
)
replace_in_file(dockerfile, "#CARGO__START", "#CARGO__END", cargo_install_command)
# NPM packages
npm_install_command = ""
if len(npm_packages) > 0:
npm_install_command = (
"WORKDIR /node-deps\n"
+ "RUN npm --no-cache install --ignore-scripts --omit=dev \\\n "
+ " \\\n ".join(list(dict.fromkeys(npm_packages)))
+ " && \\\n"
# + ' echo "Fixing audit issues with npm…" \\\n'
# + " && npm audit fix --audit-level=critical || true \\\n" # Deactivated for now
+ ' echo "Cleaning npm cache…" \\\n'
+ " && (npm cache clean --force || true) \\\n"
+ ' && echo "Changing owner of node_modules files…" \\\n'
+ ' && chown -R "$(id -u)":"$(id -g)" node_modules # fix for https://github.com/npm/cli/issues/5900 \\\n'
+ ' && echo "Removing extra node_module files…" \\\n'
+ ' && find . \\( -not -path "/proc" \\)'
+ " -and \\( -type f"
+ ' \\( -iname "*.d.ts"'
+ ' -o -iname "*.map"'
+ ' -o -iname "*.npmignore"'
+ ' -o -iname "*.travis.yml"'
+ ' -o -iname "CHANGELOG.md"'
+ ' -o -iname "README.md"'
+ ' -o -iname ".package-lock.json"'
+ ' -o -iname "package-lock.json"'
+ " \\) -o -type d -name /root/.npm/_cacache \\) -delete \n"
+ "WORKDIR /\n"
)
replace_in_file(dockerfile, "#NPM__START", "#NPM__END", npm_install_command)
# Python pip packages
pip_install_command = ""
if len(pip_packages) > 0:
pip_install_command = (
"RUN PYTHONDONTWRITEBYTECODE=1 pip3 install --no-cache-dir --upgrade pip &&"
+ " PYTHONDONTWRITEBYTECODE=1 pip3 install --no-cache-dir --upgrade \\\n '"
+ "' \\\n '".join(list(dict.fromkeys(pip_packages)))
+ "' && \\\n"
+ r"find . \( -type f \( -iname \*.pyc -o -iname \*.pyo \) -o -type d -iname __pycache__ \) -delete"
+ " \\\n && "
+ "rm -rf /root/.cache"
)
replace_in_file(dockerfile, "#PIP__START", "#PIP__END", pip_install_command)
# Python packages in venv
if len(pipvenv_packages.items()) > 0:
pipenv_install_command = (
"RUN PYTHONDONTWRITEBYTECODE=1 pip3 install"
" --no-cache-dir --upgrade pip virtualenv \\\n"
)
env_path_command = 'ENV PATH="${PATH}"'
for pip_linter, pip_linter_packages in pipvenv_packages.items():
pipenv_install_command += (
f' && mkdir -p "/venvs/{pip_linter}" '
+ f'&& cd "/venvs/{pip_linter}" '
+ "&& virtualenv . "
+ "&& source bin/activate "
+ "&& PYTHONDONTWRITEBYTECODE=1 pip3 install --no-cache-dir "
+ (" ".join(pip_linter_packages))
+ " "
+ "&& deactivate "
+ "&& cd ./../.. \\\n"
)
env_path_command += f":/venvs/{pip_linter}/bin"
pipenv_install_command = pipenv_install_command[:-2] # remove last \
pipenv_install_command += (
" \\\n && "
+ r"find /venvs \( -type f \( -iname \*.pyc -o -iname \*.pyo \) -o -type d -iname __pycache__ \) -delete"
+ " \\\n && "
+ "rm -rf /root/.cache\n"
+ env_path_command
)
else:
pipenv_install_command = ""
replace_in_file(
dockerfile, "#PIPVENV__START", "#PIPVENV__END", pipenv_install_command
)
# Ruby gem packages
gem_install_command = ""
if len(gem_packages) > 0:
gem_install_command = (
"RUN echo 'gem: --no-document' >> ~/.gemrc && \\\n"
+ " gem install \\\n "
+ " \\\n ".join(list(dict.fromkeys(gem_packages)))
)
replace_in_file(dockerfile, "#GEM__START", "#GEM__END", gem_install_command)
flavor_env = f"ENV MEGALINTER_FLAVOR={flavor}"
replace_in_file(dockerfile, "#FLAVOR__START", "#FLAVOR__END", flavor_env)
replace_in_file(
dockerfile,
"#EXTRA_DOCKERFILE_LINES__START",
"#EXTRA_DOCKERFILE_LINES__END",
"\n".join(extra_lines),
)
def match_flavor(item, flavor, flavor_info):
is_strict = "strict" in flavor_info and flavor_info["strict"] is True
if "disabled" in item and item["disabled"] is True:
return
if (
"descriptor_flavors_exclude" in item
and flavor in item["descriptor_flavors_exclude"]
):
return False
# Flavor all
elif flavor == "all":
return True
# Formatter flavor
elif flavor == "formatters":
if "is_formatter" in item and item["is_formatter"] is True:
return True
elif (
"descriptor_flavors" in item
and flavor in item["descriptor_flavors"]
and "linter_name" not in item
):
return True
else:
return False
# Other flavors
elif "descriptor_flavors" in item:
if flavor in item["descriptor_flavors"] or (
"all_flavors" in item["descriptor_flavors"]
and not flavor.endswith("_light")
and "cupcake" not in flavor
and not is_strict
):
return True
return False
# Automatically generate Dockerfile for standalone linters
def generate_linter_dockerfiles():
# Remove all the contents of LINTERS_DIR beforehand so that the result is deterministic
if DELETE_DOCKERFILES is True:
shutil.rmtree(os.path.realpath(LINTERS_DIR))
# Browse descriptors
linters_md = "# Standalone linter docker images\n\n"
linters_md += "| Linter key | Docker image | Size |\n"
linters_md += "| :----------| :----------- | :--: |\n"
descriptor_files = megalinter.linter_factory.list_descriptor_files()
gha_workflow_yml = [" linter:", " ["]
for descriptor_file in descriptor_files:
descriptor_items = []
with open(descriptor_file, "r", encoding="utf-8") as f:
descriptor = yaml.safe_load(f)
if "install" in descriptor:
descriptor_items += [descriptor]
descriptor_linters = megalinter.linter_factory.build_descriptor_linters(
descriptor_file, {"request_id": "build"}
)
# Browse descriptor linters
for linter in descriptor_linters:
# Unique linter dockerfile
linter_lower_name = linter.name.lower()
dockerfile = f"{LINTERS_DIR}/{linter_lower_name}/Dockerfile"
if not os.path.isdir(os.path.dirname(dockerfile)):
os.makedirs(os.path.dirname(dockerfile), exist_ok=True)
requires_docker = False
if linter.cli_docker_image is not None:
requires_docker = True
descriptor_and_linter = descriptor_items + [vars(linter)]
copyfile(f"{REPO_HOME}/Dockerfile", dockerfile)
extra_lines = [
f"ENV ENABLE_LINTERS={linter.name} \\",
" FLAVOR_SUGGESTIONS=false \\",
f" SINGLE_LINTER={linter.name} \\",
" PRINT_ALPACA=false \\",
" LOG_FILE=none \\",
" SARIF_REPORTER=true \\",
" TEXT_REPORTER=false \\",
" UPDATED_SOURCES_REPORTER=false \\",
" GITHUB_STATUS_REPORTER=false \\",
" GITHUB_COMMENT_REPORTER=false \\",
" EMAIL_REPORTER=false \\",
" API_REPORTER=false \\",
" FILEIO_REPORTER=false \\",
" CONFIG_REPORTER=false \\",
" SARIF_TO_HUMAN=false" "",
# "EXPOSE 80",
"RUN mkdir /root/docker_ssh && mkdir /usr/bin/megalinter-sh",
"EXPOSE 22",
"COPY entrypoint.sh /entrypoint.sh",
"COPY sh /usr/bin/megalinter-sh",
"COPY sh/megalinter_exec /usr/bin/megalinter_exec",
"COPY sh/motd /etc/motd",
'RUN find /usr/bin/megalinter-sh/ -type f -iname "*.sh" -exec chmod +x {} \\; && \\',
" chmod +x entrypoint.sh && \\",
" chmod +x /usr/bin/megalinter_exec && \\",
" echo \"alias megalinter='python -m megalinter.run'\" >> ~/.bashrc && source ~/.bashrc && \\",
" echo \"alias megalinter_exec='/usr/bin/megalinter_exec'\" >> ~/.bashrc && source ~/.bashrc",
'RUN export STANDALONE_LINTER_VERSION="$(python -m megalinter.run --input /tmp --linterversion)" && \\',
" echo $STANDALONE_LINTER_VERSION",
# " echo $STANDALONE_LINTER_VERSION >> ~/.bashrc && source ~/.bashrc",
'ENTRYPOINT ["/bin/bash", "/entrypoint.sh"]',
]
build_dockerfile(
dockerfile, descriptor_and_linter, requires_docker, "none", extra_lines
)
gha_workflow_yml += [f' "{linter_lower_name}",']
docker_image = f"{ML_DOCKER_IMAGE}-only-{linter_lower_name}:{VERSION_V}"
docker_image_badge = (
f"![Docker Image Size (tag)]({BASE_SHIELD_IMAGE_LINK}/"
f"{ML_DOCKER_IMAGE}-only-{linter_lower_name}/{VERSION_V})"
)
linters_md += (
f"| {linter.name} | {docker_image} | {docker_image_badge} |\n"
)
# Update github action workflow
gha_workflow_yml += [" ]"]
replace_in_file(
f"{REPO_HOME}/.github/workflows/deploy-DEV-linters.yml",
"# linters-start",
"# linters-end",
"\n".join(gha_workflow_yml),
)
replace_in_file(
f"{REPO_HOME}/.github/workflows/deploy-BETA-linters.yml",
"# linters-start",
"# linters-end",
"\n".join(gha_workflow_yml),
)
replace_in_file(
f"{REPO_HOME}/.github/workflows/deploy-RELEASE-linters.yml",
"# linters-start",
"# linters-end",
"\n".join(gha_workflow_yml),
)
# Write MD file
file = open(f"{REPO_HOME}/docs/standalone-linters.md", "w", encoding="utf-8")
file.write(linters_md + "\n")
file.close()
# Automatically generate a test class for each linter class
# This could be done dynamically at runtime, but having a physical class is easier for developers in IDEs
def generate_linter_test_classes():
test_linters_root = f"{REPO_HOME}/megalinter/tests/test_megalinter/linters"
if DELETE_TEST_CLASSES is True:
# Remove all the contents of test_linters_root beforehand so that the result is deterministic
shutil.rmtree(os.path.realpath(test_linters_root))
os.makedirs(os.path.realpath(test_linters_root))
linters = megalinter.linter_factory.list_all_linters(({"request_id": "build"}))
for linter in linters:
if linter.name is not None:
linter_name = linter.name
else:
lang_lower = linter.descriptor_id.lower()
linter_name = f"{lang_lower}_{linter.linter_name}"
linter_name_lower = linter_name.lower().replace("-", "_")
test_class_code = f"""# !/usr/bin/env python3
\"\"\"
Unit tests for {linter.descriptor_id} linter {linter.linter_name}
This class has been automatically {'@'}generated by .automation/build.py, please don't update it manually
\"\"\"
from unittest import TestCase
from megalinter.tests.test_megalinter.LinterTestRoot import LinterTestRoot
class {linter_name_lower}_test(TestCase, LinterTestRoot):
descriptor_id = "{linter.descriptor_id}"
linter_name = "{linter.linter_name}"
"""
test_class_file_name = f"{test_linters_root}/{linter_name_lower}_test.py"
if not os.path.isfile(test_class_file_name):
file = open(
test_class_file_name,
"w",
encoding="utf-8",
)
file.write(test_class_code)
file.close()
logging.info("Updated " + file.name)
def list_descriptors_for_build():
global DESCRIPTORS_FOR_BUILD_CACHE
if DESCRIPTORS_FOR_BUILD_CACHE is not None:
return DESCRIPTORS_FOR_BUILD_CACHE
descriptor_files = megalinter.linter_factory.list_descriptor_files()
linters_by_type = {"language": [], "format": [], "tooling_format": [], "other": []}
descriptors = []
for descriptor_file in descriptor_files:
descriptor = megalinter.linter_factory.build_descriptor_info(descriptor_file)
descriptors += [descriptor]
descriptor_linters = megalinter.linter_factory.build_descriptor_linters(
descriptor_file, {"request_id": "build"}
)
linters_by_type[descriptor_linters[0].descriptor_type] += descriptor_linters
DESCRIPTORS_FOR_BUILD_CACHE = descriptors, linters_by_type
return descriptors, linters_by_type
# Automatically generate README linters table and a MD file for each linter
def generate_documentation():
descriptors, linters_by_type = list_descriptors_for_build()
# Build descriptors documentation
for descriptor in descriptors:
generate_descriptor_documentation(descriptor)
# Build README linters table and linters documentation
linters_tables_md = []
process_type(linters_by_type, "language", "Languages", linters_tables_md)
process_type(linters_by_type, "format", "Formats", linters_tables_md)
process_type(
linters_by_type, "tooling_format", "Tooling formats", linters_tables_md
)
process_type(linters_by_type, "other", "Other", linters_tables_md)
linters_tables_md_str = "\n".join(linters_tables_md)
logging.info("Generated Linters table for README:\n" + linters_tables_md_str)
replace_in_file(
f"{REPO_HOME}/README.md",
"<!-- linters-table-start -->",
"<!-- linters-table-end -->",
linters_tables_md_str,
)
replace_in_file(
f"{REPO_HOME}/mega-linter-runner/README.md",
"<!-- linters-table-start -->",
"<!-- linters-table-end -->",
linters_tables_md_str,
)
# Update welcome phrase
welcome_phrase = (
"MegaLinter is an **Open-Source** tool for **CI/CD workflows** "
+ "that analyzes the **consistency of your "
+ "code**, **IAC**, **configuration**, and **scripts** in your repository "
+ "sources, to **ensure all your projects "
+ "sources are clean and formatted** whatever IDE/toolbox is used by "
+ "their developers, powered by [**OX Security**](https://www.ox.security/?ref=megalinter).\n\n"
+ f"Supporting [**{len(linters_by_type['language'])}** languages]"
+ "(#languages), "
+ f"[**{len(linters_by_type['format'])}** formats](#formats), "
+ f"[**{len(linters_by_type['tooling_format'])}** tooling formats](#tooling-formats) "
+ "and **ready to use out of the box**, as a GitHub action or any CI system, "
+ "**highly configurable** and **free for all uses**.\n\n"
+ "MegaLinter has **native integrations** with many of the major CI/CD tools of the market.\n\n"
+ "[![GitHub](https://github.com/oxsecurity/megalinter/blob/main/docs/assets/icons/integrations/github.png?raw=true>)](https://github.com/oxsecurity/megalinter/tree/main/docs/reporters/GitHubCommentReporter.md)\n" # noqa: E501
+ "[![Gitlab](https://github.com/oxsecurity/megalinter/blob/main/docs/assets/icons/integrations/gitlab.png?raw=true>)](https://github.com/oxsecurity/megalinter/tree/main/docs/reporters/GitlabCommentReporter.md)\n" # noqa: E501
+ "[![Azure](https://github.com/oxsecurity/megalinter/blob/main/docs/assets/icons/integrations/azure.png?raw=true>)](https://github.com/oxsecurity/megalinter/tree/main/docs/reporters/AzureCommentReporter.md)\n" # noqa: E501
+ "[![Bitbucket](https://github.com/oxsecurity/megalinter/blob/main/docs/assets/icons/integrations/bitbucket.png?raw=true>)](https://github.com/oxsecurity/megalinter/tree/main/docs/reporters/BitbucketCommentReporter.md)\n" # noqa: E501
+ "[![Jenkins](https://github.com/oxsecurity/megalinter/blob/main/docs/assets/icons/integrations/jenkins.png?raw=true>)](https://github.com/oxsecurity/megalinter/tree/main/docs/install-jenkins.md)\n" # noqa: E501
+ "[![Drone](https://github.com/oxsecurity/megalinter/blob/main/docs/assets/icons/integrations/drone.png?raw=true>)](https://github.com/oxsecurity/megalinter/tree/main/docs/install-drone.md)\n" # noqa: E501
+ "[![Concourse](https://github.com/oxsecurity/megalinter/blob/main/docs/assets/icons/integrations/concourse.png?raw=true>)](https://github.com/oxsecurity/megalinter/tree/main/docs/install-concourse.md)\n" # noqa: E501
+ "[![Docker](https://github.com/oxsecurity/megalinter/blob/main/docs/assets/icons/integrations/docker.png?raw=true>)](https://github.com/oxsecurity/megalinter/tree/main/docs/install-docker.md)\n" # noqa: E501
+ "[![SARIF](https://github.com/oxsecurity/megalinter/blob/main/docs/assets/icons/integrations/sarif.png?raw=true>)](https://github.com/oxsecurity/megalinter/tree/main/docs/reporters/SarifReporter.md)\n" # noqa: E501
+ "[![Grafana](https://github.com/oxsecurity/megalinter/blob/main/docs/assets/icons/integrations/grafana.png?raw=true>)](https://github.com/oxsecurity/megalinter/tree/main/docs/reporters/ApiReporter.md)\n\n" # noqa: E501
)
# Update README.md file
replace_in_file(
f"{REPO_HOME}/README.md",
"<!-- welcome-phrase-start -->",
"<!-- welcome-phrase-end -->",
welcome_phrase,
)
# Update mkdocs.yml file
replace_in_file(
f"{REPO_HOME}/mkdocs.yml",
"# site_description-start",
"# site_description-end",
"site_description: " + md_to_text(welcome_phrase.replace("\n", "")),
)
# Build & Update flavors table
flavors_table_md = build_flavors_md_table()
flavors_table_md_str = "\n".join(flavors_table_md)
logging.info("Generated Flavors table for README:\n" + flavors_table_md_str)
replace_in_file(
f"{REPO_HOME}/README.md",
"<!-- flavors-table-start -->",
"<!-- flavors-table-end -->",
flavors_table_md_str,
)
# Build & Update flavors table
plugins_table_md = build_plugins_md_table()
plugins_table_md_str = "\n".join(plugins_table_md)
logging.info("Generated Plugins table for README:\n" + plugins_table_md_str)
replace_in_file(
f"{REPO_HOME}/README.md",
"<!-- plugins-table-start -->",
"<!-- plugins-table-end -->",
plugins_table_md_str,
)
# Generate flavors individual documentations
flavors = megalinter.flavor_factory.get_all_flavors()
for flavor, flavor_info in flavors.items():
generate_flavor_documentation(flavor, flavor_info, linters_tables_md)
# Automate generation of /docs items generated from README sections
finalize_doc_build()
# Generate a MD page for a descriptor (language, format, tooling_format)
def generate_descriptor_documentation(descriptor):
descriptor_file = f"{descriptor.get('descriptor_id').lower()}.yml"
descriptor_url = f"{URL_ROOT}/megalinter/descriptors/{descriptor_file}"
linter_names = [
linter.get("linter_name") for linter in descriptor.get("linters", [])
]
is_are = "is" if len(linter_names) == 1 else "are"
descriptor_md = [
"---",
f"title: {descriptor.get('descriptor_id')} linters in MegaLinter",
f"description: {', '.join(linter_names)} {is_are} available to analyze "
f"{descriptor.get('descriptor_id')} files in MegaLinter",
"---",
"<!-- markdownlint-disable MD003 MD020 MD033 MD041 -->",
f"<!-- {'@'}generated by .automation/build.py, please don't update manually -->",
f"<!-- Instead, update descriptor file at {descriptor_url} -->",
]
# Title
descriptor_md += [
f"# {descriptor.get('descriptor_label', descriptor.get('descriptor_id'))}",
"",
]
# List of linters
lang_lower = descriptor.get("descriptor_id").lower()
descriptor_md += [
"## Linters",
"",
"| Linter | Additional |",
"| ------ | ---------- |",
]
for linter in descriptor.get("linters", []):
linter_name_lower = linter.get("linter_name").lower().replace("-", "_")
linter_doc_url = f"{lang_lower}_{linter_name_lower}.md"
badges = get_badges(linter)
md_extra = " ".join(badges)
linter_key = linter.get("name", "")
if linter_key == "":
linter_key = (
descriptor.get("descriptor_id")
+ "_"
+ linter.get("linter_name").upper().replace("-", "_")
)
descriptor_md += [
f"| [**{linter.get('linter_name')}**]({doc_url(linter_doc_url)})<br/>"
f"[_{linter_key}_]({doc_url(linter_doc_url)}) "
f"| {md_extra} |"
]
# Criteria used by the descriptor to identify files to lint
descriptor_md += ["", "## Linted files", ""]
if len(descriptor.get("active_only_if_file_found", [])) > 0:
descriptor_md += [
f"- Activated only if at least one of these files is found:"
f" `{', '.join(descriptor.get('active_only_if_file_found'))}`"
]
if len(descriptor.get("file_extensions", [])) > 0:
descriptor_md += ["- File extensions:"]
for file_extension in descriptor.get("file_extensions"):
descriptor_md += [f" - `{file_extension}`"]
descriptor_md += [""]
if len(descriptor.get("file_names_regex", [])) > 0:
descriptor_md += ["- File names:"]
for file_name in descriptor.get("file_names_regex"):
descriptor_md += [f" - `{file_name}`"]
descriptor_md += [""]
if len(descriptor.get("file_contains_regex", [])) > 0:
descriptor_md += ["- Detected file content:"]
for file_contains_expr in descriptor.get("file_contains_regex"):
descriptor_md += [f" - `{file_contains_expr}`"]
descriptor_md += [""]
# Mega-linter variables
descriptor_md += [
"## Configuration in MegaLinter",
"",
"| Variable | Description | Default value |",
"| ----------------- | -------------- | -------------- |",
]
descriptor_md += [
f"| {descriptor.get('descriptor_id')}_PRE_COMMANDS | List of bash commands to run before the linters | None |",
f"| {descriptor.get('descriptor_id')}_POST_COMMANDS | List of bash commands to run after the linters | None |",
f"| {descriptor.get('descriptor_id')}_FILTER_REGEX_INCLUDE | Custom regex including filter | |",
f"| {descriptor.get('descriptor_id')}_FILTER_REGEX_EXCLUDE | Custom regex excluding filter | |",
"",