prek 0.4.14

A fast Git hook manager written in Rust, designed as a drop-in alternative to pre-commit, reimagined.
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
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
use std::ffi::OsString;
use std::path::PathBuf;
use std::process::ExitCode;

use clap::builder::styling::{AnsiColor, Effects};
use clap::builder::{ArgPredicate, PathBufValueParser, Styles, TypedValueParser};
use clap::{ArgAction, Args, Parser, Subcommand, ValueHint};
use clap_complete::engine::ArgValueCompleter;
use globset::Glob;
use prek_consts::env_vars::EnvVars;
use serde::{Deserialize, Serialize};

use crate::config::{HookType, Language, Stage};
use crate::fs::expand_tilde;

mod cache_clean;
mod cache_gc;
mod cache_size;
mod completion;
mod exec;
mod hook_impl;
mod identify;
mod install;
mod list;
mod list_builtins;
pub mod reporter;
pub mod run;
mod sample_config;
#[cfg(feature = "self-update")]
mod self_update;
mod try_repo;
mod update;
mod validate;
mod yaml_to_toml;

pub(crate) use cache_clean::cache_clean;
pub(crate) use cache_gc::cache_gc;
pub(crate) use cache_size::cache_size;
use completion::selector_completer;
pub(crate) use exec::exec;
pub(crate) use hook_impl::hook_impl;
pub(crate) use identify::identify;
pub(crate) use install::{init_template_dir, install, prepare_hooks, uninstall};
pub(crate) use list::list;
pub(crate) use list_builtins::list_builtins;
pub(crate) use run::run;
pub(crate) use sample_config::sample_config;
#[cfg(feature = "self-update")]
pub(crate) use self_update::self_update;
pub(crate) use try_repo::try_repo;
pub(crate) use update::update;
pub(crate) use validate::{validate_configs, validate_manifest};
pub(crate) use yaml_to_toml::yaml_to_toml;

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub(crate) enum ExitStatus {
    /// The command succeeded.
    Success,

    /// The command failed due to an error in the user input.
    Failure,

    /// The command failed with an unexpected error.
    Error,

    /// The command was interrupted.
    Interrupted,

    /// The command's exit status is propagated from an external command.
    External(u8),
}

impl From<ExitStatus> for ExitCode {
    fn from(status: ExitStatus) -> Self {
        match status {
            ExitStatus::Success => Self::from(0),
            ExitStatus::Failure => Self::from(1),
            ExitStatus::Error => Self::from(2),
            ExitStatus::Interrupted => Self::from(130),
            ExitStatus::External(code) => Self::from(code),
        }
    }
}

impl From<u8> for ExitStatus {
    fn from(code: u8) -> Self {
        match code {
            0 => Self::Success,
            other => Self::External(other),
        }
    }
}

#[derive(Debug, Copy, Clone, clap::ValueEnum)]
pub enum ColorChoice {
    /// Enables colored output only when the output is going to a terminal or TTY with support.
    Auto,

    /// Enables colored output regardless of the detected environment.
    Always,

    /// Disables colored output.
    Never,
}

impl From<ColorChoice> for anstream::ColorChoice {
    fn from(value: ColorChoice) -> Self {
        match value {
            ColorChoice::Auto => Self::Auto,
            ColorChoice::Always => Self::Always,
            ColorChoice::Never => Self::Never,
        }
    }
}

/// Given a boolean flag pair (like `--fail-fast` and `--no-fail-fast`), resolve the value of the flag.
pub(crate) fn flag(yes: bool, no: bool) -> Option<bool> {
    match (yes, no) {
        (true, false) => Some(true),
        (false, true) => Some(false),
        (false, false) => None,
        (true, true) => unreachable!("clap should prevent both flags from being set"),
    }
}

const STYLES: Styles = Styles::styled()
    .header(AnsiColor::Green.on_default().effects(Effects::BOLD))
    .usage(AnsiColor::Green.on_default().effects(Effects::BOLD))
    .literal(AnsiColor::Cyan.on_default().effects(Effects::BOLD))
    .placeholder(AnsiColor::Cyan.on_default());

#[derive(Parser)]
#[command(
    name = "prek",
    long_version = crate::version::version(),
    about = "A fast Git hook manager written in Rust, designed as a drop-in alternative to pre-commit, reimagined."
)]
#[command(
    propagate_version = true,
    disable_help_flag = true,
    disable_help_subcommand = true,
    disable_version_flag = true
)]
#[command(styles=STYLES)]
pub(crate) struct Cli {
    #[command(subcommand)]
    pub(crate) command: Option<Command>,

    // run as the default subcommand
    #[command(flatten)]
    pub(crate) run_args: RunArgs,

    #[command(flatten)]
    pub(crate) globals: GlobalArgs,
}

#[derive(Debug, Args)]
#[command(next_help_heading = "Global options", next_display_order = 1000)]
#[allow(clippy::struct_excessive_bools)]
pub(crate) struct GlobalArgs {
    /// Path to alternate config file.
    #[arg(
        global = true,
        short,
        long,
        value_parser = PathBufValueParser::new().map(expand_tilde),
    )]
    pub(crate) config: Option<PathBuf>,

    /// Change to directory before running.
    #[arg(
        global = true,
        short = 'C',
        long,
        value_name = "DIR",
        value_hint = ValueHint::DirPath,
        value_parser = PathBufValueParser::new().map(expand_tilde),
    )]
    pub(crate) cd: Option<PathBuf>,

    /// Whether to use color in output.
    #[arg(
        global = true,
        long,
        value_enum,
        env = EnvVars::PREK_COLOR,
        default_value_t = ColorChoice::Auto,
    )]
    pub(crate) color: ColorChoice,

    /// Refresh all cached data.
    #[arg(global = true, long)]
    pub(crate) refresh: bool,

    /// Display the concise help for this command.
    #[arg(global = true, short, long, action = ArgAction::HelpShort)]
    help: (),

    /// Hide all progress outputs.
    ///
    /// For example, spinners or progress bars.
    #[arg(global = true, long)]
    pub no_progress: bool,

    /// Use quiet output.
    ///
    /// Repeating this option, e.g., `-qq`, will enable a silent mode in which
    /// prek will write no output to stdout.
    #[arg(global = true, short, long, env = EnvVars::PREK_QUIET, conflicts_with = "verbose", action = ArgAction::Count)]
    pub quiet: u8,

    /// Use verbose output.
    #[arg(global = true, short, long, action = ArgAction::Count)]
    pub(crate) verbose: u8,

    /// Write trace logs to the specified file.
    /// If not specified, trace logs will be written to `$PREK_HOME/prek.log`.
    #[arg(
        global = true,
        long,
        value_name = "LOG_FILE",
        value_hint = ValueHint::FilePath,
        value_parser = PathBufValueParser::new().map(expand_tilde),
    )]
    pub(crate) log_file: Option<PathBuf>,

    /// Do not write trace logs to a log file.
    #[arg(global = true, long, overrides_with = "log_file", hide = true)]
    pub(crate) no_log_file: bool,

    /// Display the prek version.
    #[arg(global = true, short = 'V', long, action = ArgAction::Version)]
    version: (),

    /// Show the resolved settings for the current command.
    ///
    /// This option is used for debugging and development purposes.
    #[arg(global = true, long, hide = true)]
    pub show_settings: bool,
}

