cargo-rail 0.27.0

Cargo-native Rust workspace engine for affected CI, Rust source-surface analysis, compiler reuse, dependency coherence, exact-SHA releases, and split/sync
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
//! User-facing command preparation and dispatch.
//!
//! Commands share one captured [`crate::workspace::WorkspaceContext`], but planning, compiler
//! reuse, dependency repair, Surface, release, split, and sync retain separate
//! decision and mutation boundaries.

pub(crate) mod cache;
/// Intent-file management.
pub mod change;
/// Preview or remove selected Cargo-Rail state.
pub mod clean;
/// CLI argument definitions (clap structs) - internal, not part of stable API.
#[doc(hidden)]
pub mod cli;
/// Common utilities for command implementations.
pub mod common;
/// Inspect, validate, and explain repository policy.
pub mod config;
/// Read-only workspace and toolchain diagnostics.
pub mod doctor;
/// Generate sparse repository policy.
pub mod init;
/// Deterministic affected-work planner.
pub mod plan;
/// Durable exact-SHA release transactions.
pub mod release;
/// Crate extraction with preserved Git history.
pub mod split;
/// Complete Rust declaration reachability and visibility analysis.
pub mod surface;
/// Synchronization with configured split repositories.
pub mod sync;
/// Deterministic workspace dependency repair.
pub mod unify;

pub use change::{ChangeCheckOptions, run_change_add, run_change_check, run_change_status};
pub use clean::{CleanContext, run_clean};
#[doc(hidden)]
pub use cli::{
    CacheCommand, CacheScope, ChangeCommand, Commands, DoctorCommand, RailCli, ReleaseCommand, SplitCommand,
    generate_completions,
};
pub use common::{ChangeOutputFormat, SplitOutputFormat, SurfaceOutputFormat, TextJsonOutputFormat};
pub use config::{
    StrictnessMode, run_config_explain, run_config_locate, run_config_print, run_config_validate_standalone,
};
pub use doctor::run_native_cache_doctor;
pub use init::{run_init, run_init_standalone};
pub use plan::{PlanOptions, run_plan};
pub use release::{
    run_release_init, run_release_plan, run_release_publication_check, run_release_publish,
    run_release_status_standalone,
};
pub use split::{run_split, run_split_init};
pub use surface::{SurfaceOptions, run_surface};
pub use sync::run_sync;
pub use unify::{UnifyAnalyzeOptions, run_unify_analyze, run_unify_apply, run_unify_doctor, run_unify_undo};

use crate::error::RailResult;
use crate::workspace::WorkspaceContext;
use std::path::{Path, PathBuf};

/// Result of attempting to dispatch a command without building WorkspaceContext.
#[derive(Debug)]
#[doc(hidden)]
pub enum PreContextDispatch {
    /// The command ran and the process should exit.
    Handled,
    /// The command requires a WorkspaceContext to run.
    NeedsContext(PreparedContext),
}

/// A command paired with the context-construction contract it requires.
#[derive(Debug)]
#[doc(hidden)]
pub struct PreparedContext {
    command: Box<Commands>,
    config_override: Option<PathBuf>,
    plan_options: Option<PlanOptions>,
}

impl PreparedContext {
    fn new(command: Commands, config_override: Option<&Path>) -> RailResult<Self> {
        Ok(Self {
            command: Box::new(command),
            config_override: config_override.map(Path::to_path_buf),
            plan_options: None,
        })
    }

    fn new_plan(command: Commands, config_override: Option<&Path>, plan_options: PlanOptions) -> Self {
        Self {
            command: Box::new(command),
            config_override: config_override.map(Path::to_path_buf),
            plan_options: Some(plan_options),
        }
    }

