homeboy 0.70.0

CLI for multi-component deployment and development workflow automation
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
use clap::{Args, ValueEnum};
use homeboy::log_status;
use serde::Serialize;

use homeboy::component;
use homeboy::deploy::{self, DeployConfig};
use homeboy::release::{self, ReleasePlan, ReleaseRun};

use super::args::{DryRunArgs, HiddenJsonArgs, PositionalComponentArgs};
use super::{CmdResult, ProjectsSummary};

#[derive(Clone, ValueEnum)]
pub enum BumpType {
    Patch,
    Minor,
    Major,
}

impl BumpType {
    pub fn as_str(&self) -> &'static str {
        match self {
            BumpType::Patch => "patch",
            BumpType::Minor => "minor",
            BumpType::Major => "major",
        }
    }
}

#[derive(Args)]
pub struct ReleaseArgs {
    #[command(flatten)]
    comp: PositionalComponentArgs,

    /// Version bump type (patch, minor, major) — not needed with --recover
    #[arg(
        value_name = "BUMP_TYPE",
        ignore_case = true,
        required_unless_present = "recover"
    )]
    bump_type: Option<BumpType>,

    #[command(flatten)]
    dry_run_args: DryRunArgs,

    #[command(flatten)]
    _json: HiddenJsonArgs,

    /// Deploy to all projects using this component after release
    #[arg(long)]
    deploy: bool,

    /// Recover from an interrupted release (tag + push current version)
    #[arg(long, conflicts_with = "bump_type")]
    recover: bool,

    /// Skip pre-release lint and test checks
    #[arg(long)]
    skip_checks: bool,

    /// Allow bump type lower than commit-derived semver recommendation
    #[arg(long)]
    allow_underbump: bool,

    /// Skip publish/package steps (version bump + tag + push only).
    /// Use when CI handles publishing after the tag is pushed.
    #[arg(long)]
    skip_publish: bool,
}

#[derive(Serialize)]
pub struct DeploymentResult {
    pub projects: Vec<ProjectDeployResult>,
    pub summary: ProjectsSummary,
}

#[derive(Serialize)]
pub struct ProjectDeployResult {
    pub project_id: String,
    pub status: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub component_result: Option<homeboy::deploy::ComponentDeployResult>,
}

#[derive(Serialize)]
#[serde(tag = "command", rename = "release")]
pub struct ReleaseOutput {
    pub result: ReleaseResult,
}

#[derive(Serialize)]
pub struct ReleaseResult {
    pub component_id: String,
    pub bump_type: String,
    pub dry_run: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub plan: Option<ReleasePlan>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub run: Option<ReleaseRun>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deployment: Option<DeploymentResult>,
}

pub fn run(args: ReleaseArgs, _global: &crate::commands::GlobalArgs) -> CmdResult<ReleaseOutput> {
    let component_id = args.comp.id().to_string();

    if args.recover {
        return run_recover(&args.comp);
    }

    let bump_type = args.bump_type.ok_or_else(|| {
        homeboy::Error::validation_missing_argument(vec!["bump_type".to_string()])
    })?;
    let options = release::ReleaseOptions {
        bump_type: bump_type.as_str().to_string(),
        dry_run: args.dry_run_args.dry_run,
        path_override: args.comp.path.clone(),
        skip_checks: args.skip_checks,
        allow_underbump: args.allow_underbump,
        skip_publish: args.skip_publish,
    };

    if args.dry_run_args.dry_run {
        let plan = release::plan(&component_id, &options)?;

        let deployment = if args.deploy {
            Some(plan_deployment(&component_id))
        } else {
            None
        };

        Ok((
            ReleaseOutput {
                result: ReleaseResult {
                    component_id,
                    bump_type: options.bump_type,
                    dry_run: true,
                    plan: Some(plan),
                    run: None,
                    deployment,
                },
            },
            0,
        ))
    } else {
        let run_result = release::run(&component_id, &options)?;
        display_release_summary(&run_result);

        // Exit code 3 when release succeeded but post-release hooks failed.
        // Distinct from 1 (release failure) so callers can distinguish.
        let post_release_exit = if has_post_release_warnings(&run_result) {
            3
        } else {
            0
        };

        let (deployment, deploy_exit_code) = if args.deploy {
            execute_deployment(&component_id)
        } else {
            (None, 0)
        };

        // deploy failure (1) takes priority over post-release warning (3)
        let exit_code = if deploy_exit_code != 0 {
            deploy_exit_code
        } else {
            post_release_exit
        };

        Ok((
            ReleaseOutput {
                result: ReleaseResult {
                    component_id,
                    bump_type: options.bump_type,
                    dry_run: false,
                    plan: None,
                    run: Some(run_result),
                    deployment,
                },
            },
            exit_code,
        ))
    }
}

