xbp 10.57.0

XBP is a zero-config build pack that can also interact with proxies, kafka, sockets, synthetic monitors.
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
//! Version management commands and adapters.

use crate::cli::auto_commit::{commit_paths, print_skip, AutoCommitRequest, AutoCommitResult};
use crate::commands::cli_session::{
    post_version_activity, CliVersionActivityPayload,
};
#[cfg(feature = "openapi-gen")]
use crate::commands::{generate_openapi, GenerateOpenApiArgs};
use crate::config::{
    load_package_name_files_registry, load_versioning_files_registry,
};
use crate::utils::find_xbp_config_upwards;
use semver::Version;
use std::collections::BTreeSet;
use std::env;
use std::path::{Path, PathBuf};
#[cfg(feature = "openapi-gen")]
use xbp_openapi_gen::cache::{cache_key as openapi_cache_key, source_metadata};

mod adapters;
mod change_guard;
mod path_utils;
pub(crate) use change_guard::*;
pub(crate) use path_utils::*;
mod change_selection;
mod git_ops;
mod registry_paths;
mod report;
mod release_workflow;

pub use release_workflow::run_version_release_command;
pub(crate) use release_workflow::*;

mod scope;

pub(crate) use git_ops::*;
pub(crate) use registry_paths::*;
pub(crate) use report::*;
pub(crate) use scope::*;

mod types;

pub(crate) use change_selection::*;
pub use types::{ReleaseLatestPolicy, VersionReleaseOptions};
pub(crate) use types::*;

mod bump;
mod cargo_dist;
mod discover_services;
mod domain;
mod github_release;
mod release_docs;
mod release_ledger;
#[cfg(feature = "linear")]
mod release_linear;
mod release_notes;
pub(crate) mod release_timings;
mod versioning_history;
mod versioning_suggest;
mod workspace_release;

// Re-export adapter helpers used across this package (and tests in this module).
pub(crate) use adapters::*;

pub use bump::run_version_bump_command;
pub use discover_services::run_version_discover_services;
pub use domain::{
    check_domain_for_cloudflare_release, run_version_domain_command, VersionDomainCommand,
    VersionDomainCommandOptions, VersionDomainDiagnoseOptions, VersionDomainDoctorOptions,
    VersionDomainInitOptions, VersionDomainReleaseOptions, VersionDomainSyncOptions,
};
#[cfg(not(feature = "linear"))]
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
struct PublishedLinearInitiative {
    id: String,
    name: String,
    url: Option<String>,
}
pub(crate) use workspace_release::{
    heal_publish_surface_for_release, resolve_manifest_workspace_publish,
    ManifestWorkspacePublishResolution,
};
pub use workspace_release::{
    run_version_workspace_command, WorkspacePublishHealOptions, WorkspacePublishPlanOptions,
    WorkspacePublishRunOptions, WorkspaceVersionCheckOptions, WorkspaceVersionCommand,
    WorkspaceVersionCommandOptions, WorkspaceVersionSyncOptions, WorkspaceVersionValidateOptions,
};

pub(crate) const LEDGER_STEP_SYNC_VERSION: &str = "sync_version";
pub(crate) const LEDGER_STEP_WORKSPACE_SYNC: &str = "workspace_sync";
pub(crate) const LEDGER_STEP_PUBLISH_PACKAGES: &str = "publish_packages";
pub(crate) const LEDGER_STEP_PUSH_TAG: &str = "push_tag";
pub(crate) const LEDGER_STEP_CREATE_GITHUB_RELEASE: &str = "github_release";
pub(crate) const LEDGER_STEP_CARGO_DIST_BUILD: &str = "cargo_dist_build";
pub(crate) const LEDGER_STEP_UPLOAD_DIST_ASSETS: &str = "upload_dist_assets";
pub(crate) const LEDGER_STEP_UPLOAD_OPENAPI_ASSETS: &str = "upload_openapi_assets";
pub(crate) const LEDGER_STEP_PUBLISH_LINEAR: &str = "publish_linear";
pub(crate) const LEDGER_STEP_SYNC_RELEASE_DOCS: &str = "sync_release_docs";
pub(crate) const LEDGER_STEP_COMMIT_RELEASE_DOCS: &str = "commit_release_docs";
#[cfg(feature = "openapi-gen")]
pub(crate) const LEDGER_STEP_GENERATE_OPENAPI: &str = "generate_openapi";

