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 #1538 from cloudflare/nat/structuredout-publish
Browse files Browse the repository at this point in the history
Structured out for happy publish path
  • Loading branch information
nataliescottdavidson authored Sep 25, 2020
2 parents 7410c7f + 79481a4 commit d6068cc
Show file tree
Hide file tree
Showing 9 changed files with 116 additions and 40 deletions.
4 changes: 2 additions & 2 deletions src/build/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::settings::toml::{Target, TargetType};
use crate::terminal::message::{Message, StdOut};
use crate::terminal::message::{Message, StdErr};
use crate::terminal::styles;
use crate::wranglerjs;
use crate::{commands, install};
Expand Down Expand Up @@ -49,7 +49,7 @@ pub fn build_target(target: &Target) -> Result<String, failure::Error> {
}

pub fn command(args: &[&str], binary_path: &PathBuf) -> Command {
StdOut::working("Compiling your project to WebAssembly...");
StdErr::working("Compiling your project to WebAssembly...");

let mut c = if cfg!(target_os = "windows") {
let mut c = Command::new("cmd");
Expand Down
6 changes: 3 additions & 3 deletions src/commands/kv/bulk/put.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use crate::kv::bulk::put;
use crate::kv::bulk::BATCH_KEY_MAX;
use crate::settings::global_user::GlobalUser;
use crate::settings::toml::Target;
use crate::terminal::message::{Message, StdOut};
use crate::terminal::message::{Message, StdErr};
pub fn run(
target: &Target,
user: &GlobalUser,
Expand All @@ -40,7 +40,7 @@ pub fn run(

let len = pairs.len();

StdOut::working(&format!("uploading {} key value pairs", len));
StdErr::working(&format!("uploading {} key value pairs", len));
let progress_bar = if len > BATCH_KEY_MAX {
let pb = ProgressBar::new(len as u64);
pb.set_style(ProgressStyle::default_bar().template("{wide_bar} {pos}/{len}\n{msg}"));
Expand All @@ -55,6 +55,6 @@ pub fn run(
pb.finish_with_message(&format!("uploaded {} key value pairs", len));
}

StdOut::success("Success");
StdErr::success("Success");
Ok(())
}
70 changes: 61 additions & 9 deletions src/commands/publish.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::env;
use std::path::{Path, PathBuf};

use indicatif::{ProgressBar, ProgressStyle};
use serde::{Deserialize, Serialize};

use crate::build::build_target;
use crate::deploy;
Expand All @@ -11,19 +12,33 @@ use crate::settings::global_user::GlobalUser;
use crate::settings::toml::{DeployConfig, Target};
use crate::sites;
use crate::terminal::emoji;
use crate::terminal::message::{Message, StdOut};
use crate::terminal::message::{Message, Output, StdErr, StdOut};
use crate::upload;

#[derive(Serialize, Deserialize, Default)]
pub struct PublishOutput {
pub success: bool,
pub name: String,
pub urls: Vec<String>,
}

pub fn publish(
user: &GlobalUser,
target: &mut Target,
deploy_config: DeployConfig,
out: Output,
) -> Result<(), failure::Error> {
validate_target_required_fields_present(target)?;

// Build the script before uploading.
build_target(&target)?;

// Build the script before uploading and log build result
let build_result = build_target(&target);
match build_result {
Ok(msg) => {
StdErr::success(&msg);
Ok(())
}
Err(e) => Err(e),
}?;
if let Some(site_config) = &target.site {
let path = &site_config.bucket.clone();
validate_bucket_location(path)?;
Expand All @@ -35,7 +50,7 @@ pub fn publish(
sites::sync(target, user, &site_namespace.id, &path)?;

// First, upload all existing files in bucket directory
StdOut::working("Uploading site files");
StdErr::working("Uploading site files");
let upload_progress_bar = if to_upload.len() > bulk::BATCH_KEY_MAX {
let upload_progress_bar = ProgressBar::new(to_upload.len() as u64);
upload_progress_bar
Expand All @@ -62,11 +77,30 @@ pub fn publish(
// Next, upload and deploy the worker with the updated asset_manifest
upload::script(&upload_client, &target, Some(asset_manifest))?;

deploy::worker(&user, &deploy_config)?;
match deploy::worker(&user, &deploy_config) {
Ok(urls) => {
let result_msg = format!("Successfully published your script to {}", urls[0]);
match out {
Output::Json => {
let mut jsonout = PublishOutput::default();
jsonout.success = true;
jsonout.name = target.name.clone();
jsonout.urls = urls;
StdErr::success(&result_msg);
StdOut::as_json(&jsonout);
}
Output::PlainText => {
StdOut::success(&result_msg);
}
}
Ok(())
}
Err(e) => Err(e),
}?;

// Finally, remove any stale files
if !to_delete.is_empty() {
StdOut::info("Deleting stale files...");
StdErr::info("Deleting stale files...");

let delete_progress_bar = if to_delete.len() > bulk::BATCH_KEY_MAX {
let delete_progress_bar = ProgressBar::new(to_delete.len() as u64);
Expand Down Expand Up @@ -94,8 +128,26 @@ pub fn publish(
let upload_client = http::legacy_auth_client(user);

upload::script(&upload_client, &target, None)?;

deploy::worker(&user, &deploy_config)?;
match deploy::worker(&user, &deploy_config) {
Ok(urls) => {
let result_msg = format!("Successfully published your script to {}", urls[0]);
match out {
Output::Json => {
let mut jsonout = PublishOutput::default();
jsonout.success = true;
jsonout.name = target.name.clone();
jsonout.urls = urls;
StdErr::success(&result_msg);
StdOut::as_json(&jsonout);
}
Output::PlainText => {
StdOut::success(&result_msg);
}
}
Ok(())
}
Err(e) => Err(e),
}?;
}

Ok(())
Expand Down
25 changes: 9 additions & 16 deletions src/deploy/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,36 +5,29 @@ use crate::commands::subdomain::Subdomain;
use crate::http;
use crate::settings::global_user::GlobalUser;
use crate::settings::toml::{DeployConfig, Zoneless};
use crate::terminal::message::{Message, StdOut};
pub fn worker(user: &GlobalUser, deploy_config: &DeployConfig) -> Result<(), failure::Error> {

pub fn worker(
user: &GlobalUser,
deploy_config: &DeployConfig,
) -> Result<Vec<String>, failure::Error> {
match deploy_config {
DeployConfig::Zoneless(zoneless_config) => {
// this is a zoneless deploy
log::info!("publishing to workers.dev subdomain");
let deploy_address = publish_zoneless(user, zoneless_config)?;

StdOut::success(&format!(
"Successfully published your script to {}",
deploy_address
));

Ok(())
let addresses = vec![deploy_address];
Ok(addresses)
}
DeployConfig::Zoned(zoned_config) => {
// this is a zoned deploy
log::info!("publishing to zone {}", zoned_config.zone_id);

let published_routes = publish_routes(&user, zoned_config)?;

let display_results: Vec<String> =
let addresses: Vec<String> =
published_routes.iter().map(|r| format!("{}", r)).collect();

StdOut::success(&format!(
"Deployed to the following routes:\n{}",
display_results.join("\n")
));

Ok(())
Ok(addresses)
}
}
}
Expand Down
16 changes: 13 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use wrangler::preview::{HttpMethod, PreviewOpt};
use wrangler::settings;
use wrangler::settings::global_user::GlobalUser;
use wrangler::settings::toml::TargetType;
use wrangler::terminal::message::{Message, StdOut};
use wrangler::terminal::message::{Message, Output, StdOut};
use wrangler::terminal::{emoji, interactive, styles};
use wrangler::version::background_check_for_updates;

Expand Down Expand Up @@ -559,6 +559,13 @@ fn run() -> Result<(), failure::Error> {
.long("release")
.takes_value(false)
.help("[deprecated] alias of wrangler publish")
)
.arg(
Arg::with_name("output")
.short("o")
.long("output")
.takes_value(true)
.possible_value("json")
),
)
.subcommand(
Expand Down Expand Up @@ -855,8 +862,11 @@ fn run() -> Result<(), failure::Error> {
let env = matches.value_of("env");
let mut target = manifest.get_target(env, is_preview)?;
let deploy_config = manifest.deploy_config(env)?;

commands::publish(&user, &mut target, deploy_config)?;
if matches.is_present("output") && matches.value_of("output") == Some("json") {
commands::publish(&user, &mut target, deploy_config, Output::Json)?;
} else {
commands::publish(&user, &mut target, deploy_config, Output::PlainText)?;
}
} else if let Some(matches) = matches.subcommand_matches("subdomain") {
log::info!("Getting project settings");
let config_path = Path::new(
Expand Down
6 changes: 3 additions & 3 deletions src/sites/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use cloudflare::endpoints::workerskv::write_bulk::KeyValuePair;
use crate::kv::namespace::{upsert, UpsertedNamespace};
use crate::settings::global_user::GlobalUser;
use crate::settings::toml::{KvNamespace, Target};
use crate::terminal::message::{Message, StdOut};
use crate::terminal::message::{Message, StdErr};
pub const KEY_MAX_SIZE: usize = 512;
// Oddly enough, metadata.len() returns a u64, not usize.
pub const VALUE_MAX_SIZE: u64 = 10 * 1024 * 1024;
Expand All @@ -42,13 +42,13 @@ pub fn add_namespace(
let site_namespace = match upsert(target, &user, title)? {
UpsertedNamespace::Created(namespace) => {
let msg = format!("Created namespace for Workers Site \"{}\"", namespace.title);
StdOut::working(&msg);
StdErr::working(&msg);

namespace
}
UpsertedNamespace::Reused(namespace) => {
let msg = format!("Using namespace for Workers Site \"{}\"", namespace.title);
StdOut::working(&msg);
StdErr::working(&msg);

namespace
}
Expand Down
4 changes: 2 additions & 2 deletions src/sites/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use crate::http;
use crate::kv::key::KeyList;
use crate::settings::global_user::GlobalUser;
use crate::settings::toml::Target;
use crate::terminal::message::{Message, StdOut};
use crate::terminal::message::{Message, StdErr};

pub fn sync(
target: &Target,
Expand Down Expand Up @@ -57,7 +57,7 @@ pub fn sync(
.map(|key| key.to_owned())
.collect();

StdOut::success("Success");
StdErr::success("Success");
Ok((to_upload, to_delete, asset_manifest))
}

Expand Down
21 changes: 21 additions & 0 deletions src/terminal/message.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
use super::emoji;

use billboard::{Billboard, BorderColor, BorderStyle};
use serde::Serialize;

pub enum Output {
Json,
PlainText,
}
pub trait Message {
fn message(msg: &str);

Expand Down Expand Up @@ -42,6 +47,9 @@ pub trait Message {

fn billboard(msg: &str);
fn deprecation_warning(msg: &str);
fn as_json<T>(value: &T)
where
T: ?Sized + Serialize;
}

pub struct StdOut;
Expand All @@ -68,6 +76,13 @@ impl Message for StdOut {
.build();
bb.display(msg);
}

fn as_json<T>(value: &T)
where
T: ?Sized + Serialize,
{
println!("{}", &serde_json::to_string(value).unwrap());
}
}

pub struct StdErr;
Expand All @@ -84,4 +99,10 @@ impl Message for StdErr {
fn deprecation_warning(_msg: &str) {
panic!("Can't display billboard warning to stderr.")
}
fn as_json<T>(_value: &T)
where
T: ?Sized + Serialize,
{
panic!("Json output intended for stdout, not stderr.")
}
}
4 changes: 2 additions & 2 deletions src/wranglerjs/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use semver::Version;

use crate::install;
use crate::settings::toml::Target;
use crate::terminal::message::{Message, StdOut};
use crate::terminal::message::{Message, StdErr, StdOut};
use crate::upload::package::Package;
use crate::watch::{wait_for_changes, COOLDOWN_PERIOD};

Expand Down Expand Up @@ -126,7 +126,7 @@ fn write_wranglerjs_output(
custom_webpack: bool,
) -> Result<(), failure::Error> {
if output.has_errors() {
StdOut::user_error(output.get_errors().as_str());
StdErr::user_error(output.get_errors().as_str());
if custom_webpack {
failure::bail!(
"webpack returned an error. Try configuring `entry` in your webpack config relative to the current working directory, or setting `context = __dirname` in your webpack config."
Expand Down

0 comments on commit d6068cc

Please sign in to comment.