Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
bryn committed May 21, 2022
1 parent 6b7bc96 commit c865033
Show file tree
Hide file tree
Showing 10 changed files with 159 additions and 135 deletions.
34 changes: 5 additions & 29 deletions Cargo.lock

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

6 changes: 4 additions & 2 deletions apollo-router-scaffold/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "apollo-router-scaffold"
version = "0.9.1"
version = "0.9.2"
authors = ["Apollo Graph, Inc. <packages@apollographql.com>"]
edition = "2021"
license = "Elastic-2.0"
Expand All @@ -9,7 +9,9 @@ publish = false
[dependencies]
clap = { version = "3.1.8", features = ["derive"] }
anyhow = "1.0.56"
cargo-scaffold = {path="../../cargo-scaffold"}
cargo-scaffold = "0.7.0"
regex = "1"
str_inflector = "0.12.0"
toml = "0.5.8"
[dev-dependencies]
tempfile = "3.3.0"
104 changes: 104 additions & 0 deletions apollo-router-scaffold/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,107 @@ impl RouterAction {
}
}
}

#[cfg(test)]
mod test {
use anyhow::Result;
use cargo_scaffold::{Opts, ScaffoldDescription};
use inflector::Inflector;
use std::collections::BTreeMap;
use std::env;
use std::path::PathBuf;
use std::process::Command;
use tempfile::TempDir;

#[test]
fn test_scaffold() -> Result<()> {
let temp_dir = tempfile::Builder::new()
.prefix("router_scaffold")
.tempdir()?;
let current_dir = env::current_dir()?;
// Scaffold the main project
let opts = Opts::builder()
.project_name("temp")
.target_dir(temp_dir.path())
.template_path("templates/base")
.force(true)
.build();
ScaffoldDescription::new(opts)?.scaffold_with_parameters(BTreeMap::from([(
"integration_test".to_string(),
toml::Value::String(
current_dir
.to_str()
.expect("current dir must be convertable to string")
.to_string(),
),
)]))?;
test_build(&temp_dir)?;

// Scaffold one of each type of plugin
scaffold_plugin(&current_dir, &temp_dir, "basic")?;
scaffold_plugin(&current_dir, &temp_dir, "auth")?;
scaffold_plugin(&current_dir, &temp_dir, "tracing")?;
std::fs::write(
temp_dir.path().join("src/plugins/mod.rs"),
"mod auth;\nmod basic;\nmod tracing;\n",
)?;
test_build(&temp_dir)?;

drop(temp_dir);
Ok(())
}

fn scaffold_plugin(current_dir: &PathBuf, dir: &TempDir, plugin_type: &str) -> Result<()> {
let opts = Opts::builder()
.project_name(plugin_type)
.target_dir(dir.path())
.append(true)
.template_path("templates/plugin")
.build();
ScaffoldDescription::new(opts)?.scaffold_with_parameters(BTreeMap::from([
(
format!("type_{}", plugin_type),
toml::Value::String(plugin_type.to_string()),
),
(
"snake_name".to_string(),
toml::Value::String(plugin_type.to_snake_case()),
),
(
"pascal_name".to_string(),
toml::Value::String(plugin_type.to_pascal_case()),
),
(
"project_name".to_string(),
toml::Value::String("acme".to_string()),
),
(
"integration_test".to_string(),
toml::Value::String(
current_dir
.to_str()
.expect("current dir must be convertable to string")
.to_string(),
),
),
]))?;
Ok(())
}

fn test_build(dir: &TempDir) -> Result<()> {
let output = Command::new("cargo")
.args(["test"])
.current_dir(dir)
.output()?;
if !output.status.success() {
eprintln!("failed to build scaffolded project");
eprintln!("{}", String::from_utf8(output.stdout)?);
eprintln!("{}", String::from_utf8(output.stderr)?);
panic!(
"build failed with exit code {}",
output.status.code().unwrap_or_default()
);
}
Ok(())
}
}
41 changes: 31 additions & 10 deletions apollo-router-scaffold/src/plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,44 +3,61 @@ use cargo_scaffold::ScaffoldDescription;
use clap::Subcommand;
use inflector::Inflector;
use regex::Regex;
use std::fs;
use std::path::{Path, PathBuf};
use toml::Value;

#[derive(Subcommand, Debug)]
pub enum PluginAction {
/// Add a plugin
/// Add a plugin.
Create {
/// The name of the plugin you want to add
/// The name of the plugin you want to add.
name: String,

/// Optional override of the scaffold template path.
#[clap(long)]
template_override: Option<PathBuf>,
},

/// Remove a plugin
/// Remove a plugin.
Remove {
/// The name of the plugin you want to remove
/// The name of the plugin you want to remove.
name: String,
},
}

