haj 0.3.7

the beautiful, cross-distro package manager and tui.
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
use clap::{Parser, Subcommand, ValueEnum};

#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
pub enum SourceScope {
    Aur,
    Repo,
    Repos,
}

#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompletionShell {
    Bash,
    Zsh,
    Fish,
}

#[derive(Parser, Debug)]
#[command(
    name = "haj",
    author = "asitos",
    version,
    about = "the beautiful, cross-distro package manager and tui.",
    long_about = None,
    disable_version_flag = true,
    help_template = "\
{about}

Usage: \x1b[36;1mhaj\x1b[0m [OPTIONS] <COMMAND>

Commands (alias):
  \x1b[36;1mtui (t)\x1b[0m                         launch the interactive tui dashboard

  \x1b[36;1mupdate (sync/up)\x1b[0m                synchronize remote repositories
  \x1b[36;1mupgrade (jump)\x1b[0m [pkg]            upgrade system or packages [--no-sync]
  \x1b[36;1minstall/add (i/a)\x1b[0m <pkg|file>    install packages or local archive
  \x1b[36;1mremove (rm/toss)\x1b[0m <pkg>          remove packages & unneeded deps
  \x1b[36;1msearch (s/find)\x1b[0m <query>         search repositories & external
  \x1b[36;1mshow (info/about)\x1b[0m <pkg>         show detailed package information
  \x1b[36;1mgroup (g)\x1b[0m <name>                browse & install package groups
  \x1b[36;1mlist (ls)\x1b[0m [filter]              list (explicit|deps|aur|orphans|updates)
  \x1b[36;1mstats (st)\x1b[0m                      show system health and statistics
  \x1b[36;1mload (l)\x1b[0m <path>                 install a local package archive
  \x1b[36;1mfetch (f/get)\x1b[0m <pkg>             download packages without installing
  \x1b[36;1mdowngrade (sink)\x1b[0m <pkg> [ver]    downgrade an installed package

  \x1b[36;1mowns (ow/which)\x1b[0m <path>          find which package owns a file
  \x1b[36;1mfiles (lf)\x1b[0m [in|of] <pkg>        list files owned by a package
  \x1b[36;1mlocate (loc/where)\x1b[0m <query>      search repositories for a file

  \x1b[36;1mhistory (h)\x1b[0m [-l <n>]            show recent package transactions
  \x1b[36;1morphan (o/prune)\x1b[0m                list or prune orphaned dependencies
  \x1b[36;1mclean (c)\x1b[0m [cache|orphans]       clean cache [-k <n>] or orphans
  \x1b[36;1mmark (m)\x1b[0m <pkg> [as exp|dep]     set or toggle package install reason
  \x1b[36;1mdiff (pn/merge)\x1b[0m                 interactively merge config files
  \x1b[36;1mpkgbuild (pb)\x1b[0m <pkg>             inspect PKGBUILD of an AUR package

Options:
{options}

run 'haj <cmd> --help' for subcommands, or 'man haj' for all aliases & docs."
)]
#[command(
    name = "haj",
    version,
    about = "the beautiful, cross-distro package manager and tui."
)]
pub struct Cli {
    #[command(subcommand)]
    pub command: Option<Commands>,

    /// restrict operations to aur/external sources
    #[arg(short = 'a', long, global = true)]
    pub aur: bool,

    /// restrict operations to native repositories
    #[arg(short = 'r', long, global = true)]
    pub repo: bool,

    /// restrict source ('aur' or 'repo')
    #[arg(
        long,
        global = true,
        value_enum,
        hide_possible_values = true,
        value_name = "SOURCE"
    )]
    pub from: Option<SourceScope>,

    /// bypass all confirmation prompts
    #[arg(short = 'y', long, global = true)]
    pub noconfirm: bool,

    /// do not reinstall up-to-date packages
    #[arg(short = 'n', long, global = true)]
    pub needed: bool,

    /// ignore upgrades (comma-separated: pkg1,pkg2)
    #[arg(
        short = 'i',
        long,
        global = true,
        value_delimiter = ',',
        value_name = "PKG"
    )]
    pub ignore: Vec<String>,

    /// specify an alternate config file
    #[arg(short = 'c', long, global = true, value_name = "PATH")]
    pub config: Option<String>,

    /// specify an alternate installation root
    #[arg(long, global = true, value_name = "PATH")]
    pub root: Option<String>,

    /// enable verbose debug logging
    #[arg(short, long, global = true)]
    pub verbose: bool,

    /// preview without modifying the system
    #[arg(short = 'd', long, global = true)]
    pub dry_run: bool,

    /// show version info
    #[arg(short = 'V', long, action = clap::ArgAction::Version)]
    pub version: Option<bool>,
}

#[derive(Subcommand, Debug, Clone)]
pub enum Commands {
    #[command(
        alias = "t",
        help_template = "\
\x1b[36;1mhaj tui (alias: t)\x1b[0m

Usage: haj tui [OPTIONS]

Description:
  launch the interactive package manager terminal dashboard
  features stats, search, orphans cleaner, news reader, and transaction history

Options:
  -v, --verbose  enable verbose debug logging
  -h, --help     print help"
    )]
    Tui,

    #[command(
        aliases = ["add", "i", "a"],
        help_template = "\
\x1b[36;1mhaj install/add (aliases: i, a)\x1b[0m

Usage: haj install [OPTIONS] <packages>...

Description:
  install packages from repositories/AUR or a local package archive

Examples:
  haj add neovim
  haj add yay-bin from aur
  haj add ./foo.pkg.tar.zst

Arguments:
  <packages>...  list of packages or local archive paths to install

Options:
  -a, --aur              restrict operations to the aur
  -r, --repo             restrict operations to arch repositories
      --from <SOURCE>    restrict operations to 'aur' or 'repo'
  -n, --needed           do not reinstall up-to-date packages
  -i, --ignore <IGNORE>  ignore a package upgrade (comma-separated)
  -y, --noconfirm        bypass all confirmation prompts
      --root <PATH>      specify an alternate installation root
  -v, --verbose          enable verbose debug logging
  -d, --dry-run          preview a command without modifying the system
  -h, --help             print help"
    )]
    Install {
        #[arg(required = true)]
        packages: Vec<String>,
    },

    #[command(
        aliases = ["rm", "toss", "uninstall", "delete", "drop"],
        help_template = "\
\x1b[36;1mhaj remove (aliases: rm, toss, uninstall, delete, drop)\x1b[0m

Usage: haj remove [OPTIONS] <packages>...

Description:
  remove packages along with their unneeded dependencies (via pacman -Rs)

Arguments:
  <packages>...  list of packages to remove

Options:
  -y, --noconfirm      bypass all confirmation prompts
      --root <PATH>    specify an alternate installation root
  -v, --verbose        enable verbose debug logging
  -d, --dry-run        preview a command without modifying the system
  -h, --help           print help"
    )]
    Remove {
        #[arg(required = true)]
        packages: Vec<String>,
    },

    #[command(
        aliases = ["up", "sync", "refresh"],
        help_template = "\
\x1b[36;1mhaj update (aliases: up, sync, refresh)\x1b[0m

Usage: haj update [OPTIONS]

Description:
  synchronize package databases from remote repositories

Options:
  -a, --aur            restrict operations to the aur
  -r, --repo           restrict operations to arch repositories
      --root <PATH>    specify an alternate installation root
  -v, --verbose        enable verbose debug logging
  -d, --dry-run        preview a command without modifying the system
  -h, --help           print help"
    )]
    Update,

    #[command(
        alias = "jump",
        help_template = "\
\x1b[36;1mhaj upgrade (alias: jump)\x1b[0m

Usage: haj upgrade [OPTIONS] [packages]...

Description:
  perform a full system upgrade or upgrade specific packages

Arguments:
  [packages]...        optional specific packages to upgrade

Options:
      --no-sync        do not sync package databases from remote mirrors
  -a, --aur            restrict operations to the aur
  -r, --repo           restrict operations to arch repositories
      --from <SOURCE>  restrict operations to 'aur' or 'repo'
  -y, --noconfirm      bypass all confirmation prompts
      --root <PATH>    specify an alternate installation root
  -v, --verbose        enable verbose debug logging
  -d, --dry-run        preview a command without modifying the system
  -h, --help           print help"
    )]
    Upgrade {
        /// Do not sync package databases before upgrading
        #[arg(long)]
        no_sync: bool,
        /// Optional specific packages to upgrade
        packages: Vec<String>,
    },

    #[command(
        aliases = ["s", "find"],
        help_template = "\
\x1b[36;1mhaj search (aliases: s, find)\x1b[0m

Usage: haj search [OPTIONS] <query>

Description:
  search official repositories and AUR for matching packages

Arguments:
  <query>  the search term to query

Options:
  -a, --aur            restrict operations to the aur
  -r, --repo           restrict operations to arch repositories
      --from <SOURCE>  restrict operations to 'aur' or 'repo'
  -v, --verbose        enable verbose debug logging
  -h, --help           print help"
    )]
    Search { query: String },

    #[command(
        aliases = ["info", "about", "describe"],
        help_template = "\
\x1b[36;1mhaj show (aliases: info, about, describe)\x1b[0m

Usage: haj show [OPTIONS] <package>

Description:
  display detailed package information such as size, installation reason, and dependencies

Arguments:
  <package>  the package name to inspect

Options:
  -v, --verbose  enable verbose debug logging
  -h, --help     print help"
    )]
    Show { package: String },

    #[command(
        alias = "g",
        help_template = "\
\x1b[36;1mhaj group (alias: g)\x1b[0m

Usage: haj group [OPTIONS] <name>

Description:
  browse and install packages associated with a package group or meta-package

Arguments:
  <name>  the package group or meta-package name

Options:
  -y, --noconfirm  bypass all confirmation prompts
  -d, --dry-run    preview a command without modifying the system
  -v, --verbose    enable verbose debug logging
  -h, --help       print help"
    )]
    Group { name: String },

    #[command(
        alias = "ls",
        help_template = "\
\x1b[36;1mhaj list (alias: ls)\x1b[0m

Usage: haj list [OPTIONS] [filter]

Description:
  list installed packages or query subsets (explicit, deps, aur, orphans, updates)

Examples:
  haj list explicit
  haj list aur
  haj list updates

Arguments:
  [filter]        optional filter word (explicit|deps|aur|foreign|orphans|updates)

Options:
  -e, --explicit  show only packages installed explicitly
  -p, --deps      show only packages installed as dependencies
  -f, --foreign   show only foreign/AUR packages
  -v, --verbose   enable verbose debug logging
  -h, --help      print help"
    )]
    List {
        /// show only packages installed explicitly
        #[arg(short, long)]
        explicit: bool,
        /// show only packages installed as dependencies
        #[arg(short = 'p', long)]
        deps: bool,
        /// show only foreign/aur packages
        #[arg(short = 'f', long)]
        foreign: bool,
        /// natural filter keyword (explicit|deps|aur|foreign|orphans|updates)
        filter: Option<String>,
    },

    #[command(
        alias = "st",
        help_template = "\
\x1b[36;1mhaj stats (alias: st)\x1b[0m

Usage: haj stats [OPTIONS]

Description:
  display system health score, disk usage, cache statistics, and package counts

Options:
  -v, --verbose  enable verbose debug logging
  -h, --help     print help"
    )]
    Stats,

    #[command(
        alias = "h",
        help_template = "\
\x1b[36;1mhaj history (alias: h)\x1b[0m

Usage: haj history [OPTIONS]

Description:
  show recent transaction history (installs, upgrades, removals)

Options:
  -l, --limit <LIMIT>  number of recent changes to show [default: 50]
  -v, --verbose        enable verbose debug logging
  -h, --help           print help"
    )]
    History {
        /// number of recent changes to show
        #[arg(short = 'l', long, default_value_t = 50)]
        limit: usize,
    },

    #[command(
        aliases = ["sink", "rollback"],
        help_template = "\
\x1b[36;1mhaj downgrade (aliases: sink, rollback)\x1b[0m

Usage: haj downgrade [OPTIONS] <package> [to] [version]

Description:
  downgrade an installed package using cached archives

Examples:
  haj downgrade bash
  haj downgrade bash to 5.2.026-1

Arguments:
  <package>  the package name to downgrade
  [version]  optional target version

Options:
  -y, --noconfirm      bypass all confirmation prompts
      --root <PATH>    specify an alternate installation root
  -v, --verbose        enable verbose debug logging
  -d, --dry-run        preview a command without modifying the system
  -h, --help           print help"
    )]
    Downgrade {
        /// package to downgrade
        package: String,
        /// optional target version
        version: Option<String>,
    },

    #[command(
        alias = "c",
        help_template = "\
\x1b[36;1mhaj clean (alias: c)\x1b[0m

Usage: haj clean [OPTIONS] [target]

Description:
  clean the package cache (default) or orphaned dependencies

Examples:
  haj clean
  haj clean cache -k 2
  haj clean orphans

Arguments:
  [target]           optional target: 'cache' (default) or 'orphans'

Options:
  -k, --keep <KEEP>  number of package versions to keep in cache [default: 3]
  -y, --noconfirm    bypass all confirmation prompts
  -d, --dry-run      preview a command without modifying the system
  -v, --verbose      enable verbose debug logging
  -h, --help         print help"
    )]
    Clean {
        /// clean target ('cache' or 'orphans')
        target: Option<String>,
        /// number of package versions to keep in cache
        #[arg(short = 'k', long, default_value_t = 3)]
        keep: usize,
    },

    #[command(
        aliases = ["o", "orphans", "autoremove", "prune"],
        help_template = "\
\x1b[36;1mhaj orphan (aliases: o, orphans, autoremove, prune)\x1b[0m

Usage: haj orphan [OPTIONS]

Description:
  detect and optionally remove orphaned package dependencies

Options:
  -y, --noconfirm  bypass all confirmation prompts
  -d, --dry-run    preview a command without modifying the system
  -v, --verbose    enable verbose debug logging
  -h, --help       print help"
    )]
    Orphan,

    #[command(
        aliases = ["ow", "owner", "which"],
        help_template = "\
\x1b[36;1mhaj owns (aliases: ow, owner, which)\x1b[0m

Usage: haj owns [OPTIONS] <file_path>

Description:
  find which installed package owns a given file path ('haj who owns <path>')

Arguments:
  <file_path>  the file path to query (e.g. /usr/bin/bash)

Options:
  -v, --verbose  enable verbose debug logging
  -h, --help     print help"
    )]
    Owns { file_path: String },

    #[command(
        aliases = ["loc", "where", "find-file"],
        help_template = "\
\x1b[36;1mhaj locate (aliases: loc, where, find-file)\x1b[0m

Usage: haj locate [OPTIONS] <query>

Description:
  search remote package repositories for a file name matching the query (using pacman -F)

Arguments:
  <query>  the file name or pattern to search for

Options:
  -v, --verbose  enable verbose debug logging
  -h, --help     print help"
    )]
    Locate { query: String },

    #[command(
        alias = "lf",
        help_template = "\
\x1b[36;1mhaj files (alias: lf)\x1b[0m

Usage: haj files [OPTIONS] <package>

Description:
  list all files installed by a specific package ('haj list files <pkg>')

Arguments:
  <package>  the name of the package

Options:
  -v, --verbose  enable verbose debug logging
  -h, --help     print help"
    )]
    Files { package: String },

    #[command(
        alias = "l",
        help_template = "\
\x1b[36;1mhaj load (alias: l)\x1b[0m

Usage: haj load [OPTIONS] <archive_path>

Description:
  install a local package archive (.pkg.tar.zst) onto the system

Arguments:
  <archive_path>  the path to the local package archive file

Options:
  -y, --noconfirm      bypass all confirmation prompts
      --root <PATH>    specify an alternate installation root
  -v, --verbose        enable verbose debug logging
  -d, --dry-run        preview a command without modifying the system
  -h, --help           print help"
    )]
    Load { archive_path: String },

    #[command(
        aliases = ["f", "download", "get"],
        help_template = "\
\x1b[36;1mhaj fetch (aliases: f, download, get)\x1b[0m

Usage: haj fetch [OPTIONS] <packages>...

Description:
  download package archives to the cache directory without installing them

Arguments:
  <packages>...  list of packages to fetch

Options:
      --root <PATH>    specify an alternate installation root
  -v, --verbose        enable verbose debug logging
  -d, --dry-run        preview a command without modifying the system
  -h, --help           print help"
    )]
    Fetch { packages: Vec<String> },

    #[command(
        alias = "m",
        help_template = "\
\x1b[36;1mhaj mark (alias: m)\x1b[0m

Usage: haj mark [OPTIONS] <package> [reason]

Description:
  set or toggle an installed package's install reason

Examples:
  haj mark bash
  haj mark bash as explicit
  haj mark bash dep

Arguments:
  <package>      the package to modify
  [reason]       optional reason: 'explicit'/'manual' or 'dep'/'deps'/'auto'

Options:
      --as-explicit  mark package as explicitly installed
      --as-deps      mark package as installed as a dependency
      --root <PATH>  specify an alternate installation root
  -v, --verbose      enable verbose debug logging
  -d, --dry-run      preview a command without modifying the system
  -h, --help         print help"
    )]
    Mark {
        package: String,
        /// optional target reason ('explicit'|'manual' or 'dep'|'deps'|'auto')
        reason: Option<String>,
        /// mark package as explicitly installed
        #[arg(long)]
        as_explicit: bool,
        /// mark package as dependency
        #[arg(long)]
        as_deps: bool,
    },

    #[command(
        aliases = ["pn", "pacnew", "merge"],
        help_template = "\
\x1b[36;1mhaj diff (aliases: pn, pacnew, merge)\x1b[0m

