Skip to content

Commit 71f9b8e

Browse files
authored
fix(common): find target by path if present (#10538)
* fix(`common`): prefer to find by path if present * test
1 parent 9e53778 commit 71f9b8e

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

crates/common/src/contracts.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -454,6 +454,29 @@ pub fn find_target_path(project: &Project, identifier: &PathOrContractInfo) -> R
454454
match identifier {
455455
PathOrContractInfo::Path(path) => Ok(canonicalized(project.root().join(path))),
456456
PathOrContractInfo::ContractInfo(info) => {
457+
if let Some(path) = info.path.as_ref() {
458+
let path = canonicalized(project.root().join(path));
459+
let sources = project.sources()?;
460+
let contract_path = sources
461+
.iter()
462+
.find_map(|(src_path, _)| {
463+
if **src_path == path {
464+
return Some(src_path.clone());
465+
}
466+
None
467+
})
468+
.ok_or_else(|| {
469+
eyre::eyre!(
470+
"Could not find source file for contract `{}` at {}",
471+
info.name,
472+
path.strip_prefix(project.root()).unwrap().display()
473+
)
474+
})?;
475+
return Ok(contract_path)
476+
}
477+
// If ContractInfo.path hasn't been provided we try to find the contract using the name.
478+
// This will fail if projects have multiple contracts with the same name. In that case,
479+
// path must be specified.
457480
let path = project.find_contract_path(&info.name)?;
458481
Ok(path)
459482
}

crates/forge/tests/cli/cmd.rs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3569,6 +3569,42 @@ forgetest!(test_inspect_contract_with_same_name, |prj, cmd| {
35693569
╰-------------------------------+----------╯
35703570
35713571
3572+
"#]]);
3573+
});
3574+
3575+
// <https://github.com/foundry-rs/foundry/issues/10531>
3576+
forgetest!(inspect_multiple_contracts_with_different_paths, |prj, cmd| {
3577+
prj.add_source(
3578+
"Source.sol",
3579+
r#"
3580+
contract Source {
3581+
function foo() public {}
3582+
}
3583+
"#,
3584+
)
3585+
.unwrap();
3586+
3587+
prj.add_source(
3588+
"another/Source.sol",
3589+
r#"
3590+
contract Source {
3591+
function bar() public {}
3592+
}
3593+
"#,
3594+
)
3595+
.unwrap();
3596+
3597+
cmd.args(["inspect", "src/another/Source.sol:Source", "methodIdentifiers"])
3598+
.assert_success()
3599+
.stdout_eq(str![[r#"
3600+
3601+
╭--------+------------╮
3602+
| Method | Identifier |
3603+
+=====================+
3604+
| bar() | febb0f7e |
3605+
╰--------+------------╯
3606+
3607+
35723608
"#]]);
35733609
});
35743610

0 commit comments

Comments
 (0)