#[derive(Debug, Subcommand)]
pub(crate) enum Command {
    /// Install prek Git hook shims.
    ///
    /// The effective hooks directory defaults to `.git/hooks/`, but repo-local
    /// or worktree-local `core.hooksPath` is honored when set.
    ///
    /// The Git shims installed by this command are determined by `--hook-type`
    /// or `default_install_hook_types` in the config file, falling back to
    /// `pre-commit` when neither is set.
    ///
    /// A hook's `stages` field does not affect which Git shims this
    /// command installs.
    Install(InstallArgs),
    /// Prepare environments for configured hooks.
    ///
    /// This command does not install Git shims. To install the Git shims
    /// along with the hook environments in one command, use `prek install --prepare-hooks`.
    #[command(alias = "install-hooks")]
    PrepareHooks(PrepareHooksArgs),
    /// Run configured hooks.
    Run(Box<RunArgs>),
    /// Run a command in the environment prepared for a configured hook.
    Exec(ExecArgs),
    /// List configured hooks.
    List(ListArgs),
    /// Uninstall prek Git hook shims.
    Uninstall(UninstallArgs),
    /// Validate prek configuration files.
    ValidateConfig(ValidateConfigArgs),
    /// Validate pre-commit hook manifests (`.pre-commit-hooks.yaml`).
    ValidateManifest(ValidateManifestArgs),
    /// Generate a sample prek configuration file.
    SampleConfig(SampleConfigArgs),
    /// Update configured repositories.
    #[command(aliases = ["auto-update", "autoupdate"])]
    Update(UpdateArgs),
    /// Manage the prek cache.
    Cache(CacheNamespace),
    /// Remove unused cached repositories, hook environments, and other data.
    #[command(hide = true)]
    GC(CacheGcArgs),
    /// Remove all prek cached data.
    #[command(hide = true)]
    Clean,
    /// Install Git shims in a directory intended for use with `git config init.templateDir`.
    #[command(alias = "init-templatedir", hide = true)]
    InitTemplateDir(InitTemplateDirArgs),
    /// Try hooks from a repository.
    TryRepo(Box<TryRepoArgs>),
    /// The implementation of the prek Git shim that is installed in Git's effective hooks directory.
    #[command(hide = true)]
    HookImpl(HookImplArgs),
    /// Run utility commands.
    Util(UtilNamespace),
    /// Manage the prek installation.
    #[command(name = "self")]
    Self_(SelfNamespace),
}

#[derive(Debug, Args)]
pub(crate) struct ExecArgs {
    /// Hook whose execution environment should be used.
    ///
    /// Supports `hook-id` and `project-path:hook-id` selectors and must resolve
    /// to exactly one configured hook.
    #[arg(
        value_name = "HOOK",
        value_hint = ValueHint::Other,
        add = ArgValueCompleter::new(selector_completer)
    )]
    pub(crate) selector: String,

    /// Command and arguments to execute.
    #[arg(
        value_name = "COMMAND",
        required = true,
        num_args = 1..,
        last = true,
        value_hint = ValueHint::CommandWithArguments
    )]
    pub(crate) command: Vec<OsString>,
}

#[derive(Debug, Args)]
pub(crate) struct InstallArgs {
    /// Include the specified hooks or projects.
    ///
    /// Supports flexible selector syntax:
    ///
    /// - `hook-id`: Run all hooks with the specified ID across all projects
    ///
    /// - `project-path/`: Run all hooks from the specified project
    ///
    /// - `project-path:hook-id`: Run only the specified hook from the specified project
    ///
    /// Can be specified multiple times to select multiple hooks/projects.
    #[arg(
        value_name = "HOOK|PROJECT",
        value_hint = ValueHint::Other,
        add = ArgValueCompleter::new(selector_completer)
    )]
    pub(crate) includes: Vec<String>,

    /// Skip the specified hooks or projects.
    ///
    /// Supports flexible selector syntax:
    ///
    /// - `hook-id`: Skip all hooks with the specified ID across all projects
    ///
    /// - `project-path/`: Skip all hooks from the specified project
    ///
    /// - `project-path:hook-id`: Skip only the specified hook from the specified project
    ///
    /// Can be specified multiple times. Also accepts `PREK_SKIP` or `SKIP` environment variables (comma-delimited).
    #[arg(long = "skip", value_name = "HOOK|PROJECT", add = ArgValueCompleter::new(selector_completer))]
    pub(crate) skips: Vec<String>,

    /// Force installation and overwrite existing Git shims.
    ///
    /// If `core.hooksPath` is configured outside this repository, install the
    /// shims into this repository's default hooks directory.
    #[arg(short = 'f', long, alias = "overwrite")]
    pub(crate) force: bool,

    /// Also prepare environments for all hooks used in the config file.
    #[arg(long, alias = "install-hooks")]
    pub(crate) prepare_hooks: bool,

    /// Which Git shim(s) to install.
    ///
    /// Specifies which Git hook type(s) you want to install shims for.
    /// Can be specified multiple times to install shims for multiple hook types.
    ///
    /// If not specified, uses `default_install_hook_types` from the config file,
    /// or defaults to `pre-commit` if that is also not set.
    ///
    /// Note: This is different from a hook's `stages` parameter in the config file,
    /// which declares which stages a hook *can* run in.
    #[arg(short = 't', long = "hook-type", value_name = "HOOK_TYPE", value_enum)]
    pub(crate) hook_types: Vec<HookType>,

    /// Allow a missing configuration file.
    #[arg(long)]
    pub(crate) allow_missing_config: bool,

    /// Install Git shims into the `hooks` subdirectory of the given git directory (`<GIT_DIR>/hooks/`).
    ///
    /// When this flag is used, `prek install` bypasses the safety check that normally
    /// refuses to install shims while `core.hooksPath` is configured outside the repo.
    /// It only writes shims to `<GIT_DIR>/hooks`; Git will keep using
    /// `core.hooksPath` until that config changes.
    #[arg(
        long,
        value_name = "GIT_DIR",
        value_hint = ValueHint::DirPath,
        value_parser = PathBufValueParser::new().map(expand_tilde),
    )]
    pub(crate) git_dir: Option<PathBuf>,
}

