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

feat(sozo): support for feature flags #2112

Merged
merged 9 commits into from
Jul 10, 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
34 changes: 27 additions & 7 deletions bin/sozo/src/commands/build.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
use anyhow::{Context, Result};
use clap::Args;
use clap::{Args, Parser};
use dojo_bindgen::{BuiltinPlugins, PluginManager};
use dojo_lang::scarb_internal::compile_workspace;
use dojo_world::manifest::MANIFESTS_DIR;
use dojo_world::metadata::dojo_metadata_from_workspace;
use prettytable::format::consts::FORMAT_NO_LINESEP_WITH_TITLE;
use prettytable::{format, Cell, Row, Table};
use scarb::core::{Config, TargetKind};
use scarb::ops::{CompileOpts, FeaturesOpts, FeaturesSelector};
use scarb::ops::CompileOpts;
use scarb_ui::args::FeaturesSpec;
use sozo_ops::statistics::{get_contract_statistics_for_dir, ContractStatistics};
use tracing::trace;

Expand All @@ -18,7 +19,7 @@ const CONTRACT_CLASS_SIZE_LABEL: &str = "Contract Class size [in bytes]\n(Sierra

const CONTRACT_NAME_LABEL: &str = "Contract";

#[derive(Debug, Args, Default)]
#[derive(Debug, Args)]
pub struct BuildArgs {
// Should we deprecate typescript bindings codegen?
// Disabled due to lack of support in dojo.js
Expand All @@ -39,6 +40,10 @@ pub struct BuildArgs {

#[arg(long, help = "Display statistics about the compiled contracts")]
pub stats: bool,

/// Specify the features to activate.
#[command(flatten)]
pub features: FeaturesSpec,
}

impl BuildArgs {
Expand Down Expand Up @@ -71,18 +76,17 @@ impl BuildArgs {

let profile_dir = manifest_dir.join(MANIFESTS_DIR).join(profile_name);
CleanArgs::clean_manifests(&profile_dir)?;

let features_opts =
FeaturesOpts { features: FeaturesSelector::AllFeatures, no_default_features: false };
let packages: Vec<scarb::core::PackageId> = ws.members().map(|p| p.id).collect();

let compile_info = compile_workspace(
config,
CompileOpts {
include_target_names: vec![],
include_target_kinds: vec![],
exclude_target_kinds: vec![TargetKind::TEST],
features: features_opts,
features: self.features.try_into()?,
},
packages,
)?;
trace!(?compile_info, "Compiled workspace.");

Expand Down Expand Up @@ -153,6 +157,21 @@ impl BuildArgs {
}
}

impl Default for BuildArgs {
fn default() -> Self {
// use the clap defaults
let features = FeaturesSpec::parse_from([""]);

Self {
features,
typescript_v2: false,
unity: false,
bindings_output: "bindings".to_string(),
stats: false,
}
}
}

fn create_stats_table(mut contracts_statistics: Vec<ContractStatistics>) -> Table {
let mut table = Table::new();
table.set_format(*FORMAT_NO_LINESEP_WITH_TITLE);
Expand Down Expand Up @@ -219,6 +238,7 @@ mod tests {
unity: true,
typescript_v2: true,
stats: true,
..Default::default()
};
let result = build_args.run(&config);
assert!(result.is_ok());
Expand Down
31 changes: 21 additions & 10 deletions bin/sozo/src/commands/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@
use dojo_lang::scarb_internal::crates_config_for_compilation_unit;
use scarb::compiler::helpers::collect_main_crate_ids;
use scarb::compiler::{CairoCompilationUnit, CompilationUnit, CompilationUnitAttributes};
use scarb::core::Config;
use scarb::ops::{self, FeaturesOpts, FeaturesSelector};
use scarb::core::{Config, TargetKind};
use scarb::ops::{self, CompileOpts};
use scarb_ui::args::FeaturesSpec;
use tracing::trace;

pub(crate) const LOG_TARGET: &str = "sozo::cli::commands::test";
Expand Down Expand Up @@ -58,6 +59,9 @@
/// Should we print the resource usage.
#[arg(long, default_value_t = false)]
print_resource_usage: bool,
/// Specify the features to activate.
#[command(flatten)]
features: FeaturesSpec,
}

impl TestArgs {
Expand All @@ -68,15 +72,22 @@
});

let resolve = ops::resolve_workspace(&ws)?;
// TODO: Compute all compilation units and remove duplicates, could be unnecessary in future
// version of Scarb.

let features_opts =
FeaturesOpts { features: FeaturesSelector::AllFeatures, no_default_features: false };

let mut compilation_units = ops::generate_compilation_units(&resolve, &features_opts, &ws)?;
compilation_units.sort_by_key(|unit| unit.main_package_id());
compilation_units.dedup_by_key(|unit| unit.main_package_id());
let opts = CompileOpts {
include_target_kinds: vec![TargetKind::TEST],
exclude_target_kinds: vec![],
include_target_names: vec![],
features: self.features.try_into()?,

Check warning on line 80 in bin/sozo/src/commands/test.rs

View check run for this annotation

Codecov / codecov/patch

bin/sozo/src/commands/test.rs#L76-L80

Added lines #L76 - L80 were not covered by tests
};

let compilation_units = ops::generate_compilation_units(&resolve, &opts.features, &ws)?
.into_iter()
.filter(|cu| !opts.exclude_target_kinds.contains(&cu.main_component().target_kind()))
.filter(|cu| {
opts.include_target_kinds.is_empty()
|| opts.include_target_kinds.contains(&cu.main_component().target_kind())
})
.collect::<Vec<_>>();

Check warning on line 90 in bin/sozo/src/commands/test.rs

View check run for this annotation

Codecov / codecov/patch

bin/sozo/src/commands/test.rs#L83-L90

Added lines #L83 - L90 were not covered by tests

for unit in compilation_units {
let unit = if let CompilationUnit::Cairo(unit) = unit {
Expand Down
14 changes: 9 additions & 5 deletions bin/sozo/tests/test_migrate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,13 @@ async fn migrate_dry_run() {
];

let assert = get_snapbox().args(args_vec.iter()).assert().success();
assert!(format!("{:?}", assert.get_output()).contains("Migration Strategy"));
assert!(format!("{:?}", assert.get_output()).contains("# Base Contract"));
assert!(format!("{:?}", assert.get_output()).contains("# Models (8)"));
assert!(format!("{:?}", assert.get_output()).contains("# World"));
assert!(format!("{:?}", assert.get_output()).contains("# Contracts (3)"));
let output = format!("{:#?}", assert.get_output());

dbg!("{}", &output);

assert!(output.contains("Migration Strategy"));
assert!(output.contains("# Base Contract"));
assert!(output.contains("# Models (8)"));
assert!(output.contains("# World"));
assert!(output.contains("# Contracts (4)"));
}
3 changes: 3 additions & 0 deletions crates/dojo-lang/src/compiler_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ fn test_compiler_cairo_features() {

let features_opts =
FeaturesOpts { features: FeaturesSelector::AllFeatures, no_default_features: false };
let ws = scarb::ops::read_workspace(config.manifest_path(), &config).unwrap();
let packages: Vec<scarb::core::PackageId> = ws.members().map(|p| p.id).collect();

let compile_info = scarb_internal::compile_workspace(
&config,
Expand All @@ -22,6 +24,7 @@ fn test_compiler_cairo_features() {
exclude_target_kinds: vec![TargetKind::TEST],
features: features_opts,
},
packages,
)
.unwrap();

Expand Down
18 changes: 9 additions & 9 deletions crates/dojo-lang/src/scarb_internal/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ use cairo_lang_test_plugin::test_plugin_suite;
use cairo_lang_utils::ordered_hash_map::OrderedHashMap;
use camino::Utf8PathBuf;
use scarb::compiler::{CairoCompilationUnit, CompilationUnit, CompilationUnitAttributes};
use scarb::core::Config;
use scarb::ops::{CompileOpts, FeaturesOpts, FeaturesSelector};
use scarb::core::{Config, PackageId};
use scarb::ops::CompileOpts;
use smol_str::SmolStr;
use tracing::trace;

Expand Down Expand Up @@ -57,7 +57,7 @@ pub fn crates_config_for_compilation_unit(unit: &CairoCompilationUnit) -> AllCra
.contains(&SmolStr::new_inline("negative_impls")),
coupons: experimental_features.contains(&SmolStr::new_inline("coupons")),
},
..Default::default()
cfg_set: component.cfg_set.clone(),
},
)
})
Expand All @@ -83,15 +83,15 @@ pub fn build_scarb_root_database(unit: &CairoCompilationUnit) -> Result<RootData
/// This function is an alternative to `ops::compile`, it's doing the same job.
/// However, we can control the injection of the plugins, required to have dojo plugin present
/// for each compilation.
pub fn compile_workspace(config: &Config, opts: CompileOpts) -> Result<CompileInfo> {
pub fn compile_workspace(
config: &Config,
opts: CompileOpts,
packages: Vec<PackageId>,
) -> Result<CompileInfo> {
let ws = scarb::ops::read_workspace(config.manifest_path(), config)?;
let packages: Vec<scarb::core::PackageId> = ws.members().map(|p| p.id).collect();
let resolve = scarb::ops::resolve_workspace(&ws)?;

let features_opts =
FeaturesOpts { features: FeaturesSelector::AllFeatures, no_default_features: false };

let compilation_units = scarb::ops::generate_compilation_units(&resolve, &features_opts, &ws)?
let compilation_units = scarb::ops::generate_compilation_units(&resolve, &opts.features, &ws)?
.into_iter()
.filter(|cu| !opts.exclude_target_kinds.contains(&cu.main_component().target_kind()))
.filter(|cu| {
Expand Down
3 changes: 3 additions & 0 deletions crates/dojo-test-utils/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ fn main() {

let features_opts =
FeaturesOpts { features: FeaturesSelector::AllFeatures, no_default_features: false };
let ws = scarb::ops::read_workspace(config.manifest_path(), &config).unwrap();
let packages: Vec<scarb::core::PackageId> = ws.members().map(|p| p.id).collect();

compile_workspace(
&config,
Expand All @@ -62,6 +64,7 @@ fn main() {
include_target_names: vec![],
features: features_opts,
},
packages,
)
.unwrap();
}
Expand Down
4 changes: 4 additions & 0 deletions crates/dojo-test-utils/src/compiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,9 @@ pub fn copy_build_project_temp(

let features_opts =
FeaturesOpts { features: FeaturesSelector::AllFeatures, no_default_features: false };
let ws = scarb::ops::read_workspace(config.manifest_path(), &config).unwrap();

let packages: Vec<scarb::core::PackageId> = ws.members().map(|p| p.id).collect();

let compile_info = if do_build {
Some(
Expand All @@ -85,6 +88,7 @@ pub fn copy_build_project_temp(
exclude_target_kinds: vec![TargetKind::TEST],
features: features_opts,
},
packages,
)
.unwrap(),
)
Expand Down
4 changes: 2 additions & 2 deletions crates/dojo-world/src/manifest/manifest_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -353,10 +353,10 @@ fn fetch_remote_manifest() {
});

assert_eq!(local_manifest.models.len(), 8);
assert_eq!(local_manifest.contracts.len(), 3);
assert_eq!(local_manifest.contracts.len(), 4);

assert_eq!(remote_manifest.models.len(), 8);
assert_eq!(remote_manifest.contracts.len(), 3);
assert_eq!(remote_manifest.contracts.len(), 4);

// compute diff from local and remote manifest

Expand Down
5 changes: 5 additions & 0 deletions examples/spawn-and-move/Scarb.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ dojo = { path = "../../crates/dojo-core" }
[[target.dojo]]
build-external-contracts = [ ]

[features]
default = ["something"]
something = []

# `dev` profile

[tool.dojo.world]
Expand All @@ -31,6 +35,7 @@ account_address = "0x6162896d1d7ab204c7ccac6dd5f8e9e7c25ecd5ae4fcb4ad32e57786bb4
private_key = "0x1800000000300000180000000000030000000000003006001800006600"
world_address = "0x504b804eeac62e68d12dc030e56b8f62cb047950c346e60a974da02795f6aba"


# `release` profile
#
# for now configurations in `tool` are not merged recursively so to override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,18 @@
],
"outputs": [],
"state_mutability": "external"
},
{
"type": "function",
"name": "call_something",
"inputs": [
{
"name": "something_address",
"type": "core::starknet::contract_address::ContractAddress"
}
],
"outputs": [],
"state_mutability": "view"
}
]
},
Expand Down
Loading
Loading