Skip to content

Commit

Permalink
Use templates.json for generating a project.
Browse files Browse the repository at this point in the history
  • Loading branch information
kubaplas committed May 15, 2024
1 parent 70a2e5f commit 43347f9
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 31 deletions.
14 changes: 10 additions & 4 deletions src/actions/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,12 @@ use ureq::serde_json;
use crate::{
cli::InitCommand,
command::{rename_file, replace_in_file},
consts::{ODRA_GITHUB_API_DATA, ODRA_TEMPLATE_GH_REPO},
consts::{ODRA_GITHUB_API_DATA, ODRA_TEMPLATE_GH_RAW_REPO, ODRA_TEMPLATE_GH_REPO},
errors::Error,
log,
paths,
project::OdraLocation,
template::TemplateGenerator,
};

/// InitAction configuration.
Expand All @@ -32,10 +33,15 @@ impl InitAction {

let odra_location = Self::odra_location(init_command.source);

let template_repository_path =
TemplateGenerator::new(ODRA_TEMPLATE_GH_RAW_REPO.to_string(), odra_location.clone())
.find_template(&init_command.template)
.path;

let template_path = match odra_location.clone() {
OdraLocation::Local(local_path) => TemplatePath {
auto_path: Some(local_path.as_os_str().to_str().unwrap().to_string()),
subfolder: Some(format!("templates/{}", init_command.template)),
subfolder: Some(template_repository_path),
test: false,
git: None,
branch: None,
Expand All @@ -46,7 +52,7 @@ impl InitAction {
},
OdraLocation::Remote(repo, branch) => TemplatePath {
auto_path: Some(repo),
subfolder: Some(format!("templates/{}", init_command.template)),
subfolder: Some(template_repository_path),
test: false,
git: None,
branch,
Expand All @@ -57,7 +63,7 @@ impl InitAction {
},
OdraLocation::CratesIO(version) => TemplatePath {
auto_path: Some(ODRA_TEMPLATE_GH_REPO.to_string()),
subfolder: Some(format!("templates/{}", init_command.template)),
subfolder: Some(template_repository_path),
test: false,
git: None,
branch: Some(format!("release/{}", version)),
Expand Down
26 changes: 18 additions & 8 deletions src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ pub enum OdraSubcommand {
Generate(GenerateCommand),
/// Cleans all temporary data generated by cargo odra.
Clean(CleanCommand),
/// Lists all available templates.
ListTemplates,
/// Generates completions for given shell
Completions {
/// The shell to generate the completions for
Expand All @@ -80,10 +82,8 @@ pub struct InitCommand {
/// It can be a version, a branch, commit hash or a location on the filesystem.
#[clap(value_parser, long, short)]
pub source: Option<String>,
/// Template to use. Default is "full" - which contains a sample contract and a test.
/// Other templates are:
/// "blank" - which only sets up Cargo.toml and directory structure and
/// "workspace" - which sets up a workspace with a sub crate.
/// Template to use.
/// To see all available templates, run `cargo odra list-templates`.
#[clap(value_parser, long, short, default_value = consts::ODRA_TEMPLATE_DEFAULT_TEMPLATE)]
pub template: String,
}
Expand Down Expand Up @@ -138,10 +138,17 @@ pub struct CleanCommand {}

#[derive(clap::Args, Debug)]
/// `cargo odra update`
pub struct UpdateCommand {
/// If set, runs cargo update for the given builder instead of everyone.
#[clap(value_parser, long, short, value_parser = [consts::ODRA_CASPER_BACKEND])]
pub backend: Option<String>,
pub struct UpdateCommand {}

#[derive(clap::Args, Debug)]
/// `cargo odra list-templates`
pub struct ListTemplatesCommand {
/// Odra source to use. By default, it uses currently used Odra version.
/// If ran without a project, it uses the latest release of Odra.
/// If passed as a parameter, it can be a version, a branch,
/// commit hash or a location on the filesystem.
#[clap(value_parser, long, short)]
pub source: Option<String>,
}

/// Cargo odra main parser function.
Expand Down Expand Up @@ -185,5 +192,8 @@ pub fn make_action() {
let project = Project::detect(current_dir);
SchemaAction::new(&project, schema.contracts_names).build();
}
OdraSubcommand::ListTemplates => {
println!("Available templates:");
}
}
}
2 changes: 2 additions & 0 deletions src/consts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,5 @@ pub const MODULE_TEMPLATE: &str = "flipper";

/// Module register snippet.
pub const MODULE_REGISTER: &str = "module_register";

pub const TEMPLATES_JSON_PATH: &str = "templates/templates.json";
43 changes: 24 additions & 19 deletions src/template.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use ureq::{get, serde_json};

use crate::{
command::read_file_content,
consts::{MODULE_REGISTER, MODULE_TEMPLATE},
consts::{MODULE_REGISTER, MODULE_TEMPLATE, TEMPLATES_JSON_PATH},
errors::Error,
project::OdraLocation,
};
Expand Down Expand Up @@ -47,7 +47,7 @@ impl TemplateGenerator {
fn fetch_templates(&self) -> Vec<Template> {
match self.odra_location.clone() {
OdraLocation::Local(path) => {
let path = path.join("templates/templates.json");
let path = path.join(TEMPLATES_JSON_PATH);
let path_string = path.to_str().unwrap().to_string();
serde_json::from_str(&read_file_content(path).unwrap_or_else(|_| {
Error::FailedToFetchTemplatesFile(path_string.clone()).print_and_die()
Expand All @@ -56,7 +56,7 @@ impl TemplateGenerator {
}
OdraLocation::Remote(_, branch) => {
let branch = branch.unwrap_or_else(|| "releases/latest".to_string());
let template_path = self.template_path("templates.json", branch);
let template_path = self.template_path(TEMPLATES_JSON_PATH, branch);
let templates_json = get(&template_path)
.call()
.unwrap_or_else(|_| {
Expand All @@ -72,7 +72,7 @@ impl TemplateGenerator {
}
OdraLocation::CratesIO(version) => {
let branch = format!("release/{}", version);
let template_path = self.template_path("templates.json", branch);
let template_path = self.template_path(TEMPLATES_JSON_PATH, branch);
let templates_json = get(&template_path)
.call()
.unwrap_or_else(|_| {
Expand All @@ -89,46 +89,51 @@ impl TemplateGenerator {
}
}

fn find_template(&self, template_name: &str) -> Template {
pub fn find_template(&self, template_name: &str) -> Template {
self.fetch_templates()
.into_iter()
.find(|template| template.name == template_name)
.unwrap_or_else(|| Error::TemplateNotFound(template_name.to_owned()).print_and_die())
}

fn fetch_template(&self, template_name: &str) -> Result<String, Error> {
pub fn fetch_template(&self, template_name: &str) -> String {
let template = self.find_template(template_name);

if template.template_type == TemplateType::Project {
return Err(Error::IncorrectTemplateType);
Error::IncorrectTemplateType.print_and_die()
}

match self.odra_location.clone() {
OdraLocation::Local(path) => {
let path = path.join(template.path);
read_file_content(path)
.map_err(|_| Error::FailedToFetchTemplate(template_name.to_owned()))
read_file_content(path).unwrap_or_else(|_| {
Error::FailedToFetchTemplate(template_name.to_owned()).print_and_die()
})
}
OdraLocation::Remote(_, branch) => {
let branch = branch.unwrap_or_else(|| "releases/latest".to_string());
let template_path = self.template_path(&template.path, branch);
get(&template_path)
.call()
.map_err(|_| Error::FailedToFetchTemplate(template_path.clone()))
.and_then(|res| {
res.into_string()
.map_err(|_| Error::FailedToParseTemplate(template_path.clone()))
.unwrap_or_else(|_| {
Error::FailedToFetchTemplate(template_path.clone()).print_and_die()
})
.into_string()
.unwrap_or_else(|_| {
Error::FailedToParseTemplate(template_path.clone()).print_and_die()
})
}
OdraLocation::CratesIO(version) => {
let branch = format!("release/{}", version);
let template_path = self.template_path(&template.path, branch);
get(&template_path)
.call()
.map_err(|_| Error::FailedToFetchTemplate(template_path.clone()))
.and_then(|res| {
res.into_string()
.map_err(|_| Error::FailedToParseTemplate(template_path.clone()))
.unwrap_or_else(|_| {
Error::FailedToFetchTemplate(template_path.clone()).print_and_die()
})
.into_string()
.unwrap_or_else(|_| {
Error::FailedToParseTemplate(template_path.clone()).print_and_die()
})
}
}
Expand All @@ -142,7 +147,7 @@ impl TemplateGenerator {
) -> Result<String, Error> {
let template_name = template_name.unwrap_or_else(|| MODULE_TEMPLATE.to_string());
Ok(self
.fetch_template(&template_name)?
.fetch_template(&template_name)
.replace("#module_name", module_name))
}

Expand All @@ -153,7 +158,7 @@ impl TemplateGenerator {
module_name: &str,
) -> Result<String, Error> {
Ok(self
.fetch_template(MODULE_REGISTER)?
.fetch_template(MODULE_REGISTER)
.replace("#contract_name", contract_name)
.replace("#module_name", module_name))
}
Expand Down

0 comments on commit 43347f9

Please sign in to comment.