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
use super::traits::{PipelineRunner, Publisher, RegistryQuery};
use super::{CrateRef, Pipeline, PromoteError, PublishOpts, Stage};

/// Drives a crate through pipeline stages.
pub struct PipelineEngine<P: Publisher, Q: RegistryQuery> {
    publisher: P,
    registry_query: Q,
    confirmer: Box<dyn Fn(&str) -> bool>,
}

impl<P: Publisher> PipelineEngine<P, NullRegistryQuery> {
    pub fn new(publisher: P, confirmer: impl Fn(&str) -> bool + 'static) -> Self {
        Self {
            publisher,
            registry_query: NullRegistryQuery,
            confirmer: Box::new(confirmer),
        }
    }
}

impl<P: Publisher, Q: RegistryQuery> PipelineEngine<P, Q> {
    pub fn with_query(
        publisher: P,
        registry_query: Q,
        confirmer: impl Fn(&str) -> bool + 'static,
    ) -> Self {
        Self {
            publisher,
            registry_query,
            confirmer: Box::new(confirmer),
        }
    }

    /// Publish to a single stage.
    pub fn run_stage(
        &self,
        krate: &CrateRef,
        stage: &Stage,
        opts: &PublishOpts,
    ) -> Result<(), PromoteError> {
        // Skip-if-already-published guard
        if !opts.force {
            if let Ok(true) =
                self.registry_query
                    .crate_exists(&stage.registry, &krate.name, &krate.version)
            {
                eprintln!(
                    "=> {} v{} already exists in '{}', skipping (use --force to override)",
                    krate.name, krate.version, stage.registry.name
                );
                return Ok(());
            }
        }

        if stage.registry.confirm && !opts.skip_confirm && !opts.dry_run {
            let prompt = format!(
                "About to publish {} v{} to '{}'. Continue?",
                krate.name, krate.version, stage.registry.name
            );
            if !(self.confirmer)(&prompt) {
                return Err(PromoteError::Aborted);
            }
        }
        self.publisher.publish(krate, &stage.registry, opts)
    }

    /// Run all stages in the pipeline sequentially.
    pub fn run_full(
        &self,
        krate: &CrateRef,
        pipeline: &Pipeline,
        opts: &PublishOpts,
    ) -> Result<(), PromoteError> {
        for stage in &pipeline.stages {
            self.run_stage(krate, stage, opts)?;
        }
        Ok(())
    }

    /// Advance from `current_stage` to the next stage in the pipeline.
    pub fn promote_next(
        &self,
        krate: &CrateRef,
        pipeline: &Pipeline,
        current_stage: &str,
        opts: &PublishOpts,
    ) -> Result<(), PromoteError> {
        let idx = pipeline
            .stages
            .iter()
            .position(|s| s.registry.name == current_stage)
            .ok_or_else(|| PromoteError::StageNotFound {
                pipeline: pipeline.name.clone(),
                stage: current_stage.to_string(),
            })?;

        let next = pipeline
            .stages
            .get(idx + 1)
            .ok_or_else(|| PromoteError::NoNextStage {
                pipeline: pipeline.name.clone(),
                stage: current_stage.to_string(),
            })?;

        self.run_stage(krate, next, opts)
    }
}

impl<P: Publisher, Q: RegistryQuery> PipelineRunner for PipelineEngine<P, Q> {
    fn run_stage(
        &self,
        krate: &CrateRef,
        stage: &Stage,
        opts: &PublishOpts,
    ) -> Result<(), PromoteError> {
        PipelineEngine::run_stage(self, krate, stage, opts)
    }

    fn run_full(
        &self,
        krate: &CrateRef,
        pipeline: &Pipeline,
        opts: &PublishOpts,
    ) -> Result<(), PromoteError> {
        PipelineEngine::run_full(self, krate, pipeline, opts)
    }

    fn promote_next(
        &self,
        krate: &CrateRef,
        pipeline: &Pipeline,
        current_stage: &str,
        opts: &PublishOpts,
    ) -> Result<(), PromoteError> {
        PipelineEngine::promote_next(self, krate, pipeline, current_stage, opts)
    }
}

/// A no-op registry query that always returns `false` for `crate_exists`.
pub struct NullRegistryQuery;

