tracel-xtask-cli 1.1.4

CLI entrypoint for Tracel xtask
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
mod args;
mod deps;
mod emojis;

#[cfg(test)]
mod test;

use std::{
    collections::BTreeMap,
    env,
    ffi::{OsStr, OsString},
    fs,
    io::Write as _,
    path::{Path, PathBuf},
    process::{Command, ExitCode},
};

use toml_edit::DocumentMut;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ToolchainOverride {
    Nightly,
}

impl ToolchainOverride {
    fn as_rustup_arg(self) -> &'static str {
        match self {
            Self::Nightly => "+nightly",
        }
    }

    fn display_name(self) -> &'static str {
        match self {
            Self::Nightly => "nightly",
        }
    }
}

fn take_toolchain_override(args: &mut Vec<OsString>) -> Option<ToolchainOverride> {
    let first = args.first()?;
    match first.to_str() {
        Some("+nightly") | Some("+n") => {
            args.remove(0);
            Some(ToolchainOverride::Nightly)
        }
        _ => None,
    }
}

fn apply_toolchain_env(cmd: &mut Command, toolchain: Option<ToolchainOverride>) {
    if let Some(toolchain) = toolchain {
        match toolchain {
            ToolchainOverride::Nightly => {
                cmd.env("RUSTUP_TOOLCHAIN", "nightly");
            }
        }
    }
}

#[derive(Debug, Clone)]
enum XtaskInvocation {
    /// The xtask crate is a real workspace member, so we can invoke it via:
    /// `cargo run --package <package> --bin <bin> -- ...`
    WorkspaceMember { package: String },
    /// The xtask crate is not a workspace member (commonly because it's under `[workspace].exclude`),
    /// so we must invoke it via:
    /// `cargo run --manifest-path <path/to/Cargo.toml> --bin <bin> -- ...`
    ManifestPath {
        manifest_path: PathBuf,
        package: String,
    },
}

impl XtaskInvocation {
    fn package_name(&self) -> &str {
        match self {
            XtaskInvocation::WorkspaceMember { package } => package,
            XtaskInvocation::ManifestPath { package, .. } => package,
        }
    }
}

#[derive(Debug, Clone)]
struct Workspace {
    path: PathBuf,
    dir_name: String,
    xtask_bin: String,
    xtask: XtaskInvocation,
    toolchain: Option<ToolchainOverride>,
}

impl Workspace {
    fn with_toolchain(mut self, toolchain: Option<ToolchainOverride>) -> Self {
        self.toolchain = toolchain;
        self
    }
}
#[derive(Debug, Clone)]
struct DispatchSummary {
    entries: Vec<SubrepoExecutionResult>,
}

impl DispatchSummary {
    fn new() -> Self {
        Self {
            entries: Vec::new(),
        }
    }

    fn push(&mut self, entry: SubrepoExecutionResult) {
        self.entries.push(entry);
    }

    fn success_count(&self) -> usize {
        self.entries
            .iter()
            .filter(|entry| entry.is_success())
            .count()
    }

    fn failure_count(&self) -> usize {
        self.entries.len().saturating_sub(self.success_count())
    }

    fn has_failures(&self) -> bool {
        self.failure_count() > 0
    }

    fn final_exit_code(&self) -> ExitCode {
        if self.has_failures() {
            ExitCode::from(1)
        } else {
            ExitCode::SUCCESS
        }
    }

    fn print(&self) {
        eprintln!();
        eprintln!("==================== Execution summary ====================");

        if !self.has_failures() {
            eprintln!("✅ All {} subrepos succeeded!", self.entries.len());
            return;
        }

        for entry in &self.entries {
            match &entry.outcome {
                RepoExecutionOutcome::Success => {
                    eprintln!("✅ {:<16} success", entry.repo);
                }
                RepoExecutionOutcome::Failure { code } => {
                    eprintln!("❌ {:<16} failed with exit code {}", entry.repo, code);
                }
                RepoExecutionOutcome::Error { message } => {
                    eprintln!("💥 {:<16} dispatch error: {}", entry.repo, message);
                }
            }
        }

        eprintln!();
        eprintln!("Total subrepos : {}", self.entries.len());
        eprintln!("Succeeded      : {}", self.success_count());
        eprintln!("Failed         : {}", self.failure_count());

        let failed = self
            .entries
            .iter()
            .filter(|entry| !entry.is_success())
            .map(|entry| entry.repo.as_str())
            .collect::<Vec<_>>()
            .join(", ");

        eprintln!("Failed subrepos: {failed}");
        eprintln!("===========================================================");
    }
}

