vdev/utils/
cargo.rs

1//! Cargo.toml parsing and version utilities
2
3use std::{collections::BTreeMap, fs};
4
5use anyhow::{Context, Result};
6use serde::Deserialize;
7use serde_json::Value;
8
9#[derive(Deserialize)]
10pub struct CargoTomlPackage {
11    pub version: String,
12}
13
14/// The bits of the top-level `Cargo.toml` configuration that `vdev` uses to drive its features.
15#[derive(Deserialize)]
16pub struct CargoToml {
17    pub package: CargoTomlPackage,
18    pub features: BTreeMap<String, Value>,
19}
20
21impl CargoToml {
22    pub fn load() -> Result<CargoToml> {
23        let text = fs::read_to_string("Cargo.toml").context("Could not read `Cargo.toml`")?;
24        toml::from_str::<CargoToml>(&text).context("Invalid contents in `Cargo.toml`")
25    }
26}
27
28/// Read the version string from `Cargo.toml`
29pub fn read_version() -> Result<String> {
30    CargoToml::load().map(|cargo| cargo.package.version)
31}
32
33/// Use the version provided by env vars or default to reading from `Cargo.toml`.
34pub fn get_version() -> Result<String> {
35    std::env::var("VERSION")
36        .or_else(|_| std::env::var("VECTOR_VERSION"))
37        .or_else(|_| read_version())
38}