File: arguments.py

package info (click to toggle)
pmbootstrap 3.9.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,864 kB
  • sloc: python: 17,395; sh: 425; makefile: 17
file content (1365 lines) | stat: -rw-r--r-- 47,104 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
# Copyright 2023 Oliver Smith
# SPDX-License-Identifier: GPL-3.0-or-later
import argparse
import contextlib
import os
import sys
from collections.abc import Sequence
from pathlib import Path
from typing import Any, cast

from pmb.core import Config
from pmb.core.arch import Arch
from pmb.helpers.exceptions import NonBugError
from pmb.types import PmbArgs, RunOutputTypeDefault

with contextlib.suppress(ImportError):
    import argcomplete

import pmb.config
import pmb.helpers.args
import pmb.helpers.pmaports

"""This file is about parsing command line arguments passed to pmbootstrap, as
   well as generating the help pages (pmbootstrap -h). All this is done with
   Python's argparse. The parsed arguments get extended and finally stored in
   the "args" variable, which is prominently passed to most functions all
   over the pmbootstrap code base.

   See pmb/helpers/args.py for more information about the args variable.
"""


def toggle_other_boolean_flags(
    *other_destinations: str, value: bool = True
) -> type[argparse.Action]:
    """
    Group several argparse flags to one.

    Sets multiple other_destination to value.

    :param other_destinations: 'the other argument names' str

    :param value 'the value to set the other_destinations to' bool

    :returns custom Action
    """

    class SetOtherDestinationsAction(argparse.Action):
        def __init__(self, option_strings: list[str], dest: str, **kwargs: Any) -> None:
            super().__init__(option_strings, dest, nargs=0, const=value, default=value, **kwargs)

        def __call__(
            self,
            parser: argparse.ArgumentParser,
            namespace: argparse.Namespace,
            values: str | Sequence[Any] | None,
            option_string: str | None = None,
        ) -> None:
            for destination in other_destinations:
                setattr(namespace, destination, value)

    return SetOtherDestinationsAction


def type_ondev_cp(val: str) -> list[str]:
    """
    Parse and validate arguments to 'pmbootstrap install --ondev --cp'.

    :param val: 'HOST_SRC:CHROOT_DEST' string

    :returns: [HOST_SRC, CHROOT_DEST]
    """
    ret = val.split(":")

    if len(ret) != 2:
        raise argparse.ArgumentTypeError(f"does not have HOST_SRC:CHROOT_DEST format: {val}")
    host_src = ret[0]
    if not os.path.exists(host_src):
        raise argparse.ArgumentTypeError(f"HOST_SRC not found: {host_src}")
    if not os.path.isfile(host_src):
        raise argparse.ArgumentTypeError(f"HOST_SRC is not a file: {host_src}")

    chroot_dest = ret[1]
    if not chroot_dest.startswith("/"):
        raise argparse.ArgumentTypeError(f"CHROOT_DEST must start with '/': {chroot_dest}")
    return ret


