coding-agent-search 0.5.2

Unified TUI search over local coding agent histories
Documentation
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
//! GitHub Pages deployment module.
//!
//! Deploys encrypted archives to GitHub Pages using the gh CLI.
//! Creates a repository, pushes to gh-pages branch, and enables Pages.

use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::thread;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

/// Maximum number of retry attempts for network operations
const MAX_RETRIES: u32 = 3;

/// Base delay for exponential backoff (milliseconds)
const BASE_DELAY_MS: u64 = 1000;

/// Maximum site size for GitHub Pages (1 GB)
const MAX_SITE_SIZE_BYTES: u64 = 1024 * 1024 * 1024;

/// Warning threshold for file size (50 MiB)
const FILE_SIZE_WARNING_BYTES: u64 = 50 * 1024 * 1024;

/// Maximum file size for GitHub (100 MiB)
const MAX_FILE_SIZE_BYTES: u64 = 100 * 1024 * 1024;

/// Prerequisites for GitHub Pages deployment
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Prerequisites {
    /// gh CLI version if installed
    pub gh_version: Option<String>,
    /// Whether gh CLI is authenticated
    pub gh_authenticated: bool,
    /// GitHub username if authenticated
    pub gh_username: Option<String>,
    /// Git version if installed
    pub git_version: Option<String>,
    /// Available disk space in MB
    pub disk_space_mb: u64,
    /// Estimated bundle size in MB
    pub estimated_size_mb: u64,
}

impl Prerequisites {
    /// Check if all prerequisites are met
    pub fn is_ready(&self) -> bool {
        self.gh_version.is_some() && self.gh_authenticated && self.git_version.is_some()
    }

    /// Get a list of missing prerequisites
    pub fn missing(&self) -> Vec<&'static str> {
        let mut missing = Vec::new();
        if self.gh_version.is_none() {
            missing.push("gh CLI not installed (install from https://cli.github.com)");
        }
        if !self.gh_authenticated {
            missing.push("gh CLI not authenticated (run 'gh auth login')");
        }
        if self.git_version.is_none() {
            missing.push("git not installed");
        }
        missing
    }
}

/// File size check result
#[derive(Debug, Clone)]
pub struct SizeCheck {
    /// Total size of all files in bytes
    pub total_bytes: u64,
    /// Number of files
    pub file_count: usize,
    /// Files exceeding warning threshold
    pub large_files: Vec<(String, u64)>,
    /// Whether total size exceeds limit
    pub exceeds_limit: bool,
    /// Whether any file exceeds max file size
    pub has_oversized_files: bool,
}

/// Deployment result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeployResult {
    /// Repository URL
    pub repo_url: String,
    /// Pages URL (where the site is accessible)
    pub pages_url: String,
    /// Whether Pages was successfully enabled
    pub pages_enabled: bool,
    /// Deployment commit SHA
    pub commit_sha: String,
}

/// GitHub Pages deployer
pub struct GitHubDeployer {
    /// Repository name
    repo_name: String,
    /// Repository description
    description: String,
    /// Whether to make the repo public
    public: bool,
    /// Whether to force overwrite existing repo
    force: bool,
}

impl Default for GitHubDeployer {
    fn default() -> Self {
        Self::new("cass-archive")
    }
}

impl GitHubDeployer {
    /// Create a new deployer with the given repository name
    pub fn new(repo_name: impl Into<String>) -> Self {
        Self {
            repo_name: repo_name.into(),
            description: "Encrypted cass archive".to_string(),
            public: true,
            force: false,
        }
    }

    /// Set the repository description
    pub fn description(mut self, desc: impl Into<String>) -> Self {
        self.description = desc.into();
        self
    }

    /// Set whether the repository should be public
    pub fn public(mut self, public: bool) -> Self {
        self.public = public;
        self
    }

    /// Set whether to force overwrite existing repository
    pub fn force(mut self, force: bool) -> Self {
        self.force = force;
        self
    }

    /// Check deployment prerequisites
    pub fn check_prerequisites(&self) -> Result<Prerequisites> {
        // Check gh CLI
        let gh_version = get_gh_version();
        let (gh_authenticated, gh_username) = if gh_version.is_some() {
            check_gh_auth()
        } else {
            (false, None)
        };

        // Check git
        let git_version = get_git_version();

        // Check disk space (simplified - just get available space)
        let disk_space_mb = get_available_space_mb().unwrap_or(0);

        Ok(Prerequisites {
            gh_version,
            gh_authenticated,
            gh_username,
            git_version,
            disk_space_mb,
            estimated_size_mb: 0, // Set by caller if known
        })
    }

    /// Check size of bundle directory
    pub fn check_size(&self, bundle_dir: &Path) -> Result<SizeCheck> {
        let bundle_dir = super::resolve_site_dir(bundle_dir)?;
        let mut total_bytes = 0u64;
        let mut file_count = 0usize;
        let mut large_files = Vec::new();
        let mut has_oversized = false;

        visit_files(&bundle_dir, &mut |path, size| {
            total_bytes += size;
            file_count += 1;

            if size > MAX_FILE_SIZE_BYTES {
                has_oversized = true;
                let rel_path = path
                    .strip_prefix(bundle_dir.as_path())
                    .unwrap_or(path)
                    .to_string_lossy()
                    .to_string();
                large_files.push((rel_path, size));
            } else if size > FILE_SIZE_WARNING_BYTES {
                let rel_path = path
                    .strip_prefix(bundle_dir.as_path())
                    .unwrap_or(path)
                    .to_string_lossy()
                    .to_string();
                large_files.push((rel_path, size));
            }
        })?;

        Ok(SizeCheck {
            total_bytes,
            file_count,
            large_files,
            exceeds_limit: total_bytes > MAX_SITE_SIZE_BYTES,
            has_oversized_files: has_oversized,
        })
    }