impl RegistryQuery for NullRegistryQuery {
    fn list_crates(
        &self,
        registry: &super::Registry,
    ) -> Result<Vec<super::CrateInfo>, PromoteError> {
        let _ = registry;
        Ok(vec![])
    }
}

/// Drives a crate through git branch-based stages.
pub struct BranchPipeline;

impl BranchPipeline {
    /// Run a bump operation (version bump + promote.lock creation + commit/push).
    pub fn bump(
        krate: &CrateRef,
        stages: &[String],
        repo_path: &std::path::Path,
        git: &crate::infra::git::local::LocalGit,
    ) -> Result<(), PromoteError> {
        use crate::domain::promote_lock::PromoteLock;

        let (old_version, new_version) = crate::domain::version::bump_manifest_version(
            &krate.manifest_path,
            crate::domain::version::BumpLevel::Patch,
        )
        .map_err(PromoteError::Other)?;

        eprintln!("=> bumped {} v{old_version} -> v{new_version}", krate.name);

        let source_hash =
            PromoteLock::compute_source_hash(repo_path).map_err(PromoteError::Other)?;

        let entered_pipeline = stages.first().cloned().unwrap_or_default();
        let lock = PromoteLock {
            version: new_version.to_string(),
            source_hash,
            bumped_at: chrono::Local::now().format("%Y%m%d::%H%M%S").to_string(),
            entered_pipeline,
        };

        lock.write(repo_path).map_err(PromoteError::Other)?;

        git.stage(&["Cargo.toml", "promote.lock"])?;
        git.commit(&format!("bump: {} v{}", krate.name, new_version))?;
        git.push_head()?;

        Ok(())
    }

    /// Branch from one stage to the next (with hash verification).
    // qual:allow(iosp) reason: "integration root — orchestrates verify + merge + push"
    pub fn branch(
        stages: &[String],
        from_stage: &str,
        merger: &dyn crate::domain::traits::BranchMerger,
        pusher: &dyn crate::domain::traits::RemotePusher,
        repo_path: &std::path::Path,
    ) -> Result<(), PromoteError> {
        use crate::domain::promote_lock::PromoteLock;

        // Find the next stage
        let from_idx = stages
            .iter()
            .position(|s| s == from_stage)
            .ok_or_else(|| PromoteError::Other(anyhow::anyhow!("unknown stage '{from_stage}'")))?;

        let to_stage = stages.get(from_idx + 1).ok_or_else(|| {
            PromoteError::Other(anyhow::anyhow!("no next stage after '{from_stage}'"))
        })?;

        // Read and verify promote.lock
        let lock = PromoteLock::read(repo_path).map_err(PromoteError::Other)?;

        lock.verify_hash(repo_path).map_err(PromoteError::Other)?;

        eprintln!("=> hash verified, merging '{from_stage}' -> '{to_stage}'");

        // Perform fast-forward merge
        merger.fast_forward(from_stage, to_stage)?;

        // Push the target branch
        pusher.push_branch(to_stage)?;

        eprintln!("=> {to_stage} updated and pushed");

        Ok(())
    }

