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
use crate::{
error::{ConfigError, HookExecutionError, Result, ValidationError},
git_related::{check_for_git_hooks, get_git_hooks_path},
my_clap_theme,
utils::{format_list, print_error, print_success, print_warning},
HooksmithError,
};
use dialoguer::{Confirm, MultiSelect};
use serde::{Deserialize, Deserializer};
use std::{
fs::{self},
path::Path,
process::{Command, ExitStatus},
time::{Duration, Instant},
};
const GIT_HOOKS: [&str; 28] = [
"applypatch-msg",
"pre-applypatch",
"post-applypatch",
"pre-commit",
"pre-merge-commit",
"prepare-commit-msg",
"commit-msg",
"post-commit",
"pre-rebase",
"post-checkout",
"post-merge",
"pre-push",
"pre-receive",
"update",
"proc-receive",
"post-receive",
"post-update",
"reference-transaction",
"push-to-checkout",
"pre-auto-gc",
"post-rewrite",
"sendemail-validate",
"fsmonitor-watchman",
"p4-changelist",
"p4-prepare-changelist",
"p4-post-changelist",
"p4-pre-submit",
"post-index-change",
];
/// Represents a command that can be either a simple string or a named command
#[derive(Debug, Clone)]
pub struct HookCommand {
pub name: Option<String>,
pub command: String,
}
impl HookCommand {
/// Create a new unnamed command
pub fn new_unnamed(command: String) -> Self {
Self {
name: None,
command,
}
}
/// Create a new named command
pub fn new_named(name: String, command: String) -> Self {
Self {
name: Some(name),
command,
}
}
}
/// Custom deserializer for commands that supports both string and named formats
fn deserialize_commands<'de, D>(deserializer: D) -> std::result::Result<Vec<HookCommand>, D::Error>
where
D: Deserializer<'de>,
{
use serde::de::{Error, SeqAccess, Visitor};
use serde_yaml::Value;
struct CommandsVisitor;
impl<'de> Visitor<'de> for CommandsVisitor {
type Value = Vec<HookCommand>;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("a sequence of commands")
}
fn visit_seq<A>(self, mut seq: A) -> std::result::Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
let mut commands = Vec::new();
while let Some(value) = seq.next_element::<Value>()? {
match value {
// Handle string commands: "cargo fmt --all -- --check"
Value::String(cmd) => {
commands.push(HookCommand::new_unnamed(cmd));
}
// Handle named commands: "clippy-linter": "cargo clippy ..."
Value::Mapping(map) => {
for (key, val) in map {
if let (Value::String(name), Value::String(command)) = (key, val) {
commands.push(HookCommand::new_named(name, command));
} else {
return Err(A::Error::custom(
"Named commands must have string keys and values",
));
}
}
}
_ => {
return Err(A::Error::custom(
"Commands must be strings or named command objects",
));
}
}
}
Ok(commands)
}
}
deserializer.deserialize_seq(CommandsVisitor)
}
/// Custom deserializer for optional commands
fn deserialize_optional_commands<'de, D>(
deserializer: D,
) -> std::result::Result<Option<Vec<HookCommand>>, D::Error>
where
D: Deserializer<'de>,
{
use serde::de::Visitor;
struct OptionalCommandsVisitor;
impl<'de> Visitor<'de> for OptionalCommandsVisitor {
type Value = Option<Vec<HookCommand>>;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("an optional sequence of commands")
}
fn visit_none<E>(self) -> std::result::Result<Self::Value, E>
where
E: serde::de::Error,
{
Ok(None)
}
fn visit_some<D>(self, deserializer: D) -> std::result::Result<Self::Value, D::Error>
where
D: Deserializer<'de>,
{
deserialize_commands(deserializer).map(Some)
}
}
deserializer.deserialize_option(OptionalCommandsVisitor)
}
/// Configuration structure for hooksmith.
#[derive(Deserialize)]
struct Config {
#[serde(flatten)]
hooks: std::collections::HashMap<String, Hook>,
}
/// Path-scoped configuration for a hook.
#[derive(Deserialize)]
struct PathScopedConfig {
#[serde(deserialize_with = "deserialize_commands")]
commands: Vec<HookCommand>,
#[serde(default)]
working_directory: Option<String>,
}
/// Hook structure for hooksmith.
#[derive(Deserialize)]
struct Hook {
#[serde(default)]
#[serde(deserialize_with = "deserialize_optional_commands")]
commands: Option<Vec<HookCommand>>,
#[serde(default)]
paths: Option<std::collections::HashMap<String, PathScopedConfig>>, // path prefix -> config
}
/// Timing information for a single command execution.
#[derive(Debug, Clone)]
pub struct CommandTiming {
pub command: String,
pub name: Option<String>,
pub duration: Duration,
}
/// Timing information for a hook execution.
#[derive(Debug, Clone)]
pub struct HookTiming {
pub hook_name: String,
pub commands: Vec<CommandTiming>,
pub total_duration: Duration,
}
/// Collection of timing information for multiple hooks.
#[derive(Debug, Clone)]
pub struct TimingReport {
pub hooks: Vec<HookTiming>,
pub total_duration: Duration,
}
/// Hooksmith structure for managing git hooks.
pub struct Hooksmith {
config: Config,
dry_run: bool,
verbose: bool,
}
impl Hooksmith {
/// Create a new instance of `Hooksmith` from a configuration file.
///
/// # Arguments
/// * `config` - Path to the configuration file
/// * `dry_run` - Whether to run in dry run mode
/// * `verbose` - Whether to print verbose output
///
/// # Errors
/// * If the configuration file cannot be read or parsed
pub fn new_from_config(config: &Path, dry_run: bool, verbose: bool) -> Result<Self> {
let config = Self::read_config(config)?;
if dry_run {
println!("🔄 DRY RUN MODE - No commands will be executed\n");
}
Ok(Self {
config,
dry_run,
verbose,
})
}
/// Check for hooks that are in config but not installed.
/// Iterates through hooks in the config and checks if they are installed.
/// Updates the `differences_found` flag and prints messages for missing hooks.
///
/// # Arguments
/// * `git_hooks_path` - Path to the git hooks directory
/// * `differences_found` - Mutable reference to track if differences were found
fn check_missing_hooks(&self, git_hooks_path: &Path, differences_found: &mut bool) {
for hook_name in self.config.hooks.keys() {
let hook_path = git_hooks_path.join(hook_name);
if !hook_path.exists() {
if !*differences_found {
println!("\n❌ Differences found:");
*differences_found = true;
}
println!(" - Hook '{hook_name}' is in config but not installed");
}
}
}
/// Check for hooks that are installed but not in config.
/// Scans the git hooks directory and checks if each hook is in the config.
/// Updates the `differences_found` flag and prints messages for extra hooks.
///
/// # Arguments
/// * `git_hooks_path` - Path to the git hooks directory
/// * `differences_found` - Mutable reference to track if differences were found
///
/// # Errors
/// * If there is an error reading the git hooks directory
fn check_extra_hooks(&self, git_hooks_path: &Path, differences_found: &mut bool) {
if let Ok(entries) = fs::read_dir(git_hooks_path) {
for entry in entries.flatten() {
if let Ok(file_type) = entry.file_type() {
if !file_type.is_file() {
continue;
}
let hook_name = entry.file_name().to_string_lossy().to_string();
if hook_name.ends_with(".sample") {
continue;
}
if !self.config.hooks.contains_key(&hook_name) {
if !*differences_found {
println!("\n❌ Differences found:");
*differences_found = true;
}
println!(" - Hook '{hook_name}' is installed but not in config");
}
}
}
}
}
/// Compare installed hooks with the configuration file.
///
/// # Errors
/// * If there is an error reading the git hooks directory.
pub fn compare_hooks(&self) -> Result<()> {
let git_hooks_path = get_git_hooks_path()?;
let mut differences_found = false;
if self.verbose {
println!("🔍 Comparing installed hooks with configuration file...");
}
// Check for hooks in config but not installed
self.check_missing_hooks(&git_hooks_path, &mut differences_found);
// Check for installed hooks not in config
self.check_extra_hooks(&git_hooks_path, &mut differences_found);
if !differences_found {
println!("✅ All hooks match the configuration file");
}
Ok(())
}
/// Creates the git hooks directory if it doesn't exist.
/// Handles both normal and dry run modes.
///
/// # Arguments
/// * `git_hooks_path` - Path to the git hooks directory
///
/// # Errors
/// * If the directory cannot be created
fn ensure_hooks_directory(&self, git_hooks_path: &Path) -> Result<()> {
if !git_hooks_path.exists() {
if self.dry_run {
println!("🪝 Skipping creation of .git/hooks directory in dry run mode");
} else {
if self.verbose {
println!(" - Creating .git/hooks directory...");
}
fs::create_dir_all(git_hooks_path)?;
}
}
Ok(())
}
/// Generates configuration content for a specific hook type
///
/// # Arguments
/// * `hook` - The name of the hook to generate configuration for
///
/// # Returns
/// * `String` - The generated configuration content for the hook
fn generate_hook_config(hook: &str) -> String {
let mut config = String::new();
config.push_str(hook);
config.push_str(":\n");
config.push_str(" commands:\n");
// Add hook-specific default commands and comments
let (echo_msg, examples) = match hook {
"pre-commit" => (
"Running pre-commit checks...",
vec![
"# Add your pre-commit commands here",
"# Examples:",
"# - cargo fmt --all -- --check",
"# - cargo clippy -- --deny warnings",
],
),
"pre-push" => (
"Running pre-push checks...",
vec![
"# Add your pre-push commands here",
"# Examples:",
"# - cargo test",
"# - cargo build --release",
],
),
"commit-msg" => (
"Validating commit message...",
vec![
"# Add your commit message validation here",
"# Example:",
"# - ./scripts/validate-commit-msg.sh $1",
],
),
"post-commit" => (
"Post-commit actions...",
vec!["# Add your post-commit commands here"],
),
_ => (
&format!("Running {hook} hook...")[..],
vec!["# Add your commands here"],
),
};
config.push_str(&format!(" - echo \"{echo_msg}\"\n")[..]);
for example in examples {
config.push_str(&format!(" {example}\n")[..]);
}
config.push('\n');
config
}
/// Initialize hooksmith configuration interactively.
///
/// # Arguments
/// * `config_path` - Path where the configuration file will be created
/// * `dry_run` - Whether to run in dry run mode
/// * `verbose` - Whether to print verbose output
///
/// # Errors
/// * If the user cancels the selection
/// * If there's an error writing the configuration file
pub fn init_interactive(config_path: &Path, dry_run: bool, verbose: bool) -> Result<()> {
if dry_run {
println!("🔄 DRY RUN MODE - No files will be created\n");
}
if verbose {
println!("🚀 Initializing hooksmith configuration...");
}
// Check if config file already exists
if config_path.exists() && !dry_run {
let overwrite = Confirm::with_theme(&my_clap_theme::ColorfulTheme::default())
.with_prompt(format!(
"Configuration file '{}' already exists. Overwrite?",
config_path.display()
))
.default(false)
.interact()
.map_err(|e| HookExecutionError::HookNotFound(e.to_string()))?;
if !overwrite {
println!("❌ Initialization cancelled");
return Ok(());
}
}
// Get all available Git hooks
let hook_options: Vec<String> = GIT_HOOKS.iter().map(|&s| s.to_string()).collect();
// Interactive hook selection
let selections = MultiSelect::with_theme(&my_clap_theme::ColorfulTheme::default())
.with_prompt("Select hooks to configure (Space to select, Enter to confirm)")
.items(&hook_options)
.interact()
.map_err(|e| HookExecutionError::HookNotFound(e.to_string()))?;
if selections.is_empty() {
println!("❌ No hooks selected. Configuration file not created.");
return Ok(());
}
let selected_hooks: Vec<String> = selections
.into_iter()
.map(|i| hook_options[i].clone())
.collect();
if verbose {
println!("📝 Selected hooks: {}", selected_hooks.join(", "));
}
// Create configuration content
let config_content: String = selected_hooks
.iter()
.map(|hook| Self::generate_hook_config(hook))
.collect();
// Write configuration file
if dry_run {
println!(
"🔍 Would create configuration file '{}' with content:",
config_path.display()
);
println!("{config_content}");
} else {
fs::write(config_path, config_content)?;
println!(
"✅ Configuration file '{}' created successfully!",
config_path.display()
);
println!("📝 You can now edit the file to customize your hook commands.");
println!("🚀 Run 'hooksmith install' to install the configured hooks.");
}
Ok(())
}
/// Generates the hook script content.
/// Creates a shell script that checks for hooksmith and runs the specified hook.
///
/// # Arguments
/// * `hook_name` - Name of the hook to create content for
fn generate_hook_content(hook_name: &str) -> String {
format!(
"#!/bin/sh\n
if hooksmith -h >/dev/null 2>&1
then
exec hooksmith run {hook_name}
else
cargo install hooksmith
exec hooksmith run {hook_name}
fi"
)
}
/// Writes the hook file and sets appropriate permissions.
/// Handles both normal and dry run modes.
///
/// # Arguments
/// * `hook_path` - Path where the hook file should be written
/// * `hook_name` - Name of the hook being installed
/// * `content` - Content to write to the hook file
///
/// # Errors
/// * If the file cannot be written
/// * If permissions cannot be set
fn write_hook_file(&self, hook_path: &Path, hook_name: &str, content: &str) -> Result<()> {
if self.dry_run {
println!("🪝 Skipping installation of {hook_name} hook in dry run mode");
return Ok(());
}
fs::write(hook_path, content)?;
if self.verbose {
println!(" - Installing {hook_name} file...");
}
// Linux only
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mut permissions = fs::metadata(hook_path)?.permissions();
permissions.set_mode(0o755);
fs::set_permissions(hook_path, permissions)?;
if self.verbose {
println!(" - Setting file permissions...");
}
}
Ok(())
}
/// Install a single, given hook.
///
/// # Arguments
/// * `hook_name` - Name of the hook to install
///
/// # Errors
/// * If the `.git/hooks` directory cannot be created
/// * If the hook cannot be installed/given permission
pub fn install_hook(&self, hook_name: &str) -> Result<()> {
if self.verbose && !self.dry_run {
println!("🪝 Installing {hook_name} hook...");
}
let git_hooks_path = get_git_hooks_path()?;
self.ensure_hooks_directory(&git_hooks_path)?;
let hook_path = git_hooks_path.join(hook_name);
let hook_content = Self::generate_hook_content(hook_name);
self.write_hook_file(&hook_path, hook_name, &hook_content)?;
if self.verbose {
println!(" ✅ Installed {hook_name} file");
}
Ok(())
}
/// Install all hooks.
///
/// # Errors
/// * If the `.git/hooks` directory cannot be created
///
/// # Arguments
/// * `config` - Parsed configuration file
pub fn install_hooks(&self) -> Result<()> {
self.validate_hooks()?;
let git_hooks_path = get_git_hooks_path()?;
if !check_for_git_hooks() {
fs::create_dir_all(&git_hooks_path)?;
}
if self.verbose {
println!("🪝 Installing hooks...");
}
for hook_name in self.config.hooks.keys() {
self.install_hook(hook_name)?;
}
if !self.dry_run {
println!(
"Installed {} hook(s) successfully.",
self.config.hooks.len()
);
}
Ok(())
}
/// Executes a single command and handles its output
///
/// # Arguments
/// * `hook_command` - The command to execute
/// * `hook_name` - The name of the hook being executed
fn execute_single_command(
&self,
hook_command: &HookCommand,
hook_name: &str,
working_directory: Option<&Path>,
) {
if self.verbose && !self.dry_run {
let display = if let Some(name) = &hook_command.name {
format!("{} ({})", name, hook_command.command)
} else {
hook_command.command.clone()
};
println!(" - Running command: {display}");
}
match self.execute_command(&hook_command.command, working_directory) {
Ok(status) if status.success() => {
if self.verbose && !self.dry_run {
println!("\n ✅ Command completed successfully");
}
}
Ok(status) => {
let code = status.code().unwrap_or(1);
print_error(
"Command failed",
&format!("Hook '{hook_name}' command failed with status code {code}"),
"Please check your command and try again.",
);
std::process::exit(code);
}
Err(e) => {
print_error(
"Failed to execute command",
&format!("Error: {e}"),
"Please ensure the command exists and is executable.",
);
std::process::exit(1);
}
}
}
/// Get a list of available hooks from the configuration.
#[must_use]
pub fn get_available_hooks(&self) -> Vec<String> {
self.config.hooks.keys().cloned().collect()
}
/// Handle the "hook not found error"
///
/// # Arguments
/// * `hook_name` - The name of the hook being executed
///
/// # Errors
/// * If the hook is not found in the configuration.
fn handle_hook_not_found(&self, hook_name: &str) -> Result<()> {
let formatted_hooks = format_list(&self.config.hooks.keys().collect::<Vec<_>>());
print_error(
"Hook not found",
&format!("No commands defined for hook '{hook_name}'"),
&format!(
"Available hooks:\n{formatted_hooks}\n\nPlease check your configuration file."
),
);
Err(HookExecutionError::HookNotFound(hook_name.to_string()).into())
}
/// Runs multiple hooks with timing information.
///
/// # Arguments
/// * `hook_names` - Vector of hook names to run
///
/// # Errors
/// * If a command cannot be executed
/// * If any hook is not found in the configuration
pub fn run_hooks_with_timing(&self, hook_names: &[String]) -> Result<()> {
let start_time = Instant::now();
let mut hook_timings = Vec::new();
let total_hooks = hook_names.len();
for (hook_idx, hook_name) in hook_names.iter().enumerate() {
if true {
println!(
"running `{hook_name}`, {}/{total_hooks} steps:",
hook_idx + 1
);
}
let hook_start = Instant::now();
let hook_timing = self.run_hook_internal_with_timing(hook_name)?;
let hook_duration = hook_start.elapsed();
// Update the hook timing with the actual total duration
let mut updated_timing = hook_timing;
updated_timing.total_duration = hook_duration;
hook_timings.push(updated_timing);
}
let total_duration = start_time.elapsed();
let timing_report = TimingReport {
hooks: hook_timings,
total_duration,
};
Self::print_timing_report(self, &timing_report);
Ok(())
}
/// Runs multiple hooks by executing their commands.
///
/// # Arguments
/// * `hook_names` - Vector of hook names to run
///
/// # Errors
/// * If a command cannot be executed
/// * If any hook is not found in the configuration
pub fn run_hooks(&self, hook_names: &[String]) -> Result<()> {
let total_hooks = hook_names.len();
for (hook_idx, hook_name) in hook_names.iter().enumerate() {
if true {
println!(
"running `{hook_name}`, {}/{total_hooks} steps:",
hook_idx + 1
);
}
self.run_hook_internal(hook_name)?;
}
Ok(())
}
/// Internal method to run a single hook
///
/// # Arguments
/// * `hook_name` - Name of the hook to run
///
/// # Errors
/// * If a command cannot be executed
/// * If the hook is not found in the configuration
fn run_hook_internal(&self, hook_name: &str) -> Result<()> {
let Some(hook) = self.config.hooks.get(hook_name) else {
return self.handle_hook_not_found(hook_name);
};
if self.verbose && !self.dry_run {
println!("📋 Running Hook: {hook_name}");
}
let executed_commands_count = self.run_path_scoped_commands(hook_name, hook)
+ self.run_global_commands(hook_name, hook);
if self.dry_run {
println!(
"🏁 Dry run completed. {executed_commands_count} command(s) would be executed",
);
}
Ok(())
}
/// Internal method to run a single hook with timing information
///
/// # Arguments
/// * `hook_name` - Name of the hook to run
///
/// # Errors
/// * If a command cannot be executed
/// * If the hook is not found in the configuration
fn run_hook_internal_with_timing(&self, hook_name: &str) -> Result<HookTiming> {
let Some(hook) = self.config.hooks.get(hook_name) else {
self.handle_hook_not_found(hook_name)?;
// This should never be reached due to the error above
return Ok(HookTiming {
hook_name: hook_name.to_string(),
commands: Vec::new(),
total_duration: Duration::from_secs(0),
});
};
if self.verbose && !self.dry_run {
println!("📋 Running Hook: {hook_name}");
}
let mut command_timings = Vec::new();
// Run path-scoped commands with timing
let path_timings = self.run_path_scoped_commands_with_timing(hook_name, hook);
command_timings.extend(path_timings);
// Run global commands with timing
let global_timings = self.run_global_commands_with_timing(hook_name, hook);
command_timings.extend(global_timings);
let total_commands = command_timings.len();
if self.dry_run {
println!("🏁 Dry run completed. {total_commands} command(s) would be executed",);
}
Ok(HookTiming {
hook_name: hook_name.to_string(),
commands: command_timings,
total_duration: Duration::from_secs(0), // Will be updated by caller
})
}
/// Execute a list of commands with an optional working directory override.
/// Returns the number of commands executed (or that would be executed in dry-run).
fn run_commands_for_scope(
&self,
hook_name: &str,
commands: &[HookCommand],
working_directory_override: Option<&str>,
) -> usize {
let total_commands = commands.len();
if self.dry_run {
for (idx, hook_command) in commands.iter().enumerate() {
if working_directory_override.is_some() {
handle_dry_run_with_dir(
hook_command,
idx,
total_commands,
working_directory_override,
);
} else {
handle_dry_run(hook_command, idx, total_commands);
}
}
return total_commands;
}
let working_directory = working_directory_override.map(Path::new);
for (idx, hook_command) in commands.iter().enumerate() {
if true {
let display = hook_command
.name
.as_deref()
.unwrap_or(&hook_command.command);
println!(" running `{display}` {}/{total_commands}", idx + 1);
}
self.execute_single_command(hook_command, hook_name, working_directory);
}
total_commands
}
/// Execute a list of commands with timing information.
/// Returns timing information for each command executed.
fn run_commands_for_scope_with_timing(
&self,
hook_name: &str,
commands: &[HookCommand],
working_directory_override: Option<&str>,
) -> Vec<CommandTiming> {
let mut timings = Vec::new();
let total_commands = commands.len();
if self.dry_run {
for (idx, hook_command) in commands.iter().enumerate() {
if working_directory_override.is_some() {
handle_dry_run_with_dir(
hook_command,
idx,
total_commands,
working_directory_override,
);
} else {
handle_dry_run(hook_command, idx, total_commands);
}
// For dry run, we still add timing entries with zero duration
timings.push(CommandTiming {
command: hook_command.command.clone(),
name: hook_command.name.clone(),
duration: Duration::from_secs(0),
});
}
return timings;
}
let working_directory = working_directory_override.map(Path::new);
for (idx, hook_command) in commands.iter().enumerate() {
if true {
let display = hook_command
.name
.as_deref()
.unwrap_or(&hook_command.command);
println!(" running `{display}` {}/{total_commands}", idx + 1);
}
let start_time = Instant::now();
self.execute_single_command(hook_command, hook_name, working_directory);
let duration = start_time.elapsed();
timings.push(CommandTiming {
command: hook_command.command.clone(),
name: hook_command.name.clone(),
duration,
});
}
timings
}
/// Execute global commands for a hook, if any, and return how many were executed.
fn run_global_commands(&self, hook_name: &str, hook: &Hook) -> usize {
match &hook.commands {
Some(commands) => self.run_commands_for_scope(hook_name, commands, None),
None => 0,
}
}
/// Execute global commands for a hook with timing, if any, and return timing information.
fn run_global_commands_with_timing(&self, hook_name: &str, hook: &Hook) -> Vec<CommandTiming> {
match &hook.commands {
Some(commands) => self.run_commands_for_scope_with_timing(hook_name, commands, None),
None => Vec::new(),
}
}
/// Execute path-scoped commands that match changed files for the hook.
/// Returns the number of commands executed.
fn run_path_scoped_commands(&self, hook_name: &str, hook: &Hook) -> usize {
let Some(paths_map) = &hook.paths else {
return 0;
};
let Some(changed_files) = Self::detect_changed_files(hook_name) else {
return 0;
};
let mut executed = 0usize;
for (path_prefix, path_cfg) in paths_map {
let has_match = changed_files.iter().any(|f| f.starts_with(path_prefix));
if !has_match {
continue;
}
executed += self.run_commands_for_scope(
hook_name,
&path_cfg.commands,
path_cfg.working_directory.as_deref(),
);
}
executed
}
/// Execute path-scoped commands that match changed files for the hook with timing.
/// Returns timing information for commands executed.
fn run_path_scoped_commands_with_timing(
&self,
hook_name: &str,
hook: &Hook,
) -> Vec<CommandTiming> {
let Some(paths_map) = &hook.paths else {
return Vec::new();
};
let Some(changed_files) = Self::detect_changed_files(hook_name) else {
return Vec::new();
};
let mut timings = Vec::new();
for (path_prefix, path_cfg) in paths_map {
let has_match = changed_files.iter().any(|f| f.starts_with(path_prefix));
if !has_match {
continue;
}
let mut command_timings = self.run_commands_for_scope_with_timing(
hook_name,
&path_cfg.commands,
path_cfg.working_directory.as_deref(),
);
timings.append(&mut command_timings);
}
timings
}
/// Runs hooks either interactively or from provided names.
///
/// # Arguments
/// * `hook_names` - Optional vector of hook names to run. If None, and interactive is true, will prompt for selection.
/// * `interactive` - Whether to use interactive selection when `hook_names` is None.
/// * `profile` - Whether to enable performance profiling and show timing information.
///
/// # Errors
/// * If a command cannot be executed
/// * If hook selection fails
/// * If any hook is not found in the configuration
pub fn run_hook(
&self,
hook_names: Option<&[String]>,
interactive: bool,
profile: bool,
) -> Result<()> {
if interactive {
let selected_hooks = self.select_hooks_interactively()?;
if profile {
self.run_hooks_with_timing(&selected_hooks)
} else {
self.run_hooks(&selected_hooks)
}
} else if let Some(names) = hook_names {
if names.is_empty() {
return Err(
HookExecutionError::HookNotFound("No hooks specified".to_string()).into(),
);
}
// remove duplicate hooks
let unique_hooks = names
.iter()
.cloned()
.collect::<std::collections::HashSet<_>>()
.into_iter()
.collect::<Vec<_>>();
if profile {
self.run_hooks_with_timing(&unique_hooks)
} else {
self.run_hooks(&unique_hooks)
}
} else {
Err(HookExecutionError::HookNotFound(
"No hook specified and interactive mode is disabled".to_string(),
)
.into())
}
}
/// Uninstalls a single, given hook by removing its file.
///
/// # Arguments
/// * `hook_name` - The name of the hook to run.
///
/// # Errors
/// * Errors if the command fails to remove the file.
pub fn uninstall_given_hook(&self, hook_name: &str) -> Result<()> {
if self.config.hooks.contains_key(hook_name) {
if self.verbose && !self.dry_run {
println!("🗑️ Uninstalling hook: {hook_name}");
}
let git_hooks_path = get_git_hooks_path()?;
let hook_path = git_hooks_path.join(hook_name);
if hook_path.exists() {
if self.dry_run {
println!(
" 🚧 Dry run: Would remove hook file: {}",
hook_path.display()
);
} else {
fs::remove_file(&hook_path)?;
}
} else {
println!(" ⚠️ No hook file found for {hook_name}");
}
} else {
let possible_hooks = self.config.hooks.keys().collect::<Vec<_>>();
eprintln!("No file found for hook '{hook_name}'");
eprintln!("Possible hooks: {possible_hooks:?}");
return Err(ValidationError::InvalidHookName(hook_name.to_string()).into());
}
Ok(())
}
/// Uninstalls all hooks by removing their files.
///
/// # Errors
/// * If there is an error uninstalling a hook.
pub fn uninstall_hooks(&self) -> Result<()> {
if self.verbose && !self.dry_run {
println!("🗑️ Uninstalling all hooks");
}
for hook_name in self.config.hooks.keys() {
self.uninstall_given_hook(hook_name)?;
}
if self.verbose && !self.dry_run {
println!(
"🏁 Uninstallation completed: {} hooks removed",
self.config.hooks.len()
);
}
Ok(())
}
/// Validate that hooks in the configuration file are standard Git hooks.
///
/// # Errors
/// None, I just return Ok(()) to aggregate all calls in a `match` statement in the main function.
pub fn validate_hooks(&self) -> Result<()> {
if self.verbose {
println!("🔍 Validating hooks in configuration file...");
}
let mut invalid_hooks = Vec::new();
let mut valid_hooks = 0;
for hook_name in self.config.hooks.keys() {
if GIT_HOOKS.contains(&hook_name.as_str()) {
valid_hooks += 1;
if self.verbose {
println!(" ✅ Hook '{hook_name}' is valid");
}
} else {
invalid_hooks.push(hook_name.clone());
}
}
if invalid_hooks.is_empty() {
if self.verbose {
print_success(
"All hooks are valid",
&format!("Found {valid_hooks} valid Git hooks in your configuration."),
);
}
} else {
print_warning(
"Invalid hooks detected",
&format!(
"The following hooks are not recognized by Git:\n{}\n\nPlease use only valid Git hook names in your configuration.",
format_list(&invalid_hooks)
),
);
}
Ok(())
}
/// Validate hooks configuration before installation.
///
/// # Errors
/// * If any invalid hook names are found.
pub fn validate_hooks_for_install(&self) -> Result<()> {
if self.verbose {
println!("🔍 Validating hooks before installation...");
}
let mut invalid_hooks = Vec::new();
for hook_name in self.config.hooks.keys() {
if !GIT_HOOKS.contains(&hook_name.as_str()) {
invalid_hooks.push(hook_name.clone());
}
}
if !invalid_hooks.is_empty() {
let error_message = format!(
"Invalid hook names detected\n\nThe following hooks are not recognized by Git:\n{}\n\nPlease check your configuration file and use only valid Git hook names.",
format_list(&invalid_hooks)
);
return Err(ValidationError::InvalidHookName(error_message).into());
}
Ok(())
}
/// Executes a command.
///
/// # Arguments
/// * `command` - The command to execute.
///
/// # Errors
/// * If a command cannot be executed
fn execute_command(
&self,
command: &str,
working_directory: Option<&Path>,
) -> Result<ExitStatus> {
if self.dry_run {
println!("🔍 Would execute: {command}");
#[cfg(unix)]
{
use std::os::unix::process::ExitStatusExt;
Ok(ExitStatusExt::from_raw(0))
}
#[cfg(windows)]
{
use std::os::windows::process::ExitStatusExt;
Ok(ExitStatusExt::from_raw(0))
}
} else {
let mut cmd = Command::new("sh");
cmd.arg("-c").arg(command);
if let Some(dir) = working_directory {
cmd.current_dir(dir);
}
Ok(cmd.status()?)
}
}
/// Read the configuration file and parse it into a Config struct.
///
/// # Arguments
/// * `config_path` - Path to the configuration file
///
/// # Errors
/// * If the configuration file cannot be read or parsed
///
/// # Returns
/// * `Config` - Parsed configuration file
fn read_config(config_path: &Path) -> Result<Config> {
let config_string = fs::read_to_string(config_path)?;
match serde_yaml::from_str(&config_string) {
Ok(config) => Ok(config),
Err(err) => Err(HooksmithError::Config(ConfigError::Parse(err))),
}
}
/// Select hooks interactively using `dialoguer`.
///
/// # Errors
/// * If the user cancels the selection, or an error occurs during selection
/// * If the selection is empty
///
/// # Returns
/// * `Vec<String>` - Selected hooks
fn select_hooks_interactively(&self) -> Result<Vec<String>> {
let hooks = self.get_available_hooks();
if hooks.is_empty() {
return Err(HookExecutionError::HookNotFound(
"No hooks available in configuration".to_string(),
)
.into());
}
let selections = MultiSelect::with_theme(&my_clap_theme::ColorfulTheme::default())
.with_prompt("Select hooks to run (Space to select, Enter to confirm)")
.items(&hooks)
.interact()
.map_err(|e| HookExecutionError::HookNotFound(e.to_string()))?;
if selections.is_empty() {
return Err(HookExecutionError::HookNotFound("No hooks selected".to_string()).into());
}
Ok(selections.into_iter().map(|i| hooks[i].clone()).collect())
}
}
/// Handles the dry run output for a command
fn handle_dry_run(hook_command: &HookCommand, idx: usize, total_commands: usize) {
let current_dir = std::env::current_dir();
println!("Step {} of {}:", idx + 1, total_commands);
if let Some(name) = &hook_command.name {
println!(" Command: {} ({})", name, hook_command.command);
} else {
println!(" Command: {}", hook_command.command);
}
if let Ok(dir) = current_dir {
println!(" Working directory: {}", dir.display());
}
println!();
}
/// Handles dry run output for a command with an explicit working directory
fn handle_dry_run_with_dir(
hook_command: &HookCommand,
idx: usize,
total_commands: usize,
working_directory: Option<&str>,
) {
println!("Step {} of {}:", idx + 1, total_commands);
if let Some(name) = &hook_command.name {
println!(" Command: {} ({})", name, hook_command.command);
} else {
println!(" Command: {}", hook_command.command);
}
if let Some(dir) = working_directory {
println!(" Working directory (override): {dir}");
} else if let Ok(dir) = std::env::current_dir() {
println!(" Working directory: {}", dir.display());
}
println!();
}
impl Hooksmith {
/// Detect changed files for a given hook when possible.
///
/// Behavior by hook name:
/// - `pre-commit`: Returns the list of staged files using `git diff --name-only --cached`.
/// - `pre-push`: Attempts to diff against the configured upstream with `@{u}..HEAD`.
/// If no upstream is configured or that diff fails, falls back to `HEAD~1..HEAD`.
///
/// # Arguments
/// * `hook_name` - The hook to compute changed files for.
///
/// # Returns
/// * `Some(Vec<String>)` when detection succeeds (the vector may be empty if no files changed).
/// * `None` if the hook is not supported or if detection fails (e.g., not a Git repo, no upstream, or the git command fails).
///
/// # Notes
/// This helper is best-effort and never returns an error. Callers should treat `None`
/// as "path-scoped execution not applicable" and continue with global commands.
fn detect_changed_files(hook_name: &str) -> Option<Vec<String>> {
match hook_name {
"pre-commit" => Self::git_diff_name_only(&["--cached"]).ok(),
"pre-push" => {
// Try to diff against upstream; fall back to last commit range
if let Ok(files) = Self::git_diff_upstream_range() {
Some(files)
} else {
Self::git_diff_name_only(&["HEAD~1..HEAD"]).ok()
}
}
_ => None,
}
}
/// Compute the list of files changed relative to the configured upstream branch.
///
/// Attempts to diff `@{u}..HEAD` if an upstream is configured. If no upstream is
/// configured, returns an error so callers can fall back to an alternative range.
///
/// # Errors
/// * If no upstream is configured or if running the underlying `git` command fails.
fn git_diff_upstream_range() -> Result<Vec<String>> {
// Check if upstream exists; if so, diff against it
let upstream_check = Command::new("git")
.args(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"])
.output();
if let Ok(output) = upstream_check {
if output.status.success() {
return Self::git_diff_name_only(&["@{u}..HEAD"]);
}
}
Err(HookExecutionError::HookNotFound("No upstream configured".to_string()).into())
}
/// Run `git diff --name-only` with the provided arguments and return changed file paths.
///
/// # Arguments
/// * `args` - Additional arguments or revision ranges to pass to `git diff`.
///
/// # Returns
/// A vector of path strings for files reported by `git diff --name-only`.
///
/// # Errors
/// * If the underlying `git diff` command fails.
fn git_diff_name_only(args: &[&str]) -> Result<Vec<String>> {
let mut cmd = Command::new("git");
cmd.arg("diff").arg("--name-only");
for a in args {
cmd.arg(a);
}
let output = cmd.output()?;
if !output.status.success() {
return Err(HookExecutionError::HookNotFound(
"Failed to compute changed files".to_string(),
)
.into());
}
let stdout = String::from_utf8_lossy(&output.stdout);
let files = stdout
.lines()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect::<Vec<_>>();
Ok(files)
}
/// Print a formatted timing report showing execution times for hooks and commands.
///
/// # Arguments
/// * `timing_report` - The timing report to print
fn print_timing_report(_: &Self, timing_report: &TimingReport) {
if timing_report.hooks.is_empty() {
return;
}
println!("\n⏱️ Hook execution summary:");
for hook_timing in &timing_report.hooks {
if hook_timing.commands.is_empty() {
continue;
}
println!(
" Hook '{}' ({})",
hook_timing.hook_name,
Self::format_duration(&hook_timing.total_duration)
);
for command_timing in &hook_timing.commands {
// Use command name if available, otherwise use the command itself
let display_command = if let Some(name) = &command_timing.name {
if name.len() > 60 {
format!("{}...", &name[..57])
} else {
name.clone()
}
} else if command_timing.command.len() > 60 {
format!("{}...", &command_timing.command[..57])
} else {
command_timing.command.clone()
};
println!(
" {}: {}",
display_command,
Self::format_duration(&command_timing.duration)
);
}
}
println!(
" Total: {}",
Self::format_duration(&timing_report.total_duration)
);
}
/// Format a duration for display in the timing report.
///
/// # Arguments
/// * `duration` - The duration to format
///
/// # Returns
/// A formatted string representation of the duration
fn format_duration(duration: &Duration) -> String {
let total_millis = duration.as_millis();
if total_millis >= 1000 {
format!("{:.1}s", duration.as_secs_f64())
} else {
format!("{total_millis}ms")
}
}
}