    /// Deploy bundle to GitHub Pages
    ///
    /// # Arguments
    /// * `bundle_dir` - Path to the site/ directory from bundle builder
    /// * `progress` - Progress callback (phase, message)
    pub fn deploy<P: AsRef<Path>>(
        &self,
        bundle_dir: P,
        mut progress: impl FnMut(&str, &str),
    ) -> Result<DeployResult> {
        let bundle_dir = super::resolve_site_dir(bundle_dir.as_ref())?;

        // Step 1: Check prerequisites
        progress("prereq", "Checking prerequisites...");
        let prereqs = self.check_prerequisites()?;

        if !prereqs.is_ready() {
            let missing = prereqs.missing();
            bail!("Prerequisites not met:\n{}", missing.join("\n"));
        }

        let username = prereqs
            .gh_username
            .as_ref()
            .context("Could not determine GitHub username")?;

        // Step 2: Check size
        progress("size", "Checking bundle size...");
        let size_check = self.check_size(&bundle_dir)?;

        if size_check.exceeds_limit {
            bail!(
                "Bundle size ({:.1} MB) exceeds GitHub Pages limit ({:.1} MB)",
                size_check.total_bytes as f64 / (1024.0 * 1024.0),
                MAX_SITE_SIZE_BYTES as f64 / (1024.0 * 1024.0)
            );
        }

        if size_check.has_oversized_files {
            let oversized: Vec<_> = size_check
                .large_files
                .iter()
                .filter(|(_, size)| *size > MAX_FILE_SIZE_BYTES)
                .map(|(path, size)| {
                    format!("  {} ({:.1} MB)", path, *size as f64 / (1024.0 * 1024.0))
                })
                .collect();
            bail!(
                "Files exceed GitHub's 100 MiB limit:\n{}",
                oversized.join("\n")
            );
        }

        // Warn about large files (above 50 MiB but under 100 MiB)
        let warning_files: Vec<_> = size_check
            .large_files
            .iter()
            .filter(|(_, size)| *size <= MAX_FILE_SIZE_BYTES && *size > FILE_SIZE_WARNING_BYTES)
            .collect();
        if !warning_files.is_empty() {
            let warnings: Vec<_> = warning_files
                .iter()
                .map(|(path, size)| {
                    format!("{} ({:.1} MB)", path, *size as f64 / (1024.0 * 1024.0))
                })
                .collect();
            progress(
                "warning",
                &format!(
                    "Large files detected (may slow deployment): {}",
                    warnings.join(", ")
                ),
            );
        }

        // Step 3: Create or verify repository
        progress("repo", "Creating repository...");
        let repo_url = self.ensure_repository(username)?;

        // Step 4: Clone to temp directory
        progress("clone", "Cloning repository...");
        let temp_dir = create_temp_dir()?;
        clone_repo(&repo_url, temp_dir.path())?;

        // Step 5: Copy bundle contents
        progress("copy", "Copying bundle files...");
        let work_dir = temp_dir.path().join(&self.repo_name);
        copy_bundle_to_repo(&bundle_dir, &work_dir)?;
        configure_git_identity(&work_dir, username)?;

        // Step 6: Create orphan branch and push
        progress("push", "Pushing to gh-pages branch...");
        let commit_sha = push_gh_pages(&work_dir)?;

        // Step 7: Enable GitHub Pages
        progress("pages", "Enabling GitHub Pages...");
        let pages_enabled = enable_github_pages(username, &self.repo_name);

        // Construct URLs
        let pages_url = format!("https://{}.github.io/{}", username, self.repo_name);

        progress("complete", "Deployment complete!");

        Ok(DeployResult {
            repo_url,
            pages_url,
            pages_enabled,
            commit_sha,
        })
    }

    /// Ensure repository exists, create if needed
    fn ensure_repository(&self, username: &str) -> Result<String> {
        let repo_full_name = format!("{}/{}", username, self.repo_name);

        // Check if repo exists
        let exists = check_repo_exists(&repo_full_name);

        if exists && !self.force {
            bail!(
                "Repository {} already exists. Use --force to overwrite.",
                repo_full_name
            );
        }

        if !exists {
            // Create repository
            let visibility = if self.public { "--public" } else { "--private" };
            let output = Command::new("gh")
                .args([
                    "repo",
                    "create",
                    &self.repo_name,
                    visibility,
                    "--description",
                    &self.description,
                ])
                .output()
                .context("Failed to run gh repo create")?;

            if !output.status.success() {
                let stderr = String::from_utf8_lossy(&output.stderr);
                bail!("Failed to create repository: {}", stderr);
            }
        }

        Ok(format!("https://github.com/{}", repo_full_name))
    }
}

// Helper functions

struct TempDeployDir {
    path: PathBuf,
}

impl TempDeployDir {
    fn path(&self) -> &Path {
        &self.path
    }
}

impl Drop for TempDeployDir {
    fn drop(&mut self) {
        if deploy_staging_path_is_real_dir(&self.path).unwrap_or(false) {
            let _ = std::fs::remove_dir_all(&self.path);
        }
    }
}

