cargo-promote 0.1.2

Publish crates to minibox registry and promote to crates.io
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
pub mod config;
pub mod domain;
pub mod infra;

use std::collections::{HashMap, HashSet};
use std::path::Path;

use anyhow::{Context, Result};

use config::Config;
use domain::deferral::{Deferral, DeferralKind, DeferralStatus};
use domain::depgraph;
use domain::manifest::{self, ManifestDescription};
use domain::pipeline::PipelineEngine;
use domain::traits::{Forge, NoopForge, Notifier, PipelineRunner, RegistryQuery};
use domain::version;
use domain::{CrateInfo, CrateRef, Pipeline, PublishOpts, Stage};
use infra::cargo::CargoPublisher;
use infra::git::gitea::GiteaRegistry;
use infra::token::CargoTokenResolver;

/// If autobump is configured, bump the manifest version and return an
/// updated CrateRef.
pub fn maybe_autobump(krate: CrateRef, cfg: &Config) -> Result<CrateRef> {
    let per_pkg = cfg.package_override(&krate.name).and_then(|o| o.autobump);
    let Some(level) = per_pkg.or(cfg.autobump) else {
        return Ok(krate);
    };
    let (old, new) = version::bump_manifest_version(&krate.manifest_path, level)?;
    eprintln!("=> autobump: {} v{old} -> v{new}", krate.name);
    Ok(CrateRef {
        version: new.to_string(),
        ..krate
    })
}

/// Library API for driving promotion pipelines programmatically.
pub struct Api {
    config: Config,
    engine: Box<dyn PipelineRunner>,
    registry_query: Box<dyn RegistryQuery>,
    notifier: Box<dyn Notifier>,
    forge: Box<dyn Forge>,
}

/// Builder for `Api` with injectable dependencies.
pub struct ApiBuilder {
    config: Option<Config>,
    engine: Option<Box<dyn PipelineRunner>>,
    registry_query: Option<Box<dyn RegistryQuery>>,
    notifier: Option<Box<dyn Notifier>>,
    forge: Option<Box<dyn Forge>>,
}

impl ApiBuilder {
    pub fn config(mut self, config: Config) -> Self {
        self.config = Some(config);
        self
    }

    pub fn engine(mut self, engine: Box<dyn PipelineRunner>) -> Self {
        self.engine = Some(engine);
        self
    }

    pub fn registry_query(mut self, query: Box<dyn RegistryQuery>) -> Self {
        self.registry_query = Some(query);
        self
    }

    pub fn notifier(mut self, notifier: Box<dyn Notifier>) -> Self {
        self.notifier = Some(notifier);
        self
    }

    pub fn forge(mut self, forge: Box<dyn Forge>) -> Self {
        self.forge = Some(forge);
        self
    }

    pub fn build(self) -> Result<Api> {
        Ok(Api {
            config: self
                .config
                .ok_or_else(|| anyhow::anyhow!("config required"))?,
            engine: self
                .engine
                .ok_or_else(|| anyhow::anyhow!("engine required"))?,
            registry_query: self
                .registry_query
                .ok_or_else(|| anyhow::anyhow!("registry_query required"))?,
            notifier: self
                .notifier
                .ok_or_else(|| anyhow::anyhow!("notifier required"))?,
            forge: self.forge.unwrap_or_else(|| Box::new(NoopForge)),
        })
    }
}

impl Api {
    /// Build with default adapters (CargoPublisher, GiteaRegistry,
    /// NoopNotifier) and auto-accepting confirmer.
    pub fn new(dir: &Path) -> Result<Self> {
        Self::with_confirmer(dir, |_| true)
    }