    /// Publish (create git tag on release branch).
    pub fn publish(
        krate: &CrateRef,
        _release_branch: &str,
        tagger: &dyn crate::domain::traits::Tagger,
        pusher: &dyn crate::domain::traits::RemotePusher,
    ) -> Result<(), PromoteError> {
        let tag = format!("v{}", krate.version);
        let message = format!("Release {} v{}", krate.name, krate.version);

        tagger.create_tag(&tag, &message)?;
        eprintln!("=> created tag '{tag}'");

        pusher.push_tag(&tag)?;
        eprintln!("=> pushed tag '{tag}'");

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain::traits::Publisher;
    use crate::domain::{CrateRef, PublishOpts, Registry, Stage};
    use std::cell::RefCell;
    use std::path::PathBuf;

    struct RecordingPublisher {
        published_to: RefCell<Vec<String>>,
    }

    impl RecordingPublisher {
        fn new() -> Self {
            Self {
                published_to: RefCell::new(Vec::new()),
            }
        }

        fn published(&self) -> Vec<String> {
            self.published_to.borrow().clone()
        }
    }

    impl Publisher for RecordingPublisher {
        fn publish(
            &self,
            _krate: &CrateRef,
            registry: &Registry,
            _opts: &PublishOpts,
        ) -> Result<(), PromoteError> {
            self.published_to.borrow_mut().push(registry.name.clone());
            Ok(())
        }
    }

    fn test_crate() -> CrateRef {
        CrateRef {
            name: "test-crate".to_string(),
            version: "0.1.0".to_string(),
            manifest_path: PathBuf::from("Cargo.toml"),
        }
    }

    fn reg(name: &str, confirm: bool) -> Registry {
        Registry {
            name: name.to_string(),
            cargo_name: Some(name.to_string()),
            api_url: None,
            confirm,
        }
    }

    fn two_stage_pipeline() -> Pipeline {
        Pipeline {
            name: "default".to_string(),
            stages: vec![
                Stage {
                    registry: reg("staging", false),
                },
                Stage {
                    registry: reg("production", true),
                },
            ],
        }
    }

    #[test]
    fn run_full_publishes_all_stages_in_order() {
        let pub_ = RecordingPublisher::new();
        let engine = PipelineEngine::new(&pub_, |_| true);
        let opts = PublishOpts {
            skip_confirm: true,
            ..Default::default()
        };

        engine
            .run_full(&test_crate(), &two_stage_pipeline(), &opts)
            .expect("should succeed");

        assert_eq!(pub_.published(), vec!["staging", "production"]);
    }

    #[test]
    fn run_stage_with_confirm_aborts_on_deny() {
        let pub_ = RecordingPublisher::new();
        let engine = PipelineEngine::new(&pub_, |_| false);
        let stage = Stage {
            registry: reg("production", true),
        };

        let result = engine.run_stage(&test_crate(), &stage, &PublishOpts::default());
        assert!(matches!(result, Err(PromoteError::Aborted)));
        assert!(pub_.published().is_empty());
    }

    #[test]
    fn run_stage_skips_confirm_when_flag_set() {
        let pub_ = RecordingPublisher::new();
        let engine = PipelineEngine::new(&pub_, |_| panic!("should not be called"));
        let stage = Stage {
            registry: reg("production", true),
        };
        let opts = PublishOpts {
            skip_confirm: true,
            ..Default::default()
        };

        engine
            .run_stage(&test_crate(), &stage, &opts)
            .expect("should succeed");
        assert_eq!(pub_.published(), vec!["production"]);
    }

    #[test]
    fn promote_next_advances_to_correct_stage() {
        let pub_ = RecordingPublisher::new();
        let engine = PipelineEngine::new(&pub_, |_| true);
        let opts = PublishOpts {
            skip_confirm: true,
            ..Default::default()
        };

        engine
            .promote_next(&test_crate(), &two_stage_pipeline(), "staging", &opts)
            .expect("should succeed");

        assert_eq!(pub_.published(), vec!["production"]);
    }

    #[test]
    fn promote_next_errors_on_unknown_stage() {
        let pub_ = RecordingPublisher::new();
        let engine = PipelineEngine::new(&pub_, |_| true);

        let result = engine.promote_next(
            &test_crate(),
            &two_stage_pipeline(),
            "nonexistent",
            &PublishOpts::default(),
        );
        assert!(matches!(result, Err(PromoteError::StageNotFound { .. })));
    }

    #[test]
    fn pipeline_engine_implements_pipeline_runner() {
        let pub_ = RecordingPublisher::new();
        let engine = PipelineEngine::new(&pub_, |_| true);
        let runner: &dyn crate::domain::traits::PipelineRunner = &engine;
        let opts = PublishOpts {
            skip_confirm: true,
            ..Default::default()
        };
        runner
            .run_stage(
                &test_crate(),
                &Stage {
                    registry: reg("staging", false),
                },
                &opts,
            )
            .expect("should succeed via trait object");
        assert_eq!(pub_.published(), vec!["staging"]);
    }

    #[test]
    fn promote_next_errors_on_last_stage() {
        let pub_ = RecordingPublisher::new();
        let engine = PipelineEngine::new(&pub_, |_| true);

        let result = engine.promote_next(
            &test_crate(),
            &two_stage_pipeline(),
            "production",
            &PublishOpts::default(),
        );
        assert!(matches!(result, Err(PromoteError::NoNextStage { .. })));
    }
}