/// Displays release success summary to stderr.
pub fn display_release_summary(run: &ReleaseRun) {
    if let Some(ref summary) = run.result.summary {
        if !summary.success_summary.is_empty() {
            eprintln!();
            for line in &summary.success_summary {
                log_status!("release", "{}", line);
            }
        }
    }
}

/// Returns true if any post-release step had hook failures.
/// Checks the structured `all_succeeded` field in the step data.
pub fn has_post_release_warnings(run: &ReleaseRun) -> bool {
    run.result.steps.iter().any(|step| {
        step.step_type == "post_release"
            && step
                .data
                .as_ref()
                .and_then(|d| d.get("all_succeeded"))
                .and_then(|v| v.as_bool())
                == Some(false)
    })
}

fn plan_deployment(component_id: &str) -> DeploymentResult {
    let projects = component::projects_using(component_id).unwrap_or_default();

    if projects.is_empty() {
        log_status!(
            "release",
            "Warning: No projects use component '{}'. Nothing to deploy.",
            component_id
        );
    }

    let project_results: Vec<ProjectDeployResult> = projects
        .iter()
        .map(|project_id| ProjectDeployResult {
            project_id: project_id.clone(),
            status: "planned".to_string(),
            error: None,
            component_result: None,
        })
        .collect();

    let total = project_results.len() as u32;
    DeploymentResult {
        projects: project_results,
        summary: ProjectsSummary {
            total_projects: total,
            succeeded: 0,
            failed: 0,
            skipped: 0,
            planned: 0,
        },
    }
}

fn execute_deployment(component_id: &str) -> (Option<DeploymentResult>, i32) {
    let projects = component::projects_using(component_id).unwrap_or_default();

    if projects.is_empty() {
        log_status!(
            "release",
            "Warning: No projects use component '{}'. Nothing to deploy.",
            component_id
        );
        return (
            Some(DeploymentResult {
                projects: vec![],
                summary: ProjectsSummary {
                    total_projects: 0,
                    succeeded: 0,
                    failed: 0,
                    skipped: 0,
                    planned: 0,
                },
            }),
            0,
        );
    }

    log_status!(
        "release",
        "Deploying '{}' to {} project(s)...",
        component_id,
        projects.len()
    );

    let mut project_results = Vec::new();
    let mut succeeded: u32 = 0;
    let mut failed: u32 = 0;

    for project_id in &projects {
        log_status!("release", "Deploying to project '{}'...", project_id);

        let config = DeployConfig {
            component_ids: vec![component_id.to_string()],
            all: false,
            outdated: false,
            dry_run: false,
            check: false,
            force: false,
            skip_build: true,
            keep_deps: false,
            expected_version: None, // Release already validated version
            no_pull: true,          // Release already pushed, no need to pull
            head: true,             // Release just tagged — deploy from current state
        };

        match deploy::run(project_id, &config) {
            Ok(result) => {
                let component_result = result.results.into_iter().next();
                let deploy_failed = result.summary.failed > 0;

                if deploy_failed {
                    let error_msg = component_result
                        .as_ref()
                        .and_then(|r| r.error.clone())
                        .unwrap_or_else(|| "Deployment failed".to_string());

                    project_results.push(ProjectDeployResult {
                        project_id: project_id.clone(),
                        status: "failed".to_string(),
                        error: Some(error_msg),
                        component_result,
                    });
                    failed += 1;
                } else {
                    project_results.push(ProjectDeployResult {
                        project_id: project_id.clone(),
                        status: "deployed".to_string(),
                        error: None,
                        component_result,
                    });
                    succeeded += 1;
                }
            }
            Err(e) => {
                project_results.push(ProjectDeployResult {
                    project_id: project_id.clone(),
                    status: "failed".to_string(),
                    error: Some(e.to_string()),
                    component_result: None,
                });
                failed += 1;
            }
        }
    }

    let total = project_results.len() as u32;
    let exit_code = if failed > 0 { 1 } else { 0 };

    (
        Some(DeploymentResult {
            projects: project_results,
            summary: ProjectsSummary {
                total_projects: total,
                succeeded,
                failed,
                skipped: 0,
                planned: 0,
            },
        }),
        exit_code,
    )
}