    /// Build with default adapters and a custom confirmer.
    pub fn with_confirmer(dir: &Path, confirmer: impl Fn(&str) -> bool + 'static) -> Result<Self> {
        let config = Config::load(dir)?;
        let engine = PipelineEngine::new(CargoPublisher, confirmer);
        Ok(Self {
            config,
            engine: Box::new(engine),
            registry_query: Box::new(GiteaRegistry::new(std::sync::Arc::new(
                CargoTokenResolver::new(),
            ))),
            notifier: Box::new(infra::notify::NoopNotifier),
            forge: Box::new(NoopForge),
        })
    }

    /// Build with default adapters, custom confirmer, and a
    /// notification command.
    pub fn with_notifier(
        dir: &Path,
        confirmer: impl Fn(&str) -> bool + 'static,
        command: Vec<String>,
    ) -> Result<Self> {
        let config = Config::load(dir)?;
        let engine = PipelineEngine::new(CargoPublisher, confirmer);
        Ok(Self {
            config,
            engine: Box::new(engine),
            registry_query: Box::new(GiteaRegistry::new(std::sync::Arc::new(
                CargoTokenResolver::new(),
            ))),
            notifier: Box::new(infra::notify::SpawnNotifier { command }),
            forge: Box::new(NoopForge),
        })
    }

    /// Return a builder for full dependency injection.
    pub fn builder() -> ApiBuilder {
        ApiBuilder {
            config: None,
            engine: None,
            registry_query: None,
            notifier: None,
            forge: None,
        }
    }

    /// Access the loaded configuration.
    pub fn config(&self) -> &Config {
        &self.config
    }

    // -- pipeline helpers --

    fn resolve_pipeline(&self, name: Option<&str>) -> Result<&Pipeline> {
        self.config
            .pipeline(name)
            .ok_or_else(|| anyhow::anyhow!("pipeline '{}' not found", name.unwrap_or("default")))
    }

    /// Publish a crate to the first stage of a pipeline (or a named
    /// registry).
    pub fn publish(
        &self,
        path: Option<&Path>,
        package: Option<&str>,
        allow_dirty: bool,
        force: bool,
        pipeline: Option<&str>,
        registry: Option<&str>,
    ) -> Result<()> {
        let krate = manifest::resolve_crate(path, package)?;
        let krate = maybe_autobump(krate, &self.config)?;
        let opts = PublishOpts {
            allow_dirty,
            force,
            ..Default::default()
        };

        if let Some(reg_name) = registry {
            let reg = self
                .config
                .registry(reg_name)
                .ok_or_else(|| anyhow::anyhow!("unknown registry '{reg_name}'"))?;
            let stage = Stage {
                registry: reg.clone(),
            };
            self.engine.run_stage(&krate, &stage, &opts)?;
        } else {
            let pl = self.resolve_pipeline(pipeline)?;
            let first = pl.stages.first().context("pipeline has no stages")?;
            self.engine.run_stage(&krate, first, &opts)?;
        }
        Ok(())
    }

    /// Promote a crate from one pipeline stage to the next.
    pub fn promote(
        &self,
        path: Option<&Path>,
        package: Option<&str>,
        yes: bool,
        dry_run: bool,
        pipeline: Option<&str>,
        from: Option<&str>,
    ) -> Result<()> {
        let krate = manifest::resolve_crate(path, package)?;
        let opts = PublishOpts {
            skip_confirm: yes,
            dry_run,
            ..Default::default()
        };
        let pl = self.resolve_pipeline(pipeline)?;
        let from_stage = from.unwrap_or_else(|| &pl.stages[0].registry.name);
        self.engine.promote_next(&krate, pl, from_stage, &opts)?;
        Ok(())
    }

    /// Run all stages of a pipeline sequentially.
    pub fn ship(
        &self,
        path: Option<&Path>,
        package: Option<&str>,
        allow_dirty: bool,
        yes: bool,
        force: bool,
        pipeline: Option<&str>,
    ) -> Result<()> {
        let krate = manifest::resolve_crate(path, package)?;
        let krate = maybe_autobump(krate, &self.config)?;
        let opts = PublishOpts {
            allow_dirty,
            skip_confirm: yes,
            force,
            ..Default::default()
        };
        let pl = self.resolve_pipeline(pipeline)?;
        self.engine.run_full(&krate, pl, &opts)?;
        Ok(())
    }

