Skip to main content

ghaction_version_gen/
rust.rs

1// Copyright (C) 2021 Leandro Lisboa Penz <lpenz@lpenz.org>
2// This file is subject to the terms and conditions defined in
3// file 'LICENSE', which is part of this source code package.
4
5use std::fs;
6use std::io::ErrorKind;
7use std::path::Path;
8
9use color_eyre::Result;
10use color_eyre::eyre::OptionExt;
11
12use toml::Table;
13
14#[derive(Debug, PartialEq, Eq)]
15pub struct Crate {
16    pub name: String,
17    pub version: String,
18}
19
20pub fn crate_data<P: AsRef<Path>>(repo: P) -> Result<Option<Crate>> {
21    let cargofile = repo.as_ref().join("Cargo.toml");
22    let result = fs::read_to_string(cargofile);
23    if let Err(e) = result {
24        return if e.kind() == ErrorKind::NotFound {
25            Ok(None)
26        } else {
27            Err(e.into())
28        };
29    }
30    let contents = result.unwrap();
31    let info = contents.parse::<Table>()?;
32    if info.get("workspace").is_some() {
33        return Ok(None);
34    }
35    let package = &info
36        .get("package")
37        .ok_or_eyre("could not find package section")?;
38    let mut name: String = package
39        .get("name")
40        .ok_or_eyre("could not find name in package section")?
41        .to_string();
42    if &name[0..1] == "\"" && &name[name.len() - 1..name.len()] == "\"" {
43        name = name[1..name.len() - 1].to_string();
44    }
45    let version_value = &package
46        .get("version")
47        .ok_or_eyre("could not find version in package section")?;
48    let version_str = version_value
49        .as_str()
50        .ok_or_eyre("could not find convert version to string")?;
51    Ok(Some(Crate {
52        name: name.to_string(),
53        version: version_str.to_string(),
54    }))
55}