#[derive(Debug, Clone)]
struct SubrepoExecutionResult {
    repo: String,
    outcome: RepoExecutionOutcome,
}

impl SubrepoExecutionResult {
    fn success(repo: impl Into<String>) -> Self {
        Self {
            repo: repo.into(),
            outcome: RepoExecutionOutcome::Success,
        }
    }

    fn failure(repo: impl Into<String>, code: u8) -> Self {
        Self {
            repo: repo.into(),
            outcome: RepoExecutionOutcome::Failure { code },
        }
    }

    fn error(repo: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            repo: repo.into(),
            outcome: RepoExecutionOutcome::Error {
                message: message.into(),
            },
        }
    }

    fn is_success(&self) -> bool {
        matches!(self.outcome, RepoExecutionOutcome::Success)
    }
}

#[derive(Debug, Clone)]
enum RepoExecutionOutcome {
    Success,
    Failure { code: u8 },
    Error { message: String },
}

fn main() -> ExitCode {
    let mut args: Vec<OsString> = env::args_os().skip(1).collect();
    let toolchain = take_toolchain_override(&mut args);

    let git_root = match git_repo_root()
        .map_err(|e| format!("xtask should run inside a git repository: {e}"))
    {
        Ok(root) => root,
        Err(err) => {
            eprintln!("{err}");
            return ExitCode::from(1);
        }
    };

    if is_cli_help_invocation(&args) {
        match show_xtask_cli_help(&git_root, toolchain) {
            Ok(code) => code,
            Err(err) => {
                eprintln!("{err}");
                ExitCode::from(1)
            }
        }
    } else if is_transparent_help_invocation(&args) {
        match show_all_help(&git_root, &mut args, toolchain) {
            Ok(code) => code,
            Err(err) => {
                eprintln!("{err}");
                ExitCode::from(1)
            }
        }
    } else {
        match run(&git_root, &mut args, toolchain) {
            Ok(code) => code,
            Err(err) => {
                eprintln!("{err}");
                ExitCode::from(1)
            }
        }
    }
}

fn run(
    git_root: &Path,
    args: &mut Vec<OsString>,
    toolchain: Option<ToolchainOverride>,
) -> Result<ExitCode, String> {
    let selector = args::take_subrepo_selector(args);
    let cwd = env::current_dir().map_err(|e| format!("failed to read current directory: {e}"))?;

    // Selector provided
    if let Some(sel) = selector {
        if sel == "all" {
            // :all magic selector
            let subrepos = list_subrepo_workspaces(git_root, toolchain)?;
            if subrepos.is_empty() {
                return Err(format!(
                    "xtask :all requires at least one subrepo workspace under git root.\n\
                     Git root: {}",
                    git_root.display()
                ));
            }
            return exec_cargo_xtask_all(git_root, args, &subrepos);
        } else {
            // :<subrepo> selector
            let ws = select_subrepo_workspace(git_root, &sel, toolchain)?;
            return exec_cargo_xtask(git_root, &ws, args).map(ExitCode::from);
        }
    }

    // No selector provided
    // Behavior depends on standard repo vs monorepo
    let root_xtask = is_workspace(git_root)?;
    if let Some(xtask) = root_xtask {
        // Standard repo -> execute at git root
        let xtask_bin = xtask.package_name().to_string();
        let ws = Workspace {
            path: git_root.to_path_buf(),
            dir_name: "root".to_string(),
            xtask_bin,
            xtask,
            toolchain,
        };
        exec_cargo_xtask(git_root, &ws, args).map(ExitCode::from)
    } else {
        // Monorepo:
        if let Some(ws) = find_subrepo_workspace_root(&cwd, git_root, toolchain)? {
            // inside a subrepo workspace at any depth then we execute in that subrepo.
            exec_cargo_xtask(git_root, &ws, args).map(ExitCode::from)
        } else {
            // At monorepo root we dispatch to all subrepos after confirmation
            let subrepos = list_subrepo_workspaces(git_root, toolchain)?;
            if subrepos.is_empty() {
                return Err(format!(
                    "No xtask workspaces found under git root: {}",
                    git_root.display()
                ));
            }
            if !confirm_dispatch_all()? {
                return Ok(ExitCode::SUCCESS);
            }
            exec_cargo_xtask_all(git_root, args, &subrepos)
        }
    }
}

