Skip to content

Commit

Permalink
Add dynamic version constant feature
Browse files Browse the repository at this point in the history
* Add custom build script to generate VERSION constant from Cargo.toml
version field
  • Loading branch information
ByteOtter committed Sep 6, 2024
1 parent fe93bf8 commit 35ffbe1
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
5 changes: 5 additions & 0 deletions src/bindgen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,11 @@ fn create_lib_dir(output_path: &Path) -> io::Result<()> {
output_path.file_name().unwrap().to_string_lossy()
)?;

fs::write(
output_path.join("build.rs"),
include_str!("templates/build.rs.template"),
)?;

// Create the "README.md" file.
fs::write(
output_path.join("README.md"),
Expand Down
6 changes: 5 additions & 1 deletion src/templates/Cargo.toml.template
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,17 @@ name = "{}"
version = "0.1.0"
authors = ["Your Name"]
edition = "2021"
build = "build.rs"

[lib]
path = "src/lib.rs"

[build-dependencies]
toml = "0.8.19"

[dependencies]
serde = {{ version = "1.0.195", features = ["derive"] }}
serde_json = "1.0.108"
serde_qs = "0.12.0"
chrono = "0.4.31"
reqwest = {{ version = "0.11.22", features = ["blocking", "json"] }}
reqwest = {{ version = "0.11.22", features = ["blocking", "json"] }}
26 changes: 26 additions & 0 deletions src/templates/build.rs.template
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
use std::fs::File;
use std::io::Write;
use std::path::Path;
use toml::Value;

fn main() {
let manifest_path = Path::new("Cargo.toml");

let content =
std::fs::read_to_string(manifest_path).expect("Unable to read manifest to string.");
let parsed_toml: Value = content.parse().expect("Failed to parse toml!");

let version = parsed_toml["package"]["version"]
.as_str()
.unwrap_or("0.0.0");

let version_file_path = Path::new("src").join("version.rs");
let mut file = File::create(version_file_path).expect("Unable to create version.rs!");
writeln!(
file,
"#[allow(dead_code)]\npub const VERSION: &str = \"{}\";",
version
)
.expect("Unable to write to file!");
}

0 comments on commit 35ffbe1

Please sign in to comment.