Skip to main content

nerdbank_gitversioning/
release_manager.rs

1// Copyright (c) .NET Foundation and Contributors. All rights reserved.
2// Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
4//! Release branch preparation and the Git mutations it requires.
5
6use std::fmt;
7use std::path::Path;
8use std::process::Command;
9
10use git2::build::CheckoutBuilder;
11use git2::{BranchType, Oid, Repository, Signature, Status, StatusOptions};
12use serde::{Serialize, Serializer};
13
14use crate::{
15    GitContext, GitEngine, ReleaseOptions, ReleaseVersionIncrement, SemanticVersion, Version,
16    VersionFile, VersionFileRequirements, VersionOptions,
17};
18
19/// Classifies failures that can occur while preparing a release.
20#[derive(Clone, Copy, Debug, Eq, PartialEq)]
21pub enum ReleasePreparationError {
22    /// The project directory is not in a Git repository.
23    NoGitRepo,
24    /// The index or working tree contains changes.
25    UncommittedChanges,
26    /// The release branch template is invalid.
27    InvalidBranchNameSetting,
28    /// The release tag template is invalid.
29    InvalidTagNameSetting,
30    /// No applicable version file was found.
31    NoVersionFile,
32    /// A requested version is older than the current version.
33    VersionDecrement,
34    /// The development version would not increment.
35    NoVersionIncrement,
36    /// The release branch already exists.
37    BranchAlreadyExists,
38    /// Git user name or email is not configured.
39    UserNotConfigured,
40    /// `HEAD` is detached.
41    DetachedHead,
42    /// The selected increment cannot be applied to the current version.
43    InvalidVersionIncrementSetting,
44    /// The Git executable required for signing failed.
45    GitCommandFailed,
46    /// An in-process libgit2 operation failed.
47    GitOperationFailed,
48    /// A version file could not be read or written.
49    VersionFileError,
50}
51
52/// A release preparation failure with a stable classification and useful detail.
53#[derive(Debug)]
54pub struct ReleasePreparationException {
55    /// The stable error classification.
56    pub error: ReleasePreparationError,
57    message: String,
58}
59
60impl ReleasePreparationException {
61    fn new(error: ReleasePreparationError, message: impl Into<String>) -> Self {
62        Self {
63            error,
64            message: message.into(),
65        }
66    }
67}
68
69impl fmt::Display for ReleasePreparationException {
70    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
71        formatter.write_str(&self.message)
72    }
73}
74
75impl std::error::Error for ReleasePreparationException {}
76
77/// A result returned by release preparation.
78pub type ReleasePreparationResult<T> = std::result::Result<T, ReleasePreparationException>;
79
80/// Selects the rendered output format.
81#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
82pub enum ReleaseManagerOutputMode {
83    /// Human-readable status lines.
84    #[default]
85    Text,
86    /// A JSON [`ReleaseInfo`] object.
87    Json,
88}
89
90/// Options controlling one release preparation operation.
91#[derive(Clone, Debug)]
92pub struct PrepareReleaseOptions {
93    /// An optional prerelease tag for the release branch.
94    pub release_unstable_tag: Option<String>,
95    /// An explicit next development version.
96    pub next_version: Option<Version>,
97    /// An override for the configured development-version increment.
98    pub version_increment: Option<ReleaseVersionIncrement>,
99    /// The output representation to produce.
100    pub output_mode: ReleaseManagerOutputMode,
101    /// A commit message pattern in which `{0}` is replaced by the new version.
102    pub commit_message: Option<String>,
103    /// Calculate and report changes without modifying the repository.
104    pub dry_run: bool,
105    /// Merge the release branch into the development branch.
106    pub merge_release_branch: bool,
107}
108
109impl Default for PrepareReleaseOptions {
110    fn default() -> Self {
111        Self {
112            release_unstable_tag: None,
113            next_version: None,
114            version_increment: None,
115            output_mode: ReleaseManagerOutputMode::Text,
116            commit_message: None,
117            dry_run: false,
118            merge_release_branch: true,
119        }
120    }
121}
122
123/// Information about a branch created or updated during release preparation.
124#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
125#[serde(rename_all = "PascalCase")]
126pub struct ReleaseBranchInfo {
127    /// The friendly branch name.
128    pub name: String,
129    /// The branch-tip object ID.
130    pub commit: String,
131    /// The version configured on the branch.
132    #[serde(serialize_with = "serialize_semantic_version")]
133    pub version: SemanticVersion,
134}
135
136/// Information about the branches affected by release preparation.
137#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
138#[serde(rename_all = "PascalCase")]
139pub struct ReleaseInfo {
140    /// The branch from which the release was prepared.
141    pub current_branch: ReleaseBranchInfo,
142    /// The newly-created release branch, or `None` when advancing one.
143    pub new_branch: Option<ReleaseBranchInfo>,
144}
145
146impl ReleaseInfo {
147    /// Serializes this result using the same property names as the .NET implementation.
148    pub fn to_json(&self) -> ReleasePreparationResult<String> {
149        serde_json::to_string_pretty(self).map_err(|error| {
150            ReleasePreparationException::new(
151                ReleasePreparationError::VersionFileError,
152                format!("Failed to serialize release information: {error}"),
153            )
154        })
155    }
156}
157
158/// The complete result of a release preparation operation.
159#[derive(Clone, Debug, Eq, PartialEq)]
160pub struct PreparedRelease {
161    /// The final (or simulated) branch information.
162    pub info: ReleaseInfo,
163    /// Text or JSON suitable for writing to standard output.
164    pub output: String,
165    /// Whether the repository was modified.
166    pub changed: bool,
167}
168
169/// Creates or advances release branches and updates their version files.
170#[derive(Clone, Copy, Debug, Default)]
171pub struct ReleaseManager;
172
173impl ReleaseManager {
174    /// Creates a release manager.
175    #[must_use]
176    pub const fn new() -> Self {
177        Self
178    }
179
180    /// Prepares a release rooted at `project_directory`.
181    pub fn prepare_release(
182        &self,
183        project_directory: impl AsRef<Path>,
184        options: &PrepareReleaseOptions,
185    ) -> ReleasePreparationResult<PreparedRelease> {
186        let project_directory = project_directory.as_ref();
187        let context = GitContext::create(project_directory, None, GitEngine::ReadWrite)
188            .map_err(|error| version_file_error("Failed to discover repository", error))?;
189        if !context.is_repository() {
190            return Err(ReleasePreparationException::new(
191                ReleasePreparationError::NoGitRepo,
192                format!(
193                    "No git repository found above directory '{}'.",
194                    project_directory.display()
195                ),
196            ));
197        }
198
199        let repository = context.repository().expect("repository context");
200        ensure_clean(repository, project_directory)?;
201        let head = repository.head().map_err(git_operation_error)?;
202        if !head.is_branch() {
203            return Err(ReleasePreparationException::new(
204                ReleasePreparationError::DetachedHead,
205                "Detached head. Check out a branch first.",
206            ));
207        }
208        let original_branch_name = head.shorthand().map_err(git_operation_error)?;
209        let original_branch_name = original_branch_name.to_owned();
210        let original_tip = head.peel_to_commit().map_err(git_operation_error)?.id();
211        get_signature(repository)?;
212
213        let (version_options, _) = VersionFile::new(&context)
214            .get_version(VersionFileRequirements::default())
215            .map_err(|error| version_file_error("Failed to load version file", error))?;
216        let version_options = version_options.ok_or_else(|| {
217            ReleasePreparationException::new(
218                ReleasePreparationError::NoVersionFile,
219                format!(
220                    "Failed to load version file for directory '{}'.",
221                    project_directory.display()
222                ),
223            )
224        })?;
225        let current_version = version_options.version.as_ref().ok_or_else(|| {
226            ReleasePreparationException::new(
227                ReleasePreparationError::NoVersionFile,
228                "The applicable version file does not specify a version.",
229            )
230        })?;
231        let release_branch_name = format_release_branch_name(&version_options)?;
232        let release_version = current_version
233            .set_first_prerelease_tag(options.release_unstable_tag.as_deref().unwrap_or(""))
234            .map_err(|error| version_file_error("Invalid release prerelease tag", error))?;
235
236        if original_branch_name.eq_ignore_ascii_case(&release_branch_name) {
237            let simulated_info = ReleaseInfo {
238                current_branch: branch_info(
239                    &release_branch_name,
240                    original_tip,
241                    release_version.clone(),
242                ),
243                new_branch: None,
244            };
245            if options.dry_run {
246                return finish(
247                    simulated_info,
248                    options.output_mode,
249                    format!(
250                        "What-if: {release_branch_name} branch would be advanced from {current_version} to {release_version}."
251                    ),
252                    false,
253                );
254            }
255
256            update_version(
257                project_directory,
258                current_version,
259                &release_version,
260                options.commit_message.as_deref(),
261            )?;
262            let repository =
263                Repository::discover(project_directory).map_err(git_operation_error)?;
264            let final_tip = repository
265                .head()
266                .and_then(|head| head.peel_to_commit())
267                .map_err(git_operation_error)?
268                .id();
269            return finish(
270                ReleaseInfo {
271                    current_branch: branch_info(
272                        &release_branch_name,
273                        final_tip,
274                        release_version.clone(),
275                    ),
276                    new_branch: None,
277                },
278                options.output_mode,
279                format!(
280                    "{release_branch_name} branch advanced from {current_version} to {release_version}."
281                ),
282                true,
283            );
284        }
285
286        let next_dev_version = get_next_dev_version(&version_options, options)?;
287        if current_version.version == next_dev_version.version {
288            return Err(ReleasePreparationException::new(
289                ReleasePreparationError::NoVersionIncrement,
290                format!(
291                    "Version on '{original_branch_name}' is already set to next version {}.",
292                    next_dev_version.version
293                ),
294            ));
295        }
296        if repository
297            .find_branch(&release_branch_name, BranchType::Local)
298            .is_ok()
299        {
300            return Err(ReleasePreparationException::new(
301                ReleasePreparationError::BranchAlreadyExists,
302                format!("Cannot create branch '{release_branch_name}' because it already exists."),
303            ));
304        }
305        validate_branch_name(&release_branch_name)?;
306
307        let simulated_info = ReleaseInfo {
308            current_branch: branch_info(
309                &original_branch_name,
310                original_tip,
311                next_dev_version.clone(),
312            ),
313            new_branch: Some(branch_info(
314                &release_branch_name,
315                original_tip,
316                release_version.clone(),
317            )),
318        };
319        if options.dry_run {
320            return finish(
321                simulated_info,
322                options.output_mode,
323                format!(
324                    "What-if: {release_branch_name} branch would track v{release_version} stabilization and release.\nWhat-if: {original_branch_name} branch would track v{next_dev_version} development."
325                ),
326                false,
327            );
328        }
329
330        let head_commit = repository
331            .find_commit(original_tip)
332            .map_err(git_operation_error)?;
333        repository
334            .branch(&release_branch_name, &head_commit, false)
335            .map_err(git_operation_error)?;
336        checkout_branch(repository, &release_branch_name)?;
337        drop(head_commit);
338        update_version(
339            project_directory,
340            current_version,
341            &release_version,
342            options.commit_message.as_deref(),
343        )?;
344        let repository = Repository::discover(project_directory).map_err(git_operation_error)?;
345        checkout_branch(&repository, &original_branch_name)?;
346        update_version(
347            project_directory,
348            current_version,
349            &next_dev_version,
350            options.commit_message.as_deref(),
351        )?;
352
353        let repository = Repository::discover(project_directory).map_err(git_operation_error)?;
354        if options.merge_release_branch {
355            merge_release_branch(&repository, &release_branch_name)?;
356        }
357        let final_original_tip = repository
358            .head()
359            .and_then(|head| head.peel_to_commit())
360            .map_err(git_operation_error)?
361            .id();
362        let final_release_tip = repository
363            .find_branch(&release_branch_name, BranchType::Local)
364            .and_then(|branch| branch.get().peel_to_commit())
365            .map_err(git_operation_error)?
366            .id();
367        finish(
368            ReleaseInfo {
369                current_branch: branch_info(
370                    &original_branch_name,
371                    final_original_tip,
372                    next_dev_version.clone(),
373                ),
374                new_branch: Some(branch_info(
375                    &release_branch_name,
376                    final_release_tip,
377                    release_version.clone(),
378                )),
379            },
380            options.output_mode,
381            format!(
382                "{release_branch_name} branch now tracks v{release_version} stabilization and release.\n{original_branch_name} branch now tracks v{next_dev_version} development."
383            ),
384            true,
385        )
386    }
387}
388
389/// Formats the configured release branch name using the numeric current version.
390pub fn format_release_branch_name(
391    version_options: &VersionOptions,
392) -> ReleasePreparationResult<String> {
393    let version = version_options.version.as_ref().ok_or_else(|| {
394        ReleasePreparationException::new(
395            ReleasePreparationError::NoVersionFile,
396            "The version options do not specify a version.",
397        )
398    })?;
399    format_version_template(
400        version_options
401            .release_or_default()
402            .branch_name_or_default(),
403        &version.version.to_string(),
404        ReleasePreparationError::InvalidBranchNameSetting,
405        "branchName",
406    )
407}
408
409/// Formats a release tag template using a semantic version.
410pub fn format_release_tag_name(
411    release_options: &ReleaseOptions,
412    version: &SemanticVersion,
413) -> ReleasePreparationResult<String> {
414    format_version_template(
415        release_options.tag_name_or_default(),
416        &version.to_string(),
417        ReleasePreparationError::InvalidTagNameSetting,
418        "tagName",
419    )
420}
421
422fn format_version_template(
423    template: &str,
424    version: &str,
425    error: ReleasePreparationError,
426    setting: &str,
427) -> ReleasePreparationResult<String> {
428    if template.is_empty() || !template.contains("{version}") {
429        return Err(ReleasePreparationException::new(
430            error,
431            format!(
432                "Invalid '{setting}' setting '{template}'. Missing version placeholder '{{version}}'."
433            ),
434        ));
435    }
436    Ok(template.replace("{version}", version))
437}
438
439fn ensure_clean(repository: &Repository, path: &Path) -> ReleasePreparationResult<()> {
440    let mut options = StatusOptions::new();
441    options
442        .include_untracked(true)
443        .recurse_untracked_dirs(true)
444        .include_ignored(false);
445    let statuses = repository
446        .statuses(Some(&mut options))
447        .map_err(git_operation_error)?;
448    let changed = statuses
449        .iter()
450        .filter(|entry| entry.status() != Status::CURRENT)
451        .collect::<Vec<_>>();
452    if !changed.is_empty() {
453        let details = changed
454            .iter()
455            .map(|entry| {
456                format!(
457                    "- {} changed with FileStatus {}",
458                    entry.path().unwrap_or_default(),
459                    file_status_name(entry.status())
460                )
461            })
462            .collect::<Vec<_>>()
463            .join("\n");
464        return Err(ReleasePreparationException::new(
465            ReleasePreparationError::UncommittedChanges,
466            format!(
467                "No uncommitted changes are allowed, but {} are present in directory '{}':\n{details}",
468                changed.len(),
469                path.display(),
470            ),
471        ));
472    }
473    Ok(())
474}
475
476fn file_status_name(status: Status) -> String {
477    let names = [
478        (Status::INDEX_NEW, "NewInIndex"),
479        (Status::INDEX_MODIFIED, "ModifiedInIndex"),
480        (Status::INDEX_DELETED, "DeletedFromIndex"),
481        (Status::INDEX_RENAMED, "RenamedInIndex"),
482        (Status::INDEX_TYPECHANGE, "TypeChangeInIndex"),
483        (Status::WT_NEW, "NewInWorkdir"),
484        (Status::WT_MODIFIED, "ModifiedInWorkdir"),
485        (Status::WT_DELETED, "DeletedFromWorkdir"),
486        (Status::WT_RENAMED, "RenamedInWorkdir"),
487        (Status::WT_TYPECHANGE, "TypeChangeInWorkdir"),
488        (Status::CONFLICTED, "Conflicted"),
489    ];
490    names
491        .into_iter()
492        .filter_map(|(flag, name)| status.contains(flag).then_some(name))
493        .collect::<Vec<_>>()
494        .join(", ")
495}
496
497fn get_next_dev_version(
498    version_options: &VersionOptions,
499    options: &PrepareReleaseOptions,
500) -> ReleasePreparationResult<SemanticVersion> {
501    let current = version_options.version.as_ref().ok_or_else(|| {
502        ReleasePreparationException::new(
503            ReleasePreparationError::NoVersionFile,
504            "The version options do not specify a version.",
505        )
506    })?;
507    let incremented = if let Some(version) = options.next_version {
508        SemanticVersion::new(
509            version,
510            current.prerelease.clone(),
511            current.build_metadata.clone(),
512        )
513        .map_err(|error| version_file_error("Invalid next version", error))?
514    } else {
515        let increment = options.version_increment.unwrap_or_else(|| {
516            version_options
517                .release_or_default()
518                .version_increment_or_default()
519        });
520        if increment == ReleaseVersionIncrement::Build && current.version.build.is_none() {
521            return Err(ReleasePreparationException::new(
522                ReleasePreparationError::InvalidVersionIncrementSetting,
523                format!(
524                    "Cannot apply version increment 'build' to version '{current}' because it only has major and minor segments."
525                ),
526            ));
527        }
528        current.increment(increment).map_err(|error| {
529            ReleasePreparationException::new(
530                ReleasePreparationError::InvalidVersionIncrementSetting,
531                error.to_string(),
532            )
533        })?
534    };
535    incremented
536        .set_first_prerelease_tag(
537            version_options
538                .release_or_default()
539                .first_unstable_tag_or_default(),
540        )
541        .map_err(|error| version_file_error("Invalid first unstable tag", error))
542}
543
544fn update_version(
545    project_directory: &Path,
546    old_version: &SemanticVersion,
547    new_version: &SemanticVersion,
548    commit_message: Option<&str>,
549) -> ReleasePreparationResult<()> {
550    if is_version_decrement(old_version, new_version) {
551        return Err(ReleasePreparationException::new(
552            ReleasePreparationError::VersionDecrement,
553            format!(
554                "Cannot change version from {old_version} to {new_version} because {new_version} is older than {old_version}."
555            ),
556        ));
557    }
558
559    let context = GitContext::create(project_directory, None, GitEngine::ReadWrite)
560        .map_err(|error| version_file_error("Failed to open repository", error))?;
561    let requirements = VersionFileRequirements::NON_MERGED_RESULT
562        | VersionFileRequirements::VERSION_SPECIFIED
563        | VersionFileRequirements::ACCEPT_INHERITING_FILE;
564    let (version_options, locations) = VersionFile::new(&context)
565        .get_version(requirements)
566        .map_err(|error| version_file_error("Failed to load writable version file", error))?;
567    let mut version_options = version_options.ok_or_else(|| {
568        ReleasePreparationException::new(
569            ReleasePreparationError::NoVersionFile,
570            "No writable version file specifies a version.",
571        )
572    })?;
573    if version_options.version.as_ref() == Some(new_version) {
574        return Ok(());
575    }
576
577    if version_options.version_height_offset != Some(-1)
578        && version_options.version_height_offset.is_some()
579        && let (Some(local_version), Some(position)) = (
580            version_options.version.as_ref(),
581            version_options.version_height_position(),
582        )
583        && SemanticVersion::will_version_change_reset_version_height(
584            local_version,
585            new_version,
586            position,
587        )
588        .map_err(|error| version_file_error("Failed to compare version heights", error))?
589    {
590        version_options.version_height_offset = None;
591        version_options.version_height_offset_applies_to = None;
592    }
593    version_options.version = Some(new_version.clone());
594    let directory = locations
595        .version_specifying_version_directory
596        .ok_or_else(|| {
597            ReleasePreparationException::new(
598                ReleasePreparationError::NoVersionFile,
599                "The version-specifying directory could not be determined.",
600            )
601        })?;
602    let path = VersionFile::new(&context)
603        .set_version(directory, &version_options, true)
604        .map_err(|error| version_file_error("Failed to write version file", error))?;
605    context
606        .stage(path)
607        .map_err(|error| version_file_error("Failed to stage version file", error))?;
608    let repository = context.repository().expect("repository context");
609    let mut index = repository.index().map_err(git_operation_error)?;
610    let tree_id = index.write_tree().map_err(git_operation_error)?;
611    let parent = repository
612        .head()
613        .and_then(|head| head.peel_to_commit())
614        .map_err(git_operation_error)?;
615    if parent.tree_id() == tree_id {
616        return Ok(());
617    }
618
619    let message = format_commit_message(
620        commit_message.unwrap_or("Set version to '{0}'"),
621        new_version,
622    );
623    if should_sign_commits(repository)? {
624        run_git(
625            repository,
626            &["commit", "--gpg-sign", "--no-verify", "--message", &message],
627        )?;
628    } else {
629        let signature = get_signature(repository)?;
630        let tree = repository.find_tree(tree_id).map_err(git_operation_error)?;
631        repository
632            .commit(
633                Some("HEAD"),
634                &signature,
635                &signature,
636                &message,
637                &tree,
638                &[&parent],
639            )
640            .map_err(git_operation_error)?;
641    }
642    Ok(())
643}
644
645fn is_version_decrement(old: &SemanticVersion, new: &SemanticVersion) -> bool {
646    new.version < old.version
647        || (new.version == old.version && old.prerelease.is_empty() && !new.prerelease.is_empty())
648}
649
650fn format_commit_message(pattern: &str, version: &SemanticVersion) -> String {
651    pattern
652        .replace("{{", "\u{0}")
653        .replace("}}", "\u{1}")
654        .replace("{0}", &version.to_string())
655        .replace('\u{0}', "{")
656        .replace('\u{1}', "}")
657}
658
659fn checkout_branch(repository: &Repository, name: &str) -> ReleasePreparationResult<()> {
660    repository
661        .set_head(&format!("refs/heads/{name}"))
662        .map_err(git_operation_error)?;
663    repository
664        .checkout_head(Some(CheckoutBuilder::new().safe()))
665        .map_err(git_operation_error)?;
666    Ok(())
667}
668
669fn merge_release_branch(
670    repository: &Repository,
671    release_branch_name: &str,
672) -> ReleasePreparationResult<()> {
673    if should_sign_commits(repository)? {
674        return run_git(
675            repository,
676            &[
677                "merge",
678                "--gpg-sign",
679                "--no-edit",
680                "--no-verify",
681                "--strategy-option=ours",
682                &format!("refs/heads/{release_branch_name}"),
683            ],
684        );
685    }
686
687    let signature = get_signature(repository)?;
688    let development = repository
689        .head()
690        .and_then(|head| head.peel_to_commit())
691        .map_err(git_operation_error)?;
692    let release = repository
693        .find_branch(release_branch_name, BranchType::Local)
694        .and_then(|branch| branch.get().peel_to_commit())
695        .map_err(git_operation_error)?;
696    if repository
697        .graph_descendant_of(development.id(), release.id())
698        .map_err(git_operation_error)?
699    {
700        return Ok(());
701    }
702    let tree = development.tree().map_err(git_operation_error)?;
703    repository
704        .commit(
705            Some("HEAD"),
706            &signature,
707            &signature,
708            &format!("Merge branch '{release_branch_name}'"),
709            &tree,
710            &[&development, &release],
711        )
712        .map_err(git_operation_error)?;
713    Ok(())
714}
715
716fn should_sign_commits(repository: &Repository) -> ReleasePreparationResult<bool> {
717    let config = repository.config().map_err(git_operation_error)?;
718    match config.get_bool("commit.gpgSign") {
719        Ok(value) => Ok(value),
720        Err(error) if error.code() == git2::ErrorCode::NotFound => Ok(false),
721        Err(error) => Err(git_operation_error(error)),
722    }
723}
724
725fn run_git(repository: &Repository, arguments: &[&str]) -> ReleasePreparationResult<()> {
726    let working_directory = repository.workdir().ok_or_else(|| {
727        ReleasePreparationException::new(
728            ReleasePreparationError::GitCommandFailed,
729            "Signed commits cannot be created in a bare repository.",
730        )
731    })?;
732    let output = Command::new("git")
733        .args(arguments)
734        .current_dir(working_directory)
735        .output()
736        .map_err(|error| {
737            ReleasePreparationException::new(
738                ReleasePreparationError::GitCommandFailed,
739                format!("Commit signing is enabled, but Git could not be started: {error}"),
740            )
741        })?;
742    if !output.status.success() {
743        let stderr = String::from_utf8_lossy(&output.stderr);
744        let stdout = String::from_utf8_lossy(&output.stdout);
745        let detail = if stderr.trim().is_empty() {
746            stdout.trim()
747        } else {
748            stderr.trim()
749        };
750        return Err(ReleasePreparationException::new(
751            ReleasePreparationError::GitCommandFailed,
752            format!(
753                "Git {} failed while creating a signed commit: {detail}",
754                arguments.first().copied().unwrap_or_default()
755            ),
756        ));
757    }
758    Ok(())
759}
760
761fn get_signature(repository: &Repository) -> ReleasePreparationResult<Signature<'static>> {
762    let config = repository.config().map_err(git_operation_error)?;
763    let name = config.get_string("user.name").map_err(|_| {
764        ReleasePreparationException::new(
765            ReleasePreparationError::UserNotConfigured,
766            "Cannot create commits in this repo because git user name and email are not configured.",
767        )
768    })?;
769    let email = config.get_string("user.email").map_err(|_| {
770        ReleasePreparationException::new(
771            ReleasePreparationError::UserNotConfigured,
772            "Cannot create commits in this repo because git user name and email are not configured.",
773        )
774    })?;
775    if name.trim().is_empty() || email.trim().is_empty() {
776        return Err(ReleasePreparationException::new(
777            ReleasePreparationError::UserNotConfigured,
778            "Cannot create commits in this repo because git user name and email are not configured.",
779        ));
780    }
781    Signature::now(&name, &email).map_err(git_operation_error)
782}
783
784fn validate_branch_name(name: &str) -> ReleasePreparationResult<()> {
785    if !git2::Reference::is_valid_name(&format!("refs/heads/{name}")) {
786        return Err(ReleasePreparationException::new(
787            ReleasePreparationError::InvalidBranchNameSetting,
788            format!("The formatted release branch name '{name}' is not a valid Git reference."),
789        ));
790    }
791    Ok(())
792}
793
794fn branch_info(name: &str, commit: Oid, version: SemanticVersion) -> ReleaseBranchInfo {
795    ReleaseBranchInfo {
796        name: name.to_owned(),
797        commit: commit.to_string(),
798        version,
799    }
800}
801
802fn serialize_semantic_version<S>(
803    version: &SemanticVersion,
804    serializer: S,
805) -> std::result::Result<S::Ok, S::Error>
806where
807    S: Serializer,
808{
809    serializer.serialize_str(&version.to_string())
810}
811
812fn finish(
813    info: ReleaseInfo,
814    mode: ReleaseManagerOutputMode,
815    text: String,
816    changed: bool,
817) -> ReleasePreparationResult<PreparedRelease> {
818    let output = match mode {
819        ReleaseManagerOutputMode::Text => text,
820        ReleaseManagerOutputMode::Json => info.to_json()?,
821    };
822    Ok(PreparedRelease {
823        info,
824        output,
825        changed,
826    })
827}
828
829fn git_operation_error(error: git2::Error) -> ReleasePreparationException {
830    ReleasePreparationException::new(
831        ReleasePreparationError::GitOperationFailed,
832        format!("Git operation failed: {error}"),
833    )
834}
835
836fn version_file_error(
837    operation: &str,
838    error: impl std::error::Error,
839) -> ReleasePreparationException {
840    ReleasePreparationException::new(
841        ReleasePreparationError::VersionFileError,
842        format!("{operation}: {error}"),
843    )
844}
845
846#[cfg(test)]
847mod tests {
848    use std::env;
849    use std::fs;
850    use std::path::PathBuf;
851    use std::sync::atomic::{AtomicU64, Ordering};
852    use std::time::{SystemTime, UNIX_EPOCH};
853
854    use git2::{ObjectType, Repository, Signature};
855
856    use super::*;
857
858    static NEXT_DIRECTORY: AtomicU64 = AtomicU64::new(0);
859
860    struct TestRepository {
861        path: PathBuf,
862    }
863
864    impl TestRepository {
865        fn new(version_json: Option<&str>, configure_user: bool) -> Self {
866            let nonce = SystemTime::now()
867                .duration_since(UNIX_EPOCH)
868                .expect("clock after epoch")
869                .as_nanos();
870            let sequence = NEXT_DIRECTORY.fetch_add(1, Ordering::Relaxed);
871            let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
872                .join("target")
873                .join("release-manager-tests")
874                .join(format!("{}-{nonce}-{sequence}", std::process::id()));
875            fs::create_dir_all(&path).unwrap();
876            let repository = Repository::init(&path).unwrap();
877            if configure_user {
878                let mut config = repository.config().unwrap();
879                config.set_str("user.name", "Release Test").unwrap();
880                config.set_str("user.email", "release@example.com").unwrap();
881            }
882            if let Some(json) = version_json {
883                fs::write(path.join("version.json"), json).unwrap();
884                let mut index = repository.index().unwrap();
885                index.add_path(Path::new("version.json")).unwrap();
886                index.write().unwrap();
887                let tree_id = index.write_tree().unwrap();
888                let tree = repository.find_tree(tree_id).unwrap();
889                let signature = Signature::now("Release Test", "release@example.com").unwrap();
890                repository
891                    .commit(
892                        Some("HEAD"),
893                        &signature,
894                        &signature,
895                        "Initial version",
896                        &tree,
897                        &[],
898                    )
899                    .unwrap();
900            } else {
901                fs::write(path.join("README"), "test").unwrap();
902                let mut index = repository.index().unwrap();
903                index.add_path(Path::new("README")).unwrap();
904                index.write().unwrap();
905                let tree_id = index.write_tree().unwrap();
906                let tree = repository.find_tree(tree_id).unwrap();
907                let signature = Signature::now("Release Test", "release@example.com").unwrap();
908                repository
909                    .commit(Some("HEAD"), &signature, &signature, "Initial", &tree, &[])
910                    .unwrap();
911            }
912            drop(repository);
913            Self { path }
914        }
915
916        fn repository(&self) -> Repository {
917            Repository::open(&self.path).unwrap()
918        }
919
920        fn branch_version(&self, branch: &str) -> VersionOptions {
921            let repository = self.repository();
922            let commit = repository
923                .find_branch(branch, BranchType::Local)
924                .unwrap()
925                .get()
926                .peel_to_commit()
927                .unwrap();
928            let tree = commit.tree().unwrap();
929            let blob = tree
930                .get_path(Path::new("version.json"))
931                .unwrap()
932                .to_object(&repository)
933                .unwrap()
934                .peel(ObjectType::Blob)
935                .unwrap();
936            VersionOptions::from_json(
937                std::str::from_utf8(blob.as_blob().unwrap().content()).unwrap(),
938                "",
939            )
940            .unwrap()
941        }
942
943        fn current_branch(&self) -> String {
944            self.repository()
945                .head()
946                .unwrap()
947                .shorthand()
948                .unwrap()
949                .to_owned()
950        }
951
952        fn checkout_new_branch(&self, name: &str) {
953            let repository = self.repository();
954            let commit = repository.head().unwrap().peel_to_commit().unwrap();
955            repository.branch(name, &commit, false).unwrap();
956            checkout_branch(&repository, name).unwrap();
957        }
958    }
959
960    impl Drop for TestRepository {
961        fn drop(&mut self) {
962            let _ = fs::remove_dir_all(&self.path);
963        }
964    }
965
966    fn json(version: &str) -> String {
967        format!(r#"{{"version":"{version}"}}"#)
968    }
969
970    #[test]
971    fn dry_run_reports_without_mutating() {
972        let fixture = TestRepository::new(Some(&json("1.2-beta")), true);
973        let before = fixture
974            .repository()
975            .head()
976            .unwrap()
977            .peel_to_commit()
978            .unwrap()
979            .id();
980        let result = ReleaseManager::new()
981            .prepare_release(
982                &fixture.path,
983                &PrepareReleaseOptions {
984                    dry_run: true,
985                    release_unstable_tag: Some("rc".to_owned()),
986                    ..PrepareReleaseOptions::default()
987                },
988            )
989            .unwrap();
990
991        assert!(!result.changed);
992        assert_eq!(result.info.current_branch.version.to_string(), "1.3-alpha");
993        assert_eq!(
994            result.info.new_branch.as_ref().unwrap().version.to_string(),
995            "1.2-rc"
996        );
997        assert!(result.output.starts_with("What-if:"));
998        let repository = fixture.repository();
999        assert_eq!(
1000            repository.head().unwrap().peel_to_commit().unwrap().id(),
1001            before
1002        );
1003        assert!(repository.find_branch("v1.2", BranchType::Local).is_err());
1004    }
1005
1006    #[test]
1007    fn prepares_and_merges_release_with_json_result() {
1008        let fixture = TestRepository::new(Some(&json("1.0-beta")), true);
1009        let original_branch = fixture.current_branch();
1010        let result = ReleaseManager::new()
1011            .prepare_release(
1012                &fixture.path,
1013                &PrepareReleaseOptions {
1014                    output_mode: ReleaseManagerOutputMode::Json,
1015                    ..PrepareReleaseOptions::default()
1016                },
1017            )
1018            .unwrap();
1019
1020        assert!(result.changed);
1021        assert_eq!(fixture.current_branch(), original_branch);
1022        assert_eq!(
1023            fixture
1024                .branch_version(&original_branch)
1025                .version
1026                .unwrap()
1027                .to_string(),
1028            "1.1-alpha"
1029        );
1030        assert_eq!(
1031            fixture.branch_version("v1.0").version.unwrap().to_string(),
1032            "1.0"
1033        );
1034        let repository = fixture.repository();
1035        assert_eq!(
1036            repository
1037                .head()
1038                .unwrap()
1039                .peel_to_commit()
1040                .unwrap()
1041                .parent_count(),
1042            2
1043        );
1044        let value: serde_json::Value = serde_json::from_str(&result.output).unwrap();
1045        assert_eq!(value["CurrentBranch"]["Name"], original_branch);
1046        assert_eq!(value["NewBranch"]["Name"], "v1.0");
1047        assert_eq!(value["NewBranch"]["Version"], "1.0");
1048    }
1049
1050    #[test]
1051    fn no_merge_leaves_divergent_single_parent_commits() {
1052        let fixture = TestRepository::new(Some(&json("1.0-beta")), true);
1053        ReleaseManager::new()
1054            .prepare_release(
1055                &fixture.path,
1056                &PrepareReleaseOptions {
1057                    merge_release_branch: false,
1058                    ..PrepareReleaseOptions::default()
1059                },
1060            )
1061            .unwrap();
1062        let repository = fixture.repository();
1063        assert_eq!(
1064            repository
1065                .head()
1066                .unwrap()
1067                .peel_to_commit()
1068                .unwrap()
1069                .parent_count(),
1070            1
1071        );
1072        assert_eq!(
1073            repository
1074                .find_branch("v1.0", BranchType::Local)
1075                .unwrap()
1076                .get()
1077                .peel_to_commit()
1078                .unwrap()
1079                .parent_count(),
1080            1
1081        );
1082    }
1083
1084    #[test]
1085    fn advances_an_existing_release_branch() {
1086        let fixture = TestRepository::new(Some(&json("1.2-beta")), true);
1087        fixture.checkout_new_branch("v1.2");
1088        let result = ReleaseManager::new()
1089            .prepare_release(&fixture.path, &PrepareReleaseOptions::default())
1090            .unwrap();
1091        assert!(result.info.new_branch.is_none());
1092        assert_eq!(
1093            fixture.branch_version("v1.2").version.unwrap().to_string(),
1094            "1.2"
1095        );
1096    }
1097
1098    #[test]
1099    fn custom_commit_message_is_formatted() {
1100        let fixture = TestRepository::new(Some(&json("1.0-beta")), true);
1101        ReleaseManager::new()
1102            .prepare_release(
1103                &fixture.path,
1104                &PrepareReleaseOptions {
1105                    commit_message: Some("{0} Custom {{message}}".to_owned()),
1106                    merge_release_branch: false,
1107                    ..PrepareReleaseOptions::default()
1108                },
1109            )
1110            .unwrap();
1111        let repository = fixture.repository();
1112        let message = repository
1113            .find_branch("v1.0", BranchType::Local)
1114            .unwrap()
1115            .get()
1116            .peel_to_commit()
1117            .unwrap()
1118            .summary()
1119            .unwrap()
1120            .unwrap()
1121            .to_owned();
1122        assert_eq!(message, "1.0 Custom {message}");
1123    }
1124
1125    #[test]
1126    fn detects_validation_failures() {
1127        let outside =
1128            env::temp_dir().join(format!("nbgv-release-no-repository-{}", std::process::id()));
1129        fs::create_dir_all(&outside).unwrap();
1130        let error = ReleaseManager::new()
1131            .prepare_release(&outside, &PrepareReleaseOptions::default())
1132            .unwrap_err();
1133        assert_eq!(error.error, ReleasePreparationError::NoGitRepo);
1134        fs::remove_dir_all(&outside).unwrap();
1135
1136        let no_version = TestRepository::new(None, true);
1137        assert_eq!(
1138            ReleaseManager::new()
1139                .prepare_release(&no_version.path, &PrepareReleaseOptions::default())
1140                .unwrap_err()
1141                .error,
1142            ReleasePreparationError::NoVersionFile
1143        );
1144
1145        let no_user = TestRepository::new(Some(&json("1.0-beta")), false);
1146        let repository = no_user.repository();
1147        let mut config = repository.config().unwrap();
1148        config.set_str("user.name", "").unwrap();
1149        config.set_str("user.email", "").unwrap();
1150        drop(config);
1151        drop(repository);
1152        assert_eq!(
1153            ReleaseManager::new()
1154                .prepare_release(&no_user.path, &PrepareReleaseOptions::default())
1155                .unwrap_err()
1156                .error,
1157            ReleasePreparationError::UserNotConfigured
1158        );
1159    }
1160
1161    #[test]
1162    fn rejects_dirty_detached_existing_and_invalid_increment() {
1163        let dirty = TestRepository::new(Some(&json("1.0-beta")), true);
1164        fs::write(dirty.path.join("dirty"), "dirty").unwrap();
1165        assert_eq!(
1166            ReleaseManager::new()
1167                .prepare_release(&dirty.path, &PrepareReleaseOptions::default())
1168                .unwrap_err()
1169                .error,
1170            ReleasePreparationError::UncommittedChanges
1171        );
1172
1173        let detached = TestRepository::new(Some(&json("1.0-beta")), true);
1174        let repository = detached.repository();
1175        let id = repository.head().unwrap().peel_to_commit().unwrap().id();
1176        repository.set_head_detached(id).unwrap();
1177        repository.checkout_head(None).unwrap();
1178        drop(repository);
1179        assert_eq!(
1180            ReleaseManager::new()
1181                .prepare_release(&detached.path, &PrepareReleaseOptions::default())
1182                .unwrap_err()
1183                .error,
1184            ReleasePreparationError::DetachedHead
1185        );
1186
1187        let existing = TestRepository::new(Some(&json("1.0-beta")), true);
1188        let repository = existing.repository();
1189        let commit = repository.head().unwrap().peel_to_commit().unwrap();
1190        repository.branch("v1.0", &commit, false).unwrap();
1191        drop(commit);
1192        drop(repository);
1193        assert_eq!(
1194            ReleaseManager::new()
1195                .prepare_release(&existing.path, &PrepareReleaseOptions::default())
1196                .unwrap_err()
1197                .error,
1198            ReleasePreparationError::BranchAlreadyExists
1199        );
1200
1201        let invalid_increment = TestRepository::new(
1202            Some(r#"{"version":"1.2","release":{"versionIncrement":"build"}}"#),
1203            true,
1204        );
1205        assert_eq!(
1206            ReleaseManager::new()
1207                .prepare_release(&invalid_increment.path, &PrepareReleaseOptions::default())
1208                .unwrap_err()
1209                .error,
1210            ReleasePreparationError::InvalidVersionIncrementSetting
1211        );
1212    }
1213
1214    #[test]
1215    fn rejects_version_decrement_and_no_increment() {
1216        let decrement = TestRepository::new(Some(&json("1.2")), true);
1217        assert_eq!(
1218            ReleaseManager::new()
1219                .prepare_release(
1220                    &decrement.path,
1221                    &PrepareReleaseOptions {
1222                        release_unstable_tag: Some("rc".to_owned()),
1223                        ..PrepareReleaseOptions::default()
1224                    }
1225                )
1226                .unwrap_err()
1227                .error,
1228            ReleasePreparationError::VersionDecrement
1229        );
1230
1231        let no_increment = TestRepository::new(Some(&json("1.2")), true);
1232        assert_eq!(
1233            ReleaseManager::new()
1234                .prepare_release(
1235                    &no_increment.path,
1236                    &PrepareReleaseOptions {
1237                        next_version: Some(Version::new(1, 2)),
1238                        ..PrepareReleaseOptions::default()
1239                    }
1240                )
1241                .unwrap_err()
1242                .error,
1243            ReleasePreparationError::NoVersionIncrement
1244        );
1245    }
1246
1247    #[test]
1248    fn formats_branch_and_tag_templates() {
1249        let options = VersionOptions::from_json(
1250            r#"{"version":"1.2-beta","release":{"branchName":"release/v{version}"}}"#,
1251            "",
1252        )
1253        .unwrap();
1254        assert_eq!(
1255            format_release_branch_name(&options).unwrap(),
1256            "release/v1.2"
1257        );
1258        let release = ReleaseOptions {
1259            tag_name: Some("product-{version}".to_owned()),
1260            ..ReleaseOptions::default()
1261        };
1262        assert_eq!(
1263            format_release_tag_name(&release, &"1.2-rc".parse().unwrap()).unwrap(),
1264            "product-1.2-rc"
1265        );
1266        assert_eq!(
1267            format_release_tag_name(
1268                &ReleaseOptions {
1269                    tag_name: Some("invalid".to_owned()),
1270                    ..ReleaseOptions::default()
1271                },
1272                &"1.2".parse().unwrap()
1273            )
1274            .unwrap_err()
1275            .error,
1276            ReleasePreparationError::InvalidTagNameSetting
1277        );
1278    }
1279
1280    #[test]
1281    fn signing_failure_is_explicit() {
1282        let fixture = TestRepository::new(Some(&json("1.0-beta")), true);
1283        let repository = fixture.repository();
1284        let mut config = repository.config().unwrap();
1285        config.set_bool("commit.gpgSign", true).unwrap();
1286        config.set_str("gpg.format", "openpgp").unwrap();
1287        config
1288            .set_str("user.signingKey", "definitely-not-a-real-key")
1289            .unwrap();
1290        drop(config);
1291        drop(repository);
1292        assert_eq!(
1293            ReleaseManager::new()
1294                .prepare_release(&fixture.path, &PrepareReleaseOptions::default())
1295                .unwrap_err()
1296                .error,
1297            ReleasePreparationError::GitCommandFailed
1298        );
1299    }
1300}