/// Sync dependency versions from the root fake Dependencies.toml
fn sync_monorepo_dependencies(git_root: &Path, subrepos: &[Workspace]) -> Result<(), String> {
    let deps_toml = git_root.join("Dependencies.toml");
    if !deps_toml.exists() {
        return Ok(());
    }
    eprintln!(
        "🔗 Syncing dependencies from {}...",
        deps_toml.file_name().unwrap().to_string_lossy()
    );
    let subrepo_roots: Vec<PathBuf> = subrepos.iter().map(|ws| ws.path.clone()).collect();
    let report = deps::sync_subrepos(&deps_toml, &subrepo_roots)
        .map_err(|e| format!("dependency sync should succeed: {e}"))?;
    for (manifest, table_path, dep) in report.missing_canonical_dependencies {
        eprintln!(
            "warning: {} declares dependency '{}' in [{}] but it is missing from root [workspace.dependencies]",
            manifest.display(),
            dep,
            table_path,
        );
    }

    Ok(())
}

fn confirm_dispatch_all() -> Result<bool, String> {
    eprintln!(
        "⚠️ This will run the command in all subrepos (to suppress this prompt use the ':all' selector)"
    );
    eprint!("Continue? [y/N] ");

    std::io::stderr().flush().ok();
    let mut buf = String::new();
    std::io::stdin()
        .read_line(&mut buf)
        .map_err(|e| format!("failed to read confirmation from stdin: {e}"))?;
    let answer = buf.trim().to_ascii_lowercase();
    Ok(answer == "y" || answer == "yes")
}

fn is_cli_help_invocation(args: &[OsString]) -> bool {
    args.is_empty()
}

fn is_transparent_help_invocation(args: &[OsString]) -> bool {
    args.is_empty()
        || (args.len() == 1 && (args[0] == OsStr::new("-h") || args[0] == OsStr::new("--help")))
}

