1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
//! The output of a compiled project
use crate::{
artifacts::{
contract::{CompactContractBytecode, CompactContractRef, Contract},
Error, Severity,
},
buildinfo::RawBuildInfo,
info::ContractInfoRef,
sources::{VersionedSourceFile, VersionedSourceFiles},
ArtifactId, ArtifactOutput, Artifacts, CompilerOutput, ConfigurableArtifacts, SolcIoError,
};
use contracts::{VersionedContract, VersionedContracts};
use semver::Version;
use std::{collections::BTreeMap, fmt, path::Path};
use tracing::trace;
pub mod contracts;
pub mod info;
pub mod sources;
/// Contains a mixture of already compiled/cached artifacts and the input set of sources that still
/// need to be compiled.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ProjectCompileOutput<T: ArtifactOutput = ConfigurableArtifacts> {
/// contains the aggregated `CompilerOutput`
pub(crate) compiler_output: AggregatedCompilerOutput,
/// all artifact files from `output` that were freshly compiled and written
pub(crate) compiled_artifacts: Artifacts<T::Artifact>,
/// All artifacts that were read from cache
pub(crate) cached_artifacts: Artifacts<T::Artifact>,
/// errors that should be omitted
pub(crate) ignored_error_codes: Vec<u64>,
/// set minimum level of severity that is treated as an error
pub(crate) compiler_severity_filter: Severity,
}
impl<T: ArtifactOutput> ProjectCompileOutput<T> {
/// Converts all `\\` separators in _all_ paths to `/`
pub fn slash_paths(&mut self) {
self.compiler_output.slash_paths();
self.compiled_artifacts.slash_paths();
self.cached_artifacts.slash_paths();
}
/// Convenience function fo [`Self::slash_paths()`]
pub fn with_slashed_paths(mut self) -> Self {
self.slash_paths();
self
}
/// All artifacts together with their contract file name and name `<file name>:<name>`
///
/// This returns a chained iterator of both cached and recompiled contract artifacts
///
/// # Example
///
/// ```no_run
/// use std::collections::btree_map::BTreeMap;
/// use ethers_solc::ConfigurableContractArtifact;
/// use ethers_solc::{ArtifactId, Project};
///
/// let project = Project::builder().build().unwrap();
/// let contracts: BTreeMap<ArtifactId, ConfigurableContractArtifact> = project.compile().unwrap().into_artifacts().collect();
/// ```
pub fn into_artifacts(self) -> impl Iterator<Item = (ArtifactId, T::Artifact)> {
let Self { cached_artifacts, compiled_artifacts, .. } = self;
cached_artifacts.into_artifacts::<T>().chain(compiled_artifacts.into_artifacts::<T>())
}
/// This returns a chained iterator of both cached and recompiled contract artifacts that yields
/// the contract name and the corresponding artifact
///
/// # Example
///
/// ```no_run
/// use std::collections::btree_map::BTreeMap;
/// use ethers_solc::ConfigurableContractArtifact;
/// use ethers_solc::Project;
///
/// let project = Project::builder().build().unwrap();
/// let artifacts: BTreeMap<String, &ConfigurableContractArtifact> = project.compile().unwrap().artifacts().collect();
/// ```
pub fn artifacts(&self) -> impl Iterator<Item = (String, &T::Artifact)> {
self.versioned_artifacts().map(|(name, (artifact, _))| (name, artifact))
}
/// This returns a chained iterator of both cached and recompiled contract artifacts that yields
/// the contract name and the corresponding artifact
///
/// # Example
///
/// ```no_run
/// use std::collections::btree_map::BTreeMap;
/// use semver::Version;
/// use ethers_solc::ConfigurableContractArtifact;
/// use ethers_solc::Project;
///
/// let project = Project::builder().build().unwrap();
/// let artifacts: BTreeMap<String, (&ConfigurableContractArtifact, &Version)> = project.compile().unwrap().versioned_artifacts().collect();
/// ```
pub fn versioned_artifacts(&self) -> impl Iterator<Item = (String, (&T::Artifact, &Version))> {
self.cached_artifacts
.artifact_files()
.chain(self.compiled_artifacts.artifact_files())
.filter_map(|artifact| {
T::contract_name(&artifact.file)
.map(|name| (name, (&artifact.artifact, &artifact.version)))
})
}
/// All artifacts together with their contract file and name as tuple `(file, contract
/// name, artifact)`
///
/// This returns a chained iterator of both cached and recompiled contract artifacts
///
/// # Example
///
/// ```no_run
/// use std::collections::btree_map::BTreeMap;
/// use ethers_solc::{ConfigurableContractArtifact, Project};
///
/// let project = Project::builder().build().unwrap();
/// let contracts: Vec<(String, String, ConfigurableContractArtifact)> = project.compile().unwrap().into_artifacts_with_files().collect();
/// ```
///
/// **NOTE** the `file` will be returned as is, see also [`Self::with_stripped_file_prefixes()`]
pub fn into_artifacts_with_files(self) -> impl Iterator<Item = (String, String, T::Artifact)> {
let Self { cached_artifacts, compiled_artifacts, .. } = self;
cached_artifacts
.into_artifacts_with_files()
.chain(compiled_artifacts.into_artifacts_with_files())
}
/// All artifacts together with their ID and the sources of the project.
///
/// Note: this only returns the `SourceFiles` for freshly compiled contracts because, if not
/// included in the `Artifact` itself (see
/// [`crate::ConfigurableContractArtifact::source_file()`]), is only available via the solc
/// `CompilerOutput`
pub fn into_artifacts_with_sources(
self,
) -> (BTreeMap<ArtifactId, T::Artifact>, VersionedSourceFiles) {
let Self { cached_artifacts, compiled_artifacts, compiler_output, .. } = self;
(
cached_artifacts
.into_artifacts::<T>()
.chain(compiled_artifacts.into_artifacts::<T>())
.collect(),
compiler_output.sources,
)
}
/// Strips the given prefix from all artifact file paths to make them relative to the given
/// `base` argument
///
/// # Example
///
/// Make all artifact files relative to the project's root directory
///
/// ```no_run
/// use ethers_solc::Project;
///
/// let project = Project::builder().build().unwrap();
/// let output = project.compile().unwrap().with_stripped_file_prefixes(project.root());
/// ```
pub fn with_stripped_file_prefixes(mut self, base: impl AsRef<Path>) -> Self {
let base = base.as_ref();
self.cached_artifacts = self.cached_artifacts.into_stripped_file_prefixes(base);
self.compiled_artifacts = self.compiled_artifacts.into_stripped_file_prefixes(base);
self.compiler_output.strip_prefix_all(base);
self
}
/// Get the (merged) solc compiler output
/// ```no_run
/// use std::collections::btree_map::BTreeMap;
/// use ethers_solc::artifacts::contract::Contract;
/// use ethers_solc::Project;
///
/// let project = Project::builder().build().unwrap();
/// let contracts: BTreeMap<String, Contract> =
/// project.compile().unwrap().output().contracts_into_iter().collect();
/// ```
pub fn output(self) -> AggregatedCompilerOutput {
self.compiler_output
}
/// Whether this type has a compiler output
pub fn has_compiled_contracts(&self) -> bool {
self.compiler_output.is_empty()
}
/// Whether this type does not contain compiled contracts
pub fn is_unchanged(&self) -> bool {
self.compiler_output.is_unchanged()
}
/// Whether there were errors
pub fn has_compiler_errors(&self) -> bool {
self.compiler_output.has_error(&self.ignored_error_codes, &self.compiler_severity_filter)
}
/// Whether there were warnings
pub fn has_compiler_warnings(&self) -> bool {
self.compiler_output.has_warning(&self.ignored_error_codes)
}
/// Returns the set of `Artifacts` that were cached and got reused during
/// [`crate::Project::compile()`]
pub fn cached_artifacts(&self) -> &Artifacts<T::Artifact> {
&self.cached_artifacts
}
/// Returns the set of `Artifacts` that were compiled with `solc` in
/// [`crate::Project::compile()`]
pub fn compiled_artifacts(&self) -> &Artifacts<T::Artifact> {
&self.compiled_artifacts
}
/// Returns a `BTreeMap` that maps the compiler version used during
/// [`crate::Project::compile()`] to a Vector of tuples containing the contract name and the
/// `Contract`
pub fn compiled_contracts_by_compiler_version(
&self,
) -> BTreeMap<Version, Vec<(String, Contract)>> {
let mut contracts: BTreeMap<_, Vec<_>> = BTreeMap::new();
let versioned_contracts = &self.compiler_output.contracts;
for (_, name, contract, version) in versioned_contracts.contracts_with_files_and_version() {
contracts
.entry(version.to_owned())
.or_default()
.push((name.to_string(), contract.clone()));
}
contracts
}
/// Removes the contract with matching path and name using the `<path>:<contractname>` pattern
/// where `path` is optional.
///
/// If the `path` segment is `None`, then the first matching `Contract` is returned, see
/// [Self::remove_first]
///
/// # Example
///
///
/// ```
/// use ethers_solc::Project;
/// use ethers_solc::artifacts::*;
/// use ethers_solc::info::ContractInfo;
///
/// # fn demo(project: Project) {
/// let output = project.compile().unwrap();
/// let info = ContractInfo::new("src/Greeter.sol:Greeter");
/// let contract = output.find_contract(&info).unwrap();
/// # }
/// ```
pub fn find_contract<'a>(&self, info: impl Into<ContractInfoRef<'a>>) -> Option<&T::Artifact> {
let ContractInfoRef { path, name } = info.into();
if let Some(path) = path {
self.find(path, name)
} else {
self.find_first(name)
}
}
/// Finds the artifact with matching path and name
///
/// # Example
///
/// ```
/// use ethers_solc::Project;
/// use ethers_solc::artifacts::*;
/// # fn demo(project: Project) {
/// let output = project.compile().unwrap();
/// let contract = output.find("src/Greeter.sol", "Greeter").unwrap();
/// # }
/// ```
pub fn find(&self, path: impl AsRef<str>, contract: impl AsRef<str>) -> Option<&T::Artifact> {
let contract_path = path.as_ref();
let contract_name = contract.as_ref();
if let artifact @ Some(_) = self.compiled_artifacts.find(contract_path, contract_name) {
return artifact
}
self.cached_artifacts.find(contract_path, contract_name)
}
/// Finds the first contract with the given name
pub fn find_first(&self, contract_name: impl AsRef<str>) -> Option<&T::Artifact> {
let contract_name = contract_name.as_ref();
if let artifact @ Some(_) = self.compiled_artifacts.find_first(contract_name) {
return artifact
}
self.cached_artifacts.find_first(contract_name)
}
/// Finds the artifact with matching path and name
///
/// # Example
///
/// ```
/// use ethers_solc::Project;
/// use ethers_solc::artifacts::*;
/// # fn demo(project: Project) {
/// let output = project.compile().unwrap();
/// let contract = output.find("src/Greeter.sol", "Greeter").unwrap();
/// # }
/// ```
pub fn remove(
&mut self,
path: impl AsRef<str>,
contract: impl AsRef<str>,
) -> Option<T::Artifact> {
let contract_path = path.as_ref();
let contract_name = contract.as_ref();
if let artifact @ Some(_) = self.compiled_artifacts.remove(contract_path, contract_name) {
return artifact
}
self.cached_artifacts.remove(contract_path, contract_name)
}
/// Removes the _first_ contract with the given name from the set
///
/// # Example
///
/// ```
/// use ethers_solc::Project;
/// use ethers_solc::artifacts::*;
/// # fn demo(project: Project) {
/// let mut output = project.compile().unwrap();
/// let contract = output.remove_first("Greeter").unwrap();
/// # }
/// ```
pub fn remove_first(&mut self, contract_name: impl AsRef<str>) -> Option<T::Artifact> {
let contract_name = contract_name.as_ref();
if let artifact @ Some(_) = self.compiled_artifacts.remove_first(contract_name) {
return artifact
}
self.cached_artifacts.remove_first(contract_name)
}
/// Removes the contract with matching path and name using the `<path>:<contractname>` pattern
/// where `path` is optional.
///
/// If the `path` segment is `None`, then the first matching `Contract` is returned, see
/// [Self::remove_first]
///
///
/// # Example
///
/// ```
/// use ethers_solc::Project;
/// use ethers_solc::artifacts::*;
/// use ethers_solc::info::ContractInfo;
/// # fn demo(project: Project) {
/// let mut output = project.compile().unwrap();
/// let info = ContractInfo::new("src/Greeter.sol:Greeter");
/// let contract = output.remove_contract(&info).unwrap();
/// # }
/// ```
pub fn remove_contract<'a>(
&mut self,
info: impl Into<ContractInfoRef<'a>>,
) -> Option<T::Artifact> {
let ContractInfoRef { path, name } = info.into();
if let Some(path) = path {
self.remove(path, name)
} else {
self.remove_first(name)
}
}
}
impl ProjectCompileOutput<ConfigurableArtifacts> {
/// A helper functions that extracts the underlying [`CompactContractBytecode`] from the
/// [`crate::ConfigurableContractArtifact`]
///
/// # Example
///
/// ```no_run
/// use std::collections::btree_map::BTreeMap;
/// use ethers_solc::artifacts::contract::CompactContractBytecode;
/// use ethers_solc::{ArtifactId, Project};
/// use ethers_solc::contracts::ArtifactContracts;
///
/// let project = Project::builder().build().unwrap();
/// let contracts: ArtifactContracts = project.compile().unwrap().into_contract_bytecodes().collect();
/// ```
pub fn into_contract_bytecodes(
self,
) -> impl Iterator<Item = (ArtifactId, CompactContractBytecode)> {
self.into_artifacts()
.map(|(artifact_id, artifact)| (artifact_id, artifact.into_contract_bytecode()))
}
}
impl<T: ArtifactOutput> fmt::Display for ProjectCompileOutput<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.compiler_output.is_unchanged() {
f.write_str("Nothing to compile")
} else {
self.compiler_output
.diagnostics(&self.ignored_error_codes, self.compiler_severity_filter.clone())
.fmt(f)
}
}
}
/// The aggregated output of (multiple) compile jobs
///
/// This is effectively a solc version aware `CompilerOutput`
#[derive(Clone, Debug, Default, PartialEq)]
pub struct AggregatedCompilerOutput {
/// all errors from all `CompilerOutput`
pub errors: Vec<Error>,
/// All source files combined with the solc version used to compile them
pub sources: VersionedSourceFiles,
/// All compiled contracts combined with the solc version used to compile them
pub contracts: VersionedContracts,
// All the `BuildInfo`s of solc invocations.
pub build_infos: BTreeMap<Version, RawBuildInfo>,
}
impl AggregatedCompilerOutput {
/// Converts all `\\` separators in _all_ paths to `/`
pub fn slash_paths(&mut self) {
self.sources.slash_paths();
self.contracts.slash_paths();
}
/// Whether the output contains a compiler error
pub fn has_error(
&self,
ignored_error_codes: &[u64],
compiler_severity_filter: &Severity,
) -> bool {
self.errors.iter().any(|err| {
if compiler_severity_filter.ge(&err.severity) {
if compiler_severity_filter.is_warning() {
return self.has_warning(ignored_error_codes)
}
return true
}
false
})
}
/// Whether the output contains a compiler warning
pub fn has_warning(&self, ignored_error_codes: &[u64]) -> bool {
self.errors.iter().any(|err| {
if err.severity.is_warning() {
err.error_code.as_ref().map_or(false, |code| !ignored_error_codes.contains(code))
} else {
false
}
})
}
pub fn diagnostics<'a>(
&'a self,
ignored_error_codes: &'a [u64],
compiler_severity_filter: Severity,
) -> OutputDiagnostics {
OutputDiagnostics { compiler_output: self, ignored_error_codes, compiler_severity_filter }
}
pub fn is_empty(&self) -> bool {
self.contracts.is_empty()
}
pub fn is_unchanged(&self) -> bool {
self.contracts.is_empty() && self.errors.is_empty()
}
pub fn extend_all<I>(&mut self, out: I)
where
I: IntoIterator<Item = (Version, CompilerOutput)>,
{
for (v, o) in out {
self.extend(v, o)
}
}
/// adds a new `CompilerOutput` to the aggregated output
pub fn extend(&mut self, version: Version, output: CompilerOutput) {
let CompilerOutput { errors, sources, contracts } = output;
self.errors.extend(errors);
for (path, source_file) in sources {
let sources = self.sources.as_mut().entry(path).or_default();
sources.push(VersionedSourceFile { source_file, version: version.clone() });
}
for (file_name, new_contracts) in contracts {
let contracts = self.contracts.as_mut().entry(file_name).or_default();
for (contract_name, contract) in new_contracts {
let versioned = contracts.entry(contract_name).or_default();
versioned.push(VersionedContract { contract, version: version.clone() });
}
}
}
/// Creates all `BuildInfo` files in the given `build_info_dir`
///
/// There can be multiple `BuildInfo`, since we support multiple versions.
///
/// The created files have the md5 hash `{_format,solcVersion,solcLongVersion,input}` as their
/// file name
pub fn write_build_infos(&self, build_info_dir: impl AsRef<Path>) -> Result<(), SolcIoError> {
if self.build_infos.is_empty() {
return Ok(())
}
let build_info_dir = build_info_dir.as_ref();
std::fs::create_dir_all(build_info_dir)
.map_err(|err| SolcIoError::new(err, build_info_dir))?;
for (version, build_info) in &self.build_infos {
trace!("writing build info file for solc {}", version);
let file_name = format!("{}.json", build_info.id);
let file = build_info_dir.join(file_name);
std::fs::write(&file, &build_info.build_info)
.map_err(|err| SolcIoError::new(err, file))?;
}
Ok(())
}
/// Finds the _first_ contract with the given name
///
/// # Example
///
/// ```
/// use ethers_solc::Project;
/// use ethers_solc::artifacts::*;
/// # fn demo(project: Project) {
/// let output = project.compile().unwrap().output();
/// let contract = output.find_first("Greeter").unwrap();
/// # }
/// ```
pub fn find_first(&self, contract: impl AsRef<str>) -> Option<CompactContractRef> {
self.contracts.find_first(contract)
}
/// Removes the _first_ contract with the given name from the set
///
/// # Example
///
/// ```
/// use ethers_solc::Project;
/// use ethers_solc::artifacts::*;
/// # fn demo(project: Project) {
/// let mut output = project.compile().unwrap().output();
/// let contract = output.remove_first("Greeter").unwrap();
/// # }
/// ```
pub fn remove_first(&mut self, contract: impl AsRef<str>) -> Option<Contract> {
self.contracts.remove_first(contract)
}
/// Removes the contract with matching path and name
///
/// # Example
///
/// ```
/// use ethers_solc::Project;
/// use ethers_solc::artifacts::*;
/// # fn demo(project: Project) {
/// let mut output = project.compile().unwrap().output();
/// let contract = output.remove("src/Greeter.sol", "Greeter").unwrap();
/// # }
/// ```
pub fn remove(&mut self, path: impl AsRef<str>, contract: impl AsRef<str>) -> Option<Contract> {
self.contracts.remove(path, contract)
}
/// Removes the contract with matching path and name using the `<path>:<contractname>` pattern
/// where `path` is optional.
///
/// If the `path` segment is `None`, then the first matching `Contract` is returned, see
/// [Self::remove_first]
///
///
///
/// # Example
///
/// ```
/// use ethers_solc::Project;
/// use ethers_solc::artifacts::*;
/// use ethers_solc::info::ContractInfo;
/// # fn demo(project: Project) {
/// let mut output = project.compile().unwrap().output();
/// let info = ContractInfo::new("src/Greeter.sol:Greeter");
/// let contract = output.remove_contract(&info).unwrap();
/// # }
/// ```
pub fn remove_contract<'a>(
&mut self,
info: impl Into<ContractInfoRef<'a>>,
) -> Option<Contract> {
let ContractInfoRef { path, name } = info.into();
if let Some(path) = path {
self.remove(path, name)
} else {
self.remove_first(name)
}
}
/// Iterate over all contracts and their names
pub fn contracts_iter(&self) -> impl Iterator<Item = (&String, &Contract)> {
self.contracts.contracts()
}
/// Iterate over all contracts and their names
pub fn contracts_into_iter(self) -> impl Iterator<Item = (String, Contract)> {
self.contracts.into_contracts()
}
/// Returns an iterator over (`file`, `name`, `Contract`)
pub fn contracts_with_files_iter(&self) -> impl Iterator<Item = (&String, &String, &Contract)> {
self.contracts.contracts_with_files()
}
/// Returns an iterator over (`file`, `name`, `Contract`)
pub fn contracts_with_files_into_iter(
self,
) -> impl Iterator<Item = (String, String, Contract)> {
self.contracts.into_contracts_with_files()
}
/// Returns an iterator over (`file`, `name`, `Contract`, `Version`)
pub fn contracts_with_files_and_version_iter(
&self,
) -> impl Iterator<Item = (&String, &String, &Contract, &Version)> {
self.contracts.contracts_with_files_and_version()
}
/// Returns an iterator over (`file`, `name`, `Contract`, `Version`)
pub fn contracts_with_files_and_version_into_iter(
self,
) -> impl Iterator<Item = (String, String, Contract, Version)> {
self.contracts.into_contracts_with_files_and_version()
}
/// Given the contract file's path and the contract's name, tries to return the contract's
/// bytecode, runtime bytecode, and abi
/// # Example
///
/// ```
/// use ethers_solc::Project;
/// use ethers_solc::artifacts::*;
/// # fn demo(project: Project) {
/// let output = project.compile().unwrap().output();
/// let contract = output.get("src/Greeter.sol", "Greeter").unwrap();
/// # }
/// ```
pub fn get(
&self,
path: impl AsRef<str>,
contract: impl AsRef<str>,
) -> Option<CompactContractRef> {
self.contracts.get(path, contract)
}
/// Returns the output's source files and contracts separately, wrapped in helper types that
/// provide several helper methods
///
/// # Example
///
/// ```
/// use ethers_solc::Project;
/// # fn demo(project: Project) {
/// let output = project.compile().unwrap().output();
/// let (sources, contracts) = output.split();
/// # }
/// ```
pub fn split(self) -> (VersionedSourceFiles, VersionedContracts) {
(self.sources, self.contracts)
}
/// Joins all file path with `root`
pub fn join_all(&mut self, root: impl AsRef<Path>) -> &mut Self {
let root = root.as_ref();
self.contracts.join_all(root);
self.sources.join_all(root);
self
}
/// Strips the given prefix from all file paths to make them relative to the given
/// `base` argument.
///
/// Convenience method for [Self::strip_prefix_all()] that consumes the type.
///
/// # Example
///
/// Make all sources and contracts relative to the project's root directory
///
/// ```no_run
/// use ethers_solc::Project;
///
/// let project = Project::builder().build().unwrap();
/// let output = project.compile().unwrap().output().with_stripped_file_prefixes(project.root());
/// ```
pub fn with_stripped_file_prefixes(mut self, base: impl AsRef<Path>) -> Self {
let base = base.as_ref();
self.contracts.strip_prefix_all(base);
self.sources.strip_prefix_all(base);
self
}
/// Removes `base` from all contract paths
pub fn strip_prefix_all(&mut self, base: impl AsRef<Path>) -> &mut Self {
let base = base.as_ref();
self.contracts.strip_prefix_all(base);
self.sources.strip_prefix_all(base);
self
}
}
/// Helper type to implement display for solc errors
#[derive(Clone, Debug)]
pub struct OutputDiagnostics<'a> {
/// output of the compiled project
compiler_output: &'a AggregatedCompilerOutput,
/// the error codes to ignore
ignored_error_codes: &'a [u64],
/// set minimum level of severity that is treated as an error
compiler_severity_filter: Severity,
}
impl<'a> OutputDiagnostics<'a> {
/// Returns true if there is at least one error of high severity
pub fn has_error(&self) -> bool {
self.compiler_output.has_error(self.ignored_error_codes, &self.compiler_severity_filter)
}
/// Returns true if there is at least one warning
pub fn has_warning(&self) -> bool {
self.compiler_output.has_warning(self.ignored_error_codes)
}
/// Returns true if the contract is a expected to be a test
fn is_test<T: AsRef<str>>(&self, contract_path: T) -> bool {
if contract_path.as_ref().ends_with(".t.sol") {
return true
}
self.compiler_output.find_first(&contract_path).map_or(false, |contract| {
contract.abi.map_or(false, |abi| abi.functions.contains_key("IS_TEST"))
})
}
}
impl<'a> fmt::Display for OutputDiagnostics<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.has_error() {
f.write_str("Compiler run failed")?;
} else if self.has_warning() {
f.write_str("Compiler run successful (with warnings)")?;
} else {
f.write_str("Compiler run successful")?;
}
for err in &self.compiler_output.errors {
if err.severity.is_warning() {
let is_ignored = err.error_code.as_ref().map_or(false, |code| {
if let Some(source_location) = &err.source_location {
// we ignore spdx and contract size warnings in test
// files. if we are looking at one of these warnings
// from a test file we skip
if self.is_test(&source_location.file) && (*code == 1878 || *code == 5574) {
return true
}
}
self.ignored_error_codes.contains(code)
});
if !is_ignored {
writeln!(f, "\n{err}")?;
}
} else {
writeln!(f, "\n{err}")?;
}
}
Ok(())
}
}