#[derive(Debug, Args)]
pub(crate) struct PrepareHooksArgs {
    /// Include the specified hooks or projects.
    ///
    /// Supports flexible selector syntax:
    ///
    /// - `hook-id`: Run all hooks with the specified ID across all projects
    ///
    /// - `project-path/`: Run all hooks from the specified project
    ///
    /// - `project-path:hook-id`: Run only the specified hook from the specified project
    ///
    /// Can be specified multiple times to select multiple hooks/projects.
    #[arg(
        value_name = "HOOK|PROJECT",
        value_hint = ValueHint::Other,
        add = ArgValueCompleter::new(selector_completer)
    )]
    pub(crate) includes: Vec<String>,

    /// Skip the specified hooks or projects.
    ///
    /// Supports flexible selector syntax:
    ///
    /// - `hook-id`: Skip all hooks with the specified ID across all projects
    ///
    /// - `project-path/`: Skip all hooks from the specified project
    ///
    /// - `project-path:hook-id`: Skip only the specified hook from the specified project
    ///
    /// Can be specified multiple times. Also accepts `PREK_SKIP` or `SKIP` environment variables (comma-delimited).
    #[arg(long = "skip", value_name = "HOOK|PROJECT", add = ArgValueCompleter::new(selector_completer))]
    pub(crate) skips: Vec<String>,
}

#[derive(Debug, Args)]
pub(crate) struct UninstallArgs {
    /// Uninstall all prek-managed Git shims.
    ///
    /// Scans the hooks directory and removes every hook managed by prek,
    /// regardless of hook type.
    #[arg(long, conflicts_with = "hook_types")]
    pub(crate) all: bool,

    /// Which Git shim(s) to uninstall.
    ///
    /// Specifies which Git hook type(s) you want to uninstall shims for.
    /// Can be specified multiple times to uninstall shims for multiple hook types.
    ///
    /// If not specified, uses `default_install_hook_types` from the config file,
    /// or defaults to `pre-commit` if that is also not set.
    /// Use `--all` to remove all prek-managed hooks.
    #[arg(short = 't', long = "hook-type", value_name = "HOOK_TYPE", value_enum)]
    pub(crate) hook_types: Vec<HookType>,

    /// Uninstall Git shims from the `hooks` subdirectory of the given git directory (`<GIT_DIR>/hooks/`).
    ///
    /// When this flag is used, `prek uninstall` bypasses the safety check that normally
    /// refuses to modify shims while `core.hooksPath` is configured outside the repo.
    /// It only removes shims from `<GIT_DIR>/hooks`; Git may still use the configured
    /// `core.hooksPath` until that config changes.
    #[arg(
        long,
        value_name = "GIT_DIR",
        value_hint = ValueHint::DirPath,
        value_parser = PathBufValueParser::new().map(expand_tilde),
    )]
    pub(crate) git_dir: Option<PathBuf>,
}

#[derive(Debug, Clone, Default, Args)]
pub(crate) struct RunExtraArgs {
    #[arg(long, hide = true)]
    pub(crate) remote_branch: Option<String>,
    #[arg(long, hide = true)]
    pub(crate) local_branch: Option<String>,
    #[arg(long, hide = true, required_if_eq("stage", "pre-rebase"))]
    pub(crate) pre_rebase_upstream: Option<String>,
    #[arg(long, hide = true)]
    pub(crate) pre_rebase_branch: Option<String>,
    #[arg(long, hide = true, required_if_eq_any = [("stage", "prepare-commit-msg"), ("stage", "commit-msg")])]
    pub(crate) commit_msg_filename: Option<String>,
    #[arg(long, hide = true)]
    pub(crate) prepare_commit_message_source: Option<String>,
    #[arg(long, hide = true)]
    pub(crate) commit_object_name: Option<String>,
    #[arg(long, hide = true)]
    pub(crate) remote_name: Option<String>,
    #[arg(long, hide = true)]
    pub(crate) remote_url: Option<String>,
    #[arg(long, hide = true)]
    pub(crate) checkout_type: Option<String>,
    #[arg(long, hide = true)]
    pub(crate) is_squash_merge: bool,
    #[arg(long, hide = true)]
    pub(crate) rewrite_command: Option<String>,
}

#[derive(Debug, Clone, Default, Args)]
pub(crate) struct FileSelectionArgs {
    /// Run hooks on all tracked files in the repository.
    #[arg(short, long, conflicts_with_all = ["files", "glob", "from_ref", "to_ref"])]
    pub(crate) all_files: bool,

    /// Run hooks on the specified file paths.
    ///
    /// Paths are resolved relative to the current working directory after applying `--cd`. They may
    /// be tracked or untracked. This option accepts multiple paths and can be combined with
    /// `--glob` and `--directory`.
    #[arg(
        long,
        conflicts_with_all = ["all_files", "from_ref", "to_ref"],
        num_args = 0..,
        value_hint = ValueHint::AnyPath)
    ]
    pub(crate) files: Vec<String>,

    /// Run hooks on tracked files matching the specified glob pattern.
    ///
    /// Patterns are matched against paths relative to the current working directory after applying
    /// `--cd`. Quote patterns to prevent shell expansion. This option can be repeated and combined
    /// with `--files` and `--directory`.
    #[arg(
        long,
        value_name = "PATTERN",
        conflicts_with_all = ["all_files", "from_ref", "to_ref"]
    )]
    pub(crate) glob: Vec<Glob>,

    /// Run hooks on tracked files under the specified directory.
    ///
    /// Paths are resolved relative to the current working directory after applying `--cd`. This
    /// option can be repeated and combined with `--files` and `--glob`.
    #[arg(
        short,
        long,
        value_name = "DIR",
        conflicts_with_all = ["all_files", "from_ref", "to_ref"],
        value_hint = ValueHint::DirPath
    )]
    pub(crate) directory: Vec<String>,

    /// The original ref in a `<from_ref>...<to_ref>` diff expression.
    /// Files changed in this diff will be run through the hooks.
    #[arg(short = 's', long, alias = "source", value_hint = ValueHint::Other)]
    pub(crate) from_ref: Option<String>,

    /// The destination ref in a `from_ref...to_ref` diff expression.
    /// Defaults to `HEAD` if `from_ref` is specified.
    #[arg(
        short = 'o',
        long,
        alias = "origin",
        requires = "from_ref",
        value_hint = ValueHint::Other,
        default_value_if("from_ref", ArgPredicate::IsPresent, "HEAD")
    )]
    pub(crate) to_ref: Option<String>,

    /// Run hooks against the last commit. Equivalent to `--from-ref HEAD~1 --to-ref HEAD`.
    #[arg(long, conflicts_with_all = ["all_files", "files", "glob", "directory", "from_ref", "to_ref"])]
    pub(crate) last_commit: bool,
}