def arguments_install(subparser: argparse._SubParsersAction) -> None:
    ret = subparser.add_parser(
        "install", help="set up device specific chroot and install to SD card or image file"
    )

    # Other arguments (that don't fit categories below)
    ret.add_argument(
        "--no-sshd", action="store_true", help="do not enable the SSH daemon by default"
    )
    ret.add_argument(
        "--no-firewall", action="store_true", help="do not enable the firewall by default"
    )
    ret.add_argument(
        "--password",
        help="dummy password for automating the"
        " installation - will be handled in PLAIN TEXT during"
        " install and may be logged to the logfile, do not use an"
        " important password!",
    )
    ret.add_argument(
        "--no-cgpt",
        help="do not use cgpt partition table",
        dest="install_cgpt",
        action="store_false",
        default=True,
    )
    ret.add_argument("--zap", help="zap chroots before installing", action="store_true")
    ret.add_argument(
        "--sector-size",
        help="set the sector size for the image file",
        type=int,
        default=None,
        choices=[512, 2048, 4096],
    )

    ret.add_argument(
        "--single-partition",
        action="store_true",
        help="Create a single partition that contains both boot and root files."
        " This can be used on devices that boot without mounting the boot file"
        " system (e.g. Android boot images or fastboot).",
    )

    # Image type
    group_desc = ret.add_argument_group(
        "optional image type",
        "Format of the resulting image. Default is generating a combined image"
        " of the postmarketOS boot and root partitions (--no-split). (If the"
        " device's deviceinfo_flash_method requires separate boot and root"
        " partitions, then --split is the default.) Related:"
        " https://postmarketos.org/partitions",
    )
    group = group_desc.add_mutually_exclusive_group()
    group.add_argument(
        "--no-split",
        help="create combined boot and root image file",
        dest="split",
        action="store_false",
        default=None,
    )
    group.add_argument(
        "--split", help="create separate boot and root image files", action="store_true"
    )
    group.add_argument(
        "--disk",
        "--sdcard",
        help="do not create an image file, instead"
        " write to the given block device (SD card, USB"
        " stick, etc.), for example: '/dev/mmcblk0'",
        metavar="BLOCKDEV",
        type=lambda x: Path(x),
    )
    group.add_argument(
        "--android-recovery-zip",
        help="generate TWRP flashable zip (recommended read: https://postmarketos.org/recoveryzip)",
        action="store_true",
        dest="android_recovery_zip",
    )
    group.add_argument(
        "--no-image", help="do not generate an image", action="store_true", dest="no_image"
    )

    # Image type "--disk" related
    group = ret.add_argument_group("optional image type 'disk' arguments")
    group.add_argument("--rsync", help="update the disk using rsync", action="store_true")

    # Image type "--android-recovery-zip" related
    group = ret.add_argument_group("optional image type 'android-recovery-zip' arguments")
    group.add_argument(
        "--recovery-install-partition",
        default="system",
        help="partition to flash from recovery (e.g. 'external_sd')",
        dest="recovery_install_partition",
    )
    group.add_argument(
        "--recovery-no-kernel",
        help="do not overwrite the existing kernel",
        action="store_false",
        dest="recovery_flash_kernel",
    )

    # Full disk encryption (disabled by default, --no-fde has no effect)
    group = ret.add_argument_group("optional full disk encryption arguments")
    group.add_argument(
        "--fde", help="use full disk encryption", action="store_true", dest="full_disk_encryption"
    )
    group.add_argument("--no-fde", help=argparse.SUPPRESS, action="store_true", dest="no_fde")
    group.add_argument(
        "--cipher",
        help="cryptsetup cipher used to encrypt the the rootfs (e.g. 'aes-xts-plain64')",
        default=pmb.config.defaults["cipher"],
    )
    group.add_argument(
        "--iter-time",
        help="cryptsetup iteration time (in"
        " milliseconds) to use when encrypting the system"
        " partition",
        default=pmb.config.defaults["iter_time"],
    )

    # Packages
    group = ret.add_argument_group(
        "optional packages arguments",
        "Select or deselect packages to be included in the installation.",
    )
    group.add_argument(
        "--add",
        help="comma separated list of packages to be added to the rootfs (e.g. 'vim,gcc')",
        metavar="PACKAGES",
    )
    group.add_argument(
        "--no-base",
        help="do not install postmarketos-base (advanced)",
        action="store_false",
        dest="install_base",
    )
    group.add_argument(
        "--no-recommends",
        dest="install_recommends",
        help="do not install packages listed in _pmb_recommends of the UI pmaports",
        action="store_false",
    )

    # Sparse image
    group_desc = ret.add_argument_group(
        "optional sparse image arguments", "Override deviceinfo_flash_sparse for testing purpose."
    )
    group = group_desc.add_mutually_exclusive_group()
    group.add_argument(
        "--sparse", help="generate sparse image file", default=None, action="store_true"
    )
    group.add_argument(
        "--no-sparse", help="do not generate sparse image file", dest="sparse", action="store_false"
    )

    # On-device installer
    group = ret.add_argument_group(
        "optional on-device installer arguments",
        "Wrap the resulting image in a postmarketOS based installation OS, so"
        " it can be encrypted and customized on first boot."
        " Related: https://postmarketos.org/on-device-installer",
    )
    group.add_argument(
        "--on-device-installer", "--ondev", action="store_true", help="enable on-device installer"
    )
    group.add_argument(
        "--no-local-pkgs",
        dest="install_local_pkgs",
        help="do not install locally compiled packages and package signing keys",
        action="store_false",
    )
    group.add_argument(
        "--cp",
        dest="ondev_cp",
        nargs="+",
        metavar="HOST_SRC:CHROOT_DEST",
        type=type_ondev_cp,
        help="copy one or more files from the host system path"
        " HOST_SRC to the target path CHROOT_DEST",
    )
    group.add_argument(
        "--no-rootfs",
        dest="ondev_no_rootfs",
        help="do not generate a pmOS rootfs as"
        " /var/lib/rootfs.img (install chroot). The file"
        " must either exist from a previous"
        " 'pmbootstrap install' run or by providing it"
        " as CHROOT_DEST with --cp",
        action="store_true",
    )

    # Other
    group = ret.add_argument_group("other optional arguments")
    group.add_argument(
        "--filesystem", help="root filesystem type", choices=["ext4", "f2fs", "btrfs", "xfs"]
    )


def arguments_export(subparser: argparse._SubParsersAction) -> argparse.ArgumentParser:
    ret = subparser.add_parser(
        "export",
        help="create convenience symlinks"
        " to generated image files (system, kernel,"
        " initramfs, boot.img, ...)",
    )

    ret.add_argument(
        "export_folder",
        help="export folder, defaults to /tmp/postmarketOS-export",
        default=Path("/tmp/postmarketOS-export"),
        nargs="?",
        type=lambda x: Path(x),
    )
    ret.add_argument(
        "--odin",
        help="odin flashable tar (boot.img/kernel+initramfs only)",
        action="store_true",
        dest="odin_flashable_tar",
    )
    ret.add_argument(
        "--no-install",
        dest="autoinstall",
        default=True,
        help="skip updating kernel/initfs",
        action="store_false",
    )
    return ret


def arguments_sideload(subparser: argparse._SubParsersAction) -> argparse.ArgumentParser:
    ret = subparser.add_parser(
        "sideload", help="Push packages to a running phone connected over usb or wifi"
    )
    add_packages_arg(ret, nargs="+")
    ret.add_argument(
        "--host",
        help="ip of the device over wifi (defaults to 172.16.42.1)",
        default="172.16.42.1",
    )
    ret.add_argument(
        "--port", help="SSH port of the device over wifi (defaults to 22)", default="22"
    )
    ret.add_argument("--user", help="use a different username than the one set in init")
    ret.add_argument(
        "--arch",
        help="skip automatic architecture deduction and use the given value",
        type=lambda x: Arch.from_str(x),
    )
    ret.add_argument(
        "--install-key",
        help="install the apk key from this machine if needed",
        action="store_true",
        dest="install_key",
    )
    return ret