Usage: haj diff [OPTIONS]

Description:
  interactively search, manage, and merge .pacnew configuration files on the system

Options:
  -d, --dry-run  preview command without running pacdiff
  -v, --verbose  enable verbose debug logging
  -h, --help     print help"
    )]
    Diff,

    #[command(
        alias = "pb",
        help_template = "\
\x1b[36;1mhaj pkgbuild (alias: pb)\x1b[0m

Usage: haj pkgbuild [OPTIONS] <package>

Description:
  read and print the PKGBUILD file of a package from the AUR

Arguments:
  <package>  the package to fetch the PKGBUILD for

Options:
  -d, --dry-run  preview command without fetching
  -h, --help     print help"
    )]
    Pkgbuild { package: String },

    #[command(hide = true)]
    Completions {
        #[arg(value_enum)]
        shell: CompletionShell,
    },

    #[command(external_subcommand)]
    Interactive(Vec<String>),
}

const KNOWN_VERBS: &[&str] = &[
    "tui",
    "t",
    "install",
    "add",
    "i",
    "a",
    "remove",
    "rm",
    "toss",
    "uninstall",
    "delete",
    "drop",
    "update",
    "up",
    "sync",
    "refresh",
    "upgrade",
    "jump",
    "search",
    "s",
    "find",
    "show",
    "info",
    "about",
    "describe",
    "group",
    "g",
    "list",
    "ls",
    "stats",
    "st",
    "history",
    "h",
    "downgrade",
    "sink",
    "rollback",
    "clean",
    "c",
    "orphan",
    "o",
    "orphans",
    "autoremove",
    "prune",
    "owns",
    "ow",
    "owner",
    "which",
    "locate",
    "loc",
    "where",
    "find-file",
    "files",
    "lf",
    "load",
    "l",
    "fetch",
    "f",
    "download",
    "get",
    "mark",
    "m",
    "diff",
    "pn",
    "pacnew",
    "merge",
    "pkgbuild",
    "pb",
    "completions",
    "help",
];