/// Create a temporary directory
fn create_temp_dir() -> Result<TempDeployDir> {
    let temp_base = std::env::temp_dir();
    let pid = std::process::id();
    for attempt in 0..100 {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0);
        let dir_name = format!("cass-deploy-{pid}-{timestamp}-{attempt}");
        let temp_dir = temp_base.join(dir_name);
        match std::fs::create_dir(&temp_dir) {
            Ok(()) => return Ok(TempDeployDir { path: temp_dir }),
            Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => continue,
            Err(err) => {
                return Err(err).with_context(|| {
                    format!(
                        "Failed creating GitHub deploy staging directory {}",
                        temp_dir.display()
                    )
                });
            }
        }
    }
    bail!(
        "failed to allocate unique GitHub deploy staging directory under {}",
        temp_base.display()
    )
}

fn deploy_staging_path_is_real_dir(path: &Path) -> Result<bool> {
    match std::fs::symlink_metadata(path) {
        Ok(metadata) => {
            let file_type = metadata.file_type();
            Ok(file_type.is_dir() && !file_type.is_symlink())
        }
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(false),
        Err(err) => Err(err).with_context(|| {
            format!(
                "Failed inspecting GitHub deploy staging directory before cleanup: {}",
                path.display()
            )
        }),
    }
}

/// Get gh CLI version
fn get_gh_version() -> Option<String> {
    Command::new("gh")
        .arg("--version")
        .output()
        .ok()
        .and_then(|out| {
            if out.status.success() {
                let stdout = String::from_utf8_lossy(&out.stdout);
                stdout.lines().next().map(|s| s.to_string())
            } else {
                None
            }
        })
}

/// Check gh authentication status
fn check_gh_auth() -> (bool, Option<String>) {
    let output = Command::new("gh").args(["auth", "status"]).output();

    match output {
        Ok(out) if out.status.success() => {
            let stdout = String::from_utf8_lossy(&out.stdout);
            let stderr = String::from_utf8_lossy(&out.stderr);
            let combined = format!("{}{}", stdout, stderr);

            // Parse username from output like "Logged in to github.com as username"
            let username = combined
                .lines()
                .find(|line| line.contains("Logged in to"))
                .and_then(|line| line.split(" as ").nth(1))
                .map(|s| s.split_whitespace().next().unwrap_or(s).to_string());

            (true, username)
        }
        _ => (false, None),
    }
}

/// Get git version
fn get_git_version() -> Option<String> {
    Command::new("git")
        .arg("--version")
        .output()
        .ok()
        .and_then(|out| {
            if out.status.success() {
                let stdout = String::from_utf8_lossy(&out.stdout);
                Some(stdout.trim().to_string())
            } else {
                None
            }
        })
}

/// Get available disk space in MB
fn get_available_space_mb() -> Option<u64> {
    // Use df on Unix, simplified approach
    #[cfg(unix)]
    {
        Command::new("df")
            .args(["-m", "."])
            .output()
            .ok()
            .and_then(|out| {
                if out.status.success() {
                    let stdout = String::from_utf8_lossy(&out.stdout);
                    // Parse second line, fourth column (available)
                    stdout
                        .lines()
                        .nth(1)
                        .and_then(|line| line.split_whitespace().nth(3))
                        .and_then(|s| s.parse().ok())
                } else {
                    None
                }
            })
    }
    #[cfg(not(unix))]
    {
        None
    }
}

/// Check if repository exists
fn check_repo_exists(repo_full_name: &str) -> bool {
    Command::new("gh")
        .args(["repo", "view", repo_full_name])
        .output()
        .map(|out| out.status.success())
        .unwrap_or(false)
}

/// Retry a fallible operation with exponential backoff.
///
/// Retries the operation up to `MAX_RETRIES` times with exponentially
/// increasing delays between attempts. Useful for network operations
/// that may transiently fail.
fn retry_with_backoff<T, F>(operation_name: &str, mut f: F) -> Result<T>
where
    F: FnMut() -> Result<T>,
{
    let mut last_error = None;

    for attempt in 0..MAX_RETRIES {
        match f() {
            Ok(result) => return Ok(result),
            Err(e) => {
                last_error = Some(e);
                if attempt + 1 < MAX_RETRIES {
                    let delay_ms = BASE_DELAY_MS * (1 << attempt); // 1s, 2s, 4s
                    eprintln!(
                        "[{}] Attempt {} failed, retrying in {}ms...",
                        operation_name,
                        attempt + 1,
                        delay_ms
                    );
                    thread::sleep(Duration::from_millis(delay_ms));
                }
            }
        }
    }

    Err(last_error.unwrap_or_else(|| {
        anyhow::anyhow!("{} failed after {} attempts", operation_name, MAX_RETRIES)
    }))
}

/// Clone repository to directory with retry logic
fn clone_repo(repo_url: &str, dest: &Path) -> Result<()> {
    retry_with_backoff("git clone", || {
        let output = Command::new("git")
            .args(["clone", repo_url])
            .current_dir(dest)
            .output()
            .context("Failed to run git clone")?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            // Allow empty repo warning
            if !stderr.contains("empty repository") {
                bail!("Failed to clone repository: {}", stderr);
            }
        }

        Ok(())
    })
}

/// Copy bundle contents to repository directory
fn copy_bundle_to_repo(bundle_dir: &Path, repo_dir: &Path) -> Result<()> {
    let bundle_dir = super::resolve_site_dir(bundle_dir)?;

    ensure_deploy_staging_dir(repo_dir)?;

    // Clear existing files (except .git)
    for entry in std::fs::read_dir(repo_dir)? {
        let entry = entry?;
        let path = entry.path();
        if path.file_name().map(|n| n != ".git").unwrap_or(true) {
            remove_repo_deploy_entry(&path)?;
        }
    }

    // Copy bundle files
    copy_dir_recursive(&bundle_dir, repo_dir)?;

    // Ensure .nojekyll exists
    let nojekyll = repo_dir.join(".nojekyll");
    if !nojekyll.exists() {
        std::fs::write(&nojekyll, "")?;
    }

    Ok(())
}

