Skip to content

Commit

Permalink
uniffi_macros: Force-include the Cargo.toml to read
Browse files Browse the repository at this point in the history
  • Loading branch information
badboy committed Aug 1, 2023
1 parent a305c8d commit 6344ff7
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 6 deletions.
22 changes: 22 additions & 0 deletions uniffi_macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,9 +186,31 @@ pub fn include_scaffolding(component_name: TokenStream) -> TokenStream {
},
None,
);

let toml_path = match util::manifest_path() {
Ok(path) => path.display().to_string(),
Err(_) => {
return quote! {
compile_error!("This macro assumes the crate has a build.rs script, but $OUT_DIR is not present");
}.into();
}
};

quote! {
#metadata

// FIXME(HACK):
// Include the `Cargo.toml` file into the build.
// That way cargo tracks the file and other tools relying on file
// tracking see it as well.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=1846223
// In the future we should handle that by using the `track_path::path` API,
// see https://github.com/rust-lang/rust/pull/84029
#[allow(dead_code)]
mod __unused {
const _: &[u8] = include_bytes!(#toml_path);
}

include!(concat!(env!("OUT_DIR"), "/", #name, ".uniffi.rs"));
}
}.into()
Expand Down
16 changes: 10 additions & 6 deletions uniffi_macros/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,24 @@

use proc_macro2::{Ident, Span, TokenStream};
use quote::{format_ident, quote, ToTokens};
use std::path::{Path as StdPath, PathBuf};
use syn::{
ext::IdentExt,
parse::{Parse, ParseStream},
Attribute, Path, Token,
};

pub fn manifest_path() -> Result<PathBuf, String> {
let manifest_dir =
std::env::var_os("CARGO_MANIFEST_DIR").ok_or("`CARGO_MANIFEST_DIR` is not set")?;

Ok(StdPath::new(&manifest_dir).join("Cargo.toml"))
}

#[cfg(not(feature = "nightly"))]
pub fn mod_path() -> syn::Result<String> {
// Without the nightly feature and TokenStream::expand_expr, just return the crate name

use std::path::Path;

use fs_err as fs;
use once_cell::sync::Lazy;
use serde::Deserialize;
Expand All @@ -38,11 +44,9 @@ pub fn mod_path() -> syn::Result<String> {
}

static LIB_CRATE_MOD_PATH: Lazy<Result<String, String>> = Lazy::new(|| {
let manifest_dir =
std::env::var_os("CARGO_MANIFEST_DIR").ok_or("`CARGO_MANIFEST_DIR` is not set")?;
let file = manifest_path()?;
let cargo_toml_bytes = fs::read(file).map_err(|e| e.to_string())?;

let cargo_toml_bytes =
fs::read(Path::new(&manifest_dir).join("Cargo.toml")).map_err(|e| e.to_string())?;
let cargo_toml = toml::from_slice::<CargoToml>(&cargo_toml_bytes)
.map_err(|e| format!("Failed to parse `Cargo.toml`: {e}"))?;

Expand Down

0 comments on commit 6344ff7

Please sign in to comment.