def arguments_flasher(subparser: argparse._SubParsersAction) -> argparse.ArgumentParser:
    ret = subparser.add_parser("flasher", help="flash something to the target device")
    ret.add_argument("--method", help="override flash method", dest="flash_method", default=None)
    sub = ret.add_subparsers(dest="action_flasher")
    sub.required = True

    # Boot, flash kernel
    boot = sub.add_parser("boot", help="boot a kernel once")
    boot.add_argument("--cmdline", help="override kernel commandline")
    flash_kernel = sub.add_parser("flash_kernel", help="flash a kernel")
    for action in [boot, flash_kernel]:
        action.add_argument(
            "--no-install",
            dest="autoinstall",
            default=True,
            help="skip updating kernel/initfs",
            action="store_false",
        )
    flash_kernel.add_argument(
        "--partition",
        default=None,
        help="partition to flash the kernel to (defaults to deviceinfo_flash_*_partition_kernel)",
    )

    # Flash lk2nd
    flash_lk2nd = sub.add_parser(
        "flash_lk2nd",
        help="flash lk2nd, a secondary bootloader needed for various Android devices",
    )
    flash_lk2nd.add_argument(
        "--partition",
        default=None,
        help="partition to flash lk2nd to (defaults to default boot image partition ",
    )

    # Flash rootfs
    flash_rootfs = sub.add_parser(
        "flash_rootfs",
        help="flash the rootfs to a partition on the"
        " device (partition layout does not get"
        " changed)",
    )
    flash_rootfs.add_argument(
        "--partition",
        default=None,
        help="partition to flash the rootfs to (defaults"
        " to deviceinfo_flash_*_partition_rootfs,"
        " 'userdata' on Android may have more"
        " space)",
    )

    # Flash vbmeta
    flash_vbmeta = sub.add_parser(
        "flash_vbmeta",
        help="generate and flash AVB 2.0 image with"
        " disable verification flag set to a"
        " partition on the device (typically called"
        " vbmeta)",
    )
    flash_vbmeta.add_argument(
        "--partition",
        default=None,
        help="partition to flash the vbmeta to (defaults to deviceinfo_flash_*_partition_vbmeta",
    )

    # Flash dtbo
    flash_dtbo = sub.add_parser("flash_dtbo", help="flash dtbo image")
    flash_dtbo.add_argument(
        "--partition",
        default=None,
        help="partition to flash the dtbo to (defaults to deviceinfo_flash_*_partition_dtbo)",
    )

    # Actions without extra arguments
    sub.add_parser("sideload", help="sideload recovery zip")
    sub.add_parser(
        "list_flavors",
        help="list installed kernel flavors" + " inside the device rootfs chroot on this computer",
    )
    sub.add_parser("list_devices", help="show connected devices")

    group = ret.add_argument_group(
        "heimdall options",
        "With heimdall as"
        " flash method, the device automatically"
        " reboots after each flash command. Use"
        " --no-reboot and --resume for multiple"
        " flash actions without reboot.",
    )
    group.add_argument(
        "--no-reboot",
        dest="no_reboot",
        help="don't automatically reboot after flashing",
        action="store_true",
    )
    group.add_argument(
        "--resume",
        dest="resume",
        help="resume flashing after using --no-reboot",
        action="store_true",
    )

    return ret


def arguments_initfs(subparser: argparse._SubParsersAction) -> argparse.ArgumentParser:
    ret = subparser.add_parser("initfs", help="do something with the initramfs")
    sub = ret.add_subparsers(dest="action_initfs")

    # hook ls
    sub.add_parser("hook_ls", help="list available and installed hook packages")

    # hook add/del
    hook_add = sub.add_parser("hook_add", help="add a hook package")
    hook_del = sub.add_parser("hook_del", help="uninstall a hook package")
    for action in [hook_add, hook_del]:
        action.add_argument(
            "hook",
            help="name of the hook aport, without"
            f" the '{pmb.config.initfs_hook_prefix}' prefix,"
            " for example: 'debug-shell'",
        )

    # ls, build, extract
    sub.add_parser("ls", help="list initramfs contents")
    sub.add_parser("build", help="(re)build the initramfs")
    sub.add_parser("extract", help="extract the initramfs to a temporary folder")

    return ret


