/ src / implementations / rust.rs
rust.rs
 1  use crate::utils::{open_file, read_file, write_file};
 2  use anyhow::Result;
 3  use std::{fs::File, io, process::Command};
 4  
 5  pub const CARGO_TOML: &str = "Cargo.toml";
 6  
 7  pub fn open_cargo_toml() -> io::Result<File> {
 8    open_file(CARGO_TOML)
 9  }
10  
11  pub fn get_current_version() -> Result<String> {
12    let content = read_file(&mut open_cargo_toml()?)?;
13    let content: toml::Value = toml::from_str(&content)?;
14  
15    let version = content
16      .get("package")
17      .and_then(|package| package.get("version"))
18      .and_then(|version| version.as_str())
19      .ok_or_else(|| anyhow::anyhow!("'Cargo.toml' is missing 'version' property."))?;
20  
21    Ok(version.to_string())
22  }
23  
24  /// Edits the `Cargo.toml` file and updates the value of the `version` property.
25  pub fn bump_version(version: &str) -> Result<()> {
26    let mut file = open_cargo_toml()?;
27  
28    let content = read_file(&mut file)?;
29    let mut content: toml::Value = toml::from_str(&content)?;
30  
31    let version_property = content
32      .get_mut("package")
33      .and_then(|package| package.get_mut("version"))
34      .ok_or_else(|| anyhow::anyhow!("'Cargo.toml' is missing 'version' property."))?;
35  
36    *version_property = toml::Value::String(version.to_string());
37  
38    let content = toml::to_string(&content)?;
39    write_file(&mut file, content)?;
40  
41    // We have to update the `Cargo.lock` file as well.
42    if !Command::new("cargo")
43      .arg("check")
44      .output()?
45      .status
46      .success()
47    {
48      return Err(anyhow::anyhow!("failed to update lockfile"));
49    }
50  
51    Ok(())
52  }