fn git_repo_root() -> Result<PathBuf, String> {
    let out = Command::new("git")
        .args(["rev-parse", "--show-toplevel"])
        .output()
        .map_err(|e| format!("failed to execute git: {e}"))?;
    if !out.status.success() {
        return Err(
            "git rev-parse --show-toplevel failed (are you inside a git repository?)".into(),
        );
    }

    let s = String::from_utf8(out.stdout)
        .map_err(|_| "git output should be valid UTF-8".to_string())?;
    let p = s.trim();
    if p.is_empty() {
        return Err("git toplevel path is empty".into());
    }

    Ok(PathBuf::from(p))
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum WorkspaceEntryOrigin {
    Members,
    Exclude,
}

/// Resolve workspace entries (strings), supporting the common "path/*" glob.
fn collect_workspace_dirs(
    workspace_root: &Path,
    items: &toml_edit::Item,
) -> Result<Vec<PathBuf>, String> {
    let arr = items
        .as_array()
        .ok_or_else(|| "workspace members/exclude should be an array".to_string())?;

    let mut out: Vec<PathBuf> = Vec::new();

    for it in arr.iter() {
        let s = it
            .as_str()
            .ok_or_else(|| "workspace entry should be a string".to_string())?;

        if let Some((prefix, suffix)) = s.split_once('*') {
            // Only handle the common "path/*" form
            if suffix.is_empty() {
                let base = workspace_root.join(prefix);
                if base.is_dir() {
                    let entries = fs::read_dir(&base).map_err(|e| {
                        format!("failed to read directory listing {}: {e}", base.display())
                    })?;
                    for entry in entries {
                        let entry =
                            entry.map_err(|e| format!("failed to read directory entry: {e}"))?;
                        let p = entry.path();
                        if p.is_dir() {
                            out.push(p);
                        }
                    }
                }
            }
            continue;
        }

        out.push(workspace_root.join(s));
    }

    Ok(out)
}

/// Returns how to invoke an xtask-like crate if `dir` is a Cargo workspace root that contains one.
///
/// Detection:
/// - Reads `Cargo.toml` and requires `[workspace].members` to exist (same behavior as before).
/// - Scans candidate directories from:
///   - `[workspace].members`
///   - `[workspace].exclude` (important for repos that do `members = ["crates/*"]` and `exclude = ["xtask"]`)
/// - For each candidate directory, if it has a `Cargo.toml` with `package.name` starting with `"xtask"`
///   (case-insensitive), it is considered a match.
///
/// Selection (deterministic):
/// - Prefer an exact `package.name == "xtask"` (case-insensitive).
/// - Otherwise choose the lexicographically smallest xtask-like package name.
///
/// Invocation mode:
/// - If the selected xtask-like crate came from `workspace.members`, returns:
///   `Some(XtaskInvocation::WorkspaceMember { package })`
///   (we can safely run via `cargo run --package <package> ...`)
/// - If it came only from `workspace.exclude`, returns:
///   `Some(XtaskInvocation::ManifestPath { manifest_path: <crate_dir>/Cargo.toml, package })`
fn is_workspace(dir: &Path) -> Result<Option<XtaskInvocation>, String> {
    let workspace_toml = dir.join("Cargo.toml");
    if !workspace_toml.is_file() {
        return Ok(None);
    }

    let root_src = fs::read_to_string(&workspace_toml)
        .map_err(|e| format!("failed to read {}: {e}", workspace_toml.display()))?;
    let root_doc = root_src
        .parse::<DocumentMut>()
        .map_err(|e| format!("failed to parse {}: {e}", workspace_toml.display()))?;

    let Some(ws) = root_doc.get("workspace") else {
        return Ok(None);
    };

    // Keep current behavior: not a workspace if workspace.members is missing.
    let Some(members_item) = ws.get("members") else {
        return Ok(None);
    };

    // Track candidate dirs with origin; dedupe by path.
    // If a path appears in both, prefer Members.
    let mut candidates: BTreeMap<PathBuf, WorkspaceEntryOrigin> = BTreeMap::new();

    for p in collect_workspace_dirs(dir, members_item)? {
        candidates.insert(p, WorkspaceEntryOrigin::Members);
    }

    if let Some(exclude_item) = ws.get("exclude") {
        for p in collect_workspace_dirs(dir, exclude_item)? {
            candidates.entry(p).or_insert(WorkspaceEntryOrigin::Exclude);
        }
    }

    // Scan for xtask-like crates; store (package_name, origin, manifest_path)
    let mut matches: Vec<(String, WorkspaceEntryOrigin, PathBuf)> = Vec::new();

    for (candidate_dir, origin) in candidates {
        let candidate_manifest = candidate_dir.join("Cargo.toml");
        if !candidate_manifest.is_file() {
            continue;
        }

        let src = fs::read_to_string(&candidate_manifest)
            .map_err(|e| format!("failed to read {}: {e}", candidate_manifest.display()))?;
        let doc = src
            .parse::<DocumentMut>()
            .map_err(|e| format!("failed to parse {}: {e}", candidate_manifest.display()))?;

        let package_name = doc
            .get("package")
            .and_then(|p| p.get("name"))
            .and_then(|n| n.as_str());

        if let Some(name) = package_name
            && name.to_ascii_lowercase().starts_with("xtask")
        {
            matches.push((name.to_string(), origin, candidate_manifest));
        }
    }

    if matches.is_empty() {
        return Ok(None);
    }

    matches.sort_by(|a, b| a.0.cmp(&b.0));

    // Prefer exact "xtask"
    let chosen = if let Some(idx) = matches
        .iter()
        .position(|(n, _, _)| n.eq_ignore_ascii_case("xtask"))
    {
        matches.remove(idx)
    } else {
        matches.remove(0)
    };

    let (package, origin, manifest_path) = chosen;

    Ok(Some(match origin {
        WorkspaceEntryOrigin::Members => XtaskInvocation::WorkspaceMember { package },
        WorkspaceEntryOrigin::Exclude => XtaskInvocation::ManifestPath {
            manifest_path,
            package,
        },
    }))
}

fn find_subrepo_workspace_root(
    start: &Path,
    git_root: &Path,
    toolchain: Option<ToolchainOverride>,
) -> Result<Option<Workspace>, String> {
    let mut cur = start.to_path_buf();

    loop {
        // The root of the repository cannot be a subrepo
        if cur == *git_root {
            return Ok(None);
        }

        if let Some(xtask) = is_workspace(&cur)? {
            // subrepo dir name is the first path segment under git_root
            let rel = cur.strip_prefix(git_root).map_err(|_| {
                format!(
                    "internal error: {} is not under git root {}",
                    cur.display(),
                    git_root.display()
                )
            })?;

            let subrepo = rel
                .components()
                .next()
                .ok_or_else(|| {
                    "internal error: workspace root has empty relative path".to_string()
                })?
                .as_os_str()
                .to_string_lossy()
                .to_string();

            // Keep your convention for subrepo bin names.
            // If you want package-driven bin names, swap this to `xtask.package_name().to_string()`.
            let xtask_bin = format!("xtask-{subrepo}");

            return Ok(Some(
                Workspace {
                    path: cur,
                    dir_name: subrepo,
                    xtask_bin,
                    xtask,
                    toolchain: None,
                }
                .with_toolchain(toolchain),
            ));
        }

        if !cur.pop() {
            return Ok(None);
        }
    }
}

fn list_subrepo_workspaces(
    git_root: &Path,
    toolchain: Option<ToolchainOverride>,
) -> Result<Vec<Workspace>, String> {
    let entries = fs::read_dir(git_root).map_err(|e| {
        format!(
            "failed to read git root directory listing {}: {e}",
            git_root.display()
        )
    })?;

    let mut subrepos = Vec::new();
    for entry in entries {
        let entry = entry.map_err(|e| format!("failed to read directory entry: {e}"))?;
        let path = entry.path();
        if !path.is_dir() {
            continue;
        }

        let dir_name = entry.file_name().to_string_lossy().to_string();

        if let Some(xtask) = is_workspace(&path)? {
            // Keep your convention: xtask-<subrepo>
            let xtask_bin = format!("xtask-{dir_name}");

            subrepos.push(
                Workspace {
                    path,
                    dir_name: dir_name.clone(),
                    xtask_bin,
                    xtask,
                    toolchain: None,
                }
                .with_toolchain(toolchain),
            );
        }
    }

    subrepos.sort_by(|a, b| a.dir_name.cmp(&b.dir_name));
    Ok(subrepos)
}

fn select_subrepo_workspace(
    git_root: &Path,
    selector: &str,
    toolchain: Option<ToolchainOverride>,
) -> Result<Workspace, String> {
    let subrepos = list_subrepo_workspaces(git_root, toolchain)?;

    if subrepos.is_empty() {
        return Err(format!(
            "No xtask workspaces found under git root: {}",
            git_root.display()
        ));
    }

    select_subrepo_workspace_from_list(&subrepos, selector).cloned()
}

fn select_subrepo_workspace_from_list<'a>(
    subrepos: &'a [Workspace],
    selector: &str,
) -> Result<&'a Workspace, String> {
    // Exact selector:
    //
    //   :product-backend
    if let Some(ws) = subrepos.iter().find(|ws| ws.dir_name == selector) {
        return Ok(ws);
    }

    // Prefix selector:
    //
    //   :product
    //   :prod
    //
    // Keep the existing behavior before trying shorthand resolution.
    let prefix_matches: Vec<&Workspace> = subrepos
        .iter()
        .filter(|ws| ws.dir_name.starts_with(selector))
        .collect();

    match prefix_matches.len() {
        1 => return Ok(prefix_matches[0]),
        n if n > 1 => {
            let candidates = prefix_matches
                .iter()
                .map(|ws| ws.dir_name.as_str())
                .collect::<Vec<_>>()
                .join(", ");

            return Err(format!(
                "Ambiguous subrepo selector '{}'. Matching candidates: {}",
                selector, candidates
            ));
        }
        _ => {}
    }

    // Shorthand selector:
    //
    //   product-backend -> :pb
    //   burn-central-app -> :bca
    //
    // The shorthand is accepted only when it resolves to exactly one subrepo.
    let normalized_selector = selector.to_ascii_lowercase();

    let shorthand_matches: Vec<&Workspace> = subrepos
        .iter()
        .filter(|ws| {
            subrepo_shorthand(&ws.dir_name)
                .as_deref()
                .is_some_and(|shorthand| shorthand == normalized_selector)
        })
        .collect();

    match shorthand_matches.len() {
        0 => Err(format!("No subrepo matches selector '{}'.", selector)),
        1 => Ok(shorthand_matches[0]),
        _ => {
            let candidates = shorthand_matches
                .iter()
                .map(|ws| {
                    let shorthand = subrepo_shorthand(&ws.dir_name)
                        .expect("subrepo shorthand should exist for a shorthand match");

                    format!("{} (:{})", ws.dir_name, shorthand)
                })
                .collect::<Vec<_>>()
                .join(", ");

            Err(format!(
                "Ambiguous subrepo shorthand selector '{}'. Matching candidates: {}",
                selector, candidates
            ))
        }
    }
}