    /// Build the exact workspace context required by this command.
    #[doc(hidden)]
    pub fn build(mut self, workspace_root: &Path) -> RailResult<(Commands, WorkspaceContext, Option<PlanOptions>)> {
        let historical = self
            .plan_options
            .as_ref()
            .map(|options| options.comparison.resolve_objects_before_context(workspace_root))
            .transpose()?
            .flatten();
        let context = if let Some((from, to)) = historical {
            let context = WorkspaceContext::build_historical_planning_with_config(
                workspace_root,
                &from,
                &to,
                self.config_override.as_deref(),
            );
            if let Some(options) = self.plan_options.as_mut() {
                options.comparison.replace_objects(from, to);
            }
            context
        } else if self.command.requires_workspace_snapshot() {
            WorkspaceContext::build_with_snapshot_and_config(workspace_root, self.config_override.as_deref())
        } else if self.command.requires_planning_source_capture() {
            WorkspaceContext::build_with_planning_capture_and_config(workspace_root, self.config_override.as_deref())
        } else {
            WorkspaceContext::build_with_source_capture_and_config(
                workspace_root,
                self.command.requires_worktree_source_capture(),
                self.config_override.as_deref(),
            )
        };
        Ok((*self.command, context?, self.plan_options))
    }
}

/// Handle commands that don't need WorkspaceContext.
///
/// Centralizes "pre-context" routing so `main.rs` stays thin.
#[doc(hidden)]
pub fn try_dispatch_pre_context(
    cmd: Commands,
    workspace_root: &Path,
    config_override: Option<&Path>,
    json: bool,
) -> RailResult<PreContextDispatch> {
    match cmd {
        Commands::Plan {
            verify: Some(plan_file),
            ..
        } => {
            plan::verify_saved_plan(workspace_root, config_override, &plan_file)?;
            Ok(PreContextDispatch::Handled)
        }

        Commands::Plan { schema: true, .. } => {
            plan::print_plan_schema();
            Ok(PreContextDispatch::Handled)
        }

        Commands::Plan {
            since,
            from,
            to,
            json,
            explain,
            explain_work,
            all,
            evidence,
            verify: None,
            schema: false,
        } => {
            let comparison = plan::PlanComparison::from_cli(&since, &from, &to)?;
            let command = Commands::Plan {
                since,
                from,
                to,
                json,
                explain,
                explain_work: explain_work.clone(),
                all,
                evidence: evidence.clone(),
                verify: None,
                schema: false,
            };
            Ok(PreContextDispatch::NeedsContext(PreparedContext::new_plan(
                command,
                config_override,
                PlanOptions {
                    comparison,
                    json,
                    explain,
                    explain_work,
                    all,
                    evidence,
                },
            )))
        }

        Commands::Surface { schema: true, .. } => {
            surface::print_surface_schema();
            Ok(PreContextDispatch::Handled)
        }

        command @ Commands::Surface { .. } => {
            crate::compiler::driver::CompilerFactDriverAuthority::require_surface_installation()?;
            Ok(PreContextDispatch::NeedsContext(PreparedContext::new(
                command,
                config_override,
            )?))
        }

        Commands::Init {
            output,
            force,
            dry_run,
            targets,
            detect_targets,
        } => {
            init::run_init_standalone(workspace_root, &output, force, dry_run, json, &targets, detect_targets)?;
            Ok(PreContextDispatch::Handled)
        }

        Commands::Unify {
            command:
                Some(cli::UnifyCommand::Undo {
                    list,
                    backup_id,
                    format,
                }),
            ..
        } => {
            unify::run_unify_undo(workspace_root, list, backup_id, format)?;
            Ok(PreContextDispatch::Handled)
        }

        Commands::Config { command } => {
            match command.unwrap_or(cli::ConfigCommand::Explain {
                fields: Vec::new(),
                all: false,
                format: common::TextJsonOutputFormat::Text,
            }) {
                cli::ConfigCommand::Validate {
                    format,
                    strict,
                    no_strict,
                } => {
                    let strictness = if strict {
                        StrictnessMode::Strict
                    } else if no_strict {
                        StrictnessMode::NoStrict
                    } else {
                        StrictnessMode::Auto
                    };
                    config::run_config_validate_standalone(workspace_root, config_override, format, strictness)?;
                }
                cli::ConfigCommand::Locate { format } => {
                    config::run_config_locate(workspace_root, config_override, format)?
                }
                cli::ConfigCommand::Print { format } => {
                    config::run_config_print(workspace_root, config_override, format)?
                }
                cli::ConfigCommand::Explain { fields, all, format } => {
                    config::run_config_explain(workspace_root, config_override, &fields, all, format)?
                }
            }
            Ok(PreContextDispatch::Handled)
        }

        Commands::Completions { shell } => {
            cli::generate_completions(shell);
            Ok(PreContextDispatch::Handled)
        }

        Commands::Clean {
            all,
            cache,
            prune_backups,
            all_backups,
            reports,
            release_journal,
            check,
            format,
        } => {
            let context = clean::CleanContext::capture(workspace_root, config_override)?;
            run_clean(
                &context,
                clean::CleanOptions {
                    all,
                    cache,
                    prune_backups,
                    all_backups,
                    reports,
                    release_journal,
                    check,
                    format,
                },
            )?;
            Ok(PreContextDispatch::Handled)
        }

        Commands::Cache { command } => {
            match command {
                cli::CacheCommand::Setup(setup) => {
                    let cli::CacheSetupArgs {
                        profile,
                        local_dir,
                        max_size,
                        remote,
                        remote_mode,
                        remote_environment,
                        root_portability,
                        local_only,
                        distributed_local,
                        distributed_endpoint,
                        distributed_server_name,
                        distributed_capability,
                        distributed_authority,
                        distributed_client_certificate,
                        distributed_client_private_key,
                        distributed_policy,
                        check,
                        format,
                    } = *setup;
                    cache::run_setup(
                        workspace_root,
                        crate::cache::installation::SetupRequest {
                            profile_id: profile,
                            local_dir,
                            max_bytes: max_size,
                            remote_url: remote,
                            remote_mode,
                            remote_environment,
                            root_portability,
                            local_only,
                            distributed_local,
                            distributed_endpoint,
                            distributed_server_name,
                            distributed_capability,
                            distributed_authority,
                            distributed_client_certificate,
                            distributed_client_private_key,
                            distributed_policy,
                        },
                        check,
                        format,
                    )?;
                }
                cli::CacheCommand::Normalize {
                    url,
                    mode,
                    environment,
                    format,
                } => cache::run_normalize(&url, mode.as_deref(), environment, format)?,
                cli::CacheCommand::Probe { format } => cache::run_probe(workspace_root, format)?,
                cli::CacheCommand::Report { start, finish, format } => {
                    cache::run_report(start.as_deref(), finish.as_deref(), format)?
                }
                cli::CacheCommand::Status { scope, format } => cache::run_status(workspace_root, scope, format)?,
                cli::CacheCommand::Profiles { format } => cache::run_profiles(workspace_root, format)?,
                cli::CacheCommand::Detach { check, format } => {
                    cache::run_detach(workspace_root, check, format)?;
                }
                cli::CacheCommand::DropProfile { profile, check, format } => {
                    cache::run_drop_profile(workspace_root, &profile, check, format)?;
                }

                cli::CacheCommand::Recover { check, format } => {
                    cache::run_recover(workspace_root, check, format)?;
                }
                cli::CacheCommand::Clean { scope, check, format } => {
                    cache::run_clean(workspace_root, scope, check, format)?;
                }
                cli::CacheCommand::Uninstall { check, format } => {
                    cache::run_uninstall(workspace_root, check, format)?;
                }
            }
            Ok(PreContextDispatch::Handled)
        }

        Commands::Release {
            command: cli::ReleaseCommand::Record { command },
        } => {
            let result = match command {
                cli::ReleaseRecordCommand::Inspect { transaction } => {
                    let path = crate::release::state::resolve_active(workspace_root, Some(&transaction))?;
                    serde_json::to_value(crate::release::state::ReleaseState::load(&path)?)?
                }
                cli::ReleaseRecordCommand::Store { transaction } => {
                    crate::release::transfer::store(workspace_root, &transaction)?
                }
                cli::ReleaseRecordCommand::Fetch { transaction } => {
                    crate::release::transfer::fetch(workspace_root, transaction.as_deref())?
                }
                cli::ReleaseRecordCommand::Export { transaction, directory } => {
                    crate::release::transfer::export(workspace_root, &transaction, &directory)?
                }
                cli::ReleaseRecordCommand::Import {
                    directory,
                    intent,
                    source,
                } => crate::release::transfer::import(workspace_root, &directory, &intent, &source)?,
            };
            println!("{}", serde_json::to_string(&result)?);
            Ok(PreContextDispatch::Handled)
        }

        Commands::Release {
            command: cli::ReleaseCommand::Status { state, history, format },
        } => {
            release::run_release_status_standalone(workspace_root, state.as_deref(), history, format)?;
            Ok(PreContextDispatch::Handled)
        }

        Commands::Release {
            command: cli::ReleaseCommand::Resume { transaction, executor },
        } => {
            crate::release::hosted::refresh(workspace_root, transaction.as_deref())?;
            let state = crate::release::state::resolve_active(workspace_root, transaction.as_deref())?;
            let retained = crate::release::state::ReleaseState::load(&state)?;
            if executor {
                crate::release::hosted::checkout(workspace_root, &retained)?;
            }
            if !retained.intent.hosted || executor {
                crate::release::state::prepare_recovery(workspace_root, &state)?;
            }
            Ok(PreContextDispatch::NeedsContext(PreparedContext::new(
                Commands::Release {
                    command: cli::ReleaseCommand::Resume { transaction, executor },
                },
                config_override,
            )?))
        }

        Commands::Release {
            command: cli::ReleaseCommand::Abort { transaction, yes },
        } => {
            let state = crate::release::state::resolve_active(workspace_root, transaction.as_deref())?;
            crate::release::state::prepare_recovery(workspace_root, &state)?;
            Ok(PreContextDispatch::NeedsContext(PreparedContext::new(
                Commands::Release {
                    command: cli::ReleaseCommand::Abort { transaction, yes },
                },
                config_override,
            )?))
        }

        other => Ok(PreContextDispatch::NeedsContext(PreparedContext::new(
            other,
            config_override,
        )?)),
    }
}

