Skip to content
This repository has been archived by the owner on Aug 3, 2023. It is now read-only.

Commit

Permalink
Merge pull request #72 from cloudflare/js
Browse files Browse the repository at this point in the history
feat(generate): default to js template
  • Loading branch information
ashleygwilliams authored May 20, 2019
2 parents 85f09e0 + 5fef07b commit 8ebd03e
Show file tree
Hide file tree
Showing 9 changed files with 152 additions and 145 deletions.
23 changes: 15 additions & 8 deletions src/commands/build.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,25 @@
use crate::user::settings::ProjectType;
use crate::{commands, install};
use binary_install::Cache;
use std::path::PathBuf;
use std::process::Command;

pub fn build(cache: &Cache) -> Result<(), failure::Error> {
let tool_name = "wasm-pack";
let binary_path = install::install(tool_name, "rustwasm", cache)?.binary(tool_name)?;
pub fn build(cache: &Cache, project_type: &ProjectType) -> Result<(), failure::Error> {
match project_type {
ProjectType::JavaScript => {
println!("⚠️ JavaScript project found. Skipping unecessary build!")
}
ProjectType::Rust => {
let tool_name = "wasm-pack";
let binary_path = install::install(tool_name, "rustwasm", cache)?.binary(tool_name)?;
let args = ["build", "--target", "no-modules"];

let args = ["build", "--target", "no-modules"];
let command = command(&args, binary_path);
let command_name = format!("{:?}", command);

let command = command(&args, binary_path);
let command_name = format!("{:?}", command);

commands::run(command, &command_name)?;
commands::run(command, &command_name)?;
}
}
Ok(())
}

Expand Down
20 changes: 14 additions & 6 deletions src/commands/generate.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::user::settings::ProjectSettings;
use crate::user::settings::{ProjectSettings, ProjectType};
use crate::{commands, install};
use binary_install::Cache;
use std::path::PathBuf;
Expand All @@ -10,18 +10,19 @@ pub fn generate(name: &str, template: &str, cache: &Cache) -> Result<(), failure

let args = ["generate", "--git", template, "--name", name];

let command = command(name, binary_path, &args);
let project_type = project_type(template);
let command = command(name, binary_path, &args, &project_type);
let command_name = format!("{:?}", command);

commands::run(command, &command_name)?;
ProjectSettings::generate(name.to_string())?;
ProjectSettings::generate(name.to_string(), project_type)?;
Ok(())
}