fn subrepo_shorthand(name: &str) -> Option<String> {
    let shorthand = name
        .split(|c: char| !c.is_ascii_alphanumeric())
        .filter_map(|part| part.chars().next())
        .map(|c| c.to_ascii_lowercase())
        .collect::<String>();

    if shorthand.is_empty() {
        None
    } else {
        Some(shorthand)
    }
}

fn show_all_help(
    git_root: &Path,
    args: &mut Vec<OsString>,
    toolchain: Option<ToolchainOverride>,
) -> Result<ExitCode, String> {
    let selector = args::take_subrepo_selector(args);
    let cwd = env::current_dir().map_err(|e| format!("failed to read current directory: {e}"))?;

    // Selector
    if let Some(sel) = selector {
        if sel == "all" {
            // :all magic selector
            let subrepos = list_subrepo_workspaces(git_root, toolchain)?;
            if subrepos.is_empty() {
                return Err(format!(
                    "xtask :all requires at least one subrepo workspace under git root.\n\
                     Git root: {}",
                    git_root.display()
                ));
            }
            run_help_all(&subrepos)
        } else {
            // :<subrepo> selector
            let ws = select_subrepo_workspace(git_root, &sel, toolchain)?;
            run_help_one(&ws).map(ExitCode::from)
        }
    } else {
        // No selector, behavior depends on standard repo vs monorepo.
        let root_xtask = is_workspace(git_root)?;
        if let Some(xtask) = root_xtask {
            // Standard repo: help at git root
            let ws = Workspace {
                path: git_root.to_path_buf(),
                dir_name: "root".to_string(),
                xtask_bin: xtask.package_name().to_string(),
                xtask,
                toolchain,
            };
            run_help_one(&ws).map(ExitCode::from)
        } else {
            // Monorepo:
            if let Some(ws) = find_subrepo_workspace_root(&cwd, git_root, toolchain)? {
                // if inside a subrepo workspace (any depth), show help for that subrepo.
                run_help_one(&ws).map(ExitCode::from)
            } else {
                // At monorepo root we show help for all after confirmation
                let subrepos = list_subrepo_workspaces(git_root, toolchain)?;
                if subrepos.is_empty() {
                    return Err(format!(
                        "No xtask workspaces found under git root: {}",
                        git_root.display()
                    ));
                }

                if !confirm_dispatch_all()? {
                    return Ok(ExitCode::SUCCESS);
                }

                run_help_all(&subrepos)
            }
        }
    }
}

