macro: use CARGO_PKG_NAME instead of reading Cargo.toml

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
This commit is contained in:
Wolfgang Bumiller 2021-10-13 11:28:16 +02:00
parent c9d79aaea8
commit 9de065545b
2 changed files with 10 additions and 56 deletions

View File

@ -21,7 +21,6 @@ anyhow = "1.0"
proc-macro2 = "1.0"
quote = "1.0"
syn = { version = "1.0", features = [ "full" ] }
toml = "0.5.5"
[dev-dependencies]
perlmod = { path = "../perlmod" }

View File

@ -1,8 +1,5 @@
use std::collections::HashMap;
use std::convert::TryFrom;
use std::env;
use std::fs::File;
use std::path::PathBuf;
use anyhow::Error;
@ -10,8 +7,6 @@ use proc_macro2::{Ident, Span};
use syn::AttributeArgs;
use toml::Value;
use crate::attribs::ModuleAttrs;
const MODULE_HEAD: &str = r#"
@ -138,54 +133,14 @@ impl Package {
}
}
fn read_cargo_toml(why: Span) -> Result<HashMap<String, Value>, syn::Error> {
let manifest_dir = env::var("CARGO_MANIFEST_DIR")
.map_err(|err| format_err!(why, "failed to get CARGO_MANIFEST_DIR variable: {}", err))?;
let cargo_toml_path = PathBuf::from(manifest_dir).join("Cargo.toml");
use std::io::Read;
let mut content = String::new();
File::open(cargo_toml_path)
.map_err(|err| format_err!(why, "failed to open Cargo.toml: {}", err))?
.read_to_string(&mut content)
.map_err(|err| format_err!(why, "failed to read Cargo.toml: {}", err))?;
toml::from_str(&content).map_err(|err| format_err!(why, "failed to parse Cargo.toml: {}", err))
}
static mut LIB_NAME: Option<String> = None;
pub fn get_default_lib_name(why: Span) -> Result<&'static str, syn::Error> {
unsafe {
if let Some(name) = &LIB_NAME {
return Ok(name);
}
}
let cargo = read_cargo_toml(why)?;
let package = cargo
.get("package")
.ok_or_else(|| format_err!(
why,
"did not find a [package] section in Cargo.toml, try to specify the library name manually",
))?;
let name = package.get("name").ok_or_else(|| {
format_err!(
why,
"failed to find the package name in Cargo.toml, try to specify the library name manually",
)
})?;
let name = name.as_str().ok_or_else(|| {
format_err!(
why,
"package name in Cargo.toml is not a string, try to specify the library name manually",
)
})?;
unsafe {
LIB_NAME = Some(name.replace('-', "_"));
return Ok(LIB_NAME.as_ref().unwrap());
}
pub fn get_default_lib_name(why: Span) -> Result<String, syn::Error> {
env::var("CARGO_PKG_NAME")
.map(|s| s.replace('-', "_"))
.map_err(|err| {
format_err!(
why,
"failed to get CARGO_PKG_NAME environment variable: {}",
err
)
})
}