#[derive(Clone, Debug)]
pub(crate) enum VersionScope {
    Repository,
    Crate {
        crate_root: PathBuf,
        crate_relative_root: String,
        package_name: String,
        tag_prefix: String,
    },
    Service {
        service_root: PathBuf,
        service_relative_root: String,
        service_name: String,
        tag_prefix: String,
        cargo_package_name: Option<String>,
        version_targets: Vec<String>,
        /// Relative path prefixes that trigger this service for dirty-tree versioning.
        watch_paths: Vec<String>,
    },
}

impl VersionReport {
    fn highest_worktree(&self) -> Option<Version> {
        self.worktree
            .iter()
            .map(|entry| entry.version.clone())
            .max()
    }

    fn highest_head(&self) -> Option<Version> {
        self.head.iter().map(|entry| entry.version.clone()).max()
    }

    fn highest_local_tag(&self) -> Option<Version> {
        self.local_tags
            .iter()
            .map(|entry| entry.version.clone())
            .max()
    }

    fn highest_remote_tag(&self) -> Option<Version> {
        self.remote_tags
            .iter()
            .map(|entry| entry.version.clone())
            .max()
    }

    fn highest_git(&self) -> Option<Version> {
        self.highest_remote_tag()
            .or_else(|| self.highest_local_tag())
    }

    fn highest_registry(&self) -> Option<Version> {
        self.registry_versions
            .iter()
            .filter_map(|entry| entry.latest.clone())
            .max()
    }

    fn highest_available(&self) -> Version {
        self.highest_worktree()
            .into_iter()
            .chain(self.highest_head())
            .chain(self.highest_git())
            .chain(self.highest_registry())
            .max()
            .unwrap_or_else(default_version)
    }

    fn highest_project_local_available(&self) -> Version {
        self.highest_worktree()
            .into_iter()
            .chain(self.highest_registry())
            .max()
            .unwrap_or_else(default_version)
    }

    fn divergent_versions(&self) -> Vec<Version> {
        let mut versions = BTreeSet::new();
        for entry in &self.worktree {
            versions.insert(entry.version.clone());
        }
        for entry in &self.head {
            versions.insert(entry.version.clone());
        }
        for entry in &self.local_tags {
            versions.insert(entry.version.clone());
        }
        for entry in &self.remote_tags {
            versions.insert(entry.version.clone());
        }
        for entry in &self.registry_versions {
            if let Some(version) = &entry.latest {
                versions.insert(version.clone());
            }
        }
        versions.into_iter().collect()
    }
}