fn run_help_all(subrepos: &[Workspace]) -> Result<ExitCode, String> {
    let mut first_failure: Option<u8> = None;

    for ws in subrepos {
        let code = run_help_one(ws)?;
        if code != 0 && first_failure.is_none() {
            first_failure = Some(code);
        }
        eprintln!();
    }

    Ok(ExitCode::from(first_failure.unwrap_or(0)))
}

fn run_help_one(ws: &Workspace) -> Result<u8, String> {
    let is_subrepo = ws.dir_name != "root";
    let target_dir: &Path = if is_subrepo {
        Path::new("../target/xtask")
    } else {
        Path::new("target/xtask")
    };

    if is_subrepo {
        emojis::print_run_header(&emojis::format_repo_label(&ws.dir_name));
    }

    eprintln!("🔧 Compiling xtask:{}...", ws.dir_name);

    let mut cmd = Command::new("cargo");
    if let Some(toolchain) = ws.toolchain {
        cmd.arg(toolchain.as_rustup_arg());
    }
    apply_toolchain_env(&mut cmd, ws.toolchain);
    cmd.arg("run").arg("--target-dir").arg(target_dir);

    match &ws.xtask {
        XtaskInvocation::WorkspaceMember { package } => {
            cmd.arg("--package").arg(package);
        }
        XtaskInvocation::ManifestPath { manifest_path, .. } => {
            cmd.arg("--manifest-path").arg(manifest_path);
        }
    }

    cmd.arg("--bin")
        .arg(&ws.xtask_bin)
        .arg("--")
        .arg("--help")
        .env("XTASK_CLI", "1")
        .current_dir(&ws.path);

    if is_subrepo {
        cmd.env("XTASK_MONOREPO", "1");
    }

    let status = cmd.status().map_err(|e| {
        format!(
            "failed to execute cargo run ({} --help): {e}",
            ws.path.display()
        )
    })?;

    Ok(exit_code_u8_from_status(status))
}

fn exec_cargo_xtask_all(
    git_root: &Path,
    args: &[OsString],
    subrepos: &[Workspace],
) -> Result<ExitCode, String> {
    let mut summary = DispatchSummary::new();

    for ws in subrepos {
        match exec_cargo_xtask(git_root, ws, args) {
            Ok(0) => {
                summary.push(SubrepoExecutionResult::success(ws.dir_name.clone()));
            }
            Ok(code) => {
                summary.push(SubrepoExecutionResult::failure(ws.dir_name.clone(), code));
            }
            Err(err) => {
                eprintln!("error: {err}");
                summary.push(SubrepoExecutionResult::error(ws.dir_name.clone(), err));
            }
        }
    }

    summary.print();
    Ok(summary.final_exit_code())
}