def arguments_qemu(subparser: argparse._SubParsersAction) -> argparse.ArgumentParser:
    ret = subparser.add_parser("qemu")
    ret.add_argument("--cmdline", help="override kernel commandline")
    ret.add_argument("--image-size", help="set rootfs size (e.g. 2048M or 2G)")
    ret.add_argument(
        "--second-storage",
        metavar="IMAGE_SIZE",
        help="add a second storage with the given size (default:"
        " 8G), gets created if it does not exist. Use to"
        " test install from SD to eMMC",
        nargs="?",
        default=None,
        const="8G",
    )
    ret.add_argument("-m", "--memory", type=int, default=1024, help="guest RAM (default: 1024)")
    ret.add_argument("-p", "--port", type=int, default=2222, help="SSH port (default: 2222)")

    ret.add_argument(
        "--no-kvm",
        dest="qemu_kvm",
        default=True,
        action="store_false",
        help="Avoid using hardware-assisted virtualization with KVM even when available (SLOW!)",
    )
    ret.add_argument(
        "--cpu",
        dest="qemu_cpu",
        help="Override emulated QEMU CPU. By default, the host"
        " CPU will be emulated when using KVM and the QEMU"
        " default otherwise (usually a CPU with minimal"
        " features). A useful value is 'max' (emulate all"
        " features that are available), use --cpu help to get a"
        " list of possible values from QEMU.",
    )

    ret.add_argument(
        "--tablet",
        dest="qemu_tablet",
        action="store_true",
        default=False,
        help="Use 'tablet' instead of 'mouse'"
        " input for QEMU. The tablet input device automatically"
        " grabs/releases the mouse when moving in/out of the QEMU"
        " window. (NOTE: For some reason the mouse position is"
        " not reported correctly with this in some cases...)",
    )

    ret.add_argument(
        "--display",
        dest="qemu_display",
        choices=["sdl", "gtk", "none"],
        help="QEMU's display parameter (default: gtk,gl=on)",
        default="gtk",
        nargs="?",
    )
    ret.add_argument(
        "--no-gl",
        dest="qemu_gl",
        default=True,
        action="store_false",
        help="Avoid using GL for accelerating graphics in QEMU  (use software rasterizer, slow!)",
    )
    ret.add_argument(
        "--video",
        dest="qemu_video",
        default="1024x768@60",
        help="Video resolution for QEMU (WidthxHeight@RefreshRate). Default is 1024x768@60.",
    )

    ret.add_argument(
        "--audio",
        dest="qemu_audio",
        choices=["alsa", "pa", "sdl"],
        help="QEMU's audio backend (default: none)",
        default=None,
        nargs="?",
    )

    ret.add_argument(
        "--host-qemu", dest="host_qemu", action="store_true", help="Use the host system's qemu"
    )

    ret.add_argument(
        "--efi",
        action="store_true",
        help="Use EFI boot (default: direct kernel image boot if supported by arch)",
    )

    return ret


def arguments_pkgrel_bump(subparser: argparse._SubParsersAction) -> argparse.ArgumentParser:
    ret = subparser.add_parser(
        "pkgrel_bump",
        help="increase the pkgrel to"
        " indicate that a package must be rebuilt"
        " because of a dependency change",
    )
    ret.add_argument(
        "--dry",
        action="store_true",
        help="instead of modifying APKBUILDs, exit with >0 when a package would have been bumped",
    )

    # Mutually exclusive: "--auto" or package names
    mode = ret.add_mutually_exclusive_group(required=True)
    mode.add_argument(
        "--auto",
        action="store_true",
        help="all packages which"
        " depend on a library which had an incompatible update"
        " (libraries with a soname bump)",
    )
    mode.add_argument("packages", nargs="*", default=[])
    return ret


def arguments_pkgver_bump(subparser: argparse._SubParsersAction) -> argparse.ArgumentParser:
    ret = subparser.add_parser(
        "pkgver_bump",
        help="increase the pkgver and reset pkgrel to 0. useful when dealing with metapackages.",
    )

    add_packages_arg(ret, nargs="*", default=[])
    return ret


def arguments_aportupgrade(subparser: argparse._SubParsersAction) -> argparse.ArgumentParser:
    ret = subparser.add_parser(
        "aportupgrade", help="check for outdated packages that need upgrading"
    )
    ret.add_argument(
        "--dry",
        action="store_true",
        help="instead of modifying APKBUILDs, print the changes that would be made",
    )
    ret.add_argument("--ref", help="git ref (tag, commit, etc) to use")

    # Mutually exclusive: "--all" or package names
    mode = ret.add_mutually_exclusive_group(required=True)
    mode.add_argument("--all", action="store_true", help="iterate through all packages")
    mode.add_argument(
        "--all-stable", action="store_true", help="iterate through all non-git packages"
    )
    mode.add_argument("--all-git", action="store_true", help="iterate through all git packages")
    mode.add_argument("packages", nargs="*", default=[])
    return ret


def arguments_newapkbuild(subparser: argparse._SubParsersAction) -> None:
    """
    Wrapper for Alpine's "newapkbuild" command.

    Most parameters will get directly passed through, and they are defined in
    "pmb/config/__init__.py". That way they can be used here and when passing
    them through in "pmb/helpers/frontend.py". The order of the parameters is
    kept the same as in "newapkbuild -h".
    """
    sub = subparser.add_parser("newapkbuild", help="get a template to package new software")
    sub.add_argument(
        "--folder", help="set postmarketOS aports folder (default: main)", default="main"
    )

    # Passthrough: Strings (e.g. -d "my description")
    for entry in pmb.config.newapkbuild_arguments_strings:
        sub.add_argument(entry[0], dest=entry[1], help=entry[2])

    # Passthrough: Package type switches (e.g. -C for CMake)
    group = sub.add_mutually_exclusive_group()
    for entry in pmb.config.newapkbuild_arguments_switches_pkgtypes:
        group.add_argument(entry[0], dest=entry[1], help=entry[2], action="store_true")

    # Passthrough: Other switches (e.g. -c for copying sample files)
    for entry in pmb.config.newapkbuild_arguments_switches_other:
        sub.add_argument(entry[0], dest=entry[1], help=entry[2], action="store_true")

    # Force switch
    sub.add_argument(
        "-f", dest="force", action="store_true", help="force even if directory already exists"
    )

    # Passthrough: PKGNAME[-PKGVER] | SRCURL
    sub.add_argument(
        "pkgname_pkgver_srcurl",
        metavar="PKGNAME[-PKGVER] | SRCURL",
        help="set either the package name (optionally with the"
        " PKGVER at the end, e.g. 'hello-world-1.0') or the"
        " download link to the source archive",
    )