pub async fn run_version_command(
    target: Option<String>,
    git_only: bool,
    force: bool,
    _debug: bool,
) -> Result<(), String> {
    if git_only && target.is_some() {
        return Err("`xbp version --git` does not accept `major`, `minor`, `patch`, or explicit version values.".to_string());
    }

    let invocation_dir: PathBuf = env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    let project_root: PathBuf = resolve_project_root();
    let version_scope: VersionScope =
        resolve_version_scope_with_prompt(&project_root, &invocation_dir)?;
    let registry: Vec<String> = load_versioning_files_registry()?;

    if git_only {
        print_git_versions(&project_root, &version_scope)?;
        return Ok(());
    }

    match target.as_deref() {
        None => {
            let mut report: VersionReport =
                collect_version_report(&project_root, &invocation_dir, &registry, &version_scope);
            match load_package_name_files_registry() {
                Ok(lookups) => {
                    report.registry_versions = collect_registry_versions(
                        &project_root,
                        &invocation_dir,
                        &lookups,
                        &version_scope,
                        &mut report.warnings,
                    )
                    .await;
                }
                Err(err) => report.warnings.push(err),
            }
            print_version_report(&project_root, &report);
            Ok(())
        }
        Some(bump_target @ ("major" | "minor" | "patch")) => {
            enforce_version_change_guard(&project_root, Some(&version_scope))?;
            let repo = project_root
                .file_name()
                .and_then(|value| value.to_str())
                .unwrap_or("repository")
                .to_string();
            let selection = resolve_changed_target_selection(
                &project_root,
                &invocation_dir,
                &registry,
                &version_scope,
                &repo,
            )?;
            let current: Version = read_highest_version_from_targets(&selection.version_targets)?
                .unwrap_or_else(|| {
                    resolve_current_version_for_bump(
                        &project_root,
                        &invocation_dir,
                        &registry,
                        &version_scope,
                    )
                });
            let next: Version = bump_version(&current, bump_target);
            let updated_paths =
                write_version_to_selected_paths(&selection.version_targets, &next, false)?;
            let updated = updated_paths.len();
            println!(
                "Updated {} version file(s) from {} to {}.",
                updated, current, next
            );
            let commit_ok = matches!(
                auto_commit_command_paths_result(
                    &project_root,
                    updated_paths,
                    format!("chore(version): update version to {}", next),
                    "xbp version",
                    false,
                )
                .await,
                Ok(AutoCommitResult::Committed(_))
            );
            record_version_change_guard_after_write(
                &project_root,
                Some(&version_scope),
                commit_ok,
            )?;
            sync_cli_version_write_activity(
                &project_root,
                &version_scope,
                &next,
                format!(
                    "Updated {} version file(s) from {} to {}.",
                    updated, current, next
                ),
            )
            .await;
            Ok(())
        }
        Some(explicit) => {
            enforce_version_change_guard(&project_root, Some(&version_scope))?;
            let repo = project_root
                .file_name()
                .and_then(|value| value.to_str())
                .unwrap_or("repository")
                .to_string();
            let selection = resolve_changed_target_selection(
                &project_root,
                &invocation_dir,
                &registry,
                &version_scope,
                &repo,
            )?;
            if let Some((package_name, version)) = parse_package_version_target(explicit)? {
                // Package-assignment form (e.g. tokio=1.2.3) only rewrites dependency
                // pins — not project version identity — so skip downgrade guard.
                let updated_paths = write_package_version_to_configured_files_with_paths(
                    &project_root,
                    &invocation_dir,
                    &registry,
                    &version_scope,
                    &package_name,
                    &version,
                )?;
                let updated = updated_paths.len();
                println!(
                    "Updated {} file(s) for package `{}` to {}.",
                    updated, package_name, version
                );
                let commit_ok = matches!(
                    auto_commit_command_paths_result(
                        &project_root,
                        updated_paths,
                        format!("chore(version): set {} to {}", package_name, version),
                        "xbp version",
                        false,
                    )
                    .await,
                    Ok(AutoCommitResult::Committed(_))
                );
                record_version_change_guard_after_write(
                    &project_root,
                    Some(&version_scope),
                    commit_ok,
                )?;
                sync_cli_version_write_activity(
                    &project_root,
                    &version_scope,
                    &version,
                    format!(
                        "Updated {} file(s) for package `{}` to {}.",
                        updated, package_name, version
                    ),
                )
                .await;
            } else {
                let version: Version = parse_version(explicit)?;
                reject_version_downgrade_unless_forced(
                    &project_root,
                    &invocation_dir,
                    &registry,
                    &version_scope,
                    &selection.version_targets,
                    &version,
                    force,
                )
                .await?;
                let updated_paths =
                    write_version_to_selected_paths(&selection.version_targets, &version, false)?;
                let updated = updated_paths.len();
                println!("Updated {} version file(s) to {}.", updated, version);
                let commit_ok = matches!(
                    auto_commit_command_paths_result(
                        &project_root,
                        updated_paths,
                        format!("chore(version): update version to {}", version),
                        "xbp version",
                        false,
                    )
                    .await,
                    Ok(AutoCommitResult::Committed(_))
                );
                record_version_change_guard_after_write(
                    &project_root,
                    Some(&version_scope),
                    commit_ok,
                )?;
                sync_cli_version_write_activity(
                    &project_root,
                    &version_scope,
                    &version,
                    format!("Updated {} version file(s) to {}.", updated, version),
                )
                .await;
            }
            Ok(())
        }
    }
}