impl From<FileSelectionArgs> for run::FileSelection {
    fn from(args: FileSelectionArgs) -> Self {
        let FileSelectionArgs {
            all_files,
            files,
            glob,
            directory,
            from_ref,
            to_ref,
            last_commit,
        } = args;

        if last_commit {
            return Self::Diff {
                from_ref: "HEAD~1".to_string(),
                to_ref: "HEAD".to_string(),
            };
        }

        let (from_ref, to_ref) = match (from_ref, to_ref) {
            (Some(from_ref), Some(to_ref)) => return Self::Diff { from_ref, to_ref },
            refs => refs,
        };

        if !files.is_empty() || !glob.is_empty() || !directory.is_empty() {
            return Self::Explicit {
                files,
                globs: glob,
                directories: directory,
            };
        }

        if all_files {
            Self::All { from_ref, to_ref }
        } else {
            Self::Default
        }
    }
}

#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Clone, Default, Args)]
pub(crate) struct RunOptions {
    /// Include the specified hooks or projects.
    ///
    /// Supports flexible selector syntax:
    ///
    /// - `hook-id`: Run all hooks with the specified ID across all projects
    ///
    /// - `project-path/`: Run all hooks from the specified project
    ///
    /// - `project-path:hook-id`: Run only the specified hook from the specified project
    ///
    /// Can be specified multiple times to select multiple hooks/projects.
    #[arg(
        value_name = "HOOK|PROJECT",
        value_hint = ValueHint::Other,
        add = ArgValueCompleter::new(selector_completer)
    )]
    pub(crate) includes: Vec<String>,

    /// Skip the specified hooks or projects.
    ///
    /// Supports flexible selector syntax:
    ///
    /// - `hook-id`: Skip all hooks with the specified ID across all projects
    ///
    /// - `project-path/`: Skip all hooks from the specified project
    ///
    /// - `project-path:hook-id`: Skip only the specified hook from the specified project
    ///
    /// Can be specified multiple times. Also accepts `PREK_SKIP` or `SKIP` environment variables (comma-delimited).
    #[arg(long = "skip", value_name = "HOOK|PROJECT", add = ArgValueCompleter::new(selector_completer))]
    pub(crate) skips: Vec<String>,

    #[command(flatten)]
    pub(crate) file_selection: FileSelectionArgs,

    /// When hooks fail, run `git diff` directly afterward.
    #[arg(long)]
    pub(crate) show_diff_on_failure: bool,

    /// Stop running hooks after the first failure.
    #[arg(long)]
    pub(crate) fail_fast: bool,

    /// Do not stop running hooks after the first failure.
    #[arg(long, hide = true, overrides_with = "fail_fast")]
    pub(crate) no_fail_fast: bool,

    /// Do not run the hooks, but print the hooks that would have been run.
    #[arg(long)]
    pub(crate) dry_run: bool,

    #[command(flatten)]
    pub(crate) extra: RunExtraArgs,
}

#[derive(Debug, Clone, Default, Args)]
pub(crate) struct RunArgs {
    #[command(flatten)]
    pub(crate) options: RunOptions,

    /// The stage during which the hook is fired.
    ///
    /// When specified, only hooks configured for that stage (for example `manual`,
    /// `pre-commit`, or `pre-push`) will run.
    /// When not specified and no group filter is active, this command starts with
    /// hooks eligible for `pre-commit`. If no hook is selected and the command
    /// named hook IDs, those same IDs are matched again against hooks configured
    /// for `manual`. With `--group`, `--require-group`, or `--no-group`, omitting
    /// the stage lets hooks from any configured stage match, using the default file
    /// input mode; hooks that only run at `commit-msg` or `prepare-commit-msg` are
    /// ignored.
    #[arg(long, value_enum, alias = "hook-stage")]
    pub(crate) stage: Option<Stage>,

    /// Run hooks belonging to the specified group.
    ///
    /// Can be specified multiple times; a hook may match any specified group.
    /// When combined with `--require-group`, both filters must match.
    #[arg(long = "group", value_name = "GROUP")]
    pub(crate) groups: Vec<String>,

    /// Run hooks belonging to every specified group.
    ///
    /// Can be specified multiple times; a hook must match every specified group.
    /// When combined with `--group`, it must also match at least one `--group`.
    /// `--no-group` excludes matching hooks regardless of argument order.
    ///
    /// For example, `--require-group fast --group format --group lint-only`
    /// selects hooks in `fast` and either `format` or `lint-only`.
    #[arg(long = "require-group", value_name = "GROUP")]
    pub(crate) required_groups: Vec<String>,

    /// Do not run hooks belonging to the specified group.
    ///
    /// Can be specified multiple times. Exclusion wins over inclusion.
    #[arg(long = "no-group", value_name = "GROUP")]
    pub(crate) no_groups: Vec<String>,
}

#[derive(Debug, Clone, Default, Args)]
pub(crate) struct TryRepoArgs {
    /// Repository to source hooks from.
    pub(crate) repo: String,

    /// Manually select a rev to run against, otherwise the `HEAD` revision will be used.
    #[arg(long, alias = "ref")]
    pub(crate) rev: Option<String>,

    #[command(flatten)]
    pub(crate) run_args: RunOptions,

    /// The stage during which the hook is fired.
    ///
    /// When specified, only hooks configured for that stage (for example `manual`,
    /// `pre-commit`, or `pre-push`) will run.
    /// When not specified, this command starts with hooks eligible for
    /// `pre-commit`. If no hook is selected and the command named hook IDs,
    /// those same IDs are matched again against hooks configured for `manual`.
    #[arg(long, value_enum, alias = "hook-stage")]
    pub(crate) stage: Option<Stage>,
}

#[derive(Debug, Clone, Copy, clap::ValueEnum, Default, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub(crate) enum ListOutputFormat {
    #[default]
    Text,
    Json,
}

#[derive(Debug, Clone, Copy, clap::ValueEnum, Default, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub(crate) enum IdentifyOutputFormat {
    #[default]
    Text,
    Json,
}

#[derive(Debug, Clone, Default, Args)]
pub(crate) struct ListBuiltinsArgs {
    /// The output format.
    #[arg(long, value_enum, default_value_t = ListOutputFormat::Text)]
    pub(crate) output_format: ListOutputFormat,
}

