Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Search for grammar file from CARGO_MANIFEST_DIR #702

Merged
merged 1 commit into from Aug 23, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion derive/tests/grammar.rs
Expand Up @@ -16,7 +16,7 @@ extern crate pest;
extern crate pest_derive;

#[derive(Parser)]
#[grammar = "../tests/grammar.pest"]
#[grammar = "tests/grammar.pest"]
struct GrammarParser;

#[test]
Expand Down
16 changes: 15 additions & 1 deletion generator/src/lib.rs
Expand Up @@ -41,7 +41,21 @@ pub fn derive_parser(input: TokenStream, include_grammar: bool) -> TokenStream {
let (data, path) = match content {
GrammarSource::File(ref path) => {
let root = env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".into());
let path = Path::new(&root).join("src/").join(&path);

// Check whether we can find a file at the path relative to the CARGO_MANIFEST_DIR
// first.
//
// If we cannot find the expected file over there, fallback to the
// `CARGO_MANIFEST_DIR/src`, which is the old default and kept for convenience
// reasons.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe can add a TODO with a link to https://doc.rust-lang.org/std/path/fn.absolute.html ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done :)

// TODO: This could be refactored once `std::path::absolute()` get's stabilized.
// https://doc.rust-lang.org/std/path/fn.absolute.html
let path = if Path::new(&root).join(&path).exists() {
Path::new(&root).join(&path)
} else {
Path::new(&root).join("src/").join(&path)
};

let file_name = match path.file_name() {
Some(file_name) => file_name,
None => panic!("grammar attribute should point to a file"),
Expand Down