/// Block accidental `xbp version 4.0.2` when the project is already at 10.x.
///
/// Baseline is the highest of selected worktree targets, HEAD/tags, and registry
/// (when available). Any strict downgrade requires `--force`.
async fn reject_version_downgrade_unless_forced(
    project_root: &Path,
    invocation_dir: &Path,
    registry: &[String],
    version_scope: &VersionScope,
    selected_targets: &[ResolvedRegistryPath],
    target: &Version,
    force: bool,
) -> Result<(), String> {
    let mut baseline = read_highest_version_from_targets(selected_targets)?
        .or_else(|| {
            Some(resolve_current_version_for_bump(
                project_root,
                invocation_dir,
                registry,
                version_scope,
            ))
        })
        .unwrap_or_else(default_version);

    // Prefer the full report high-water mark (includes remote tags + crates.io).
    let mut report = collect_version_report(project_root, invocation_dir, registry, version_scope);
    if let Ok(lookups) = load_package_name_files_registry() {
        let mut warnings = Vec::new();
        report.registry_versions = collect_registry_versions(
            project_root,
            invocation_dir,
            &lookups,
            version_scope,
            &mut warnings,
        )
        .await;
    }
    let highest = report.highest_available();
    if highest > baseline {
        baseline = highest;
    }

    if target >= &baseline {
        return Ok(());
    }

    let major_drop = baseline.major.saturating_sub(target.major);
    if force {
        eprintln!(
            "! Forced version downgrade: {}{} (highest known was {}).",
            baseline, target, baseline
        );
        if major_drop >= 1 {
            eprintln!(
                "  This drops {} major version(s). Confirm this is intentional before publishing.",
                major_drop
            );
        }
        return Ok(());
    }

    Err(format!(
        "Refusing to set version {target} which is lower than the highest known version {baseline} \
(worktree / HEAD / tags / registry).\n\
This guard prevents accidental multi-major downgrades (e.g. mistaking another project's \
`Fix local files with xbp version X.Y.Z` prompt for this repo).\n\
If you truly need a downgrade, re-run with `--force`:\n  xbp version {target} --force"
    ))
}

/// Print program version, install source, and enabled Cargo features.
pub async fn print_version() {
    crate::cli::help_render::emit_version_info(env!("CARGO_PKG_VERSION"));
}

fn resolve_project_root() -> PathBuf {
    let cwd: PathBuf = env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    resolve_project_root_from(&cwd)
}

fn resolve_project_root_from(cwd: &Path) -> PathBuf {
    // Canonicalize so Windows path casing matches the filesystem (cargo-dist and
    // similar tools fail when cwd is e.g. documents\github vs Documents\GitHub).
    let root = if let Some(found) = find_xbp_config_upwards(cwd) {
        found.project_root
    } else if let Some(root) = git_repository_root(cwd) {
        root
    } else {
        cwd.to_path_buf()
    };
    crate::utils::canonicalize_for_subprocess(&root)
}

pub(crate) async fn auto_commit_command_paths(
    project_root: &Path,
    paths: Vec<PathBuf>,
    message: String,
    action_label: &'static str,
) {
    let _ =
        auto_commit_command_paths_result(project_root, paths, message, action_label, false).await;
}

pub(crate) async fn auto_commit_command_paths_result(
    project_root: &Path,
    paths: Vec<PathBuf>,
    message: String,
    action_label: &'static str,
    push: bool,
) -> Result<AutoCommitResult, String> {
    match commit_paths(AutoCommitRequest {
        project_root,
        paths,
        message,
        action_label,
        push,
    })
    .await
    {
        Ok(AutoCommitResult::Committed(outcome)) => Ok(AutoCommitResult::Committed(outcome)),
        Ok(AutoCommitResult::Skipped(reason)) => {
            print_skip(action_label, &reason);
            Ok(AutoCommitResult::Skipped(reason))
        }
        Err(e) => {
            print_skip(action_label, &e);
            Err(e)
        }
    }
}


pub(crate) async fn sync_cli_version_write_activity(
    project_root: &Path,
    version_scope: &VersionScope,
    version: &Version,
    message: String,
) {
    let (repository_owner, repository_name) = resolve_optional_github_repository(project_root);
    let scope_label = version_scope_label(
        version_scope,
        repository_name.as_deref().unwrap_or_else(|| {
            project_root
                .file_name()
                .and_then(|value| value.to_str())
                .unwrap_or("repository")
        }),
    );

    let payload = CliVersionActivityPayload {
        command_kind: "version".to_string(),
        repository_owner,
        repository_name,
        scope_kind: version_scope_kind(version_scope).to_string(),
        scope_label,
        version: version.to_string(),
        tag_name: None,
        title: None,
        release_url: None,
        message_markdown: Some(message),
        published_initiatives: Vec::new(),
    };

    if let Err(error) = post_version_activity(&payload).await {
        eprintln!("Warning: {}", error);
    }
}


#[cfg(test)]
mod tests;