#[derive(Debug, Clone, Default, Args)]
pub(crate) struct ListArgs {
    /// Include the specified hooks or projects.
    ///
    /// Supports flexible selector syntax:
    ///
    /// - `hook-id`: Run all hooks with the specified ID across all projects
    ///
    /// - `project-path/`: Run all hooks from the specified project
    ///
    /// - `project-path:hook-id`: Run only the specified hook from the specified project
    ///
    /// Can be specified multiple times to select multiple hooks/projects.
    #[arg(
        value_name = "HOOK|PROJECT",
        value_hint = ValueHint::Other,
        add = ArgValueCompleter::new(selector_completer)
    )]
    pub(crate) includes: Vec<String>,

    /// Skip the specified hooks or projects.
    ///
    /// Supports flexible selector syntax:
    ///
    /// - `hook-id`: Skip all hooks with the specified ID across all projects
    ///
    /// - `project-path/`: Skip all hooks from the specified project
    ///
    /// - `project-path:hook-id`: Skip only the specified hook from the specified project
    ///
    /// Can be specified multiple times. Also accepts `PREK_SKIP` or `SKIP` environment variables (comma-delimited).
    #[arg(long = "skip", value_name = "HOOK|PROJECT", add = ArgValueCompleter::new(selector_completer))]
    pub(crate) skips: Vec<String>,

    /// Show hooks belonging to the specified group.
    ///
    /// Can be specified multiple times.
    #[arg(long = "group", value_name = "GROUP")]
    pub(crate) groups: Vec<String>,

    /// Show hooks belonging to every specified group.
    ///
    /// Can be specified multiple times. Composes with `--group` and `--no-group`.
    #[arg(long = "require-group", value_name = "GROUP")]
    pub(crate) required_groups: Vec<String>,

    /// Do not show hooks belonging to the specified group.
    ///
    /// Can be specified multiple times. Exclusion wins over inclusion.
    #[arg(long = "no-group", value_name = "GROUP")]
    pub(crate) no_groups: Vec<String>,

    /// Show only hooks that has the specified stage.
    #[arg(long, value_enum)]
    pub(crate) hook_stage: Option<Stage>,
    /// Show only hooks that are implemented in the specified language.
    #[arg(long, value_enum)]
    pub(crate) language: Option<Language>,
    /// The output format.
    #[arg(long, value_enum, default_value_t = ListOutputFormat::Text)]
    pub(crate) output_format: ListOutputFormat,
}

#[derive(Debug, Clone, Default, Args)]
pub(crate) struct IdentifyArgs {
    /// The path(s) to the file(s) to identify.
    #[arg(value_name = "PATH", value_hint = ValueHint::AnyPath)]
    pub(crate) paths: Vec<PathBuf>,
    /// The output format.
    #[arg(long, value_enum, default_value_t = IdentifyOutputFormat::Text)]
    pub(crate) output_format: IdentifyOutputFormat,
}

#[derive(Debug, Args)]
pub(crate) struct ValidateConfigArgs {
    /// The path to the configuration file.
    #[arg(value_name = "CONFIG")]
    pub(crate) configs: Vec<PathBuf>,
}

#[derive(Debug, Args)]
pub(crate) struct ValidateManifestArgs {
    /// The path to the manifest file.
    #[arg(value_name = "MANIFEST")]
    pub(crate) manifests: Vec<PathBuf>,
}

#[expect(clippy::option_option)]
#[derive(Debug, Args)]
pub(crate) struct SampleConfigArgs {
    /// Write the sample config to a file.
    ///
    /// Defaults to `.pre-commit-config.yaml` unless `--format toml` is set,
    /// which uses `prek.toml`. If a path is provided without `--format`,
    /// the format is inferred from the file extension (`.toml` uses TOML).
    #[arg(
        short,
        long,
        num_args = 0..=1,
    )]
    pub(crate) file: Option<Option<PathBuf>>,

    /// Select the sample configuration format.
    #[arg(long, value_enum)]
    pub(crate) format: Option<SampleConfigFormat>,
}

#[derive(Debug, Copy, Clone, clap::ValueEnum)]
pub(crate) enum SampleConfigFormat {
    Yaml,
    Toml,
}

#[derive(Debug)]
pub(crate) enum SampleConfigTarget {
    Stdout,
    DefaultFile,
    Path(PathBuf),
}

impl From<Option<Option<PathBuf>>> for SampleConfigTarget {
    fn from(value: Option<Option<PathBuf>>) -> Self {
        match value {
            None => Self::Stdout,
            Some(None) => Self::DefaultFile,
            Some(Some(path)) => Self::Path(path),
        }
    }
}

#[expect(clippy::struct_excessive_bools)]
#[derive(Debug, Args)]
pub(crate) struct UpdateArgs {
    /// Update to the bleeding edge of the default branch instead of the latest tagged version.
    #[arg(long)]
    pub(crate) bleeding_edge: bool,
    /// Store "frozen" hashes in `rev` instead of tag names.
    /// Defaults to `update.freeze` in the project or global config, or `false` when unset.
    #[arg(long)]
    pub(crate) freeze: bool,
    /// Only update this repository. This option may be specified multiple times.
    #[arg(long, value_name = "REPO", conflicts_with = "exclude_repo")]
    pub(crate) repo: Vec<String>,
    /// Do not update this repository. This option may be specified multiple times.
    #[arg(long, value_name = "REPO")]
    pub(crate) exclude_repo: Vec<String>,
    /// Only consider tags matching this glob pattern. This option may be specified multiple times.
    /// Defaults to `update.include_tags` in the project or global config when unset.
    ///
    /// For example, use `--include-tag 'v*'` to only consider version tags and ignore tags such as `nightly`.
    #[arg(long, value_name = "PATTERN", conflicts_with = "bleeding_edge")]
    pub(crate) include_tag: Vec<Glob>,
    /// Ignore tags matching this glob pattern. This option may be specified multiple times.
    /// Defaults to `update.exclude_tags` in the project or global config when unset.
    ///
    /// For example, use `--exclude-tag nightly` to skip a moving tag, or
    /// `--exclude-tag '*-{alpha,beta,rc}*'` to skip common prerelease tags.
    #[arg(long, value_name = "PATTERN", conflicts_with = "bleeding_edge")]
    pub(crate) exclude_tag: Vec<Glob>,
    /// Only consider tags matching this glob pattern for a repository (`<repo>=<pattern>`).
    /// This option may be specified multiple times.
    /// Overrides the effective include filters for the named repository.
    ///
    /// When set for a repository, this overrides any global `--include-tag` filters for that repository.
    ///
    /// For example, use `--repo-include-tag https://github.com/example/repo=v*` to only consider version tags for one repository.
    #[arg(
        long,
        value_name = "REPO=PATTERN",
        value_parser = parse_repo_tag_pattern,
        conflicts_with = "bleeding_edge"
    )]
    pub(crate) repo_include_tag: Vec<RepoTagPattern>,
    /// Ignore tags matching this glob pattern for a repository (`<repo>=<pattern>`).
    /// This option may be specified multiple times.
    /// Adds to the effective `update` exclude filters for the named repository.
    ///
    /// Repo-specific exclude filters are added to global `--exclude-tag` filters; matching either filter excludes the tag for that repository.
    ///
    /// For example, use `--repo-exclude-tag https://github.com/example/repo=nightly` or `--repo-exclude-tag https://github.com/example/repo=*-rc*` to skip nightly or prerelease tags for one repository.
    #[arg(
        long,
        value_name = "REPO=PATTERN",
        value_parser = parse_repo_tag_pattern,
        conflicts_with = "bleeding_edge"
    )]
    pub(crate) repo_exclude_tag: Vec<RepoTagPattern>,
    /// Do not write changes to the config file, only display what would be changed.
    #[arg(long)]
    pub(crate) dry_run: bool,
    /// Exit with status 1 if updates are available.
    #[arg(long)]
    pub(crate) exit_code: bool,
    /// Alias of `--dry-run --exit-code`.
    #[arg(long)]
    pub(crate) check: bool,
    /// Number of threads to use.
    #[arg(short, long, default_value_t = 0)]
    pub(crate) jobs: usize,
    /// Minimum release age (in days) required for a version to be eligible.
    ///
    /// The age is computed from the tag creation timestamp for annotated tags, or from the tagged commit timestamp for lightweight tags.
    /// If the current `rev` is newer than the latest cooldown-eligible tag, `prek update` keeps the current `rev` instead of downgrading it.
    /// Defaults to `update.cooldown_days` in the project or global config, or `0` when unset.
    /// Valid values are `0` through `255`; `0` disables this check.
    #[arg(long, value_name = "DAYS", conflicts_with = "bleeding_edge")]
    pub(crate) cooldown_days: Option<u8>,
}

