-
Notifications
You must be signed in to change notification settings - Fork 65
fix: create valid Standard JSON to verify for projects with symlinks #35
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
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
1500562
test: add failing test for Standard JSON Input creation
tash-2s b15ac2d
fix: create valid Standard JSON to verify for projects with symlinks
tash-2s 409414b
docs: add comment for `utils::clean_solidity_path`
tash-2s e9dfe3a
test: add more test for `utils::clean_solidity_path`
tash-2s 4adf2ad
refactor: `if let` is simpler than `match` here
tash-2s 80acefe
refactor: clarified the intent of the code
tash-2s File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -177,6 +177,81 @@ pub fn canonicalize(path: impl AsRef<Path>) -> Result<PathBuf, SolcIoError> { | |
res.map_err(|err| SolcIoError::new(err, path)) | ||
} | ||
|
||
/// Returns a normalized Solidity file path for the given import path based on the specified | ||
/// directory. | ||
/// | ||
/// This function resolves `./` and `../`, but, unlike [`canonicalize`], it does not resolve | ||
/// symbolic links. | ||
/// | ||
/// The function returns an error if the normalized path does not exist in the file system. | ||
/// | ||
/// See also: <https://docs.soliditylang.org/en/v0.8.23/path-resolution.html> | ||
pub fn normalize_solidity_import_path( | ||
directory: impl AsRef<Path>, | ||
import_path: impl AsRef<Path>, | ||
) -> Result<PathBuf, SolcIoError> { | ||
let original = directory.as_ref().join(import_path); | ||
let cleaned = clean_solidity_path(&original); | ||
|
||
// this is to align the behavior with `canonicalize` | ||
use path_slash::PathExt; | ||
let normalized = PathBuf::from(dunce::simplified(&cleaned).to_slash_lossy().as_ref()); | ||
|
||
// checks if the path exists without reading its content and obtains an io error if it doesn't. | ||
normalized.metadata().map(|_| normalized).map_err(|err| SolcIoError::new(err, original)) | ||
} | ||
|
||
// This function lexically cleans the given path. | ||
// | ||
// It performs the following transformations for the path: | ||
// | ||
// * Resolves references (current directories (`.`) and parent (`..`) directories). | ||
// * Reduces repeated separators to a single separator (e.g., from `//` to `/`). | ||
// | ||
// This transformation is lexical, not involving the file system, which means it does not account | ||
// for symlinks. This approach has a caveat. For example, consider a filesystem-accessible path | ||
// `a/b/../c.sol` passed to this function. It returns `a/c.sol`. However, if `b` is a symlink, | ||
// `a/c.sol` might not be accessible in the filesystem in some environments. Despite this, it's | ||
// unlikely that this will pose a problem for our intended use. | ||
// | ||
// # How it works | ||
// | ||
// The function splits the given path into components, where each component roughly corresponds to a | ||
// string between separators. It then iterates over these components (starting from the leftmost | ||
// part of the path) to reconstruct the path. The following steps are applied to each component: | ||
// | ||
// * If the component is a current directory, it's removed. | ||
// * If the component is a parent directory, the following rules are applied: | ||
// * If the preceding component is a normal, then both the preceding normal component and the | ||
// parent directory component are removed. (Examples of normal components include `a` and `b` | ||
// in `a/b`.) | ||
// * Otherwise (if there is no preceding component, or if the preceding component is a parent, | ||
// root, or prefix), it remains untouched. | ||
// * Otherwise, the component remains untouched. | ||
// | ||
// Finally, the processed components are reassembled into a path. | ||
fn clean_solidity_path(original_path: impl AsRef<Path>) -> PathBuf { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Could we add some docs here? I know it's an internal function, but having docs is nice and useful to revisit this later whenever needed |
||
let mut new_path = Vec::new(); | ||
|
||
for component in original_path.as_ref().components() { | ||
match component { | ||
Component::Prefix(..) | Component::RootDir | Component::Normal(..) => { | ||
new_path.push(component); | ||
} | ||
Component::CurDir => {} | ||
Component::ParentDir => { | ||
if let Some(Component::Normal(..)) = new_path.last() { | ||
new_path.pop(); | ||
} else { | ||
new_path.push(component); | ||
} | ||
} | ||
} | ||
} | ||
|
||
new_path.iter().collect() | ||
} | ||
|
||
/// Returns the same path config but with canonicalized paths. | ||
/// | ||
/// This will take care of potential symbolic linked directories. | ||
|
@@ -228,7 +303,7 @@ pub fn resolve_library(libs: &[impl AsRef<Path>], source: impl AsRef<Path>) -> O | |
/// until the `root` is reached. | ||
/// | ||
/// If an existing file under `root` is found, this returns the path up to the `import` path and the | ||
/// canonicalized `import` path itself: | ||
/// normalized `import` path itself: | ||
/// | ||
/// For example for following layout: | ||
/// | ||
|
@@ -247,7 +322,7 @@ pub fn resolve_absolute_library( | |
) -> Option<(PathBuf, PathBuf)> { | ||
let mut parent = cwd.parent()?; | ||
while parent != root { | ||
if let Ok(import) = canonicalize(parent.join(import)) { | ||
if let Ok(import) = normalize_solidity_import_path(parent, import) { | ||
return Some((parent.to_path_buf(), import)); | ||
} | ||
parent = parent.parent()?; | ||
|
@@ -654,6 +729,99 @@ pragma solidity ^0.8.0; | |
assert_eq!(Some("^0.8.0"), find_version_pragma(s).map(|s| s.as_str())); | ||
} | ||
|
||
#[test] | ||
fn can_normalize_solidity_import_path() { | ||
let dir = tempfile::tempdir().unwrap(); | ||
let dir_path = dir.path(); | ||
|
||
// File structure: | ||
// | ||
// `dir_path` | ||
// └── src (`cwd`) | ||
// ├── Token.sol | ||
// └── common | ||
// └── Burnable.sol | ||
|
||
fs::create_dir_all(dir_path.join("src/common")).unwrap(); | ||
fs::write(dir_path.join("src/Token.sol"), "").unwrap(); | ||
fs::write(dir_path.join("src/common/Burnable.sol"), "").unwrap(); | ||
|
||
// assume that the import path is specified in Token.sol | ||
let cwd = dir_path.join("src"); | ||
|
||
assert_eq!( | ||
normalize_solidity_import_path(&cwd, "./common/Burnable.sol").unwrap(), | ||
dir_path.join("src/common/Burnable.sol"), | ||
); | ||
|
||
assert!(normalize_solidity_import_path(&cwd, "./common/Pausable.sol").is_err()); | ||
} | ||
|
||
// This test is exclusive to unix because creating a symlink is a privileged action on Windows. | ||
// https://doc.rust-lang.org/std/os/windows/fs/fn.symlink_dir.html#limitations | ||
#[test] | ||
#[cfg(unix)] | ||
fn can_normalize_solidity_import_path_symlink() { | ||
let dir = tempfile::tempdir().unwrap(); | ||
let dir_path = dir.path(); | ||
|
||
// File structure: | ||
// | ||
// `dir_path` | ||
// ├── dependency | ||
// │ └── Math.sol | ||
// └── project | ||
// ├── node_modules | ||
// │ └── dependency -> symlink to actual 'dependency' directory | ||
// └── src (`cwd`) | ||
// └── Token.sol | ||
|
||
fs::create_dir_all(dir_path.join("project/src")).unwrap(); | ||
fs::write(dir_path.join("project/src/Token.sol"), "").unwrap(); | ||
fs::create_dir(dir_path.join("project/node_modules")).unwrap(); | ||
|
||
fs::create_dir(dir_path.join("dependency")).unwrap(); | ||
fs::write(dir_path.join("dependency/Math.sol"), "").unwrap(); | ||
|
||
std::os::unix::fs::symlink( | ||
dir_path.join("dependency"), | ||
dir_path.join("project/node_modules/dependency"), | ||
) | ||
.unwrap(); | ||
|
||
// assume that the import path is specified in Token.sol | ||
let cwd = dir_path.join("project/src"); | ||
|
||
assert_eq!( | ||
normalize_solidity_import_path(cwd, "../node_modules/dependency/Math.sol").unwrap(), | ||
dir_path.join("project/node_modules/dependency/Math.sol"), | ||
); | ||
} | ||
|
||
#[test] | ||
fn can_clean_solidity_path() { | ||
assert_eq!(clean_solidity_path("a"), PathBuf::from("a")); | ||
assert_eq!(clean_solidity_path("./a"), PathBuf::from("a")); | ||
assert_eq!(clean_solidity_path("../a"), PathBuf::from("../a")); | ||
assert_eq!(clean_solidity_path("/a/"), PathBuf::from("/a")); | ||
assert_eq!(clean_solidity_path("//a"), PathBuf::from("/a")); | ||
assert_eq!(clean_solidity_path("a/b"), PathBuf::from("a/b")); | ||
assert_eq!(clean_solidity_path("a//b"), PathBuf::from("a/b")); | ||
assert_eq!(clean_solidity_path("/a/b"), PathBuf::from("/a/b")); | ||
assert_eq!(clean_solidity_path("a/./b"), PathBuf::from("a/b")); | ||
assert_eq!(clean_solidity_path("a/././b"), PathBuf::from("a/b")); | ||
assert_eq!(clean_solidity_path("/a/../b"), PathBuf::from("/b")); | ||
assert_eq!(clean_solidity_path("a/./../b/."), PathBuf::from("b")); | ||
assert_eq!(clean_solidity_path("a/b/c"), PathBuf::from("a/b/c")); | ||
assert_eq!(clean_solidity_path("a/b/../c"), PathBuf::from("a/c")); | ||
assert_eq!(clean_solidity_path("a/b/../../c"), PathBuf::from("c")); | ||
assert_eq!(clean_solidity_path("a/b/../../../c"), PathBuf::from("../c")); | ||
assert_eq!( | ||
clean_solidity_path("a/../b/../../c/./Token.sol"), | ||
PathBuf::from("../c/Token.sol") | ||
); | ||
} | ||
|
||
#[test] | ||
fn can_find_ancestor() { | ||
let a = Path::new("/foo/bar/bar/test.txt"); | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Rust doesn't have this normalization function (resolves
.
and..
but doesn't resolve symlinks), so I wrote the function myself. The function is simple, but I found several crates that perform similar tasks, so I can switch to one of them if preferred.e.g.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
gotcha—I'll defer to @mattsse here, but the function is so small I don't mind keeping it here instead of pulling in an additional dep, as we also have tests.