From cb799a980fd59c61f2dbecf262b87ed1c2343b0a Mon Sep 17 00:00:00 2001 From: schaeff Date: Tue, 15 Jan 2019 16:18:44 +0100 Subject: [PATCH] branch based on first path component --- zokrates_fs_resolver/src/lib.rs | 47 ++++++++++++++++++++++++--------- 1 file changed, 35 insertions(+), 12 deletions(-) diff --git a/zokrates_fs_resolver/src/lib.rs b/zokrates_fs_resolver/src/lib.rs index 473b7abe..dc73abfb 100644 --- a/zokrates_fs_resolver/src/lib.rs +++ b/zokrates_fs_resolver/src/lib.rs @@ -1,7 +1,7 @@ use std::fs::File; use std::io; use std::io::BufReader; -use std::path::PathBuf; +use std::path::{Component, PathBuf}; const ZOKRATES_HOME: &str = &"ZOKRATES_HOME"; @@ -22,22 +22,16 @@ fn resolve_with_location( ) -> Result<(BufReader, String, String), io::Error> { let source = PathBuf::from(source); - println!( - "source :{:?} starts_with: {:?}", - source, - source.starts_with(".") - ); - - let base = match source.starts_with(".") { - false => PathBuf::from(std::env::var(ZOKRATES_HOME).unwrap_or("".to_string())), - true => PathBuf::from(location), + // paths starting with `./` or `../` are interpreted relative to the current file + // other paths `abc/def.code` are interpreted relative to $ZOKRATES_HOME + let base = match source.components().next() { + Some(Component::CurDir) | Some(Component::ParentDir) => PathBuf::from(location), + _ => PathBuf::from(std::env::var(ZOKRATES_HOME).unwrap_or("".to_string())), }; let path = base.join(PathBuf::from(source)); let (next_location, alias) = generate_next_parameters(&path)?; - println!("{:?}", path); - File::open(path).and_then(|f| Ok((BufReader::new(f), next_location, alias))) } @@ -179,6 +173,35 @@ mod tests { assert_eq!(code, "\n".to_string()); } + #[test] + fn navigate_up() { + use std::io::BufRead; + use std::io::Write; + + // create a user folder with a code file + let source_folder = tempfile::tempdir().unwrap(); + let source_subfolder = tempfile::tempdir_in(&source_folder).unwrap(); + let file_path = source_folder.path().join("bar.code"); + let mut file = File::create(file_path).unwrap(); + writeln!(file, "").unwrap(); + + let result = resolve( + &Some( + source_subfolder + .path() + .to_path_buf() + .to_string_lossy() + .to_string(), + ), + &"../bar.code".to_string(), + ); + assert!(result.is_ok()); + let mut code = String::new(); + result.unwrap().0.read_line(&mut code).unwrap(); + // the imported file should be the user's + assert_eq!(code, "\n".to_string()); + } + #[test] fn dont_fallback_to_std() { use std::io::Write;