#[derive(Clone, Debug)]
pub(crate) struct RepoTagPattern {
    pub(crate) repo: String,
    pub(crate) pattern: Glob,
}

fn parse_repo_tag_pattern(value: &str) -> Result<RepoTagPattern, String> {
    let Some((repo, pattern)) = value.rsplit_once('=') else {
        return Err("expected `<repo>=<pattern>`".to_string());
    };
    if repo.is_empty() || pattern.is_empty() {
        return Err("repo and pattern must not be empty".to_string());
    }

    Ok(RepoTagPattern {
        repo: repo.to_string(),
        pattern: pattern.parse::<Glob>().map_err(|err| err.to_string())?,
    })
}

#[derive(Debug, Args)]
pub(crate) struct HookImplArgs {
    /// Include the specified hooks or projects.
    ///
    /// Supports flexible selector syntax:
    ///
    /// - `hook-id`: Run all hooks with the specified ID across all projects
    ///
    /// - `project-path/`: Run all hooks from the specified project
    ///
    /// - `project-path:hook-id`: Run only the specified hook from the specified project
    ///
    /// Can be specified multiple times to select multiple hooks/projects.
    #[arg(
        value_name = "HOOK|PROJECT",
        value_hint = ValueHint::Other,
        add = ArgValueCompleter::new(selector_completer)
    )]
    pub(crate) includes: Vec<String>,

    /// Skip the specified hooks or projects.
    ///
    /// Supports flexible selector syntax:
    ///
    /// - `hook-id`: Skip all hooks with the specified ID across all projects
    ///
    /// - `project-path/`: Skip all hooks from the specified project
    ///
    /// - `project-path:hook-id`: Skip only the specified hook from the specified project
    ///
    /// Can be specified multiple times. Also accepts `PREK_SKIP` or `SKIP` environment variables (comma-delimited).
    #[arg(long = "skip", value_name = "HOOK|PROJECT", add = ArgValueCompleter::new(selector_completer))]
    pub(crate) skips: Vec<String>,
    #[arg(long)]
    pub(crate) hook_type: HookType,
    #[arg(long)]
    pub(crate) hook_dir: Option<PathBuf>,
    #[arg(long)]
    pub(crate) skip_on_missing_config: bool,
    /// The prek version that installs the hook.
    #[arg(long)]
    pub(crate) script_version: Option<usize>,
    #[arg(last = true)]
    pub(crate) args: Vec<OsString>,
}

#[derive(Debug, Args)]
pub(crate) struct CacheNamespace {
    #[command(subcommand)]
    pub(crate) command: CacheCommand,
}

#[derive(Debug, Args)]
pub(crate) struct UtilNamespace {
    #[command(subcommand)]
    pub(crate) command: UtilCommand,
}

#[derive(Debug, Subcommand)]
pub(crate) enum UtilCommand {
    /// Show file identification tags.
    Identify(IdentifyArgs),
    /// List all built-in hooks bundled with prek.
    ListBuiltins(ListBuiltinsArgs),
    /// Install Git shims in a directory intended for use with `git config init.templateDir`.
    #[command(alias = "init-templatedir")]
    InitTemplateDir(InitTemplateDirArgs),
    /// Convert a YAML configuration file to prek.toml.
    YamlToToml(YamlToTomlArgs),
    /// Generate shell completion scripts.
    #[command(hide = true)]
    GenerateShellCompletion(GenerateShellCompletionArgs),
}

#[derive(Debug, Args)]
pub(crate) struct YamlToTomlArgs {
    /// The YAML configuration file to convert. If omitted, discovers
    /// `.pre-commit-config.yaml` or `.pre-commit-config.yml` in the current directory.
    #[arg(value_name = "CONFIG", value_hint = ValueHint::FilePath)]
    pub(crate) input: Option<PathBuf>,

    /// Path to write the generated prek.toml file.
    /// Defaults to `prek.toml` in the same directory as the input file.
    #[arg(short, long, value_name = "OUTPUT", value_hint = ValueHint::FilePath)]
    pub(crate) output: Option<PathBuf>,

    /// Overwrite the output file if it already exists.
    #[arg(long)]
    pub(crate) force: bool,
}

#[derive(Debug, Subcommand)]
pub(crate) enum CacheCommand {
    /// Show the location of the prek cache.
    Dir,
    /// Remove unused cached repositories, hook environments, and other data.
    GC(CacheGcArgs),
    /// Remove all prek cached data.
    Clean,
    /// Show the size of the prek cache.
    Size(SizeArgs),
}

#[derive(Debug, Default, Clone, Copy, clap::ValueEnum)]
pub(crate) enum CacheSizeOutputFormat {
    /// Display a human-readable size in terminals and raw bytes otherwise.
    #[default]
    Auto,
    /// Display the cache size in a human-readable format.
    Human,
    /// Display the cache size in raw bytes.
    Machine,
}