    /// List crates in a registry.
    pub fn list(&self, registry: Option<&str>) -> Result<Vec<CrateInfo>> {
        let reg_name = registry.unwrap_or("cratebox");
        let reg = self
            .config
            .registry(reg_name)
            .ok_or_else(|| anyhow::anyhow!("unknown registry '{reg_name}'"))?;
        let crates = self.registry_query.list_crates(reg)?;
        Ok(crates)
    }

    /// Describe local crate versions.
    pub fn status(path: Option<&Path>) -> Result<ManifestDescription> {
        manifest::describe_manifest(path)
    }

    /// Publish all crates under a directory in dependency order.
    pub fn publish_all(
        &self,
        root: &Path,
        allow_dirty: bool,
        dry_run: bool,
        force: bool,
        registry: Option<&str>,
        skip: &[&str],
    ) -> Result<PublishAllResult> {
        let nodes = depgraph::scan_workspace_tree(root, skip)?;
        let publishable: Vec<_> = nodes.iter().filter(|n| !n.unpublishable).collect();
        let order =
            depgraph::topo_sort(&publishable.iter().map(|n| (*n).clone()).collect::<Vec<_>>())?;

        let blocked: Vec<_> = publishable
            .iter()
            .filter(|n| !n.path_only_deps.is_empty())
            .collect();

        let publishable_names: HashSet<&str> = publishable
            .iter()
            .filter(|n| n.path_only_deps.is_empty())
            .filter(|n| {
                self.config
                    .package_override(&n.name)
                    .and_then(|o| o.publish)
                    != Some(false)
            })
            .map(|n| n.name.as_str())
            .collect();

        let publish_order: Vec<String> = order
            .iter()
            .filter(|name| publishable_names.contains(name.as_str()))
            .cloned()
            .collect();

        let blocked_names: Vec<String> = blocked.iter().map(|n| n.name.clone()).collect();

        if dry_run {
            return Ok(PublishAllResult {
                publish_order,
                ok: 0,
                failed: vec![],
                blocked: blocked_names,
            });
        }

        let reg_name = registry.unwrap_or("cratebox");
        let reg = self
            .config
            .registry(reg_name)
            .ok_or_else(|| anyhow::anyhow!("unknown registry '{reg_name}'"))?;
        let stage = Stage {
            registry: reg.clone(),
        };
        let opts = PublishOpts {
            allow_dirty,
            skip_confirm: true,
            force,
            ..Default::default()
        };

        let node_map: HashMap<&str, &depgraph::CrateNode> =
            nodes.iter().map(|n| (n.name.as_str(), n)).collect();

        let mut ok = 0usize;
        let mut failed = Vec::new();
        for name in &publish_order {
            let node = node_map[name.as_str()];
            let krate = CrateRef {
                name: node.name.clone(),
                version: node.version.clone(),
                manifest_path: node.manifest_path.clone(),
            };
            match self.engine.run_stage(&krate, &stage, &opts) {
                Ok(()) => ok += 1,
                Err(e) => {
                    eprintln!("  FAIL: {} -- {}", name, e);
                    failed.push(name.clone());
                }
            }
        }

        Ok(PublishAllResult {
            publish_order,
            ok,
            failed,
            blocked: blocked_names,
        })
    }