def arguments_kconfig(subparser: argparse._SubParsersAction) -> None:
    # Allowed architectures
    arch_choices = Arch.supported()

    # Kconfig subparser
    ret = subparser.add_parser("kconfig", help="change or edit kernel configs")
    sub = ret.add_subparsers(dest="action_kconfig")
    sub.required = True

    # "pmbootstrap kconfig check"
    check = sub.add_parser("check", help="check kernel aport config")
    check.add_argument(
        "-f",
        "--force",
        action="store_true",
        help="check all kernels, even the ones that would be ignored by default",
    )
    check.add_argument("--arch", choices=arch_choices, dest="arch", type=lambda x: Arch.from_str(x))
    check.add_argument("--file", help="check a file directly instead of a config in a package")
    check.add_argument(
        "--no-details",
        action="store_false",
        dest="kconfig_check_details",
        help="print one generic error per component instead of"
        " listing each option that needs to be adjusted",
    )
    check.add_argument(
        "-k",
        "--keep-going",
        action="store_true",
        help="continue on errors instead of aborting on the first error",
    )
    check.add_argument(
        "--categories", help="a comma separated list of additional kconfig categories to check"
    )
    add_kernel_arg(check, nargs="*")

    # "pmbootstrap kconfig edit"
    edit = sub.add_parser("edit", help="edit kernel aport config")
    edit.add_argument("--arch", choices=arch_choices, dest="arch", type=lambda x: Arch.from_str(x))
    edit.add_argument("--fragment", help="fragment filename to save changes")
    edit_ui_chooser = edit.add_mutually_exclusive_group()
    edit_ui_chooser.add_argument(
        "-x",
        dest="xconfig",
        action="store_true",
        help="use xconfig rather than menuconfig for kernel configuration",
    )
    edit_ui_chooser.add_argument(
        "-n",
        dest="nconfig",
        action="store_true",
        help="use nconfig rather than menuconfig for kernel configuration",
    )
    add_kernel_arg(edit, nargs=1)

    # "pmbootstrap kconfig migrate"
    migrate = sub.add_parser(
        "migrate",
        help="Migrate kconfig from older version to "
        "newer. Internally runs 'make oldconfig', "
        "which asks question for every new kernel "
        "config option.",
    )
    migrate.add_argument(
        "--arch", choices=arch_choices, dest="arch", type=lambda x: Arch.from_str(x)
    )
    add_kernel_arg(migrate, nargs=1)

    generate = sub.add_parser("generate", help="generate kernel config from fragments")
    generate.add_argument(
        "--arch", choices=arch_choices, dest="arch", type=lambda x: Arch.from_str(x)
    )
    add_kernel_arg(generate, nargs=1)


def arguments_repo_missing(subparser: argparse._SubParsersAction) -> argparse.ArgumentParser:
    ret = subparser.add_parser(
        "repo_missing",
        help="list all packages + depends from pmaports for building the repository (used by bpo)",
    )
    ret.add_argument(
        "--arch", choices=Arch.supported(), default=Arch.native(), type=lambda x: Arch.from_str(x)
    )
    # Deprecated argument that is currently kept so pmbootstrap can be called
    # the same way for repo_missing by bpo with pmbv2 and pmbv3. Once we drop
    # support for pmbv2 in bpo (can do that after v24.06 is EOL), we can adjust
    # bpo to not use --built and remove this parameter from pmbootstrap.
    ret.add_argument(
        "--built",
        action="store_true",
        help=argparse.SUPPRESS,
    )
    return ret


def arguments_lint(subparser: argparse._SubParsersAction) -> None:
    lint = subparser.add_parser("lint", help="run quality checks on pmaports (required to pass CI)")
    add_packages_arg(lint, nargs="*")


def arguments_test(subparser: argparse._SubParsersAction) -> None:
    test = subparser.add_parser("test", help="Internal pmbootstrap test tools")
    sub = test.add_subparsers(dest="action_test", required=True)
    sub.add_parser("apkindex_parse_all", help="parse all APKINDEX files")


def arguments_status(subparser: argparse._SubParsersAction) -> argparse.ArgumentParser:
    ret = subparser.add_parser("status", help="show a config and pmaports overview")
    return ret


def arguments_netboot(subparser: argparse._SubParsersAction) -> argparse.ArgumentParser:
    ret = subparser.add_parser("netboot", help="launch nbd server with pmOS rootfs")
    sub = ret.add_subparsers(dest="action_netboot")
    sub.required = True

    start = sub.add_parser("serve", help="start nbd server")
    start.add_argument("--replace", action="store_true", help="replace stored netboot image")

    return ret


def arguments_ci(subparser: argparse._SubParsersAction) -> argparse.ArgumentParser:
    ret = subparser.add_parser(
        "ci",
        help="run continuous integration scripts locally of git repo in current directory",
    )
    script_args = ret.add_mutually_exclusive_group()
    script_args.add_argument("-a", "--all", action="store_true", help="run all scripts")
    script_args.add_argument("-f", "--fast", action="store_true", help="run fast scripts only")
    ret.add_argument(
        "scripts",
        nargs="*",
        metavar="script",
        help="name of the CI script to run, depending on the git repository",
    )
    return ret


def package_completer(
    prefix: str,
    action: str,
    parser: argparse.ArgumentParser | None = None,
    parsed_args: list[str] | None = None,
) -> set[str]:
    packages = {
        package for package in pmb.helpers.pmaports.get_list() if package.startswith(prefix)
    }
    return packages


def kernel_completer(
    prefix: str,
    action: str,
    parser: argparse.ArgumentParser | None = None,
    parsed_args: list[str] | None = None,
) -> list[str]:
    """:returns: matched linux-* packages, with linux-* prefix and without"""
    ret: list[str] = []

    # Full package name, starting with "linux-"
    if (len("linux-") < len(prefix) and prefix.startswith("linux-")) or "linux-".startswith(prefix):
        ret += package_completer(prefix, action, parser, parsed_args)

    # Kernel name without "linux-"
    packages = package_completer(f"linux-{prefix}", action, parser, parsed_args)
    ret += [package.replace("linux-", "", 1) for package in packages]

    return ret