/// Copy directory recursively
fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<()> {
    let canonical_base = src.canonicalize().with_context(|| {
        format!(
            "Failed to resolve deployment source root {} before copying",
            src.display()
        )
    })?;
    copy_dir_recursive_inner(src, dst, &canonical_base)
}

fn copy_dir_recursive_inner(src: &Path, dst: &Path, canonical_base: &Path) -> Result<()> {
    ensure_deploy_staging_dir(dst)?;

    for entry in std::fs::read_dir(src)? {
        let entry = entry?;
        let file_name = entry.file_name();
        if file_name == std::ffi::OsStr::new(".git") {
            continue;
        }
        let src_path = entry.path();
        let dst_path = dst.join(file_name);
        let metadata = std::fs::symlink_metadata(&src_path)?;
        let file_type = metadata.file_type();

        if file_type.is_symlink() {
            let canonical_target = src_path.canonicalize().with_context(|| {
                format!(
                    "Failed to resolve symlinked deploy entry {}",
                    src_path.display()
                )
            })?;
            if !canonical_target.starts_with(canonical_base) {
                bail!(
                    "Refusing to deploy symlinked site entry outside deployment root: {}",
                    src_path.display()
                );
            }

            let target_meta = std::fs::metadata(&src_path).with_context(|| {
                format!(
                    "Failed to inspect symlink target for deploy entry {}",
                    src_path.display()
                )
            })?;
            if !target_meta.is_file() {
                bail!(
                    "Refusing to deploy symlinked site entry that does not point to a regular file: {}",
                    src_path.display()
                );
            }

            ensure_deploy_file_destination(&dst_path)?;
            std::fs::copy(&canonical_target, &dst_path).with_context(|| {
                format!(
                    "Failed copying symlink target {} to {} during deploy staging",
                    canonical_target.display(),
                    dst_path.display()
                )
            })?;
            continue;
        }

        if file_type.is_dir() {
            copy_dir_recursive_inner(&src_path, &dst_path, canonical_base)?;
        } else if file_type.is_file() {
            ensure_deploy_file_destination(&dst_path)?;
            std::fs::copy(&src_path, &dst_path)?;
        }
    }

    Ok(())
}

fn ensure_deploy_staging_dir(path: &Path) -> Result<()> {
    match std::fs::symlink_metadata(path) {
        Ok(metadata) => {
            let file_type = metadata.file_type();
            if file_type.is_symlink() {
                bail!(
                    "Refusing to use deploy staging directory through symlink: {}",
                    path.display()
                );
            }
            if !file_type.is_dir() {
                bail!(
                    "Refusing to use deploy staging path because it is not a directory: {}",
                    path.display()
                );
            }
            Ok(())
        }
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
            std::fs::create_dir_all(path)?;
            match std::fs::symlink_metadata(path) {
                Ok(metadata)
                    if metadata.file_type().is_dir() && !metadata.file_type().is_symlink() =>
                {
                    Ok(())
                }
                Ok(_) => bail!(
                    "Refusing to use deploy staging path after create because it is not a real directory: {}",
                    path.display()
                ),
                Err(err) => Err(err).with_context(|| {
                    format!(
                        "Failed inspecting deploy staging directory after create: {}",
                        path.display()
                    )
                }),
            }
        }
        Err(err) => Err(err).with_context(|| {
            format!(
                "Failed inspecting deploy staging directory before copy: {}",
                path.display()
            )
        }),
    }
}

fn ensure_deploy_file_destination(path: &Path) -> Result<()> {
    match std::fs::symlink_metadata(path) {
        Ok(metadata) => {
            let file_type = metadata.file_type();
            if file_type.is_symlink() {
                bail!(
                    "Refusing to write deploy file through symlink: {}",
                    path.display()
                );
            }
            if !file_type.is_file() {
                bail!(
                    "Refusing to write deploy file over non-file path: {}",
                    path.display()
                );
            }
            Ok(())
        }
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(err) => Err(err).with_context(|| {
            format!(
                "Failed inspecting deploy file destination before copy: {}",
                path.display()
            )
        }),
    }
}

fn remove_repo_deploy_entry(path: &Path) -> Result<()> {
    let metadata = std::fs::symlink_metadata(path).with_context(|| {
        format!(
            "Failed inspecting existing GitHub deploy repository entry {}",
            path.display()
        )
    })?;
    let file_type = metadata.file_type();
    if file_type.is_dir() && !file_type.is_symlink() {
        std::fs::remove_dir_all(path).with_context(|| {
            format!(
                "Failed removing existing GitHub deploy directory {}",
                path.display()
            )
        })
    } else {
        std::fs::remove_file(path).with_context(|| {
            format!(
                "Failed removing existing GitHub deploy file {}",
                path.display()
            )
        })
    }
}

/// Configure a local git identity for commits in the temporary deployment clone.
fn configure_git_identity(repo_dir: &Path, username: &str) -> Result<()> {
    let email = format!("{username}@users.noreply.github.com");

    for (key, value) in [("user.name", username), ("user.email", email.as_str())] {
        let output = Command::new("git")
            .args(["config", key, value])
            .current_dir(repo_dir)
            .output()
            .with_context(|| format!("Failed to set git {key}"))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            bail!("Failed to set git {key}: {stderr}");
        }
    }

    Ok(())
}