fn takes_flag_value(arg: &str) -> bool {
    if arg.contains('=') {
        return false;
    }
    if matches!(
        arg,
        "-i" | "--ignore"
            | "-c"
            | "--config"
            | "--root"
            | "--from"
            | "-l"
            | "--limit"
            | "-k"
            | "--keep"
    ) {
        return true;
    }
    !arg.starts_with("--")
        && arg.starts_with('-')
        && arg.len() > 2
        && matches!(arg.as_bytes().last(), Some(b'i' | b'c' | b'l' | b'k'))
}

/// Rewrites natural English command phrases into canonical CLI tokens before Clap parsing,
/// while leaving bare `haj <interactive query>` inputs untouched.
pub fn normalize_args(raw: Vec<String>) -> Vec<String> {
    if raw.len() <= 1 {
        return raw;
    }

    let mut prefix_flags = Vec::new();
    let mut rest = Vec::new();
    let mut i = 1;
    while i < raw.len() {
        let arg = &raw[i];
        if arg == "--" {
            rest.extend_from_slice(&raw[i..]);
            break;
        }
        if arg.starts_with('-') {
            prefix_flags.push(arg.clone());
            if takes_flag_value(arg) && i + 1 < raw.len() {
                i += 1;
                prefix_flags.push(raw[i].clone());
            }
            i += 1;
        } else {
            rest.extend_from_slice(&raw[i..]);
            break;
        }
    }

    if rest.is_empty() {
        return raw;
    }

    // Multi-word natural verb phrases -> canonical single verb.
    if rest.len() >= 2 && rest[0] == "who" && rest[1] == "owns" {
        rest.drain(0..2);
        rest.insert(0, "owns".to_string());
    } else if rest.len() >= 2 && rest[0] == "list" && rest[1] == "files" {
        rest.drain(0..2);
        rest.insert(0, "files".to_string());
    }

    let verb = rest[0].as_str();
    if !KNOWN_VERBS.contains(&verb) {
        return raw;
    }

    let mut tail = Vec::new();
    let mut pos_idx = 0usize;
    let mut j = 1;
    while j < rest.len() {
        let cur = &rest[j];

        if cur == "--" {
            tail.extend_from_slice(&rest[j..]);
            break;
        }

        if cur.starts_with('-') {
            tail.push(cur.clone());
            if takes_flag_value(cur) && j + 1 < rest.len() {
                j += 1;
                tail.push(rest[j].clone());
            }
            j += 1;
            continue;
        }

        // "from aur" / "in aur" / "from repo(s)" / "in repo(s)"
        if (cur == "from" || cur == "in")
            && j + 1 < rest.len()
            && matches!(
                verb,
                "install"
                    | "add"
                    | "i"
                    | "a"
                    | "search"
                    | "s"
                    | "find"
                    | "upgrade"
                    | "jump"
                    | "update"
                    | "up"
                    | "sync"
                    | "refresh"
                    | "show"
                    | "info"
                    | "about"
                    | "describe"
                    | "pkgbuild"
                    | "pb"
            )
        {
            match rest[j + 1].as_str() {
                "aur" => {
                    tail.push("--aur".to_string());
                    j += 2;
                    continue;
                }
                "repo" | "repos" => {
                    tail.push("--repo".to_string());
                    j += 2;
                    continue;
                }
                _ => {}
            }
        }

        // "downgrade <pkg> to <ver>"
        if matches!(verb, "downgrade" | "sink" | "rollback")
            && cur == "to"
            && pos_idx == 1
            && j + 1 < rest.len()
        {
            j += 1;
            continue;
        }

        // "mark <pkg> as explicit|dep"
        if matches!(verb, "mark" | "m") && cur == "as" && pos_idx == 1 && j + 1 < rest.len() {
            j += 1;
            continue;
        }

        // "files in <pkg>" / "files of <pkg>"
        if matches!(verb, "files" | "lf")
            && (cur == "in" || cur == "of")
            && pos_idx == 0
            && j + 1 < rest.len()
        {
            j += 1;
            continue;
        }

        tail.push(cur.clone());
        pos_idx += 1;
        j += 1;
    }

    let mut out = Vec::with_capacity(1 + prefix_flags.len() + 1 + tail.len());
    out.push(raw[0].clone());
    out.extend(prefix_flags);
    out.push(rest[0].clone());
    out.extend(tail);
    out
}