#[derive(Args, Debug)]
pub struct SizeArgs {
    /// Select the output format.
    #[arg(long, value_enum, default_value_t = CacheSizeOutputFormat::default())]
    pub(crate) output_format: CacheSizeOutputFormat,

    /// Display the cache size in human-readable format (e.g., `1.2GiB` instead of raw bytes).
    #[arg(
        long = "human",
        short = 'H',
        alias = "human-readable",
        conflicts_with = "output_format"
    )]
    pub(crate) human: bool,
}

#[derive(Debug, Args)]
pub(crate) struct CacheGcArgs {
    /// Print what would be removed, but do not delete anything.
    #[arg(long)]
    pub(crate) dry_run: bool,
}

#[derive(Debug, Args)]
pub(crate) struct SelfNamespace {
    #[command(subcommand)]
    pub(crate) command: SelfCommand,
}

#[derive(Debug, Subcommand)]
pub(crate) enum SelfCommand {
    /// Update prek.
    Update(SelfUpdateArgs),
}

#[derive(Debug, Args)]
pub(crate) struct SelfUpdateArgs {
    /// Update to the specified version.
    /// If not provided, prek will update to the latest version.
    pub target_version: Option<String>,

    /// A GitHub token for authentication.
    /// A token is not required but can be used to reduce the chance of encountering rate limits.
    #[arg(long, env = EnvVars::GITHUB_TOKEN)]
    pub token: Option<String>,
}

#[derive(Debug, Args)]
pub(crate) struct GenerateShellCompletionArgs {
    /// The shell to generate the completion script for
    #[arg(value_enum)]
    pub shell: clap_complete::Shell,
}

#[derive(Debug, Args)]
pub(crate) struct InitTemplateDirArgs {
    /// The directory in which to write the Git shim.
    pub(crate) directory: PathBuf,

    /// Assume cloned repos should have a `pre-commit` config.
    #[arg(long)]
    pub(crate) no_allow_missing_config: bool,

    /// Which Git shim(s) to install.
    ///
    /// Specifies which Git hook type(s) you want to install shims for.
    /// Can be specified multiple times to install shims for multiple hook types.
    ///
    /// If not specified, uses `default_install_hook_types` from the config file,
    /// or defaults to `pre-commit` if that is also not set.
    #[arg(short = 't', long = "hook-type", value_name = "HOOK_TYPE", value_enum)]
    pub(crate) hook_types: Vec<HookType>,
}

#[cfg(test)]
mod tests {
    use clap::Parser;

    use super::Cli;