impl PluginAction {
pub fn execute(&self) -> Result<()> {
match self {
PluginAction::Create { name } => create_plugin(name),
PluginAction::Create {
name,
template_override,
} => create_plugin(name, template_override),
PluginAction::Remove { name } => remove_plugin(name),
}
}
}

fn create_plugin(name: &str) -> Result<()> {
fn create_plugin(name: &str, template_path: &Option<PathBuf>) -> Result<()> {
let plugin_path = plugin_path(&name);
if plugin_path.exists() {
return Err(anyhow::anyhow!("plugin '{}' already exists", name));
}

let cargo_toml = fs::read_to_string("Cargo.toml")?.parse::<toml::Value>()?;
let project_name = cargo_toml
.get("package")
.unwrap_or(&toml::Value::String("default".to_string()))
.get("name")
.map(|n| n.to_string().to_snake_case())
.unwrap_or_else(|| "default".to_string());

let opts = cargo_scaffold::Opts::builder()
.template_path(PathBuf::from(
"https://github.com/Cosmian/mpc_rust_template.git",
))
.template_commit(format!("v{}", std::env!("CARGO_PKG_VERSION")))
.template_path(template_path.as_ref().unwrap_or(&PathBuf::from(
"https://github.com/apollographql/router.git",
)))
.git_ref(format!("v{}", std::env!("CARGO_PKG_VERSION")))
.repository_template_path("apollo-router-scaffold/templates/plugin")
.target_dir(".")
.project_name(name)
.append(true)
Expand All @@ -55,6 +72,10 @@ fn create_plugin(name: &str) -> Result<()> {
"snake_name".to_string(),
Value::String(name.to_snake_case()),
);
params.insert(
"project_name".to_string(),
Value::String(project_name.to_snake_case()),
);

params.insert(
format!(
Expand Down
4 changes: 2 additions & 2 deletions apollo-router-scaffold/templates/base/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ members = [
[dependencies]
anyhow = "1.0.55"
{{#if integration_test}}
apollo-router = {path ="../apollo-router" }
apollo-router-core = { path="../apollo-router-core" }
apollo-router = {path ="{{integration_test}}/../apollo-router" }
apollo-router-core = { path="{{integration_test}}/../apollo-router-core" }
{{else}}
apollo-router = { git="https://github.com/apollographql/router.git", tag="0.9.2" }
apollo-router-core = { git="https://github.com/apollographql/router.git", tag="0.9.2" }
Expand Down
5 changes: 5 additions & 0 deletions apollo-router-scaffold/templates/base/xtask/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ version = "0.1.0"

[dependencies]
# This dependency should stay in line with your router version

{{#if integration_test}}
apollo-router-scaffold = {path ="{{integration_test}}/../apollo-router-scaffold" }
{{else}}
apollo-router-scaffold = { git="https://github.com/apollographql/router.git", tag="0.9.2"}
{{/if}}
anyhow = "1.0.56"
clap = "3.1.8"
8 changes: 6 additions & 2 deletions apollo-router-scaffold/templates/plugin/.scaffold.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,12 @@ exclude = [
]

notes = """
Creating {{name}} plugin.
Remember to add it to your router.yaml to use the plugin!
Created {{project_name}}.{{snake_name}} plugin.
To use the plugin add it to router.yaml:
plugins:
{{project_name}}.{{snake_name}}:
# Plugin configuration
"""

[parameters]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ impl Plugin for {{pascal_name}} {

// This macro allows us to use it in our plugin registry!
// register_plugin takes a group name, and a plugin name.
register_plugin!("example", "{{snake_name}}", {{pascal_name}});
register_plugin!("{{project_name}}", "{{snake_name}}", {{pascal_name}});

#[cfg(test)]
mod tests {
Expand All @@ -169,7 +169,7 @@ mod tests {
#[tokio::test]
async fn plugin_registered() {
apollo_router_core::plugins()
.get("example.{{snake_name}}")
.get("{{project_name}}.{{snake_name}}")
.expect("Plugin not found")
.create_instance(&serde_json::json!({"message" : "Starting my plugin"}))
.await
Expand Down
2 changes: 0 additions & 2 deletions apollo-router/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,6 @@ uname = "0.1.1"
uname = "0.1.1"

[dev-dependencies]
cargo-scaffold = "0.6.1"
insta = "1.12.0"
str_inflector = "0.12.0"
jsonpath_lib = "0.3.0"
Expand All @@ -117,7 +116,6 @@ test-log = { version = "0.2.10", default-features = false, features = [
"trace",
] }
test-span = "0.6"
toml = "0.5.8"
tower-test = "0.4.0"
tracing-subscriber = { version = "0.3", default-features = false, features = [
"env-filter",
Expand Down
Loading

0 comments on commit c865033

Please sign in to comment.