/// Recover from an interrupted release.
/// Detects state: version files bumped but tag/push missing, and completes the release.
fn run_recover(comp_args: &PositionalComponentArgs) -> CmdResult<ReleaseOutput> {
    let component = comp_args.load()?;
    let component_id = comp_args.id();
    let version_info = homeboy::version::read_version(Some(component_id))?;
    let current_version = &version_info.version;
    let tag_name = format!("v{}", current_version);

    // Check what state we're in
    let tag_exists_local =
        homeboy::git::tag_exists_locally(&component.local_path, &tag_name).unwrap_or(false);
    let tag_exists_remote =
        homeboy::git::tag_exists_on_remote(&component.local_path, &tag_name).unwrap_or(false);
    let uncommitted = homeboy::git::get_uncommitted_changes(&component.local_path)?;

    let mut actions = Vec::new();

    // Step 1: Commit uncommitted version files if needed
    if uncommitted.has_changes {
        log_status!("recover", "Committing uncommitted changes...");
        let msg = format!("release: v{}", current_version);
        let commit_result = homeboy::git::commit(
            Some(component_id),
            Some(msg.as_str()),
            homeboy::git::CommitOptions {
                staged_only: false,
                files: None,
                exclude: None,
                amend: false,
            },
        )?;
        if !commit_result.success {
            return Err(homeboy::Error::git_command_failed(format!(
                "Failed to commit: {}",
                commit_result.stderr
            )));
        }
        actions.push("committed version files".to_string());
    }

    // Step 2: Create tag if missing locally
    if !tag_exists_local {
        log_status!("recover", "Creating tag {}...", tag_name);
        let tag_result = homeboy::git::tag(
            Some(component_id),
            Some(&tag_name),
            Some(&format!("Release {}", tag_name)),
        )?;
        if !tag_result.success {
            return Err(homeboy::Error::git_command_failed(format!(
                "Failed to create tag: {}",
                tag_result.stderr
            )));
        }
        actions.push(format!("created tag {}", tag_name));
    }

    // Step 3: Push commits and tags if not on remote
    if !tag_exists_remote {
        log_status!("recover", "Pushing to remote...");
        let push_result = homeboy::git::push(Some(component_id), true)?;
        if !push_result.success {
            return Err(homeboy::Error::git_command_failed(format!(
                "Failed to push: {}",
                push_result.stderr
            )));
        }
        actions.push("pushed commits and tags".to_string());
    }

    if actions.is_empty() {
        log_status!(
            "recover",
            "Release v{} appears complete — nothing to recover.",
            current_version
        );
    } else {
        log_status!(
            "recover",
            "Recovery complete for v{}: {}",
            current_version,
            actions.join(", ")
        );
    }

    Ok((
        ReleaseOutput {
            result: ReleaseResult {
                component_id: component_id.to_string(),
                bump_type: "recover".to_string(),
                dry_run: false,
                plan: None,
                run: None,
                deployment: None,
            },
        },
        0,
    ))
}