fn command(name: &str, binary_path: PathBuf, args: &[&str]) -> Command {
fn command(name: &str, binary_path: PathBuf, args: &[&str], project_type: &ProjectType) -> Command {
println!(
"🐑 Generating a new rustwasm worker project with name '{}'...",
name
"🐑 Generating a new {} worker project with name '{}'...",
project_type, name
);

let mut c = if cfg!(target_os = "windows") {
Expand All @@ -36,3 +37,10 @@ fn command(name: &str, binary_path: PathBuf, args: &[&str]) -> Command {
c.args(args);
c
}

fn project_type(template: &str) -> ProjectType {
if template.contains("rust") {
return ProjectType::Rust;
}
ProjectType::JavaScript
}
84 changes: 43 additions & 41 deletions src/commands/publish/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,20 @@ pub mod preview;
mod route;
use route::Route;

use log::info;

use std::fs;
use std::path::Path;

use crate::user::settings::ProjectType;
use crate::user::User;

use reqwest::multipart::Form;

pub fn publish(user: User, name: Option<&str>) -> Result<(), failure::Error> {
if user.account.multiscript {
if name.is_none() {
println!("⚠️ You have multiscript account. Using a default name, 'wasm-worker'.")
}
let name = name.unwrap_or("wasm-worker");
multi_script(&user, name)?;
Route::create(&user, Some(name.to_string()))?;
} else {
if name.is_some() {
println!("⚠️ You only have a single script account. Ignoring name.")
}
single_script(&user)?;
Route::create(&user, None)?;
}
pub fn publish(user: User) -> Result<(), failure::Error> {
let name = &user.settings.project.name;
multi_script(&user, name)?;
Route::create(&user, Some(name.to_string()))?;
println!(
"✨ Success! Your worker was successfully published. You can view it at {}. ✨",
user.settings
Expand All @@ -35,28 +27,9 @@ pub fn publish(user: User, name: Option<&str>) -> Result<(), failure::Error> {
Ok(())
}

fn single_script(user: &User) -> Result<(), failure::Error> {
let zone_id = &user.settings.project.zone_id;
let worker_addr = format!(
"https://api.cloudflare.com/client/v4/zones/{}/workers/script",
zone_id
);

let client = reqwest::Client::new();
let settings = user.settings.clone();

client
.put(&worker_addr)
.header("X-Auth-Key", settings.global_user.api_key)
.header("X-Auth-Email", settings.global_user.email)
.multipart(build_form()?)
.send()?;

Ok(())
}

fn multi_script(user: &User, name: &str) -> Result<(), failure::Error> {
let zone_id = &user.settings.project.zone_id;
let project_type = &user.settings.project.project_type;
let worker_addr = format!(
"https://api.cloudflare.com/client/v4/zones/{}/workers/scripts/{}",
zone_id, name,
Expand All @@ -65,16 +38,45 @@ fn multi_script(user: &User, name: &str) -> Result<(), failure::Error> {
let client = reqwest::Client::new();
let settings = user.settings.clone();

client
.put(&worker_addr)
.header("X-Auth-Key", settings.global_user.api_key)
.header("X-Auth-Email", settings.global_user.email)
.multipart(build_form()?)
.send()?;
let mut res = match project_type {
ProjectType::Rust => {
info!("Rust project detected. Publishing...");
client
.put(&worker_addr)
.header("X-Auth-Key", settings.global_user.api_key)
.header("X-Auth-Email", settings.global_user.email)
.multipart(build_form()?)
.send()?
}
ProjectType::JavaScript => {
info!("JavaScript project detected. Publishing...");
client
.put(&worker_addr)
.header("X-Auth-Key", settings.global_user.api_key)
.header("X-Auth-Email", settings.global_user.email)
.header("Content-Type", "application/javascript")
.body(build_js()?)
.send()?
}
};

if res.status().is_success() {
println!("🥳 Successfully published your script.")
} else {
failure::bail!(
"⛔ Something went wrong! Status: {}, Details {}",
res.status(),
res.text()?
)
}

Ok(())
}

fn build_js() -> Result<String, failure::Error> {
Ok(fs::read_to_string("worker.js")?)
}

fn build_form() -> Result<Form, failure::Error> {
let name = krate::Krate::new("./")?.name.replace("-", "_");
build_generated_dir()?;
Expand Down
19 changes: 15 additions & 4 deletions src/commands/publish/preview/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ use crate::commands::publish;
use serde::Deserialize;
use uuid::Uuid;

use crate::user::settings::{get_project_config, ProjectType};

#[derive(Debug, Deserialize)]
struct Preview {
pub id: String,
Expand All @@ -20,10 +22,19 @@ pub fn preview(
let create_address = "https://cloudflareworkers.com/script";

let client = reqwest::Client::new();
let res = client
.post(create_address)
.multipart(publish::build_form()?)
.send();

let project_type = get_project_config()?.project_type;

let res = match project_type {
ProjectType::Rust => client
.post(create_address)
.multipart(publish::build_form()?)
.send(),
ProjectType::JavaScript => client
.post(create_address)
.body(publish::build_js()?)
.send(),
};

let p: Preview = serde_json::from_str(&res?.text()?)?;

Expand Down
55 changes: 12 additions & 43 deletions src/commands/publish/route.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,20 @@ use crate::user::User;
use reqwest::header::CONTENT_TYPE;
use serde::Serialize;

use log::info;

#[derive(Serialize)]
pub struct Route {
#[serde(skip_serializing_if = "Option::is_none")]
enabled: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
script: Option<String>,
script: String,
pattern: String,
}

impl Route {
pub fn create(user: &User, script: Option<String>) -> Result<Route, failure::Error> {
if user.account.multiscript {
match script {
match script {
Some(s) => multi_script(user, s),
None => failure::bail!("⚠️ You must provide the name of the script you'd like to associate with this route."),
}
} else {
if script.is_some() {
println!("⚠️ You only have a single script account. Ignoring name.");
}
single_script(user)
}
}
}

Expand All @@ -32,11 +24,13 @@ fn multi_script(user: &User, script: String) -> Result<Route, failure::Error> {
"⚠️ Your project config has an error, check your `wrangler.toml`: `route` must be provided.",
);
let route = Route {
script: Some(script),
script,
pattern: pattern.to_string(),
enabled: None,
};
let zone_id = &user.settings.project.zone_id;
if zone_id.is_empty() {
failure::bail!("You much provide a zone_id in your wrangler.toml.")
}
let routes_addr = format!(
"https://api.cloudflare.com/client/v4/zones/{}/workers/routes",
zone_id
Expand All @@ -46,6 +40,10 @@ fn multi_script(user: &User, script: String) -> Result<Route, failure::Error> {
let settings = user.settings.to_owned();
let body = serde_json::to_string(&route)?;

info!(
"Creating your route {} for script {}",
route.pattern, route.script
);
let mut res = client
.post(&routes_addr)
.header("X-Auth-Key", settings.global_user.api_key)
Expand All @@ -64,32 +62,3 @@ fn multi_script(user: &User, script: String) -> Result<Route, failure::Error> {
}
Ok(route)
}

fn single_script(user: &User) -> Result<Route, failure::Error> {
let pattern = user.settings.clone().project.route.expect(
"⚠️ Your project config has an error, check your `wrangler.toml`: `route` must be provided.",
);
let route = Route {
script: None,
pattern,
enabled: Some(true),
};
let zone_id = &user.settings.project.zone_id;
let filters_addr = format!(
"https://api.cloudflare.com/client/v4/zones/{}/workers/filters",
zone_id
);

let client = reqwest::Client::new();
let settings = user.settings.to_owned();

client
.put(&filters_addr)
.header("X-Auth-Key", settings.global_user.api_key)
.header("X-Auth-Email", settings.global_user.email)
.header(CONTENT_TYPE, "application/json")
.body(serde_json::to_string(&route)?)
.send()?;

Ok(route)
}
Loading

0 comments on commit 8ebd03e

Please sign in to comment.