fn exec_cargo_xtask(git_root: &Path, ws: &Workspace, args: &[OsString]) -> Result<u8, String> {
    let is_subrepo = ws.dir_name != "root";

    let target_path = format!("target/{}", ws.xtask.package_name());
    let target_dir = Path::new(&target_path);

    if is_subrepo {
        emojis::print_run_header(&emojis::format_repo_label(&ws.dir_name));
    };

    sync_monorepo_dependencies(git_root, std::slice::from_ref(ws))?;

    eprintln!("🔧 Compiling xtask:{}...", ws.dir_name);

    let mut cmd = Command::new("cargo");
    if let Some(toolchain) = ws.toolchain {
        cmd.arg(toolchain.as_rustup_arg());
    }
    apply_toolchain_env(&mut cmd, ws.toolchain);
    cmd.arg("run").arg("--target-dir").arg(target_dir);

    match &ws.xtask {
        XtaskInvocation::WorkspaceMember { package } => {
            cmd.arg("--package").arg(package);
        }
        XtaskInvocation::ManifestPath { manifest_path, .. } => {
            cmd.arg("--manifest-path").arg(manifest_path);
        }
    }

    cmd.arg("--bin")
        .arg(&ws.xtask_bin)
        .arg("--")
        .args(args)
        .env("XTASK_CLI", "1")
        .current_dir(&ws.path);

    if is_subrepo {
        cmd.env("XTASK_MONOREPO", "1");
    }

    let status = cmd
        .status()
        .map_err(|e| format!("failed to execute cargo run ({}): {e}", ws.path.display()))?;

    Ok(exit_code_u8_from_status(status))
}

fn exit_code_u8_from_status(status: std::process::ExitStatus) -> u8 {
    match status.code() {
        Some(code) if (0..=255).contains(&code) => code as u8,
        _ => 1,
    }
}

/// Try to retrieve xtask CLI binary name, otherwise fallback to xtask
fn cli_name() -> String {
    std::env::args_os()
        .next()
        .and_then(|p| {
            std::path::Path::new(&p)
                .file_name()
                .map(|s| s.to_string_lossy().to_string())
        })
        .unwrap_or_else(|| "xtask".to_string())
}

fn cli_help_header() {
    let name = cli_name();
    let version = env!("CARGO_PKG_VERSION");
    let authors = env!("CARGO_PKG_AUTHORS");
    let author = authors.split(',').next().unwrap_or(authors);
    eprintln!("{name} v{version} by {author}");
}

fn cli_help_fooder() {
    println!("LICENSE");
    println!("-------");
    println!("  This project is dual-licensed under the Apache 2.0 and MIT licenses.");
    println!("  You may choose either license when using, modifying, or distributing it.");
    println!();
    println!("  Repository: https://github.com/tracel-ai/xtask");
    println!("  See LICENSE-APACHE and LICENSE-MIT for full license texts.");
    println!();
}