/// Push to gh-pages branch as orphan
fn push_gh_pages(repo_dir: &Path) -> Result<String> {
    // Create orphan branch
    let output = Command::new("git")
        .args(["checkout", "--orphan", "gh-pages"])
        .current_dir(repo_dir)
        .output()
        .context("Failed to create orphan branch")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("Failed to create gh-pages branch: {}", stderr);
    }

    // Add all files
    let output = Command::new("git")
        .args(["add", "-A"])
        .current_dir(repo_dir)
        .output()
        .context("Failed to git add")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("Failed to add files: {}", stderr);
    }

    // Commit
    let output = Command::new("git")
        .args(["commit", "-m", "Deploy cass archive"])
        .current_dir(repo_dir)
        .output()
        .context("Failed to git commit")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("Failed to commit: {}", stderr);
    }

    // Get commit SHA
    let sha_output = Command::new("git")
        .args(["rev-parse", "HEAD"])
        .current_dir(repo_dir)
        .output()
        .context("Failed to get commit SHA")?;

    let commit_sha = String::from_utf8_lossy(&sha_output.stdout)
        .trim()
        .to_string();

    // Force push to origin with retry for network errors
    let repo_dir_owned = repo_dir.to_owned();
    retry_with_backoff("git push", move || {
        let output = Command::new("git")
            .args(["push", "-f", "origin", "gh-pages"])
            .current_dir(&repo_dir_owned)
            .output()
            .context("Failed to git push")?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            bail!("Failed to push: {}", stderr);
        }

        Ok(())
    })?;

    Ok(commit_sha)
}

/// Enable GitHub Pages via API with retry logic
fn enable_github_pages(username: &str, repo_name: &str) -> bool {
    let api_path = format!("repos/{}/{}/pages", username, repo_name);

    // Try with retry - may fail if already enabled, which is okay
    let result = retry_with_backoff("enable Pages", || {
        let output = Command::new("gh")
            .args([
                "api",
                &api_path,
                "-X",
                "POST",
                "-f",
                "source[branch]=gh-pages",
                "-f",
                "source[path]=/",
            ])
            .output()
            .context("Failed to call GitHub API")?;

        if output.status.success() {
            Ok(true)
        } else {
            let stderr = String::from_utf8_lossy(&output.stderr);
            // If Pages is already enabled, that's fine
            if stderr.contains("already exists") || stderr.contains("409") {
                Ok(true)
            } else {
                bail!("Failed to enable Pages: {}", stderr);
            }
        }
    });

    result.unwrap_or(false)
}

/// Visit all files in a directory recursively
fn visit_files(dir: &Path, f: &mut impl FnMut(&Path, u64)) -> Result<()> {
    let canonical_base = dir.canonicalize().with_context(|| {
        format!(
            "Failed to resolve deployment source root {} before sizing",
            dir.display()
        )
    })?;
    visit_files_inner(dir, &canonical_base, f)
}

