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

Dived cairo-coverage to crates #117

Merged
merged 1 commit into from
Dec 18, 2024
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 33 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
resolver = "2"
members = [
"crates/cairo-coverage",
"crates/cairo-coverage-args",
"crates/cairo-coverage-core",
"crates/cairo-coverage-test-utils",
]

[workspace.package]
Expand All @@ -25,3 +28,4 @@ serde_json = "1.0.133"
snapbox = "0.6.20"
indoc = "2.0.5"
regex = "1.11.1"
walkdir = "2.5.0"
9 changes: 9 additions & 0 deletions crates/cairo-coverage-args/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[package]
name = "cairo-coverage-args"
version.workspace = true
edition.workspace = true

[dependencies]
anyhow.workspace = true
camino.workspace = true
clap.workspace = true
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use anyhow::{ensure, Result};
use anyhow::ensure;
use camino::Utf8PathBuf;
use clap::{Parser, ValueEnum};

#[derive(Parser, Debug)]
#[command(version)]
pub struct Cli {
#[command(version, args_conflicts_with_subcommands = true)]
pub struct CairoCoverageArgs {
/// Paths to the .json files with trace data.
#[arg(value_parser = parse_trace_file, num_args = 1.., required = true)]
pub trace_files: Vec<Utf8PathBuf>,
Expand All @@ -22,6 +22,7 @@ pub struct Cli {
pub project_path: Option<Utf8PathBuf>,
}

/// Additional components that can be included in the coverage report.
#[derive(ValueEnum, Debug, Clone, Eq, PartialEq)]
pub enum IncludedComponent {
/// Run coverage on functions marked with `#[test]` attribute
Expand All @@ -30,7 +31,7 @@ pub enum IncludedComponent {
Macros,
}

fn parse_trace_file(path: &str) -> Result<Utf8PathBuf> {
fn parse_trace_file(path: &str) -> anyhow::Result<Utf8PathBuf> {
let trace_file = Utf8PathBuf::from(path);

ensure!(trace_file.exists(), "Trace file does not exist");
Expand All @@ -43,7 +44,7 @@ fn parse_trace_file(path: &str) -> Result<Utf8PathBuf> {
Ok(trace_file)
}

fn parse_project_path(path: &str) -> Result<Utf8PathBuf> {
fn parse_project_path(path: &str) -> anyhow::Result<Utf8PathBuf> {
let project_path = Utf8PathBuf::from(path);

ensure!(project_path.exists(), "Project path does not exist");
Expand Down
24 changes: 24 additions & 0 deletions crates/cairo-coverage-core/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
[package]
name = "cairo-coverage-core"
version.workspace = true
edition.workspace = true

[dependencies]
cairo-coverage-args = { path = "../cairo-coverage-args" }
anyhow.workspace = true
camino.workspace = true
cairo-annotations.workspace = true
cairo-lang-sierra.workspace = true
cairo-lang-sierra-to-casm.workspace = true
cairo-lang-starknet-classes.workspace = true
derived-deref.workspace = true
itertools.workspace = true
ignore.workspace = true
serde.workspace = true
serde_json.workspace = true
regex.workspace = true
indoc.workspace = true

[dev-dependencies]
cairo-coverage-test-utils = { path = "../cairo-coverage-test-utils" }
assert_fs.workspace = true
Original file line number Diff line number Diff line change
Expand Up @@ -51,35 +51,20 @@ fn find_ignore_file(start_dir: &Utf8Path) -> Option<Utf8PathBuf> {
#[cfg(test)]
mod tests {
use super::*;
use assert_fs::prelude::*;
use assert_fs::fixture::PathChild;
use assert_fs::TempDir;
use std::path::Path;

trait TestUtils {
fn create_ignore_file(&self) -> Utf8PathBuf;
fn to_utf8_path_buf(&self) -> Utf8PathBuf;
}

impl<T: PathChild + AsRef<Path>> TestUtils for T {
fn create_ignore_file(&self) -> Utf8PathBuf {
let ignore_file = self.child(CAIRO_COVERAGE_IGNORE);
ignore_file.touch().unwrap();
ignore_file.to_utf8_path_buf()
}

fn to_utf8_path_buf(&self) -> Utf8PathBuf {
Utf8PathBuf::from_path_buf(self.as_ref().to_path_buf()).unwrap()
}
}
use cairo_coverage_test_utils::{CreateFile, Utf8PathBufConversion};

#[test]
fn test_finds_ignore_file_in_same_directory() {
let temp_dir = TempDir::new().unwrap();
let ignore_file_path = temp_dir.create_ignore_file();
let ignore_file = temp_dir
.create_file(CAIRO_COVERAGE_IGNORE)
.to_utf8_path_buf();

let result = find_ignore_file(&ignore_file_path);
let result = find_ignore_file(&ignore_file);

assert_eq!(result, Some(ignore_file_path));
assert_eq!(result, Some(ignore_file));
}

#[test]
Expand All @@ -88,11 +73,13 @@ mod tests {
let parent_dir = temp_dir.child("parent");
let child_dir = parent_dir.child("child");

let ignore_file_path = parent_dir.create_ignore_file();
let ignore_file = parent_dir
.create_file(CAIRO_COVERAGE_IGNORE)
.to_utf8_path_buf();

let result = find_ignore_file(&child_dir.to_utf8_path_buf());

assert_eq!(result, Some(ignore_file_path));
assert_eq!(result, Some(ignore_file));
}

#[test]
Expand All @@ -102,7 +89,9 @@ mod tests {
let middle_dir = root_dir.child("middle");
let child_dir = middle_dir.child("child");

let ignore_file = root_dir.create_ignore_file();
let ignore_file = root_dir
.create_file(CAIRO_COVERAGE_IGNORE)
.to_utf8_path_buf();

let result = find_ignore_file(&child_dir.to_utf8_path_buf());

Expand All @@ -125,8 +114,12 @@ mod tests {
let middle_dir = root_dir.child("middle");
let child_dir = middle_dir.child("child");

root_dir.create_ignore_file();
let middle_ignore_file = middle_dir.create_ignore_file();
root_dir
.create_file(CAIRO_COVERAGE_IGNORE)
.to_utf8_path_buf();
let middle_ignore_file = middle_dir
.create_file(CAIRO_COVERAGE_IGNORE)
.to_utf8_path_buf();

let result = find_ignore_file(&child_dir.to_utf8_path_buf());

Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use crate::cli::IncludedComponent;
use crate::data_loader::LoadedData;
use crate::input::filter::ignore::CairoCoverageIgnoreMatcher;
use crate::input::sierra_to_cairo_map::{SimpleLibfuncName, StatementOrigin};
use cairo_annotations::annotations::coverage::SourceFileFullPath;
use cairo_annotations::annotations::profiler::FunctionName;
use cairo_coverage_args::IncludedComponent;
use camino::Utf8PathBuf;
use regex::Regex;
use std::collections::HashSet;
Expand Down
115 changes: 115 additions & 0 deletions crates/cairo-coverage-core/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
mod coverage_data;
mod data_loader;
mod input;
mod merge;
mod output;
mod types;

use crate::coverage_data::create_files_coverage_data_with_hits;
use crate::data_loader::LoadedDataMap;
use crate::input::{InputData, StatementCategoryFilter};
use crate::output::lcov::LcovFormat;
use anyhow::{bail, ensure, Context, Result};
use cairo_coverage_args::CairoCoverageArgs;
use camino::Utf8PathBuf;
use indoc::indoc;
use merge::MergeOwned;
use std::fs::OpenOptions;
use std::io::Write;

const SNFORGE_SIERRA_DIR: &str = ".snfoundry_versioned_programs";

/// Run the core logic of `cairo-coverage` with the provided [`RunArgs`] arguments.
/// This command generates a coverage report in the LCOV format.
/// The coverage report is written to the file specified in the `output_path` argument.
/// # Errors
/// Fails if it can't produce the coverage report with the error message explaining the reason.
pub fn run(
CairoCoverageArgs {
trace_files,
include,
output_path,
project_path,
}: CairoCoverageArgs,
) -> Result<()> {
let coverage_data = LoadedDataMap::load(&trace_files)?
.iter()
.map(|(source_sierra_path, loaded_data)| {
let project_path = &get_project_path(source_sierra_path, project_path.as_ref())?;
let filter = StatementCategoryFilter::new(project_path, &include, loaded_data);
let input_data = InputData::new(loaded_data, &filter)?;
Ok(create_files_coverage_data_with_hits(&input_data))
})
.collect::<Result<Vec<_>>>()?
.into_iter()
// Versioned programs and contract classes can represent the same piece of code,
// so we merge the file coverage after processing them to avoid duplicate entries.
.reduce(MergeOwned::merge_owned)
.context("No elements to merge")?;

OpenOptions::new()
.append(true)
.create(true)
.open(&output_path)
.context(format!("Failed to open output file at path: {output_path}"))?
.write_all(LcovFormat::from(coverage_data).to_string().as_bytes())
.context("Failed to write to output file")?;

Ok(())
}

fn get_project_path(
source_sierra_path: &Utf8PathBuf,
project_path: Option<&Utf8PathBuf>,
) -> Result<Utf8PathBuf> {
if let Some(project_path) = project_path {
Ok(project_path.clone())
} else {
find_user_project_path(source_sierra_path).context(indoc! {
r"Inference of project path failed.
Please provide the project path explicitly using the --project-path flag."
})
}
}

fn find_user_project_path(source_sierra_path: &Utf8PathBuf) -> Result<Utf8PathBuf> {
ensure!(
source_sierra_path.extension() == Some("json"),
"Source sierra path should have a .json extension, got: {source_sierra_path}"
);

match source_sierra_path.with_extension("").extension() {
Some("sierra") => {
navigate_and_check(source_sierra_path, &["target", "dev"])
.or_else(|| navigate_and_check(source_sierra_path, &[SNFORGE_SIERRA_DIR]))
.context(format!(
"Source sierra path should be in one of the formats: \
<project_root>/{SNFORGE_SIERRA_DIR}/<file>.sierra.json \
or <project_root>/target/dev/<file>.sierra.json, got: {source_sierra_path}"
))
}
Some("contract_class") => {
navigate_and_check(source_sierra_path, &["target", "dev"])
.context(format!(
"Source sierra path should be in the format: \
<project_root>/target/dev/<file>.contract_class.json, got: {source_sierra_path}"
))
}
_ => bail!(
"Source sierra path should have a .sierra or .contract_class extension, got: {source_sierra_path}"
),
}
}

fn navigate_and_check(path: &Utf8PathBuf, folders: &[&str]) -> Option<Utf8PathBuf> {
folders
.iter()
.rev()
.try_fold(path.parent()?, |current, &folder| {
current
.file_name()
.filter(|name| *name == folder)
.map(|_| current.parent())?
})
.map(Utf8PathBuf::from)
}
12 changes: 12 additions & 0 deletions crates/cairo-coverage-test-utils/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[package]
name = "cairo-coverage-test-utils"
version.workspace = true
edition.workspace = true

[dependencies]
assert_fs.workspace = true
camino.workspace = true




Loading
Loading