/
package_linter.py
executable file
·3114 lines (2656 loc) · 123 KB
/
package_linter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf8 -*-
import copy
import sys
import os
import re
import json
import shlex
import urllib.request
import subprocess
import time
import statistics
from datetime import datetime
try:
import toml
except Exception:
os.system("pip3 install toml")
import toml
try:
import jsonschema
except Exception:
os.system("pip3 install jsonschema")
import jsonschema
# ############################################################################
# Helper list
# ############################################################################
# Generated May 20 2024 using:
# cat /path/to/yunohost/data/helpers.d/* | grep "^ynh_" | tr -d '(){ ' > helperlist 2>/dev/null
# for HELPER in $(cat helperlist); do REQUIRE=$(grep -whB5 "^$HELPER" /path/to/yunohost/data/helpers.d/* 2>/dev/null | grep "Requires .* or higher\." | grep -o -E "[0-9].[0-9].[0-9]"); echo "'$HELPER': '$REQUIRE'",; done | tr "'" '"'
official_helpers = {
"ynh_install_apps": "",
"ynh_remove_apps": "",
"ynh_spawn_app_shell": "",
"ynh_wait_dpkg_free": "3.3.1",
"ynh_package_is_installed": "2.2.4",
"ynh_package_version": "2.2.4",
"ynh_apt": "2.4.0",
"ynh_package_update": "2.2.4",
"ynh_package_install": "2.2.4",
"ynh_package_remove": "2.2.4",
"ynh_package_autoremove": "2.2.4",
"ynh_package_autopurge": "2.7.2",
"ynh_package_install_from_equivs": "2.2.4",
"ynh_install_app_dependencies": "2.6.4",
"ynh_add_app_dependencies": "3.8.1",
"ynh_remove_app_dependencies": "2.6.4",
"ynh_install_extra_app_dependencies": "3.8.1",
"ynh_install_extra_repo": "3.8.1",
"ynh_remove_extra_repo": "3.8.1",
"ynh_add_repo": "3.8.1",
"ynh_pin_repo": "3.8.1",
"ynh_backup": "2.4.0",
"ynh_restore": "2.6.4",
"ynh_restore_file": "2.6.4",
"ynh_store_file_checksum": "2.6.4",
"ynh_backup_if_checksum_is_different": "2.6.4",
"ynh_delete_file_checksum": "3.3.1",
"ynh_backup_archive_exists": "",
"ynh_backup_before_upgrade": "2.7.2",
"ynh_restore_upgradebackup": "2.7.2",
"ynh_app_config_get_one": "",
# Commenting out config panel helpers
# that may legitimately be overwritten from config script
# "ynh_app_config_get": "",
# "ynh_app_config_show": "",
# "ynh_app_config_validate": "",
"ynh_app_config_apply_one": "",
# "ynh_app_config_apply": "",
# "ynh_app_action_run": "",
# "ynh_app_config_run": "",
"ynh_add_fail2ban_config": "4.1.0",
"ynh_remove_fail2ban_config": "3.5.0",
"ynh_handle_getopts_args": "3.2.2",
"ynh_go_try_bash_extension": "",
"ynh_use_go": "",
"ynh_install_go": "",
"ynh_remove_go": "",
"ynh_cleanup_go": "",
"ynh_get_ram": "3.8.1",
"ynh_require_ram": "3.8.1",
"ynh_die": "2.4.0",
"ynh_print_info": "3.2.0",
"ynh_print_log": "3.2.0",
"ynh_print_warn": "3.2.0",
"ynh_print_err": "3.2.0",
"ynh_exec_err": "3.2.0",
"ynh_exec_warn": "3.2.0",
"ynh_exec_warn_less": "3.2.0",
"ynh_exec_quiet": "3.2.0",
"ynh_exec_fully_quiet": "3.2.0",
"ynh_exec_and_print_stderr_only_if_error": "",
"ynh_print_OFF": "3.2.0",
"ynh_print_ON": "3.2.0",
"ynh_script_progression": "3.5.0",
"ynh_return": "3.6.0",
"ynh_use_logrotate": "2.6.4",
"ynh_remove_logrotate": "2.6.4",
"ynh_multimedia_build_main_dir": "",
"ynh_multimedia_addfolder": "",
"ynh_multimedia_addaccess": "",
"ynh_mysql_connect_as": "2.2.4",
"ynh_mysql_execute_as_root": "2.2.4",
"ynh_mysql_execute_file_as_root": "2.2.4",
"ynh_mysql_create_db": "2.2.4",
"ynh_mysql_drop_db": "2.2.4",
"ynh_mysql_dump_db": "2.2.4",
"ynh_mysql_create_user": "2.2.4",
"ynh_mysql_user_exists": "2.2.4",
"ynh_mysql_drop_user": "2.2.4",
"ynh_mysql_setup_db": "2.6.4",
"ynh_mysql_remove_db": "2.6.4",
"ynh_find_port": "2.6.4",
"ynh_port_available": "3.8.0",
"ynh_validate_ip": "2.2.4",
"ynh_validate_ip4": "2.2.4",
"ynh_validate_ip6": "2.2.4",
"ynh_add_nginx_config": "4.1.0",
"ynh_remove_nginx_config": "2.7.2",
"ynh_change_url_nginx_config": "11.1.9",
"ynh_use_nodejs": "2.7.1",
"ynh_install_nodejs": "2.7.1",
"ynh_remove_nodejs": "2.7.1",
"ynh_cron_upgrade_node": "2.7.1",
"ynh_permission_create": "3.7.0",
"ynh_permission_delete": "3.7.0",
"ynh_permission_exists": "3.7.0",
"ynh_permission_url": "3.7.0",
"ynh_permission_update": "3.7.0",
"ynh_permission_has_user": "3.7.1",
"ynh_legacy_permissions_exists": "4.1.2",
"ynh_legacy_permissions_delete_all": "4.1.2",
"ynh_add_fpm_config": "4.1.0",
"ynh_remove_fpm_config": "2.7.2",
"ynh_get_scalable_phpfpm": "",
"ynh_composer_exec": "",
"ynh_install_composer": "",
"ynh_psql_connect_as": "3.5.0",
"ynh_psql_execute_as_root": "3.5.0",
"ynh_psql_execute_file_as_root": "3.5.0",
"ynh_psql_create_db": "3.5.0",
"ynh_psql_drop_db": "3.5.0",
"ynh_psql_dump_db": "3.5.0",
"ynh_psql_create_user": "3.5.0",
"ynh_psql_user_exists": "3.5.0",
"ynh_psql_database_exists": "3.5.0",
"ynh_psql_drop_user": "3.5.0",
"ynh_psql_setup_db": "2.7.1",
"ynh_psql_remove_db": "2.7.1",
"ynh_psql_test_if_first_run": "2.7.1",
"ynh_redis_get_free_db": "",
"ynh_redis_remove_db": "",
"ynh_use_ruby": "",
"ynh_install_ruby": "",
"ynh_remove_ruby": "",
"ynh_cleanup_ruby": "",
"ynh_ruby_try_bash_extension": "",
"ynh_app_setting_get": "2.2.4",
"ynh_app_setting_set": "2.2.4",
"ynh_app_setting_delete": "2.2.4",
"ynh_app_setting": "",
"ynh_webpath_available": "2.6.4",
"ynh_webpath_register": "2.6.4",
"ynh_string_random": "2.2.4",
"ynh_replace_string": "2.6.4",
"ynh_replace_special_string": "2.7.7",
"ynh_sanitize_dbid": "2.2.4",
"ynh_normalize_url_path": "2.6.4",
"ynh_add_systemd_config": "4.1.0",
"ynh_remove_systemd_config": "2.7.2",
"ynh_systemd_action": "3.5.0",
"ynh_clean_check_starting": "3.5.0",
"ynh_user_exists": "2.2.4",
"ynh_user_get_info": "2.2.4",
"ynh_user_list": "2.4.0",
"ynh_system_user_exists": "2.2.4",
"ynh_system_group_exists": "3.5.0",
"ynh_system_user_create": "2.6.4",
"ynh_system_user_delete": "2.6.4",
"ynh_exec_as": "4.1.7",
"ynh_exit_properly": "2.6.4",
"ynh_abort_if_errors": "2.6.4",
"ynh_setup_source": "2.6.4",
"ynh_local_curl": "2.6.4",
"ynh_add_config": "4.1.0",
"ynh_replace_vars": "4.1.0",
"ynh_read_var_in_file": "",
"ynh_write_var_in_file": "",
"ynh_render_template": "",
"ynh_get_debian_release": "2.7.1",
"ynh_secure_remove": "2.6.4",
"ynh_read_manifest": "3.5.0",
"ynh_app_upstream_version": "3.5.0",
"ynh_app_package_version": "3.5.0",
"ynh_check_app_version_changed": "3.5.0",
"ynh_compare_current_package_version": "3.8.0",
}
deprecated_helpers_in_v2 = [
("ynh_clean_setup", "(?)"),
("ynh_abort_if_errors", "nothing, handled by the core, just get rid of it"),
("ynh_backup_before_upgrade", "nothing, handled by the core, just get rid of it"),
("ynh_restore_upgradebackup", "nothing, handled by the core, just get rid of it"),
("ynh_system_user_create", "the system_user resource"),
("ynh_system_user_delete", "the system_user resource"),
("ynh_webpath_register", "the permission resource"),
("ynh_webpath_available", "the permission resource"),
("ynh_permission_update", "the permission resource"),
("ynh_permission_create", "the permission resource"),
("ynh_permission_exists", "the permission resource"),
("ynh_legacy_permissions_exists", "the permission resource"),
("ynh_legacy_permissions_delete_all", "the permission resource"),
("ynh_install_app_dependencies", "the apt resource"),
("ynh_install_extra_app_dependencies", "the apt source"),
("ynh_remove_app_dependencies", "the apt resource"),
("ynh_psql_test_if_first_run", "the database resource"),
("ynh_mysql_setup_db", "the database resource"),
("ynh_psql_setup_db", "the database resource"),
("ynh_mysql_remove_db", "the database resource"),
("ynh_psql_remove_db", "the database resource"),
("ynh_find_port", "the port resource"),
(
"ynh_send_readme_to_admin",
"the doc/POST_INSTALL.md or POST_UPGRADE.md mechanism",
),
]
# Default to 1, set to 2 automatically if a toml manifest is found
app_packaging_format = None
# ############################################################################
# Utilities
# ############################################################################
class c:
HEADER = "\033[94m"
OKBLUE = "\033[94m"
OKGREEN = "\033[92m"
WARNING = "\033[93m"
MAYBE_FAIL = "\033[96m"
FAIL = "\033[91m"
END = "\033[0m"
BOLD = "\033[1m"
UNDERLINE = "\033[4m"
class TestReport:
def __init__(self, message):
self.message = message
def display(self, prefix=""):
_print(prefix + self.style % self.message)
class Warning(TestReport):
style = c.WARNING + " ! %s " + c.END
class Error(TestReport):
style = c.FAIL + " ✘ %s" + c.END
class Info(TestReport):
style = " - %s" + c.END
class Success(TestReport):
style = c.OKGREEN + " ☺ %s ♥" + c.END
class Critical(TestReport):
style = c.FAIL + " ✘✘✘ %s" + c.END
output = "plain"
def _print(*args, **kwargs):
if output == "plain":
print(*args, **kwargs)
def report_warning_not_reliable(str):
_print(c.MAYBE_FAIL + "?", str, c.END)
def print_happy(str):
_print(c.OKGREEN + " ☺ ", str, "♥")
def urlopen(url):
try:
conn = urllib.request.urlopen(url)
except urllib.error.HTTPError as e:
return {"content": "", "code": e.code}
except urllib.error.URLError as e:
_print("Could not fetch %s : %s" % (url, e))
return {"content": "", "code": 0}
return {"content": conn.read().decode("UTF8"), "code": 200}
def file_exists(file_path):
return os.path.isfile(file_path) and os.stat(file_path).st_size > 0
def spdx_licenses():
cachefile = ".spdx_licenses"
if os.path.exists(cachefile) and time.time() - os.path.getmtime(cachefile) < 3600:
return open(cachefile).read()
url = "https://spdx.org/licenses/"
content = urlopen(url)["content"]
open(cachefile, "w").write(content)
return content
def manifest_v2_schema():
cachefile = ".manifest.v2.schema.json"
if os.path.exists(cachefile) and time.time() - os.path.getmtime(cachefile) < 3600:
return json.loads(open(cachefile).read())
url = "https://raw.githubusercontent.com/YunoHost/apps/master/schemas/manifest.v2.schema.json"
content = urlopen(url)["content"]
open(cachefile, "w").write(content)
return json.loads(content)
tests = {}
tests_reports = {
"success": [],
"info": [],
"warning": [],
"error": [],
"critical": [],
}
def test(**kwargs):
def decorator(f):
clsname = f.__qualname__.split(".")[0]
if clsname not in tests:
tests[clsname] = []
tests[clsname].append((f, kwargs))
return f
return decorator
class TestSuite:
def run_tests(self):
reports = []
for test, options in tests[self.__class__.__name__]:
if "only" in options and self.name not in options["only"]:
continue
if "ignore" in options and self.name in options["ignore"]:
continue
this_test_reports = list(test(self))
for report in this_test_reports:
report.test_name = test.__qualname__
reports += this_test_reports
# Display part
def report_type(report):
return report.__class__.__name__.lower()
if any(report_type(r) in ["warning", "error", "critical"] for r in reports):
prefix = c.WARNING + "! "
elif any(report_type(r) in ["info"] for r in reports):
prefix = "ⓘ "
else:
prefix = c.OKGREEN + "✔ "
_print(" " + c.BOLD + prefix + c.OKBLUE + self.test_suite_name + c.END)
if len(reports):
_print("")
for report in reports:
report.display(prefix=" ")
if len(reports):
_print("")
for report in reports:
tests_reports[report_type(report)].append((report.test_name, report))
def run_single_test(self, test):
reports = list(test(self))
def report_type(report):
return report.__class__.__name__.lower()
for report in reports:
report.display()
test_name = test.__qualname__
tests_reports[report_type(report)].append((test_name, report))
# Defined in packaging module
# See https://github.com/pypa/packaging/blob/20cd09e00917adbc4afeaa753be831a6bc2740f7/packaging/version.py#L225
VERSION_PATTERN = r"""
v?
(?:
(?:(?P<epoch>[0-9]+)!)? # epoch
(?P<release>[0-9]+(?:\.[0-9]+)*) # release segment
(?P<pre> # pre-release
[-_\.]?
(?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview))
[-_\.]?
(?P<pre_n>[0-9]+)?
)?
(?P<post> # post release
(?:-(?P<post_n1>[0-9]+))
|
(?:
[-_\.]?
(?P<post_l>post|rev|r)
[-_\.]?
(?P<post_n2>[0-9]+)?
)
)?
(?P<dev> # dev release
[-_\.]?
(?P<dev_l>dev)
[-_\.]?
(?P<dev_n>[0-9]+)?
)?
)
(?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version
"""
# ############################################################################
# Actual high-level checks
# ############################################################################
scriptnames = ["_common.sh", "install", "remove", "upgrade", "backup", "restore"]
class App(TestSuite):
def __init__(self, path):
_print(" Analyzing app %s ..." % path)
self.path = path
self.manifest_ = Manifest(self.path)
self.manifest = self.manifest_.manifest
self.scripts = {f: Script(self.path, f) for f in scriptnames}
self.configurations = Configurations(self)
self.app_catalog = AppCatalog(self.manifest["id"])
self.test_suite_name = "General stuff, misc helper usage"
_print()
def analyze(self):
self.manifest_.run_tests()
for script in [self.scripts[s] for s in scriptnames if self.scripts[s].exists]:
script.run_tests()
self.run_tests()
self.configurations.run_tests()
self.app_catalog.run_tests()
self.report()
def report(self):
_print(" =======")
# These are meant to be the last stuff running, they are based on
# previously computed errors/warning/successes
self.run_single_test(App.qualify_for_level_7)
self.run_single_test(App.qualify_for_level_8)
self.run_single_test(App.qualify_for_level_9)
if output == "json":
print(
json.dumps(
{
"success": [test for test, _ in tests_reports["success"]],
"info": [test for test, _ in tests_reports["info"]],
"warning": [test for test, _ in tests_reports["warning"]],
"error": [test for test, _ in tests_reports["error"]],
"critical": [test for test, _ in tests_reports["critical"]],
},
indent=4,
)
)
return
if tests_reports["error"] or tests_reports["critical"]:
sys.exit(1)
def qualify_for_level_7(self):
if tests_reports["critical"]:
_print(" There are some critical issues in this app :(")
elif tests_reports["error"]:
_print(" Uhoh there are some errors to be fixed :(")
elif len(tests_reports["warning"]) >= 3:
_print(" Still some warnings to be fixed :s")
elif len(tests_reports["warning"]) == 2:
_print(" Only 2 warnings remaining! You can do it!")
elif len(tests_reports["warning"]) == 1:
_print(" Only 1 warning remaining! You can do it!")
else:
yield Success(
"Not even a warning! Congratz and thank you for keeping this package up to date with good practices! This app qualifies for level 7!"
)
def qualify_for_level_8(self):
successes = [test.split(".")[1] for test, _ in tests_reports["success"]]
# Level 8 = qualifies for level 7 + maintained + long term good quality
catalog_infos = self.app_catalog.catalog_infos
antifeatures = catalog_infos and catalog_infos.get("antifeatures", [])
if any(
af in antifeatures
for af in [
"package-not-maintained",
"deprecated-software",
"alpha-software",
"replaced-by-another-app",
]
):
_print(
" In the catalog, the app is flagged as not maintained / deprecated / alpha or replaced by another app, therefore does not qualify for level 8"
)
elif (
"qualify_for_level_7" in successes
and "is_long_term_good_quality" in successes
):
yield Success(
"The app is maintained and long-term good quality, and therefore qualifies for level 8!"
)
def qualify_for_level_9(self):
if self.app_catalog.catalog_infos.get("high_quality", False):
yield Success("The app is flagged as high-quality in the app catalog")
#########################################
# _____ _ #
# | __ \ | | #
# | | \/ ___ _ __ ___ _ __ __ _| | #
# | | __ / _ \ '_ \ / _ \ '__/ _` | | #
# | |_\ \ __/ | | | __/ | | (_| | | #
# \____/\___|_| |_|\___|_| \__,_|_| #
# #
#########################################
@test()
def v1packaging(app):
if app_packaging_format <= 1:
if datetime.today() >= datetime(2025, 2, 1):
yield Error(
"This app is still using packaging v1 which is now hard-deprecated. Packaging v2 was released more than two years ago. You should really have a look at https://yunohost.org/en/packaging_v2."
)
elif datetime.today() >= datetime(2024, 2, 1):
yield Warning(
"This app is still using packaging v1 which is now softly-deprecated. Packaging v2 was released more than one year ago and is now used by 75% of the app catalog with many other v1->v2 app transition ongoing. We encourage you to convert this app to packaging v2 following the recommendations described in https://yunohost.org/en/packaging_v2. This warning will turn into an error on February 1st, 2025."
)
@test()
def mandatory_scripts(app):
filenames = (
"LICENSE",
"README.md",
"scripts/install",
"scripts/remove",
"scripts/upgrade",
"scripts/backup",
"scripts/restore",
)
for filename in filenames:
if not file_exists(app.path + "/" + filename):
yield Error("Providing %s is mandatory" % filename)
if file_exists(app.path + "/LICENSE"):
license_content = open(app.path + "/LICENSE").read()
if "File containing the license of your package" in license_content:
yield Error("You should put an actual license in LICENSE...")
@test()
def doc_dir(app):
if not os.path.exists(app.path + "/doc"):
if app_packaging_format <= 1:
yield Warning(
"""READMEs are to be automatically generated using https://github.com/YunoHost/apps/tree/master/tools/README-generator.
- You are encouraged to create a doc/DISCLAIMER.md file, which should contain any important information to be presented to the admin before installation. Check https://github.com/YunoHost/example_ynh/blob/master/doc/DISCLAIMER.md for more details (it should be somewhat equivalent to the old 'Known limitations' and 'Specific features' section). (It's not mandatory to create this file if you're absolutely sure there's no relevant info to show to the user)
- If relevant for this app, screenshots can be added in a doc/screenshots/ folder."""
)
elif app_packaging_format >= 2:
yield Error(
"""Having a doc/ folder is now mandatory in packaging v2 and is expected to contain :
- (recommended) doc/DESCRIPTION.md : a long description of the app, typically around 5~20 lines, for example to list features
- (recommended) doc/screenshots/ : a folder containing at least one .png (or .jpg) screenshot of the app
- (if relevant) doc/ADMIN.md : an admin doc page meant to provide general info about adminstrating this app, will be available in yunohost's webadmin
- (if relevant) doc/SOME_OTHER_PAGE.md : an arbitrarily named admin doc page meant to provide info on a specific topic, will be available in yunohost's webadmin
- (if relevant) doc/PRE_INSTALL.md, POST_INSTALL.md : important informations to display to the user before/after the install (similar mechanism exists for upgrade)
"""
)
if os.path.exists(os.path.join(app.path, "doc/screenshots")):
du_output = subprocess.check_output(
["du", "-sb", app.path + "/doc/screenshots"], shell=False
)
screenshots_size = int(du_output.split()[0])
if screenshots_size > 512000:
yield Info(
"Consider keeping the content of doc/screenshots under ~512Kb for better UI/UX once the screenshots will be integrated in the webadmin app's catalog (to be discussed with the team)"
)
for _, _, files in os.walk(os.path.join(app.path, "doc/screenshots")):
for file in files:
if file == ".gitkeep":
continue
if all(
not file.lower().endswith(ext)
for ext in [".jpg", ".jpeg", ".png", ".gif", ".webp"]
):
yield Warning(
"In the doc/screenshots folder, only .jpg, .jpeg, .png, .webp and .gif are accepted"
)
break
@test()
def doc_dir_v2(app):
if app_packaging_format <= 1:
return
if os.path.exists(app.path + "/doc") and not os.path.exists(
app.path + "/doc/DESCRIPTION.md"
):
yield Error(
"A DESCRIPTION.md is now mandatory in packaging v2 and is meant to contains an extensive description of what the app is and does. Consider also adding a '/doc/screenshots/' folder with a few screenshots of what the app looks like."
)
elif (
os.system(
rf'grep -inrq "Some long and extensive description\|lorem ipsum dolor sit amet\|Ut enim ad minim veniam" {app.path}/doc/DESCRIPTION.md'
)
== 0
):
yield Error("It looks like DESCRIPTION.md just contains placeholder texts")
if os.path.exists(app.path + "/doc/DISCLAIMER.md"):
yield Warning(
"""The whole thing about doc/DISCLAIMER.md is refactored again in v2 (sorry about that :/) to improve the UX - basically people shouldnt have to actively go read the READMEs to get those infos
You are encouraged to split its infos into:
- Integration-related infos (eg. LDAP/SSO support, arch support, resource usage, ...)
-> neant to go in the 'integration' section of the manifest.toml
- Antifeatures-related infos (eg. alpha/deprecated software, arbitrary limiations, ...)
-> these are now formalized using the 'antifeatures' mechanism in the app catalog directly : cf https://github.com/YunoHost/apps/blob/master/antifeatures.yml and the 'antifeatures' key in apps.json
- Important infos that the admin should be made aware of *before* or *after* the install
-> infos *before* the install are meant to go in 'doc/PRE_INSTALL.md'
-> infos *after* the install are meant to go in 'doc/POST_INSTALL.md' (mostly meant to replace ynh_send_readme_to_admin, typically tips about how to login for the first time on the app / finish the install, ...).
-> these will be shown to the admin before/after the install (and the post_install notif will also be available in the app info page)
-> note that in these files, the __FOOBAR__ syntax is supported and replaced with the corresponding 'foobar' setting.
- General admin-related infos (eg. how to access the admin interface of the app, how to install plugin, etc)
-> meant to go in 'doc/ADMIN.md' which shall be made available in the app info page in the webadmin after installation.
-> if relevant, you can also create custom doc page, just create 'doc/WHATEVER.MD' and this will correspond to a specific documentation tab in the webadmin.
-> note that in these files, the __FOOBAR__ syntax is supported and replaced with the corresponding 'foobar' setting.
"""
)
@test()
def disclaimer_wording_or_placeholder(app):
if os.path.exists(app.path + "/doc"):
if (
os.system(
r"grep -nr -q 'Any known limitations, constrains or stuff not working, such as\|Other infos that people should be' %s/doc/"
% app.path
)
== 0
):
yield Warning(
"In DISCLAIMER.md: 'Any known limitations [...] such as' and 'Other infos [...] such as' are supposed to be placeholder sentences meant to explain to packagers what is the expected content, but is not an appropriate wording for end users :/"
)
if (
os.system(
r"grep -nr -q 'This is a dummy\|Ceci est une fausse' %s/doc/"
% app.path
)
== 0
):
yield Warning(
"The doc/ folder seems to still contain some dummy, placeholder messages in the .md markdown files. If those files are not useful in the context of your app, simply remove them."
)
@test()
def change_url_script(app):
if app_packaging_format <= 1:
args = app.manifest["arguments"].get("install", [])
else:
keyandargs = copy.deepcopy(app.manifest["install"])
for key, infos in keyandargs.items():
infos["name"] = key
args = keyandargs.values()
has_domain_arg = any(a["name"] == "domain" for a in args)
if has_domain_arg and not file_exists(app.path + "/scripts/change_url"):
yield Info(
"Consider adding a change_url script to support changing where the app can be reached"
)
@test()
def config_panel(app):
if file_exists(app.path + "config_panel.json"):
yield Error(
"JSON config panels are not supported anymore, should be replaced by a toml version"
)
if file_exists(app.path + "config_panel.toml"):
if (
os.system(
"grep -q 'version = \"0.1\"' '%s'"
% (app.path + "config_panel.toml")
)
== 0
):
yield Error(
"Config panels version 0.1 are not supported anymore, should be adapted for version 1.0"
)
elif (
os.path.exists(app.path + "/scripts/config")
and os.system(
"grep -q 'YNH_CONFIG_\\|yunohost app action' '%s'"
% (app.path + "/scripts/config")
)
== 0
):
yield Error(
"The config panel is set to version 1.x, but the config script is apparently still using some old code from 0.1 such as '$YNH_CONFIG_STUFF' or 'yunohost app action'"
)
@test()
def badges_in_readme(app):
id_ = app.manifest["id"]
if not file_exists(app.path + "/README.md"):
return
content = open(app.path + "/README.md").read()
if (
"This README was automatically generated" not in content
or not "dash.yunohost.org/integration/%s.svg" % id_ in content
):
yield Warning(
"It looks like the README was not generated automatically by https://github.com/YunoHost/apps/tree/master/tools/README-generator. "
"Note that nowadays you are not suppose to edit README.md, the yunohost bot will usually automatically update it if your app is hosted in the YunoHost-Apps org ... or you can also generate it by running the README-generator yourself."
)
superoldstuff = [
"%20%28Apps%29",
"%20%28Community%29",
"/jenkins/job",
"ci-buster",
"ci-stretch",
"ci-apps-arm",
]
if any(oldstuff in content for oldstuff in superoldstuff):
yield Error(
"The README contains references to super-old build status (such as old jenkins job or ci-apps-arm or ci-stretch...) which are not relevant anymore. Please consider switching to the new auto-generated README format which contains the standard CI badge at the top."
)
@test()
def placeholder_help_string(self):
if (
os.system(
"grep -q 'Use the help field' %s/manifest.json 2>/dev/null" % self.path
)
== 0
):
yield Warning(
"Sounds like your manifest.json contains some default placeholder help string ('Use the help field to...') ... either replace it with an actually helpful explanation, or remove the help string entirely if you don't use it."
)
if (
os.system(
"grep -q 'Explain in *a few (10~15) words* the purpose of the app\\|Expliquez en *quelques* (10~15) mots' %s/manifest.json 2>/dev/null"
% self.path
)
== 0
):
yield Error(
"Sounds like your manifest.json contains the default description string ('Explain in *a few (10~15 words) [...]') ... Please replace it with an actual description."
)
@test()
def remaining_replacebyyourapp(self):
if os.system("grep -I -qr 'REPLACEBYYOURAPP' %s 2>/dev/null" % self.path) == 0:
yield Error("You should replace all occurences of REPLACEBYYOURAPP.")
@test()
def supervisor_usage(self):
if os.system("grep -I -qr '^\s*supervisorctl' %s 2>/dev/null" % self.path) == 0:
yield Warning(
"Please don't rely on supervisor to run services. YunoHost is about standardization and the standard is to use systemd units..."
)
@test()
def bad_encoding(self):
cmd = (
"file --mime-encoding $(find %s/ -type f) | grep 'iso-8859-1\\|unknown-8bit' || true"
% self.path
)
bad_encoding_files = (
subprocess.check_output(cmd, shell=True).decode("utf-8").strip().split("\n")
)
for file_ in bad_encoding_files:
if not file_:
continue
file_ = file_.split()[0]
yield Error(
"%s appears to be encoded as latin-1 / iso-8859-1. Please convert it to utf-8 to avoid funky issues. Something like 'iconv -f iso-8859-1 -t utf-8 SOURCE > DEST' should do the trick."
% file_
)
#######################################
# _ _ _ #
# | | | | | | #
# | |__| | ___| |_ __ ___ _ __ ___ #
# | __ |/ _ \ | '_ \ / _ \ '__/ __| #
# | | | | __/ | |_) | __/ | \__ \ #
# |_| |_|\___|_| .__/ \___|_| |___/ #
# | | #
# |_| #
#######################################
@test()
def helpers_now_official(app):
cmd = "grep -IhEro 'ynh_\\w+ *\\( *\\)' '%s/scripts' | tr -d '() '" % app.path
custom_helpers = (
subprocess.check_output(cmd, shell=True).decode("utf-8").strip().split("\n")
)
custom_helpers = [c.split("__")[0] for c in custom_helpers]
for custom_helper in custom_helpers:
if custom_helper in official_helpers.keys():
yield Info(
"%s is now an official helper since version '%s'"
% (custom_helper, official_helpers[custom_helper] or "?")
)
@test()
def git_clone_usage(app):
cmd = f"grep -I 'git clone' '{app.path}'/scripts/install '{app.path}'/scripts/_common.sh 2>/dev/null | grep -qv 'xxenv\|rbenv\|oracledb'"
if os.system(cmd) == 0:
yield Info(
"Using 'git clone' is not recommended ... most forge do provide the ability to download a proper archive of the code for a specific commit. Please use the 'sources' resource in the manifest.toml in combination with ynh_setup_source."
)
@test()
def helpers_version_requirement(app):
cmd = "grep -IhEro 'ynh_\\w+ *\\( *\\)' '%s/scripts' | tr -d '() '" % app.path
custom_helpers = (
subprocess.check_output(cmd, shell=True).decode("utf-8").strip().split("\n")
)
custom_helpers = [c.split("__")[0] for c in custom_helpers]
if app_packaging_format <= 1:
yunohost_version_req = (
app.manifest.get("requirements", {}).get("yunohost", "").strip(">= ")
)
else:
yunohost_version_req = (
app.manifest.get("integration", {}).get("yunohost", "").strip(">= ")
)
cmd = "grep -IhEro 'ynh_\\w+' '%s/scripts'" % app.path
helpers_used = (
subprocess.check_output(cmd, shell=True).decode("utf-8").strip().split("\n")
)
helpers_used = sorted(set(helpers_used))
manifest_req = [int(i) for i in yunohost_version_req.split(".")] + [0, 0, 0]
def validate_version_requirement(helper_req):
if helper_req == "":
return True
helper_req = [int(i) for i in helper_req.split(".")]
for i in range(0, len(helper_req)):
if helper_req[i] == manifest_req[i]:
continue
return helper_req[i] <= manifest_req[i]
return True
for helper in [h for h in helpers_used if h in official_helpers.keys()]:
if helper in custom_helpers:
continue
helper_req = official_helpers[helper]
if not validate_version_requirement(helper_req):
major_diff = manifest_req[0] > int(helper_req[0])
message = (
"Using official helper %s implies requiring at least version %s, but manifest only requires %s"
% (helper, helper_req, yunohost_version_req)
)
yield Error(message) if major_diff else Warning(message)
@test()
def helpers_deprecated_in_v2(app):
if app_packaging_format <= 1:
return
cmd = f"grep -IhEro 'ynh_\\w+' '{app.path}/scripts/install' '{app.path}/scripts/remove' '{app.path}/scripts/upgrade' '{app.path}/scripts/backup' '{app.path}/scripts/restore' || true"
helpers_used = (
subprocess.check_output(cmd, shell=True).decode("utf-8").strip().split("\n")
)
helpers_used = sorted(set(helpers_used))
deprecated_helpers_in_v2_ = {k: v for k, v in deprecated_helpers_in_v2}
for helper in [
h for h in helpers_used if h in deprecated_helpers_in_v2_.keys()
]:
yield Warning(
f"Using helper {helper} is deprecated when using packaging v2 ... It is replaced by: {deprecated_helpers_in_v2_[helper]}"
)
@test()
def helper_consistency_apt_deps(app):
"""
Check if ynh_install_app_dependencies is present in install/upgrade/restore
so dependencies are up to date after restoration or upgrade
"""
install_script = app.scripts["install"]
if install_script.contains("ynh_install_app_dependencies"):
for name in ["upgrade", "restore"]:
if app.scripts[name].exists and not app.scripts[name].contains(
"ynh_install_app_dependencies"
):
yield Warning(
"ynh_install_app_dependencies should also be in %s script"
% name
)
cmd = (
'grep -IhEr "install_extra_app_dependencies" %s/scripts | grep -v "key" | grep -q "http://"'
% app.path
)
if os.system(cmd) == 0:
yield Warning(
"When installing dependencies from extra repository, please include a `--key` argument (yes, even if it's official debian repos such as backports - because systems like Raspbian do not ship Debian's key by default!"
)
@test()
def helper_consistency_service_add(app):
occurences = {
"install": (
app.scripts["install"].occurences("yunohost service add")
if app.scripts["install"].exists
else []
),
"upgrade": (
app.scripts["upgrade"].occurences("yunohost service add")
if app.scripts["upgrade"].exists
else []
),
"restore": (
app.scripts["restore"].occurences("yunohost service add")
if app.scripts["restore"].exists
else []
),
}