fn visit_files_inner(
    dir: &Path,
    canonical_base: &Path,
    f: &mut impl FnMut(&Path, u64),
) -> Result<()> {
    for entry in std::fs::read_dir(dir)? {
        let entry = entry?;
        let path = entry.path();
        let metadata = std::fs::symlink_metadata(&path)?;
        let file_type = metadata.file_type();

        if file_type.is_symlink() {
            let canonical_target = path.canonicalize().with_context(|| {
                format!(
                    "Failed to resolve symlinked deploy entry {}",
                    path.display()
                )
            })?;
            if !canonical_target.starts_with(canonical_base) {
                bail!(
                    "Refusing to deploy symlinked site entry outside deployment root: {}",
                    path.display()
                );
            }

            let target_meta = std::fs::metadata(&path).with_context(|| {
                format!(
                    "Failed to inspect symlink target for deploy entry {}",
                    path.display()
                )
            })?;
            if !target_meta.is_file() {
                bail!(
                    "Refusing to deploy symlinked site entry that does not point to a regular file: {}",
                    path.display()
                );
            }

            f(&path, target_meta.len());
            continue;
        }

        if file_type.is_dir() {
            visit_files_inner(&path, canonical_base, f)?;
        } else if file_type.is_file() {
            f(&path, metadata.len());
        }
    }
    Ok(())
}

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

    #[test]
    fn test_prerequisites_is_ready() {
        let prereqs = Prerequisites {
            gh_version: Some("gh version 2.0.0".to_string()),
            gh_authenticated: true,
            gh_username: Some("testuser".to_string()),
            git_version: Some("git version 2.30.0".to_string()),
            disk_space_mb: 1000,
            estimated_size_mb: 100,
        };

        assert!(prereqs.is_ready());
        assert!(prereqs.missing().is_empty());
    }

    #[test]
    fn test_prerequisites_not_ready() {
        let prereqs = Prerequisites {
            gh_version: None,
            gh_authenticated: false,
            gh_username: None,
            git_version: None,
            disk_space_mb: 1000,
            estimated_size_mb: 100,
        };

        assert!(!prereqs.is_ready());
        let missing = prereqs.missing();
        assert_eq!(missing.len(), 3);
    }

    #[test]
    fn test_deployer_builder() {
        let deployer = GitHubDeployer::new("my-archive")
            .description("My archive")
            .public(false)
            .force(true);

        assert_eq!(deployer.repo_name, "my-archive");
        assert_eq!(deployer.description, "My archive");
        assert!(!deployer.public);
        assert!(deployer.force);
    }

    #[test]
    fn test_size_check() {
        use tempfile::TempDir;

        let temp = TempDir::new().unwrap();
        let file1 = temp.path().join("small.txt");
        let file2 = temp.path().join("medium.txt");

        std::fs::write(&file1, vec![0u8; 1000]).unwrap();
        std::fs::write(&file2, vec![0u8; 10000]).unwrap();

        let deployer = GitHubDeployer::default();
        let check = deployer.check_size(temp.path()).unwrap();

        assert_eq!(check.file_count, 2);
        assert_eq!(check.total_bytes, 11000);
        assert!(!check.exceeds_limit);
        assert!(!check.has_oversized_files);
    }

    #[test]
    fn test_size_check_resolves_bundle_root_without_counting_private_artifacts() {
        use tempfile::TempDir;

        let temp = TempDir::new().unwrap();
        let site_dir = temp.path().join("site");
        let private_dir = temp.path().join("private");
        std::fs::create_dir_all(&site_dir).unwrap();
        std::fs::create_dir_all(&private_dir).unwrap();
        std::fs::write(site_dir.join("index.html"), "abcd").unwrap();
        std::fs::write(private_dir.join("master-key.json"), "secret").unwrap();

        let deployer = GitHubDeployer::default();
        let check = deployer.check_size(temp.path()).unwrap();

        assert_eq!(check.file_count, 1);
        assert_eq!(check.total_bytes, 4);
    }

    #[test]
    #[cfg(unix)]
    fn test_size_check_counts_in_tree_symlinked_files() {
        use std::os::unix::fs::symlink;
        use tempfile::TempDir;

        let temp = TempDir::new().unwrap();
        let site_dir = temp.path().join("site");
        std::fs::create_dir_all(&site_dir).unwrap();
        std::fs::write(site_dir.join("root.txt"), "root").unwrap();
        symlink("root.txt", site_dir.join("linked-file.txt")).unwrap();

        let deployer = GitHubDeployer::default();
        let check = deployer.check_size(temp.path()).unwrap();

        assert_eq!(check.file_count, 2);
        assert_eq!(check.total_bytes, 8);
    }

    #[test]
    fn test_resolve_site_dir_accepts_direct_site_directory() {
        use tempfile::TempDir;

        let temp = TempDir::new().unwrap();
        std::fs::write(temp.path().join("index.html"), "<html></html>").unwrap();

        let resolved = super::super::resolve_site_dir(temp.path()).unwrap();
        assert_eq!(resolved, temp.path());
    }

    #[test]
    #[cfg(unix)]
    fn test_resolve_site_dir_rejects_symlinked_site_directory() {
        use std::os::unix::fs::symlink;
        use tempfile::TempDir;

        let bundle_root = TempDir::new().unwrap();
        let outside = TempDir::new().unwrap();
        let outside_site = outside.path().join("site");
        std::fs::create_dir_all(&outside_site).unwrap();
        std::fs::write(outside_site.join("index.html"), "<html></html>").unwrap();
        symlink(&outside_site, bundle_root.path().join("site")).unwrap();

        let err = super::super::resolve_site_dir(bundle_root.path())
            .unwrap_err()
            .to_string();
        assert!(err.contains("must not be a symlink"));

        let direct_err = super::super::resolve_site_dir(&bundle_root.path().join("site"))
            .unwrap_err()
            .to_string();
        assert!(direct_err.contains("must not be a symlink"));
    }

    #[test]
    fn test_copy_dir_recursive() {
        use tempfile::TempDir;

        let src = TempDir::new().unwrap();
        let dst = TempDir::new().unwrap();

        // Create source structure
        std::fs::create_dir_all(src.path().join("subdir")).unwrap();
        std::fs::write(src.path().join("root.txt"), "root").unwrap();
        std::fs::write(src.path().join("subdir/nested.txt"), "nested").unwrap();

        copy_dir_recursive(src.path(), dst.path()).unwrap();

        assert!(dst.path().join("root.txt").exists());
        assert!(dst.path().join("subdir/nested.txt").exists());
    }

    #[test]
    fn test_copy_bundle_to_repo_resolves_bundle_root_without_copying_private_artifacts() {
        use tempfile::TempDir;

        let bundle_root = TempDir::new().unwrap();
        let repo_dir = TempDir::new().unwrap();
        let site_dir = bundle_root.path().join("site");
        let private_dir = bundle_root.path().join("private");
        std::fs::create_dir_all(&site_dir).unwrap();
        std::fs::create_dir_all(&private_dir).unwrap();
        std::fs::write(site_dir.join("index.html"), "<html></html>").unwrap();
        std::fs::write(site_dir.join("config.json"), "{}").unwrap();
        std::fs::write(private_dir.join("master-key.json"), "{\"secret\":true}").unwrap();

        copy_bundle_to_repo(bundle_root.path(), repo_dir.path()).unwrap();

        assert!(repo_dir.path().join("index.html").exists());
        assert!(repo_dir.path().join("config.json").exists());
        assert!(repo_dir.path().join(".nojekyll").exists());
        assert!(!repo_dir.path().join("private").exists());
        assert!(!repo_dir.path().join("site").exists());
    }

    #[test]
    fn test_copy_bundle_to_repo_ignores_bundle_git_directory_without_modifying_repo_git() {
        use tempfile::TempDir;

        let bundle_root = TempDir::new().unwrap();
        let repo_dir = TempDir::new().unwrap();
        let site_dir = bundle_root.path().join("site");
        let bundle_git_dir = site_dir.join(".git");
        let repo_git_dir = repo_dir.path().join(".git");

        std::fs::create_dir_all(&bundle_git_dir).unwrap();
        std::fs::create_dir_all(&repo_git_dir).unwrap();
        std::fs::write(site_dir.join("index.html"), "<html></html>").unwrap();
        std::fs::write(bundle_git_dir.join("config"), "bundle git config").unwrap();
        std::fs::write(repo_git_dir.join("config"), "repo git config").unwrap();

        copy_bundle_to_repo(bundle_root.path(), repo_dir.path()).unwrap();

        assert_eq!(
            std::fs::read_to_string(repo_git_dir.join("config")).unwrap(),
            "repo git config"
        );
        assert!(repo_dir.path().join("index.html").exists());
    }

    #[test]
    fn test_temp_deploy_dir_removes_real_staging_dir_on_drop() {
        let temp = create_temp_dir().unwrap();
        let temp_path = temp.path().to_path_buf();
        std::fs::write(temp_path.join("marker.txt"), "temporary clone").unwrap();

        drop(temp);

        assert!(
            !temp_path.exists(),
            "GitHub deploy temp clone directory should be removed on drop"
        );
    }

    #[test]
    #[cfg(unix)]
    fn test_temp_deploy_dir_drop_skips_symlinked_staging_path() {
        use std::os::unix::fs::symlink;
        use tempfile::TempDir;

        let parent = TempDir::new().unwrap();
        let outside = TempDir::new().unwrap();
        let temp_path = parent.path().join("cass-deploy-link");
        let sentinel = outside.path().join("sentinel.txt");
        std::fs::write(&sentinel, "keep").unwrap();
        symlink(outside.path(), &temp_path).unwrap();

        drop(TempDeployDir {
            path: temp_path.clone(),
        });

        assert_eq!(std::fs::read_to_string(&sentinel).unwrap(), "keep");
        assert!(
            std::fs::symlink_metadata(&temp_path)
                .unwrap()
                .file_type()
                .is_symlink(),
            "drop must leave symlinked staging paths untouched"
        );
    }

    #[test]
    #[cfg(unix)]
    fn test_copy_dir_recursive_materializes_in_tree_symlinked_files() {
        use std::os::unix::fs::symlink;
        use tempfile::TempDir;

        let src = TempDir::new().unwrap();
        let dst = TempDir::new().unwrap();

        std::fs::write(src.path().join("root.txt"), "root").unwrap();
        symlink("root.txt", src.path().join("linked-file.txt")).unwrap();

        copy_dir_recursive(src.path(), dst.path()).unwrap();

        let linked_metadata =
            std::fs::symlink_metadata(dst.path().join("linked-file.txt")).unwrap();
        assert!(linked_metadata.file_type().is_file());
        assert!(!linked_metadata.file_type().is_symlink());
        assert_eq!(
            std::fs::read_to_string(dst.path().join("linked-file.txt")).unwrap(),
            "root"
        );
    }

    #[test]
    #[cfg(unix)]
    fn test_copy_dir_recursive_rejects_symlinks_outside_root() {
        use std::os::unix::fs::symlink;
        use tempfile::TempDir;

        let src = TempDir::new().unwrap();
        let dst = TempDir::new().unwrap();
        let outside = TempDir::new().unwrap();

        std::fs::write(src.path().join("root.txt"), "root").unwrap();
        std::fs::write(outside.path().join("secret.txt"), "secret").unwrap();
        symlink(
            outside.path().join("secret.txt"),
            src.path().join("linked-file.txt"),
        )
        .unwrap();

        let err = copy_dir_recursive(src.path(), dst.path()).unwrap_err();
        assert!(
            err.to_string()
                .contains("Refusing to deploy symlinked site entry outside deployment root"),
            "unexpected error: {err:#}"
        );
    }

    #[test]
    #[cfg(unix)]
    fn test_copy_dir_recursive_rejects_symlinked_destination_root() {
        use std::os::unix::fs::symlink;
        use tempfile::TempDir;

        let src = TempDir::new().unwrap();
        let outside = TempDir::new().unwrap();
        let dst_parent = TempDir::new().unwrap();
        let dst = dst_parent.path().join("linked-dst");

        std::fs::write(src.path().join("root.txt"), "root").unwrap();
        symlink(outside.path(), &dst).unwrap();

        let err = copy_dir_recursive(src.path(), &dst).unwrap_err();
        assert!(
            err.to_string()
                .contains("deploy staging directory through symlink"),
            "unexpected error: {err:#}"
        );
        assert!(
            !outside.path().join("root.txt").exists(),
            "deploy staging must not copy through a symlinked destination"
        );
        assert!(
            std::fs::symlink_metadata(&dst)
                .unwrap()
                .file_type()
                .is_symlink(),
            "rejected destination symlink should be left untouched"
        );
    }

    #[test]
    #[cfg(unix)]
    fn test_copy_dir_recursive_rejects_symlinked_file_destination() {
        use std::os::unix::fs::symlink;
        use tempfile::TempDir;

        let src = TempDir::new().unwrap();
        let dst = TempDir::new().unwrap();
        let outside = TempDir::new().unwrap();
        let outside_file = outside.path().join("sentinel.txt");

        std::fs::write(src.path().join("root.txt"), "root").unwrap();
        std::fs::write(&outside_file, "keep").unwrap();
        symlink(&outside_file, dst.path().join("root.txt")).unwrap();

        let err = copy_dir_recursive(src.path(), dst.path()).unwrap_err();
        assert!(
            err.to_string()
                .contains("write deploy file through symlink"),
            "unexpected error: {err:#}"
        );
        assert_eq!(std::fs::read_to_string(&outside_file).unwrap(), "keep");
    }

    #[test]
    #[cfg(unix)]
    fn test_copy_bundle_to_repo_rejects_symlinked_repo_root() {
        use std::os::unix::fs::symlink;
        use tempfile::TempDir;

        let bundle_root = TempDir::new().unwrap();
        let site_dir = bundle_root.path().join("site");
        let outside = TempDir::new().unwrap();
        let repo_parent = TempDir::new().unwrap();
        let repo_link = repo_parent.path().join("repo");

        std::fs::create_dir_all(&site_dir).unwrap();
        std::fs::write(site_dir.join("index.html"), "<html></html>").unwrap();
        symlink(outside.path(), &repo_link).unwrap();

        let err = copy_bundle_to_repo(bundle_root.path(), &repo_link).unwrap_err();
        assert!(
            err.to_string()
                .contains("deploy staging directory through symlink"),
            "unexpected error: {err:#}"
        );
        assert!(
            !outside.path().join("index.html").exists(),
            "deploy staging must not copy through a symlinked repo root"
        );
    }

    #[test]
    #[cfg(unix)]
    fn test_copy_bundle_to_repo_removes_repo_symlink_entry_without_touching_target() {
        use std::os::unix::fs::symlink;
        use tempfile::TempDir;

        let bundle_root = TempDir::new().unwrap();
        let repo_dir = TempDir::new().unwrap();
        let outside = TempDir::new().unwrap();
        let site_dir = bundle_root.path().join("site");
        let outside_dir = outside.path().join("old-dir-target");
        let outside_file = outside_dir.join("sentinel.txt");

        std::fs::create_dir_all(&site_dir).unwrap();
        std::fs::write(site_dir.join("index.html"), "<html></html>").unwrap();
        std::fs::create_dir_all(&outside_dir).unwrap();
        std::fs::write(&outside_file, "keep").unwrap();
        symlink(&outside_dir, repo_dir.path().join("old-dir")).unwrap();

        copy_bundle_to_repo(bundle_root.path(), repo_dir.path()).unwrap();

        assert_eq!(std::fs::read_to_string(&outside_file).unwrap(), "keep");
        assert!(!repo_dir.path().join("old-dir").exists());
        assert!(repo_dir.path().join("index.html").exists());
        assert!(repo_dir.path().join(".nojekyll").exists());
    }

    #[test]
    #[cfg(unix)]
    fn test_visit_files_counts_in_tree_symlinked_files() {
        use std::os::unix::fs::symlink;
        use tempfile::TempDir;

        let src = TempDir::new().unwrap();

        std::fs::write(src.path().join("root.txt"), "root").unwrap();
        symlink("root.txt", src.path().join("linked-file.txt")).unwrap();

        let mut visited = Vec::new();
        visit_files(src.path(), &mut |path, size| {
            visited.push((
                path.strip_prefix(src.path())
                    .unwrap()
                    .to_string_lossy()
                    .to_string(),
                size,
            ));
        })
        .unwrap();

        assert!(visited.contains(&("root.txt".to_string(), 4)));
        assert!(visited.contains(&("linked-file.txt".to_string(), 4)));
    }

    #[test]
    #[cfg(unix)]
    fn test_visit_files_rejects_symlink_paths_outside_root() {
        use std::os::unix::fs::symlink;
        use tempfile::TempDir;

        let src = TempDir::new().unwrap();
        let outside = TempDir::new().unwrap();

        std::fs::write(src.path().join("root.txt"), "root").unwrap();
        std::fs::write(outside.path().join("secret.txt"), "secret").unwrap();
        std::fs::create_dir_all(outside.path().join("nested")).unwrap();
        std::fs::write(outside.path().join("nested/hidden.txt"), "hidden").unwrap();

        symlink(
            outside.path().join("secret.txt"),
            src.path().join("linked-file.txt"),
        )
        .unwrap();
        symlink(outside.path().join("nested"), src.path().join("linked-dir")).unwrap();

        let err = visit_files(src.path(), &mut |_path, _size| {}).unwrap_err();
        assert!(
            err.to_string()
                .contains("Refusing to deploy symlinked site entry outside deployment root"),
            "unexpected error: {err:#}"
        );
    }

    #[test]
    fn test_configure_git_identity_sets_local_commit_metadata() {
        use tempfile::TempDir;

        let repo = TempDir::new().unwrap();
        let init = Command::new("git")
            .args(["init"])
            .current_dir(repo.path())
            .output()
            .unwrap();
        assert!(
            init.status.success(),
            "git init failed: {}",
            String::from_utf8_lossy(&init.stderr)
        );

        configure_git_identity(repo.path(), "cass-test").unwrap();

        let name = Command::new("git")
            .args(["config", "user.name"])
            .current_dir(repo.path())
            .output()
            .unwrap();
        assert_eq!(String::from_utf8_lossy(&name.stdout).trim(), "cass-test");

        let email = Command::new("git")
            .args(["config", "user.email"])
            .current_dir(repo.path())
            .output()
            .unwrap();
        assert_eq!(
            String::from_utf8_lossy(&email.stdout).trim(),
            "cass-test@users.noreply.github.com"
        );

        std::fs::write(repo.path().join("index.html"), "<html></html>").unwrap();

        let add = Command::new("git")
            .args(["add", "-A"])
            .current_dir(repo.path())
            .output()
            .unwrap();
        assert!(
            add.status.success(),
            "git add failed: {}",
            String::from_utf8_lossy(&add.stderr)
        );

        let commit = Command::new("git")
            .args(["commit", "-m", "Test commit"])
            .current_dir(repo.path())
            .output()
            .unwrap();
        assert!(
            commit.status.success(),
            "git commit failed: {}",
            String::from_utf8_lossy(&commit.stderr)
        );
    }
}