    #[test]
    fn update_rejects_invalid_repo_tag_pattern_during_cli_parsing() {
        let Err(err) = Cli::try_parse_from([
            "prek",
            "update",
            "--repo-include-tag",
            "https://example.com/repo",
        ]) else {
            panic!("expected invalid repo tag pattern to fail");
        };

        insta::assert_snapshot!(err.to_string(), @r"
        error: invalid value 'https://example.com/repo' for '--repo-include-tag <REPO=PATTERN>': expected `<repo>=<pattern>`

        For more information, try '--help'.
        ");
    }

    #[test]
    fn update_rejects_invalid_glob_during_cli_parsing() {
        let Err(err) = Cli::try_parse_from(["prek", "update", "--include-tag", "["]) else {
            panic!("expected invalid tag pattern to fail");
        };

        insta::assert_snapshot!(err.to_string(), @r"
        error: invalid value '[' for '--include-tag <PATTERN>': error parsing glob '[': unclosed character class; missing ']'

        For more information, try '--help'.
        ");
    }
}

#[cfg(test)]
mod _gen {
    use crate::cli::Cli;
    use anyhow::{Result, bail};
    use clap::{Command, CommandFactory};
    use itertools::Itertools;
    use prek_consts::env_vars::{EnvVars, EnvVarsRead};
    use pretty_assertions::StrComparison;
    use std::cmp::max;
    use std::path::PathBuf;

    const ROOT_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../../");

    enum Mode {
        /// Update the content.
        Write,

        /// Don't write to the file, check if the file is up-to-date and error if not.
        Check,

        /// Write the generated help to stdout.
        DryRun,
    }

    fn generate(mut cmd: Command) -> String {
        let mut output = String::new();

        cmd.build();

        let mut parents = Vec::new();

        output.push_str("# CLI Reference\n\n");
        generate_command(&mut output, &cmd, &mut parents);

        let mut output = output.replace("\r\n", "\n");
        // Trim trailing whitespace
        while output.ends_with('\n') {
            output.pop();
        }
        output.push('\n');

        output
    }

    #[allow(clippy::format_push_string)]
    fn generate_command<'a>(
        output: &mut String,
        command: &'a Command,
        parents: &mut Vec<&'a Command>,
    ) {
        if command.is_hide_set() {
            return;
        }

        // Generate the command header.
        let name = if parents.is_empty() {
            command.get_name().to_string()
        } else {
            format!(
                "{} {}",
                parents.iter().map(|cmd| cmd.get_name()).join(" "),
                command.get_name()
            )
        };

        // Display the top-level `prek` command at the same level as its children
        let level = max(2, parents.len() + 1);
        output.push_str(&format!("{} {name}\n\n", "#".repeat(level)));

        // Display the command description.
        if let Some(about) = command.get_long_about().or_else(|| command.get_about()) {
            output.push_str(&about.to_string());
            output.push_str("\n\n");
        }

        // Display the usage
        {
            // This appears to be the simplest way to get rendered usage from Clap,
            // it is complicated to render it manually. It's annoying that it
            // requires a mutable reference but it doesn't really matter.
            let mut command = command.clone();
            output.push_str("<h3 class=\"cli-reference\">Usage</h3>\n\n");
            output.push_str(&format!(
                "```\n{}\n```",
                command
                    .render_usage()
                    .to_string()
                    .trim_start_matches("Usage: "),
            ));
            output.push_str("\n\n");
        }

        // Display a list of child commands
        let mut subcommands = command.get_subcommands().peekable();
        let has_subcommands = subcommands.peek().is_some();
        if has_subcommands {
            output.push_str("<h3 class=\"cli-reference\">Commands</h3>\n\n");
            output.push_str("<dl class=\"cli-reference\">");

            for subcommand in subcommands {
                if subcommand.is_hide_set() {
                    continue;
                }
                let subcommand_name = format!("{name} {}", subcommand.get_name());
                output.push_str(&format!(
                    "<dt><a href=\"#{}\"><code>{subcommand_name}</code></a></dt>",
                    subcommand_name.replace(' ', "-")
                ));
                if let Some(about) = subcommand.get_about() {
                    output.push_str(&format!(
                        "<dd>{}</dd>\n",
                        markdown::to_html(&about.to_string())
                    ));
                }
            }

            output.push_str("</dl>\n\n");
        }

        // Do not display options for commands with children
        if !has_subcommands {
            let name_key = name.replace(' ', "-");

            // Display positional arguments
            let mut arguments = command
                .get_positionals()
                .filter(|arg| !arg.is_hide_set())
                .peekable();

            if arguments.peek().is_some() {
                output.push_str("<h3 class=\"cli-reference\">Arguments</h3>\n\n");
                output.push_str("<dl class=\"cli-reference\">");

                for arg in arguments {
                    let id = format!("{name_key}--{}", arg.get_id());
                    output.push_str(&format!("<dt id=\"{id}\">"));
                    output.push_str(&format!(
                        "<a href=\"#{id}\"><code>{}</code></a>",
                        arg.get_value_names()
                            .unwrap()
                            .iter()
                            .next()
                            .unwrap()
                            .to_string()
                            .to_uppercase(),
                    ));
                    output.push_str("</dt>");
                    if let Some(help) = arg.get_long_help().or_else(|| arg.get_help()) {
                        output.push_str("<dd>");
                        output.push_str(&format!("{}\n", markdown::to_html(&help.to_string())));
                        output.push_str("</dd>");
                    }
                }

                output.push_str("</dl>\n\n");
            }

            // Display options and flags
            let mut options = command
                .get_arguments()
                .filter(|arg| !arg.is_positional())
                .filter(|arg| !arg.is_hide_set())
                .sorted_by_key(|arg| arg.get_id())
                .peekable();

            if options.peek().is_some() {
                output.push_str("<h3 class=\"cli-reference\">Options</h3>\n\n");
                output.push_str("<dl class=\"cli-reference\">");
                for opt in options {
                    let Some(long) = opt.get_long() else { continue };
                    let id = format!("{name_key}--{long}");

                    output.push_str(&format!("<dt id=\"{id}\">"));
                    output.push_str(&format!("<a href=\"#{id}\"><code>--{long}</code></a>"));
                    for long_alias in opt.get_all_aliases().into_iter().flatten() {
                        output.push_str(&format!(", <code>--{long_alias}</code>"));
                    }
                    if let Some(short) = opt.get_short() {
                        output.push_str(&format!(", <code>-{short}</code>"));
                    }
                    for short_alias in opt.get_all_short_aliases().into_iter().flatten() {
                        output.push_str(&format!(", <code>-{short_alias}</code>"));
                    }

                    // Re-implements private `Arg::is_takes_value_set` used in `Command::get_opts`
                    if opt
                        .get_num_args()
                        .unwrap_or_else(|| 1.into())
                        .takes_values()
                    {
                        if let Some(values) = opt.get_value_names() {
                            for value in values {
                                output.push_str(&format!(
                                    " <i>{}</i>",
                                    value.to_lowercase().replace('_', "-")
                                ));
                            }
                        }
                    }
                    output.push_str("</dt>");
                    if let Some(help) = opt.get_long_help().or_else(|| opt.get_help()) {
                        output.push_str("<dd>");
                        output.push_str(&format!("{}\n", markdown::to_html(&help.to_string())));
                        emit_env_option(opt, output);
                        emit_default_option(opt, output);
                        emit_possible_options(opt, output);
                        output.push_str("</dd>");
                    }
                }

                output.push_str("</dl>");
            }

            output.push_str("\n\n");
        }

        parents.push(command);

        // Recurse to all the subcommands.
        for subcommand in command.get_subcommands() {
            generate_command(output, subcommand, parents);
        }

        parents.pop();
    }

    fn emit_env_option(opt: &clap::Arg, output: &mut String) {
        if opt.is_hide_env_set() {
            return;
        }
        if let Some(env) = opt.get_env() {
            output.push_str(&markdown::to_html(&format!(
                "May also be set with the `{}` environment variable.",
                env.to_string_lossy()
            )));
        }
    }

    fn emit_default_option(opt: &clap::Arg, output: &mut String) {
        if opt.is_hide_default_value_set() || !opt.get_num_args().expect("built").takes_values() {
            return;
        }

        let values = opt.get_default_values();
        if !values.is_empty() {
            let value = format!(
                "\n[default: {}]",
                opt.get_default_values()
                    .iter()
                    .map(|s| s.to_string_lossy())
                    .join(",")
            );
            output.push_str(&markdown::to_html(&value));
        }
    }

    fn emit_possible_options(opt: &clap::Arg, output: &mut String) {
        if opt.is_hide_possible_values_set() {
            return;
        }

        let values = opt.get_possible_values();
        if !values.is_empty() {
            let value = format!(
                "\nPossible values:\n{}",
                values
                    .into_iter()
                    .filter(|value| !value.is_hide_set())
                    .map(|value| {
                        let name = value.get_name();
                        value.get_help().map_or_else(
                            || format!(" - `{name}`"),
                            |help| format!(" - `{name}`:  {help}"),
                        )
                    })
                    .collect_vec()
                    .join("\n"),
            );
            output.push_str(&markdown::to_html(&value));
        }
    }

    #[test]
    fn generate_cli_reference() -> Result<()> {
        let mode = if EnvVars.is_set(EnvVars::PREK_GENERATE) {
            Mode::Write
        } else {
            Mode::Check
        };

        let reference_string = generate(Cli::command());
        let filename = "reference/cli.md";
        let reference_path = PathBuf::from(ROOT_DIR)
            .join("docs")
            .join("reference")
            .join("cli.md");

        match mode {
            Mode::DryRun => {
                anstream::println!("{reference_string}");
            }
            Mode::Check => match fs_err::read_to_string(&reference_path) {
                Ok(current) => {
                    if current == reference_string {
                        anstream::println!("Up-to-date: {filename}");
                    } else {
                        let comparison = StrComparison::new(&current, &reference_string);
                        bail!(
                            "{filename} changed, please run `mise run generate` to update:\n{comparison}"
                        );
                    }
                }
                Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
                    bail!("{filename} not found, please run `mise run generate` to generate");
                }
                Err(err) => {
                    bail!("{filename} changed, please run `mise run generate` to update:\n{err}");
                }
            },
            Mode::Write => match fs_err::read_to_string(&reference_path) {
                Ok(current) => {
                    if current == reference_string {
                        anstream::println!("Up-to-date: {filename}");
                    } else {
                        anstream::println!("Updating: {filename}");
                        fs_err::write(reference_path, reference_string.as_bytes())?;
                    }
                }
                Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
                    anstream::println!("Updating: {filename}");
                    fs_err::write(reference_path, reference_string.as_bytes())?;
                }
                Err(err) => {
                    bail!(
                        "{filename} changed, please run `cargo dev generate-cli-reference`:\n{err}"
                    );
                }
            },
        }

        Ok(())
    }
}