Skip to content

Commit

Permalink
generalize dependency injection
Browse files Browse the repository at this point in the history
  • Loading branch information
weezy20 committed Mar 19, 2024
1 parent 1d92314 commit 5f806d8
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 23 deletions.
68 changes: 55 additions & 13 deletions src/engines/pallet_engine/dependency.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
//! Dependency representations for Pallets
use std::path;
use strum_macros::{Display, EnumString};

#[derive(EnumString, Display, Debug)]
Expand All @@ -12,28 +13,38 @@ pub(super) enum Features {
/// Custom feature
Custom(String),
}
#[derive(Display, Debug)]
#[derive(Display, Debug, Clone)]
pub(super) enum Location {
/// Local path is form `path = "X"`
Local(std::path::PathBuf),
Local(std::path::PathBuf, Option<semver::Version>),
/// `git = {url}`
Git(reqwest::Url),
Git(reqwest::Url, Option<semver::Version>),
/// String should be of format `version = "X"`
CratesIO(semver::Version),
}
impl From<reqwest::Url> for Location {
fn from(url: reqwest::Url) -> Self {
Self::Git(url)
Self::Git(url, None)
}
}
impl From<std::path::PathBuf> for Location {
fn from(path: std::path::PathBuf) -> Self {
Self::Local(path)
Self::Local(path, None)
}
}
impl From<(std::path::PathBuf, semver::Version)> for Location {
fn from(info: (std::path::PathBuf, semver::Version)) -> Self {
Self::Local(info.0, Some(info.1))
}
}
impl<'a> From<&'a std::path::Path> for Location {
fn from(path: &'a std::path::Path) -> Self {
Self::Local(path.to_path_buf())
Self::Local(path.to_path_buf(), None)
}
}
impl<'a> From<(&'a std::path::Path, semver::Version)> for Location {
fn from(info: (&'a std::path::Path, semver::Version)) -> Self {
Self::Local(info.0.to_path_buf(), Some(info.1.into()))
}
}
impl From<semver::Version> for Location {
Expand All @@ -44,36 +55,67 @@ impl From<semver::Version> for Location {
impl Into<String> for Location {
fn into(self) -> String {
match self {
Location::Local(path) => format!("path = \"{}\"", path.display()),
Location::Git(url) => format!("git = \"{}\"", url),
Location::CratesIO(version) => format!("version = \"{}\"", version),
Location::Local(path, Some(version)) => {
format!("{{ path = \"{}\", version = \"{}\" }}", path.display(), version)
},
Location::Local(path, _) => format!("{{ path = \"{}\" }}", path.display()),
Location::Git(url, Some(version)) => {
format!("{{ git = \"{}\", version = \"{}\" }}", url, version)
},
Location::Git(url, _) => format!("{{ git = \"{}\" }}", url),
Location::CratesIO(version) => format!("{{ version = \"{}\" }}", version),
}
}
}
impl Into<toml_edit::Value> for Location {
fn into(self) -> toml_edit::Value {
Into::<String>::into(self).into()
let s = Into::<String>::into(self);
let t = s
.parse::<toml_edit::Value>()
.expect("Location String parse as Toml Value failed");
toml_edit::Value::InlineTable(
t.as_inline_table().expect(" Parsed Location -> ILT cast infallible").to_owned(),
)
}
}

#[derive(Debug)]
pub(super) struct Dependency {
/// Name for the dependency
pub(super) name: String,
/// Additional features that need to be enabled. Format -> {name}/{feature}
pub(super) features: Vec<Features>,
/// Maybe local path, git url, or from crates.io in which case we will use this for version
pub(super) path: Location,
/// Default features such as `std` are disabled by default for runtime pallet dependencies
pub(super) default_features: bool,
}

impl Dependency {
/// Generate the main dependency as an inline table
pub(super) fn entry(&self) -> toml_edit::InlineTable {
let mut t = toml_edit::Table::new();
let location = Into::<toml_edit::Value>::into(self.path.clone());
t.extend(
location
.as_inline_table()
.expect("Location to String should produce valid inline table")
.to_owned(),
);
t["default-features"] = toml_edit::value(self.default_features);
t.into_inline_table()
}
/// Create dependencies required for adding a local pallet-parachain-template to runtime
/// ..$(runtime)/pallets/pallet-parachain-template
pub(super) fn local_template_runtime() -> Self {
Self {
name: format!("pallet-parachain-template"),
features: vec![Features::RuntimeBenchmarks, Features::TryRuntime, Features::Std],
// TODO hardcode for now
path: std::path::Path::new("../pallets/pallet-parachain-template")
.to_path_buf()
.into(),
path: (
std::path::Path::new("../pallets/pallet-parachain-template").to_path_buf(),
semver::Version::new(1, 0, 0),
).into(),
default_features: false,
}
}
Expand Down
17 changes: 7 additions & 10 deletions src/engines/pallet_engine/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@
//!
//! It is the goal of this module, to answer all of these questions.
mod dependency;
mod pallet_entry;
mod parser;
mod steps;
mod template;
mod dependency;

use crate::commands::add::AddPallet;
use crate::helpers::{is_git_repo_with_commits, write_to_file};
Expand Down Expand Up @@ -116,35 +116,32 @@ impl TomlEditor {
file.write_all(updated_doc.as_bytes())
.context("failed to update runtime:Cargo.toml")
}
/// Inject a dependency to a DocumentMut representation of a toml file
fn inject(&self, mut doc: DocumentMut, dep: Dependency) -> anyhow::Result<DocumentMut> {
use toml_edit::{value, Item, Table};
let Dependency { features, path, default_features } = dep;
let mut t = Table::new();
t["path"] = value(Into::<toml_edit::Value>::into(path));
t["version"] = value("1.0.0");
t["default-features"] = value(default_features);
doc["dependencies"]["pallet-parachain-template"] = value(t.into_inline_table());
doc["dependencies"][&dep.name] = value(dep.entry());
let Dependency { name, features, .. } = dep;
for feature in features {
match feature {
Features::Std => {
// features
let std = doc["features"]["std"].as_value_mut().expect("feature std not found");
let arr = std.as_array_mut().unwrap();
arr.push_formatted("pallet-parachain-template/std".into());
arr.push_formatted(format!("{}/std", name).into());
},
Features::RuntimeBenchmarks => {
let rt_bnch = doc["features"]["runtime-benchmarks"]
.as_value_mut()
.expect("feature runtime-benchmarks not found");
let arr = rt_bnch.as_array_mut().unwrap();
arr.push_formatted("pallet-parachain-template/runtime-benchmarks".into());
arr.push_formatted(format!("{}/runtime-benchmarks", name).into());
},
Features::TryRuntime => {
let try_rt = doc["features"]["try-runtime"]
.as_value_mut()
.expect("feature try-runtime not found");
let arr = try_rt.as_array_mut().unwrap();
arr.push_formatted("pallet-parachain-template/try-runtime".into());
arr.push_formatted(format!("{}/try-runtime", name).into());
},
Features::Custom(_) => unimplemented!("Custom features not supported yet"),
}
Expand Down

0 comments on commit 5f806d8

Please sign in to comment.