/// Dispatch a command to its handler
///
/// This is the main command routing logic. It takes a parsed `Commands` enum
/// and the workspace context, then calls the appropriate handler.
pub fn dispatch(cmd: Commands, ctx: &WorkspaceContext, prepared_plan: Option<PlanOptions>) -> RailResult<()> {
    match cmd {
        Commands::Doctor {
            command: cli::DoctorCommand::NativeCache { format },
        } => run_native_cache_doctor(ctx, format),

        Commands::Plan { .. } => run_plan(
            ctx,
            prepared_plan.ok_or_else(|| crate::error::RailError::message("plan comparison was not prepared"))?,
        ),

        Commands::Surface {
            prepare,
            check,
            fix,
            resume,
            dry_run,
            backup,
            format,
            output,
            explain,
            only,
            schema: _,
        } => run_surface(
            ctx,
            SurfaceOptions {
                prepare,
                check,
                fix,
                resume,
                dry_run,
                backup,
                format,
                output,
                explain,
                only,
            },
        ),

        // Init is handled before WorkspaceContext is built
        Commands::Init { .. } => Err(crate::error::RailError::message(
            "init command reached workspace dispatch",
        )),

        // Dependency Unification
        Commands::Unify {
            command,
            check,
            format,
            report,
            report_path,
            output,
            show_diff,
            explain,
        } => match command {
            Some(cli::UnifyCommand::Doctor { format }) => run_unify_doctor(ctx, format),
            Some(cli::UnifyCommand::Apply {
                plan,
                backup,
                report,
                report_path,
                format,
            }) => run_unify_apply(ctx, backup, !report, report_path, plan, format),
            Some(cli::UnifyCommand::Undo { .. }) => Err(crate::error::RailError::message(
                "unify undo reached workspace dispatch",
            )),
            None => {
                if !check {
                    crate::warn!(
                        "bare 'cargo rail unify' is preview-only; use 'cargo rail unify apply' to modify manifests"
                    );
                }
                run_unify_analyze(
                    ctx,
                    UnifyAnalyzeOptions {
                        check,
                        show_diff,
                        explain,
                        format,
                        output: output.as_ref(),
                        backup: false,
                        no_report: !report,
                        report_path: report_path.as_ref(),
                    },
                )
            }
        },

        // Split/Sync
        Commands::Split { command } => match command {
            cli::SplitCommand::Init { crate_names, dry_run } => {
                let crates = if crate_names.is_empty() {
                    None
                } else {
                    Some(crate_names)
                };
                run_split_init(ctx, crates, dry_run)
            }
            cli::SplitCommand::Run {
                crate_name,
                all,
                remote,
                check,
                plan,
                allow_dirty,
                yes,
                format,
            } => run_split(
                ctx,
                split::SplitRunArgs {
                    crate_name,
                    all,
                    remote,
                    check,
                    plan_path: plan,
                    allow_dirty,
                    yes,
                    format,
                },
            ),
        },

        Commands::Sync {
            crate_name,
            all,
            remote,
            from_remote,
            to_remote,
            strategy,
            check,
            plan,
            resume,
            allow_dirty,
            yes,
            format,
        } => run_sync(
            ctx,
            sync::SyncArgs {
                crate_name,
                all,
                remote,
                from_remote,
                to_remote,
                strategy,
                check,
                plan_path: plan,
                resume,
                allow_dirty,
                yes,
                format,
            },
        ),

        Commands::Change { command } => match command {
            cli::ChangeCommand::Add {
                crate_names,
                bump,
                message,
                name,
                format,
            } => run_change_add(ctx, crate_names, bump, message, name, format),
            cli::ChangeCommand::Status { format } => run_change_status(ctx, format),
            cli::ChangeCommand::Check {
                since,
                merge_base,
                all,
                format,
            } => run_change_check(
                ctx,
                ChangeCheckOptions {
                    since,
                    merge_base,
                    all,
                    format,
                },
            ),
        },

        // Release
        Commands::Release { command } => match command {
            cli::ReleaseCommand::Init { crate_names, dry_run } => {
                let crates = if crate_names.is_empty() {
                    None
                } else {
                    Some(crate_names)
                };
                run_release_init(ctx, crates, dry_run)
            }
            cli::ReleaseCommand::Run {
                crate_names,
                all,
                bump,
                plan,
                publish,
                skip_tag,
                pr,
                local,
                executor,
                prepare,
                retain_remote,
                include_dependents,
                yes,
                allow_non_default_branch,
                format,
            } => {
                let names = if all || crate_names.is_empty() {
                    None
                } else {
                    Some(crate_names)
                };

                run_release_publish(
                    ctx,
                    release::ReleasePublishArgs {
                        crate_names: names,
                        all,
                        bump,
                        publish,
                        skip_tag,
                        pr,
                        local,
                        executor,
                        prepare,
                        retain_remote,
                        include_dependents,
                        yes,
                        allow_non_default_branch,
                        plan_path: plan,
                        format,
                    },
                )
            }
            cli::ReleaseCommand::Check {
                crate_names,
                all,
                bump,
                publication,
                extended,
                skip_tag,
                include_dependents,
                format,
            } => {
                let names = if all || crate_names.is_empty() {
                    None
                } else {
                    Some(crate_names)
                };
                if publication {
                    release::run_release_publication_check_with_plan_inputs(
                        ctx,
                        release::ReleasePublicationCheckArgs {
                            crate_names: names,
                            all,
                            bump,
                            extended,
                            skip_tag,
                            include_dependents,
                            format,
                        },
                    )
                } else {
                    run_release_plan(ctx, names, bump, false, skip_tag, include_dependents, format)
                }
            }
            cli::ReleaseCommand::Resume { transaction, executor } => {
                release::run_release_resume(ctx, transaction.as_deref(), executor)
            }
            cli::ReleaseCommand::Status { .. } | cli::ReleaseCommand::Record { .. } => Err(
                crate::error::RailError::message("release status reached workspace dispatch"),
            ),
            cli::ReleaseCommand::Abort { transaction, yes } => {
                release::run_release_abort(ctx, transaction.as_deref(), yes)
            }
        },

        // Clean
        Commands::Clean { .. } => Err(crate::error::RailError::message(
            "clean command reached workspace dispatch",
        )),

        Commands::Cache { .. } => Err(crate::error::RailError::message(
            "cache command reached workspace dispatch",
        )),

        // Config commands are handled before WorkspaceContext is built
        Commands::Config { .. } => Err(crate::error::RailError::message(
            "config command reached workspace dispatch",
        )),

        // Completions is handled before WorkspaceContext is built
        Commands::Completions { .. } => Err(crate::error::RailError::message(
            "completions command reached workspace dispatch",
        )),
    }
}