    /// Bump version and create promote.lock.
    pub fn bump(&self, path: Option<&Path>, package: Option<&str>, cwd: &Path) -> Result<()> {
        let krate = manifest::resolve_crate(path, package)?;
        let branch_cfg = self
            .config
            .branch_pipeline
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("branch pipeline not configured in promote.toml"))?;
        let repo_path = path.unwrap_or(cwd);
        let git = infra::git::local::LocalGit::new(repo_path.to_path_buf());
        domain::pipeline::BranchPipeline::bump(&krate, &branch_cfg.stages, repo_path, &git)?;
        Ok(())
    }

    /// Branch from one stage to the next.
    pub fn branch(&self, path: Option<&Path>, from: &str, cwd: &Path) -> Result<()> {
        let branch_cfg = self
            .config
            .branch_pipeline
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("branch pipeline not configured in promote.toml"))?;
        let repo_root = path.unwrap_or(cwd);
        let git = infra::git::local::LocalGit::new(repo_root.to_path_buf());
        domain::pipeline::BranchPipeline::branch(&branch_cfg.stages, from, &git, &git, repo_root)?;
        Ok(())
    }

    /// Defer a crate's promotion to the next pipeline stage.
    ///
    /// Creates a pending deferral ticket and fires a notification.
    /// The promotion is provisional until confirmed or rejected.
    pub fn defer_to(
        &self,
        path: Option<&Path>,
        package: Option<&str>,
        from: &str,
        pipeline: Option<&str>,
        repo_root: &Path,
    ) -> Result<Deferral> {
        let krate = manifest::resolve_crate(path, package)?;
        let pl = self.resolve_pipeline(pipeline)?;

        let from_idx = pl
            .stages
            .iter()
            .position(|s| s.registry.name == from)
            .ok_or_else(|| anyhow::anyhow!("unknown stage '{from}' in pipeline"))?;
        let to_stage = pl
            .stages
            .get(from_idx + 1)
            .ok_or_else(|| anyhow::anyhow!("no next stage after '{from}'"))?;

        let source_hash = domain::promote_lock::PromoteLock::compute_source_hash(repo_root)?;

        let ticket = Deferral::ticket_id(&krate.name);
        let now = chrono::Local::now();

        let pr_number = match self.forge.create_pr(
            &format!(
                "promote: {} v{} {} -> {}",
                krate.name, krate.version, from, to_stage.registry.name
            ),
            &format!("Deferred promotion ticket: {ticket}"),
            from,
            &to_stage.registry.name,
        ) {
            Ok(0) => None, // NoopForge returns 0
            Ok(n) => Some(n),
            Err(_) => None, // Best-effort; don't fail defer on forge error
        };

        let deferral = Deferral {
            ticket: ticket.clone(),
            crate_name: krate.name.clone(),
            version: krate.version.clone(),
            from_stage: from.to_string(),
            to_stage: to_stage.registry.name.clone(),
            status: DeferralStatus::Pending,
            kind: DeferralKind::Registry,
            deferred_at: now.format("%Y%m%d.%H%M%S").to_string(),
            source_hash,
            command: vec![],
            reason: String::new(),
            pr_number,
        };

        deferral.write(repo_root)?;
        self.notifier.on_deferred(&deferral)?;
        Ok(deferral)
    }

    /// Defer a branch promotion (merge from one stage branch to the
    /// next). Verifies the promote.lock hash before creating the
    /// ticket.
    // qual:allow(iosp) reason: "integration root — orchestrates validation + deferral"
    pub fn defer_branch(
        &self,
        path: Option<&Path>,
        package: Option<&str>,
        from: &str,
        repo_root: &Path,
    ) -> Result<Deferral> {
        let krate = manifest::resolve_crate(path, package)?;
        let branch_cfg = self
            .config
            .branch_pipeline
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("branch pipeline not configured in promote.toml"))?;

        let from_idx = branch_cfg
            .stages
            .iter()
            .position(|s| s == from)
            .ok_or_else(|| anyhow::anyhow!("unknown branch stage '{from}'"))?;
        let to_stage = branch_cfg
            .stages
            .get(from_idx + 1)
            .ok_or_else(|| anyhow::anyhow!("no next stage after '{from}'"))?;

        // Verify promote.lock hash before deferring.
        let lock = domain::promote_lock::PromoteLock::read(repo_root)?;
        lock.verify_hash(repo_root)?;

        let ticket = Deferral::ticket_id(&krate.name);
        let now = chrono::Local::now();

        let pr_number = match self.forge.create_pr(
            &format!(
                "promote: {} v{} branch {} -> {}",
                krate.name, krate.version, from, to_stage
            ),
            &format!("Deferred branch promotion ticket: {ticket}"),
            from,
            to_stage,
        ) {
            Ok(0) => None,
            Ok(n) => Some(n),
            Err(_) => None,
        };

        let deferral = Deferral {
            ticket,
            crate_name: krate.name.clone(),
            version: krate.version.clone(),
            from_stage: from.to_string(),
            to_stage: to_stage.clone(),
            status: DeferralStatus::Pending,
            kind: DeferralKind::Branch,
            deferred_at: now.format("%Y%m%d.%H%M%S").to_string(),
            source_hash: lock.source_hash.clone(),
            command: vec![],
            reason: String::new(),
            pr_number,
        };

        deferral.write(repo_root)?;
        self.notifier.on_deferred(&deferral)?;
        Ok(deferral)
    }

    /// Confirm a pending deferral. For branch deferrals, this
    /// automatically executes the merge and push. The ticket is
    /// only marked confirmed after the merge succeeds — if the
    /// merge fails, the ticket remains pending.
    // qual:allow(iosp) reason: "integration root — orchestrates validation + merge + confirm"
    pub fn confirm_deferral(
        &self,
        repo_root: &Path,
        ticket: &str,
        reason: &str,
    ) -> Result<Deferral> {
        let d = Deferral::read(repo_root, ticket)?;
        if d.status != DeferralStatus::Pending {
            anyhow::bail!("deferral '{}' is already {:?}", ticket, d.status,);
        }

        if d.kind == DeferralKind::Branch {
            let branch_cfg =
                self.config.branch_pipeline.as_ref().ok_or_else(|| {
                    anyhow::anyhow!("branch pipeline not configured in promote.toml")
                })?;

            // Re-verify hash before merging.
            let lock = domain::promote_lock::PromoteLock::read(repo_root)?;
            lock.verify_hash(repo_root)?;

            let git = infra::git::local::LocalGit::new(repo_root.to_path_buf());

            // Merge first — only mark confirmed if this succeeds.
            domain::pipeline::BranchPipeline::branch(
                &branch_cfg.stages,
                &d.from_stage,
                &git,
                &git,
                repo_root,
            )?;

            eprintln!(
                "=> branch merge complete: '{}' -> '{}'",
                d.from_stage, d.to_stage,
            );
        }

        // Close associated PR if one exists (best-effort).
        if let Some(pr) = d.pr_number {
            let _ = self.forge.comment_pr(pr, &format!("Confirmed: {reason}"));
            let _ = self.forge.close_pr(pr);
        }

        // Status update happens after side effects succeed.
        let d = Deferral::confirm(repo_root, ticket, reason)?;
        Ok(d)
    }

    /// Reject a pending deferral. No side effects beyond status
    /// update.
    pub fn reject_deferral(repo_root: &Path, ticket: &str, reason: &str) -> Result<Deferral> {
        Deferral::reject(repo_root, ticket, reason)
    }

    /// List all deferrals (optionally filtered to pending only).
    // qual:allow(iosp) reason: "thin delegation with filter flag"
    pub fn deferrals(repo_root: &Path, pending_only: bool) -> Result<Vec<Deferral>> {
        if pending_only {
            Deferral::list_pending(repo_root)
        } else {
            Deferral::list(repo_root)
        }
    }
}

/// Result of a `publish_all` operation.
#[derive(Debug)]
pub struct PublishAllResult {
    /// Crates in topological publish order.
    pub publish_order: Vec<String>,
    /// Number of successfully published crates.
    pub ok: usize,
    /// Names of crates that failed to publish.
    pub failed: Vec<String>,
    /// Names of crates blocked by path-only dependencies.
    pub blocked: Vec<String>,
}