fn show_xtask_cli_help(
    git_root: &Path,
    toolchain: Option<ToolchainOverride>,
) -> Result<ExitCode, String> {
    let cwd = env::current_dir().map_err(|e| format!("failed to read current directory: {e}"))?;
    let cli_name = cli_name();
    let root_xtask = is_workspace(git_root)?;
    let is_monorepo = root_xtask.is_none();

    cli_help_header();
    println!();
    println!("A transparent wrapper around `cargo xtask` alias for standard repos and monorepos.");
    println!("It discovers xtask workspaces and dispatches your command to the right place.");
    println!();

    println!("USAGE");
    println!("-----");
    println!("  {cli_name} [+nightly|+n] [:<subrepo>|:all] [<xtask args...>]");
    println!();

    println!("BEHAVIOR");
    println!("--------");
    println!("  - With a selector:");
    println!("      :<subrepo>  Runs xtask in that subrepo workspace.");
    println!("      :all        Runs xtask in all subrepos.");
    println!("  - Without a selector:");
    println!("      Standard repo: runs xtask at the git root.");
    println!("      Monorepo: if you're inside a subrepo, runs in that subrepo context,");
    println!("                otherwise prompts then run the command in all the subrepos.");
    println!();

    println!("TOOLCHAIN");
    println!("---------");
    println!("  - `+nightly`  Runs the underlying xtask with `cargo +nightly run ...`.");
    println!("  - `+n`        Short alias for `+nightly`.");
    match toolchain {
        Some(toolchain) => {
            println!("  - Current override: {}", toolchain.display_name());
        }
        None => {
            println!("  - Current override: none");
        }
    }
    println!();

    println!("HELP");
    println!("----");
    println!("  - `{cli_name}`                   Shows this screen.");
    println!("  - `{cli_name} --help`            Shows underlying xtask help (transparent mode).");
    println!("  - `{cli_name} <command> --help`  Shows help of <command>.");
    println!();

    if !is_monorepo {
        let xtask_pkg = root_xtask
            .as_ref()
            .map(|x| x.package_name().to_string())
            .unwrap_or_else(|| "xtask".to_string());

        println!("CONTEXT");
        println!("-------");
        println!("  Current Repository mode: standard repository");
        println!("  Git root: {}", git_root.display());
        println!("  Xtask package: {xtask_pkg}");
        println!();

        println!("EXAMPLES");
        println!("--------");
        println!("  {cli_name} build");
        println!("      Run the `build` xtask command at the repository root.");
        println!("      Equivalent to `cargo xtask build`.");
        println!();
        println!("  {cli_name} test all");
        println!("      Run the `test` xtask command with argument `all`.");
        println!("      Arguments are forwarded transparently to xtask.");
        println!();
        println!("  {cli_name} fix -y all");
        println!("      Run the `fix` xtask command, auto-confirming prompts (`-y`),");
        println!("      and applying fixes to all supported targets.");
        println!();
        println!("  {cli_name} +nightly test --miri");
        println!("      Run the `test` xtask command through the nightly toolchain.");
        println!();

        cli_help_fooder();
        return Ok(ExitCode::SUCCESS);
    }

    // Monorepo context
    let subrepos = list_subrepo_workspaces(git_root, toolchain)?;
    let located = find_subrepo_workspace_root(&cwd, git_root, toolchain)?;

    // Pick real example subrepos found in this context.
    let ex1 = subrepos
        .first()
        .map(|ws| ws.dir_name.as_str())
        .unwrap_or("backend");
    let ex2 = subrepos
        .get(1)
        .map(|ws| ws.dir_name.as_str())
        .unwrap_or("frontend");

    println!("CONTEXT");
    println!("-------");
    println!("  Git root: {}", git_root.display());
    println!("  Current Repository mode: monorepo");
    match located {
        Some(ws) => {
            println!("  Current location: inside subrepo `{}`", ws.dir_name);
            println!("  Current xtask package: {}", ws.xtask.package_name());
        }
        None => {
            if cwd == git_root {
                println!("  Current location: monorepo root");
            } else {
                println!("  Current location: outside a recognized subrepo workspace");
            }
        }
    }
    println!();

    println!("SUBREPOS");
    println!("--------");
    if subrepos.is_empty() {
        println!("  (none found)");
    } else {
        for ws in &subrepos {
            let shorthand = subrepo_shorthand(&ws.dir_name)
                .map(|shorthand| format!(":{shorthand}"))
                .unwrap_or_else(|| "-".to_string());

            println!(
                "  - {:<16}  shorthand: {:<8}  xtask: {:<12}",
                ws.dir_name,
                shorthand,
                ws.xtask.package_name(),
            );
        }
    }
    println!();

    println!("EXAMPLES");
    println!("--------");
    println!("  {cli_name} :{ex1} build");
    println!("      Run `build` in the `{ex1}` subrepo, regardless of current directory within");
    println!("      the monorepo.");
    println!();
    println!("  {cli_name} :{ex2} test all");
    println!("      Run both unit and integration tests scoped to the `{ex2}` subrepo only.");
    println!();
    println!("  {cli_name} +n :{ex1} test --miri");
    println!("      Run xtask in `{ex1}` through the nightly toolchain.");
    println!();
    println!("  {cli_name} :all fix -y all");
    println!("      Run all available fixes (lint, format, audit, ...) across all subrepos,");
    println!("      auto-confirming prompts and applying fixes everywhere.");
    println!();
    println!("  {cli_name} :all build");
    println!("      Run `build` xtask command in every subrepo, regardless of current");
    println!("      directory within the monorepo. Useful to easily sync the dependencies");
    println!("      of `Dependencies.toml` with all the subrepos and verify that they all");
    println!("      still build without errors.");
    println!();

    println!("NOTES");
    println!("-----");
    println!(
        "  - If `Dependencies.toml` exists at the monorepo root, xtask will sync dependency specs"
    );
    println!("    before running subrepo commands.");
    println!(
        "  - This wrapper is designed to remain transparent: it forwards your arguments to the"
    );
    println!("    underlying xtask binary in the selected workspace(s).");
    println!("  - Subrepo selectors also support unambiguous shorthands, for example");
    println!("    `product-backend` can be selected with `:pb`.");
    println!();

    cli_help_fooder();
    Ok(ExitCode::SUCCESS)
}