Skip to main content

semver_cargo/
cargo.rs

1use std::collections::HashMap;
2
3use derive_getters::Getters;
4use r_log::{LogLevel, Logger};
5use semver_common::{Alert, Version, git, run_command};
6
7use crate::Config;
8
9#[derive(Getters)]
10pub struct Cargo {
11    config: Config,
12    version: Version,
13    logger: Logger,
14    env: HashMap<String, String>,
15    updated: bool,
16    dry_run: bool,
17}
18
19impl Cargo {
20    /// Initialize the plugin with the data from the cli arguments.
21    pub fn init(
22        config: Config,
23        version: Version,
24        level: LogLevel,
25        env: HashMap<String, String>,
26        updated: bool,
27        dry_run: bool,
28    ) -> Result<Self, Alert> {
29        if *config.publish() {
30            env.get("CARGO_REGISTRY_TOKEN")
31                .ok_or("Environment variable CARGO_REGISTRY_TOKEN must be set to publish crate.")?;
32        }
33        Ok(Self {
34            config,
35            version,
36            logger: Logger::new(level),
37            env,
38            updated,
39            dry_run,
40        })
41    }
42
43    /// Install cargo-edit to use for bumping the version in Cargo.toml.
44    pub fn install(&self) -> Result<(), Alert> {
45        run_command("cargo", ["install", "cargo-edit"], Some(&self.logger))?;
46        Ok(())
47    }
48
49    /// Run cargo set-version to bump the version in Cargo.toml.
50    pub fn set_version(&self) -> Result<(), Alert> {
51        run_command(
52            "cargo",
53            ["set-version", &self.version.short()],
54            Some(&self.logger),
55        )?;
56        Ok(())
57    }
58
59    /// Run cargo publish to publish the crate to crates.io. Can do a dry run for testing.
60    pub fn publish(&self, dry_run: bool) -> Result<(), Alert> {
61        match dry_run {
62            true => run_command("cargo", ["publish", "--dry-run"], Some(&self.logger))?,
63            false => run_command("cargo", ["publish"], Some(&self.logger))?,
64        };
65        Ok(())
66    }
67
68    /// Run the full release process for cargo.
69    pub fn release(&self) -> Result<(), Alert> {
70        if self.updated || *self.config.act_on_no_update() {
71            // Attempt to install cargo set-version
72            self.install()?;
73
74            // Update version in Cargo.toml
75            if *self.config.set_version() {
76                self.set_version()?;
77                git::commit_all(
78                    &format!(
79                        "semver-cargo bump cargo version to {}",
80                        self.version.short()
81                    ),
82                    self.logger(),
83                )?;
84            }
85
86            // Publish crate.
87            if *self.config.publish() {
88                self.publish(self.dry_run)?;
89            }
90        }
91        Ok(())
92    }
93}