def add_packages_arg(
    subparser: argparse.ArgumentParser, name: str = "packages", *args: str, **kwargs: Any
) -> None:
    arg = subparser.add_argument(name, *args, **kwargs)
    if "argcomplete" in sys.modules:
        arg.completer = package_completer  # type: ignore[attr-defined]


def add_kernel_arg(
    subparser: argparse.ArgumentParser, name: str = "package", nargs: int | str = "?"
) -> None:
    arg = subparser.add_argument(
        name, nargs=nargs, help="kernel package (e.g. linux-postmarketos-allwinner)"
    )
    if "argcomplete" in sys.modules:
        arg.completer = kernel_completer  # type: ignore[attr-defined]


def get_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(prog="pmbootstrap")
    arch_native = Arch.native()
    arch_choices = Arch.supported()

    # Other
    parser.add_argument("-V", "--version", action="version", version=pmb.__version__)
    parser.add_argument(
        "-c",
        "--config",
        dest="config",
        type=lambda x: Path(x),
        default=pmb.config.defaults["config"],
        help="path to pmbootstrap_v3.cfg file (default in ~/.config/)",
    )
    parser.add_argument(
        "-mp",
        "--mirror-pmOS",
        dest="deprecated_mp",
        help=argparse.SUPPRESS,
        action="append",
    )
    parser.add_argument(
        "-m",
        "--mirror-alpine",
        dest="deprecated_m",
        help=argparse.SUPPRESS,
    )
    parser.add_argument("-j", "--jobs", help="parallel jobs when compiling")
    parser.add_argument(
        "-E",
        "--extra-space",
        help="specify an integer with the amount of additional"
        "space to allocate to the image in MB (default"
        " 0)",
    )
    parser.add_argument(
        "-B",
        "--boot-size",
        help="specify an integer with your preferred boot"
        "partition size on target machine in MB (default"
        f" {Config.get_default('boot_size')})",
    )
    parser.add_argument(
        "-p",
        "--aports",
        help="postmarketos aports (pmaports) path",
        type=lambda x: [Path(p.strip()) for p in x.split(",")],
    )
    parser.add_argument(
        "-t",
        "--timeout",
        help="seconds after which processes get killed that stopped writing any output (default: "
        "no timeout unless the environment variable 'CI' is set, in which case it is 900)",
        type=float,
    )
    parser.add_argument(
        "-w",
        "--work",
        type=lambda x: Path(x).absolute(),
        help="folder where all data gets stored (chroots, caches, built packages)",
    )
    parser.add_argument(
        "-y",
        "--assume-yes",
        help="Assume 'yes' to all"
        " question prompts. WARNING: this option will"
        " cause normal 'are you sure?' prompts to be"
        " disabled!",
        action="store_true",
    )
    parser.add_argument(
        "--as-root",
        help="Allow running as root (not"
        " recommended, may screw up your work folders"
        " directory permissions!)",
        dest="as_root",
        action="store_true",
    )
    parser.add_argument(
        "-o",
        "--offline",
        help="Do not attempt to update the package index files",
        action="store_true",
    )

    # Compiler
    parser.add_argument(
        "--no-ccache", action="store_false", dest="ccache", help="do not cache the compiled output"
    )
    parser.add_argument(
        "--no-cross",
        action="store_false",
        dest="cross",
        help="disable cross compiler, build only with QEMU and gcc (slow!)",
    )

    # Logging
    parser.add_argument("-l", "--log", dest="log", default=None, help="path to log file")
    parser.add_argument(
        "--details-to-stdout",
        dest="details_to_stdout",
        help="print details (e.g. build output) to stdout, instead of writing to the log",
        action="store_true",
    )
    parser.add_argument(
        "-v",
        "--verbose",
        dest="verbose",
        action="store_true",
        help="write even more to the logfiles (this may reduce performance)",
    )
    parser.add_argument(
        "-q", "--quiet", dest="quiet", action="store_true", help="do not output any log messages"
    )

    # Actions
    sub = parser.add_subparsers(title="action", dest="action")
    sub.add_parser("shutdown", help="umount, unregister binfmt")
    sub.add_parser(
        "index",
        help="re-index all repositories with custom built"
        " packages (do this after manually removing package files)",
    )
    sub.add_parser(
        "work_migrate",
        help="run this before using pmbootstrap"
        " non-interactively to migrate the"
        " work folder version on demand",
    )
    arguments_repo_missing(sub)
    arguments_kconfig(sub)
    arguments_export(sub)
    arguments_sideload(sub)
    arguments_netboot(sub)
    arguments_flasher(sub)
    arguments_initfs(sub)
    arguments_qemu(sub)
    arguments_pkgrel_bump(sub)
    arguments_pkgver_bump(sub)
    arguments_aportupgrade(sub)
    arguments_newapkbuild(sub)
    arguments_lint(sub)
    arguments_test(sub)
    arguments_status(sub)
    arguments_ci(sub)

    # Action: init
    init = sub.add_parser("init", help="initialize config file")
    init.add_argument(
        "--shallow-initial-clone",
        help="do a shallow clone if pmaports has to be cloned. Primarily useful to speed up scripts.",
        action="store_true",
    )

    # Action: log
    log = sub.add_parser("log", help="follow the pmbootstrap logfile")
    log.add_argument("-n", "--lines", type=int, default=60, help="count of initial output lines")
    log.add_argument("-c", "--clear", help="clear the log", action="store_true", dest="clear_log")

    # Action: zap
    zap = sub.add_parser("zap", help="safely delete chroot folders")
    zap.add_argument(
        "--dry",
        action="store_true",
        help="instead of actually deleting anything, print out what would have been deleted",
    )
    zap.add_argument("-hc", "--http", action="store_true", help="also delete http cache")
    zap.add_argument(
        "-d", "--distfiles", action="store_true", help="also delete downloaded source tarballs"
    )
    zap.add_argument(
        "-p",
        "--pkgs-local",
        action="store_true",
        dest="pkgs_local",
        help="also delete *all* locally compiled packages",
    )
    zap.add_argument(
        "-m",
        "--pkgs-local-mismatch",
        action="store_true",
        dest="pkgs_local_mismatch",
        help="also delete locally compiled packages without existing aport of same version",
    )
    zap.add_argument(
        "-n", "--netboot", action="store_true", help="also delete stored images for netboot"
    )
    zap.add_argument(
        "-o",
        "--pkgs-online-mismatch",
        action="store_true",
        dest="pkgs_online_mismatch",
        help="also delete outdated packages from online mirrors"
        " (that have been downloaded to the apk cache)",
    )
    zap.add_argument("-r", "--rust", action="store_true", help="also delete rust related caches")

    zap_all_delete_args = [
        "http",
        "distfiles",
        "pkgs_local",
        "pkgs_local_mismatch",
        "netboot",
        "pkgs_online_mismatch",
        "rust",
    ]
    zap_all_delete_args_print = [arg.replace("_", "-") for arg in zap_all_delete_args]
    zap.add_argument(
        "-a",
        "--all",
        action=toggle_other_boolean_flags(*zap_all_delete_args),
        help=f"delete everything, equivalent to: --{' --'.join(zap_all_delete_args_print)}",
    )

    # Action: stats
    stats = sub.add_parser("stats", help="show ccache stats")
    stats.add_argument(
        "--arch", default=arch_native, choices=arch_choices, type=lambda x: Arch.from_str(x)
    )

    # Action: update
    update = sub.add_parser("update", help="update all existing APKINDEX files")
    update.add_argument(
        "--arch",
        default=None,
        choices=arch_choices,
        help="only update a specific architecture",
        type=lambda x: Arch.from_str(x),
    )
    update.add_argument(
        "--non-existing",
        action="store_true",
        help="do not only update the existing APKINDEX files, but all of them",
        dest="non_existing",
    )

    # Action: build_init / chroot
    build_init = sub.add_parser(
        "build_init",
        help="initialize build environment (usually you do not need to call this)",
    )
    chroot = sub.add_parser("chroot", help="start shell in chroot")
    chroot.add_argument(
        "--add",
        help="build/install comma separated list of packages in the chroot before entering it",
    )
    chroot.add_argument("--user", help="run the command as user, not as root", action="store_true")
    chroot.add_argument(
        "--output",
        choices=list(RunOutputTypeDefault),
        type=RunOutputTypeDefault.from_string,
        help="how the output of the"
        " program should be handled, choose from: 'log',"
        " 'stdout', 'interactive', 'tui' (default),"
        " 'background'. Details: pmb/helpers/run_core.py",
        default=RunOutputTypeDefault.TUI,
    )
    chroot.add_argument(
        "--image",
        help="Mount the rootfs image and treat it like a normal chroot.",
        action="store_true",
    )
    chroot.add_argument(
        "--usb",
        help="Make USB devices accessible inside the chroot.",
        action="store_true",
        dest="chroot_usb",
    )
    chroot.add_argument(
        "command",
        default=["sh", "-i"],
        help="command to execute inside the chroot. default: sh",
        nargs="*",
    )
    chroot.add_argument(
        "-x",
        "--xauth",
        action="store_true",
        help="Copy .Xauthority and set environment variables,"
        " so X11 applications can be started (native"
        " chroot only)",
    )
    chroot.add_argument(
        "-i",
        "--install-blockdev",
        action="store_true",
        help="Create a sparse image file and mount it as"
        " /dev/install, just like during the"
        " installation process.",
    )
    for action in [build_init, chroot]:
        suffix = action.add_mutually_exclusive_group()
        if action == chroot:
            suffix.add_argument(
                "-r", "--rootfs", action="store_true", help="Chroot for the device root file system"
            )
        suffix.add_argument(
            "-b",
            "--buildroot",
            nargs="?",
            const="device",
            choices={"device"} | {str(a) for a in arch_choices},
            help="Chroot for building packages, defaults to device architecture",
        )
        suffix.add_argument(
            "-s",
            "--suffix",
            default=None,
            help="Specify any chroot suffix, defaults to 'native'",
        )

    # Action: install
    arguments_install(sub)

    # Action: checksum
    checksum = sub.add_parser("checksum", help="update aport checksums")
    checksum.add_argument(
        "--verify",
        action="store_true",
        help="download"
        " sources and verify that the checksums of the"
        " APKBUILD match, instead of updating them",
    )
    checksum_changed = checksum.add_mutually_exclusive_group(required=True)
    checksum_changed.add_argument(
        "--changed",
        action="store_true",
        help="update checksums of all packages that have unstaged or uncommitted changes",
    )
    checksum_changed.add_argument("packages", nargs="*", default=[])

    # Action: aportgen
    aportgen = sub.add_parser(
        "aportgen",
        help="generate a postmarketOS specific package build recipe (aport/APKBUILD)",
    )
    aportgen_fork_alpine = aportgen.add_mutually_exclusive_group()
    aportgen_fork_alpine.add_argument(
        "-a",
        "--fork-alpine",
        help="fork the alpine upstream package",
        action="store_true",
        dest="fork_alpine",
    )
    aportgen_fork_alpine.add_argument(
        "-r",
        "--fork-alpine-retain-branch",
        help="fork the alpine upstream, but don't change branch to match the current channel",
        action="store_true",
        dest="fork_alpine_retain_branch",
    )
    add_packages_arg(aportgen, nargs="+")

    # Action: build
    build = sub.add_parser("build", help="create a package for a specific architecture")
    build.add_argument(
        "--arch",
        choices=arch_choices,
        default=None,
        help="CPU architecture to build for (default: "
        f"{arch_native} or first available architecture in"
        " APKBUILD)",
        type=lambda x: Arch.from_str(x),
    )
    build.add_argument("--force", action="store_true", help="even build if not necessary")
    build.add_argument(
        "--strict",
        action="store_true",
        help="(slower) zap and"
        " install only required depends when building, to"
        " detect dependency errors",
    )
    build.add_argument(
        "--src",
        help="override source used to build the"
        " package with a local folder (the APKBUILD must"
        " expect the source to be in $builddir, so you might"
        " need to adjust it)",
        nargs=1,
    )
    build.add_argument(
        "-i",
        "--ignore-depends",
        action="store_true",
        help="only build and install makedepends from an"
        " APKBUILD, ignore the depends (old behavior). This is"
        " faster for device packages for example, because then"
        " you don't need to build and install the kernel. But"
        " it is incompatible with how Alpine's abuild handles"
        " it.",
        dest="ignore_depends",
    )
    build.add_argument(
        "-n",
        "--no-depends",
        action="store_true",
        help="never build dependencies, abort instead",
        dest="no_depends",
    )
    build.add_argument(
        "--go-mod-cache",
        action="store_true",
        default=None,
        help="for go packages: Usually they should bundle the"
        " dependency sources instead of downloading them"
        " at build time. But if they don't (e.g. with"
        " pmbootstrap build --src), then this option can"
        " be used to let GOMODCACHE point into"
        " pmbootstrap's work dir to only download"
        " dependencies once. (default: true with --src,"
        " false otherwise)",
    )
    build.add_argument(
        "--no-go-mod-cache",
        action="store_false",
        dest="go_mod_cache",
        default=None,
        help="don't set GOMODCACHE",
    )
    build.add_argument(
        "--envkernel",
        action="store_true",
        help="Create an apk package from the build output of"
        " a kernel compiled locally on the host or with envkernel.sh.",
    )
    add_packages_arg(build, nargs="+")

    # Action: deviceinfo_parse
    deviceinfo_parse = sub.add_parser("deviceinfo_parse")
    deviceinfo_parse.add_argument("devices", nargs="*")
    deviceinfo_parse.add_argument(
        "--kernel",
        help="the kernel to select (for"
        " device packages with multiple kernels),"
        " e.g. 'downstream', 'mainline'",
        dest="deviceinfo_parse_kernel",
        metavar="KERNEL",
    )

    # Action: apkbuild_parse
    apkbuild_parse = sub.add_parser("apkbuild_parse")
    add_packages_arg(apkbuild_parse, nargs="*")

    # Action: apkindex_parse
    apkindex_parse = sub.add_parser("apkindex_parse")
    apkindex_parse.add_argument("apkindex_path", type=lambda x: Path(x))
    add_packages_arg(apkindex_parse, "package", nargs="?")

    # Action: config
    config = sub.add_parser("config", help="get and set pmbootstrap options")
    config.add_argument(
        "-r",
        "--reset",
        action="store_true",
        help="Reset config options with the given name to it's default.",
    )
    config.add_argument(
        "name",
        nargs="?",
        help="variable name, one of: " + ", ".join(sorted(Config.keys())),
        choices=Config.keys(),
        metavar="name",
    )
    config.add_argument("value", nargs="?", help="set variable to value")

    # Action: bootimg_analyze
    bootimg_analyze = sub.add_parser(
        "bootimg_analyze", help="Extract all the information from an existing boot.img"
    )
    bootimg_analyze.add_argument("path", help="path to the boot.img", type=lambda x: Path(x))
    bootimg_analyze.add_argument(
        "--force", "-f", action="store_true", help="force even if the file seems to be invalid"
    )

    # Action: pull
    sub.add_parser(
        "pull", help="update all git repositories that pmbootstrap cloned (pmaports, etc.)"
    )

    if "argcomplete" in sys.modules:
        argcomplete.autocomplete(parser, always_complete_options="long")

    return parser


def arguments() -> PmbArgs:
    # FIXME: It would be nice to not use cast here, but I don't know what else we could do.
    args = cast(PmbArgs, get_parser().parse_args())

    if getattr(args, "fork_alpine_retain_branch", False):
        # fork_alpine_retain_branch largely matches the behaviour of fork_alpine, so
        # just set fork_alpine here to reduce repetition.
        args.fork_alpine = args.fork_alpine_retain_branch

    pmb.helpers.args.init(args)

    if getattr(args, "deprecated_mp", None) or getattr(args, "deprecated_m", None):
        raise NonBugError(
            "Arguments --mirror-pmOS and --mirror-alpine have been removed. See docs/mirrors.md"
            " regarding how to set mirrors now."
        )

    if getattr(args, "go_mod_cache", None) is None:
        gomodcache = bool(getattr(args, "src", None))
        args.go_mod_cache = gomodcache

    return args