/// Compact top-level `-h` summary designed to fit cleanly in a 24x80 terminal.
pub fn short_help_text() -> &'static str {
    "\
the beautiful, cross-distro package manager and tui.

Usage: \x1b[36;1mhaj\x1b[0m [OPTIONS] <COMMAND>

Core: tui (t), sync (up), jump (upgrade), add (i), rm (toss), s (find),
      show (info), ls (list), st (stats), h (history), o (orphan), c (clean)
More: group, load, fetch, downgrade (sink), owns, files, locate, mark,
      diff, pkgbuild (pb)

Options:
  -a, --aur        restrict to aur/external sources
  -r, --repo       restrict to native repositories
  -y, --noconfirm  bypass confirmation prompts
  -n, --needed     skip up-to-date packages
  -d, --dry-run    preview without modifying the system
  -V, --version    show version info
  -h, --help       compact help ('--help' for full command list)

run 'haj --help', 'haj <cmd> --help', or 'man haj' for details."
}

/// Returns true for top-level `haj -h` without invoking `--help` or a subcommand first.
pub fn is_short_help_request(args: &[String]) -> bool {
    if args.len() < 2 || args.iter().any(|a| a == "--help") {
        return false;
    }
    args[1..]
        .iter()
        .take_while(|a| a.starts_with('-'))
        .any(|a| a == "-h")
}

pub fn parse_cli_from<I, S>(args: I) -> Result<Cli, clap::Error>
where
    I: IntoIterator<Item = S>,
    S: Into<String>,
{
    Cli::try_parse_from(normalize_args(args.into_iter().map(Into::into).collect()))
}

pub fn parse_cli() -> Result<Cli, clap::Error> {
    let raw: Vec<String> = std::env::args_os()
        .map(|s| s.to_string_lossy().into_owned())
        .collect();
    parse_cli_from(raw)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn norm(args: &[&str]) -> Vec<String> {
        normalize_args(args.iter().map(|s| s.to_string()).collect())
    }

    #[test]
    fn test_normalize_natural_phrases() {
        assert_eq!(
            norm(&["haj", "add", "yay", "from", "aur"]),
            vec!["haj", "add", "yay", "--aur"]
        );
        assert_eq!(
            norm(&["haj", "search", "foo", "in", "repo"]),
            vec!["haj", "search", "foo", "--repo"]
        );
        assert_eq!(
            norm(&["haj", "downgrade", "bash", "to", "5.2"]),
            vec!["haj", "downgrade", "bash", "5.2"]
        );
        assert_eq!(
            norm(&["haj", "rollback", "--dry-run", "7zip", "to", "26.05"]),
            vec!["haj", "rollback", "--dry-run", "7zip", "26.05"]
        );
        assert_eq!(
            norm(&["haj", "mark", "bash", "as", "explicit"]),
            vec!["haj", "mark", "bash", "explicit"]
        );
        assert_eq!(
            norm(&["haj", "mark", "-d", "bash", "as", "dep"]),
            vec!["haj", "mark", "-d", "bash", "dep"]
        );
        assert_eq!(
            norm(&["haj", "who", "owns", "/usr/bin/bash"]),
            vec!["haj", "owns", "/usr/bin/bash"]
        );
        assert_eq!(
            norm(&["haj", "list", "files", "of", "bash"]),
            vec!["haj", "files", "bash"]
        );
        assert_eq!(
            norm(&["haj", "files", "-v", "in", "bash"]),
            vec!["haj", "files", "-v", "bash"]
        );
        assert_eq!(
            norm(&["haj", "-vc", "pacman.conf", "install", "fd", "from", "repo"]),
            vec!["haj", "-vc", "pacman.conf", "install", "fd", "--repo"]
        );
        assert_eq!(
            norm(&["haj", "install", "--", "from", "aur"]),
            vec!["haj", "install", "--", "from", "aur"]
        );
    }

    #[test]
    fn test_bare_interactive_query_untouched() {
        assert_eq!(
            norm(&["haj", "text", "to", "speech"]),
            vec!["haj", "text", "to", "speech"]
        );
    }

    fn strip_ansi(s: &str) -> String {
        let mut out = String::with_capacity(s.len());
        let mut chars = s.chars();
        while let Some(c) = chars.next() {
            if c == '\x1b' {
                for n in chars.by_ref() {
                    if n == 'm' {
                        break;
                    }
                }
            } else {
                out.push(c);
            }
        }
        out
    }

    #[test]
    fn test_help_outputs_fit_80_columns() {
        for line in strip_ansi(short_help_text()).lines() {
            assert!(line.len() <= 80, "short -h line too wide: {line}");
        }
        assert!(short_help_text().lines().count() <= 20);

        use clap::CommandFactory;
        let long_help = Cli::command().render_long_help().to_string();
        for line in strip_ansi(&long_help).lines() {
            assert!(line.len() <= 80, "--help line exceeds 80 cols: {line}");
        }
        assert!(is_short_help_request(&["haj".into(), "-h".into()]));
        assert!(!is_short_help_request(&["haj".into(), "--help".into()]));
        assert!(!is_short_help_request(&[
            "haj".into(),
            "install".into(),
            "-h".into()
        ]));
    }

    #[test]
    fn test_completion_shell_enum_parsing() {
        assert!(matches!(
            Cli::try_parse_from(["haj", "completions", "bash"])
                .unwrap()
                .command,
            Some(Commands::Completions {
                shell: CompletionShell::Bash
            })
        ));
        assert!(matches!(
            Cli::try_parse_from(["haj", "completions", "zsh"])
                .unwrap()
                .command,
            Some(Commands::Completions {
                shell: CompletionShell::Zsh
            })
        ));
        assert!(matches!(
            Cli::try_parse_from(["haj", "completions", "fish"])
                .unwrap()
                .command,
            Some(Commands::Completions {
                shell: CompletionShell::Fish
            })
        ));
        assert!(Cli::try_parse_from(["haj", "completions", "powershell"]).is_err());
    }
}