Skip to content

Commit

Permalink
feat(cli): Improve CLI logging (#4060)
Browse files Browse the repository at this point in the history
Co-authored-by: Lucas Nogueira <lucas@tauri.studio>
  • Loading branch information
JonasKruckenberg and lucasfernog authored May 7, 2022
1 parent d4b49d7 commit 35f2147
Show file tree
Hide file tree
Showing 31 changed files with 449 additions and 534 deletions.
5 changes: 5 additions & 0 deletions .changes/bundler-remove-verbose-option.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"tauri-bundler": major
---

Remove `Settings::verbose` option. You may now bring your own `log` frontend to receive logging output from the bundler while remaining in control of verbosity and formatting.
6 changes: 6 additions & 0 deletions .changes/cli-improved-logging.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"cli.rs": minor
"cli.js": minor
---

Improve CLI's logging output, making use of the standard rust `log` system.
11 changes: 5 additions & 6 deletions tooling/bundler/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,24 +23,20 @@ exclude = [

[dependencies]
tauri-utils = { version = "1.0.0-rc.5", path = "../../core/tauri-utils", features = [ "resources" ] }
ar = "0.9.0"
icns = "0.3"
image = "0.24.2"
libflate = "1.2"
md5 = "0.7.0"
anyhow = "1.0"
thiserror = "1.0"
serde_json = "1.0"
serde = { version = "1.0", features = [ "derive" ] }
strsim = "0.10.0"
tar = "0.4.38"
termcolor = "1.1.3"
toml = "0.5.9"
walkdir = "2"
handlebars = { version = "4.2" }
zip = { version = "0.6" }
handlebars = "4.2"
tempfile = "3.3.0"
os_pipe = "1"
log = { version = "0.4.17", features = ["kv_unstable"]}

[target."cfg(target_os = \"windows\")".dependencies]
attohttpc = "0.19"
Expand All @@ -50,6 +46,7 @@ winreg = "0.10"
sha2 = "0.10"
hex = "0.4"
glob = "0.3"
zip = "0.6"

[target."cfg(target_os = \"macos\")".dependencies]
time = { version = "0.3", features = [ "formatting" ] }
Expand All @@ -60,6 +57,8 @@ regex = "1"

[target."cfg(target_os = \"linux\")".dependencies]
heck = "0.4"
ar = "0.9.0"
md5 = "0.7.0"

[lib]
name = "tauri_bundler"
Expand Down
24 changes: 20 additions & 4 deletions tooling/bundler/src/bundle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,9 @@ pub use self::{
Settings, SettingsBuilder, UpdaterSettings,
},
};
use log::{info, warn};
pub use settings::{WindowsSettings, WixLanguage, WixLanguageConfig, WixSettings};

use common::{print_finished, print_info};

use std::path::PathBuf;

/// Generated bundle metadata.
Expand Down Expand Up @@ -63,7 +62,7 @@ pub fn bundle_project(settings: Settings) -> crate::Result<Vec<Bundle>> {
// updater is dependant of multiple bundle, we send our bundles to prevent rebuilding
PackageType::Updater => updater_bundle::bundle_project(&settings, &bundles)?,
_ => {
print_info(&format!("ignoring {:?}", package_type))?;
warn!("ignoring {:?}", package_type);
continue;
}
};
Expand All @@ -74,7 +73,24 @@ pub fn bundle_project(settings: Settings) -> crate::Result<Vec<Bundle>> {
});
}

print_finished(&bundles)?;
let pluralised = if bundles.len() == 1 {
"bundle"
} else {
"bundles"
};

let mut printable_paths = String::new();
for bundle in &bundles {
for path in &bundle.bundle_paths {
let mut note = "";
if bundle.package_type == crate::PackageType::Updater {
note = " (updater)";
}
printable_paths.push_str(&format!(" {}{}\n", path.display(), note));
}
}

info!(action = "Finished"; "{} {} at:\n{}", bundles.len(), pluralised, printable_paths);

Ok(bundles)
}
Expand Down
98 changes: 25 additions & 73 deletions tooling/bundler/src/bundle/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

use crate::{CommandExt, Settings};
use log::debug;

use std::{
ffi::OsStr,
fs::{self, File},
io::{self, BufWriter, Write},
io::{self, BufWriter},
path::Path,
process::{Command, Stdio},
process::{Command, Output},
};
use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor};

/// Returns true if the path has a filename indicating that it is a high-desity
/// "retina" icon. Specifically, returns true the the file stem ends with
Expand Down Expand Up @@ -133,80 +133,32 @@ pub fn copy_dir(from: &Path, to: &Path) -> crate::Result<()> {
Ok(())
}

/// Prints a message to stderr, in the same format that `cargo` uses,
/// indicating that we are creating a bundle with the given filename.
pub fn print_bundling(filename: &str) -> crate::Result<()> {
print_progress("Bundling", filename)
}

/// Prints a message to stderr, in the same format that `cargo` uses,
/// indicating that we have finished the the given bundles.
pub fn print_finished(bundles: &[crate::bundle::Bundle]) -> crate::Result<()> {
let pluralised = if bundles.len() == 1 {
"bundle"
} else {
"bundles"
};
let msg = format!("{} {} at:", bundles.len(), pluralised);
print_progress("Finished", &msg)?;
for bundle in bundles {
for path in &bundle.bundle_paths {
let mut note = "";
if bundle.package_type == crate::PackageType::Updater {
note = " (updater)";
}
println!(" {}{}", path.display(), note,);
}
}
Ok(())
}

/// Prints a formatted bundle progress to stderr.
fn print_progress(step: &str, msg: &str) -> crate::Result<()> {
let mut output = StandardStream::stderr(ColorChoice::Always);
let _ = output.set_color(ColorSpec::new().set_fg(Some(Color::Green)).set_bold(true));
write!(output, " {}", step)?;
output.reset()?;
writeln!(output, " {}", msg)?;
output.flush()?;
Ok(())
pub trait CommandExt {
fn output_ok(&mut self) -> crate::Result<Output>;
}

/// Prints a warning message to stderr, in the same format that `cargo` uses.
#[allow(dead_code)]
pub fn print_warning(message: &str) -> crate::Result<()> {
let mut output = StandardStream::stderr(ColorChoice::Always);
let _ = output.set_color(ColorSpec::new().set_fg(Some(Color::Yellow)).set_bold(true));
write!(output, "warning:")?;
output.reset()?;
writeln!(output, " {}", message)?;
output.flush()?;
Ok(())
}
impl CommandExt for Command {
fn output_ok(&mut self) -> crate::Result<Output> {
debug!(action = "Running"; "Command `{} {}`", self.get_program().to_string_lossy(), self.get_args().map(|arg| arg.to_string_lossy()).fold(String::new(), |acc, arg| format!("{} {}", acc, arg)));

/// Prints a Info message to stderr.
pub fn print_info(message: &str) -> crate::Result<()> {
let mut output = StandardStream::stderr(ColorChoice::Always);
let _ = output.set_color(ColorSpec::new().set_fg(Some(Color::Green)).set_bold(true));
write!(output, "info:")?;
output.reset()?;
writeln!(output, " {}", message)?;
output.flush()?;
Ok(())
}
let output = self.output()?;

pub fn execute_with_verbosity(cmd: &mut Command, settings: &Settings) -> crate::Result<()> {
if settings.is_verbose() {
cmd.pipe()?;
} else {
cmd.stdout(Stdio::null()).stderr(Stdio::null());
}
let status = cmd.status().expect("failed to spawn command");
let stdout = String::from_utf8_lossy(&output.stdout);
if !stdout.is_empty() {
debug!("Stdout: {}", stdout);
}
let stderr = String::from_utf8_lossy(&output.stderr);
if !stderr.is_empty() {
debug!("Stderr: {}", stderr);
}

if status.success() {
Ok(())
} else {
Err(anyhow::anyhow!("command failed").into())
if output.status.success() {
Ok(output)
} else {
Err(crate::Error::GenericError(
String::from_utf8_lossy(&output.stderr).to_string(),
))
}
}
}

Expand Down
27 changes: 10 additions & 17 deletions tooling/bundler/src/bundle/linux/appimage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@
// SPDX-License-Identifier: MIT

use super::{
super::{common, path_utils},
super::{common::CommandExt, path_utils},
debian,
};
use crate::Settings;

use anyhow::Context;
use handlebars::Handlebars;

use log::info;
use std::{
collections::BTreeMap,
fs::{remove_dir_all, write},
Expand Down Expand Up @@ -76,7 +76,9 @@ pub fn bundle_project(settings: &Settings) -> crate::Result<Vec<PathBuf>> {

// create the shell script file in the target/ folder.
let sh_file = output_path.join("build_appimage.sh");
common::print_bundling(appimage_path.file_name().unwrap().to_str().unwrap())?;

info!(action = "Bundling"; "{} ({})", appimage_filename, appimage_path.display());

write(&sh_file, temp)?;

// chmod script for execution
Expand All @@ -90,19 +92,10 @@ pub fn bundle_project(settings: &Settings) -> crate::Result<Vec<PathBuf>> {
.expect("Failed to chmod script");

// execute the shell script to build the appimage.
let mut cmd = Command::new(&sh_file);
cmd.current_dir(output_path);

common::execute_with_verbosity(&mut cmd, settings).map_err(|_| {
crate::Error::ShellScriptError(format!(
"error running appimage.sh{}",
if settings.is_verbose() {
""
} else {
", try running with --verbose to see command output"
}
))
})?;
Command::new(&sh_file)
.current_dir(output_path)
.output_ok()
.context("error running appimage.sh")?;

remove_dir_all(&package_dir)?;
Ok(vec![appimage_path])
Expand Down
8 changes: 5 additions & 3 deletions tooling/bundler/src/bundle/linux/debian.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,11 @@

use super::super::common;
use crate::Settings;

use anyhow::Context;
use heck::ToKebabCase;
use image::{self, codecs::png::PngDecoder, GenericImageView, ImageDecoder};
use libflate::gzip;
use log::info;
use walkdir::WalkDir;

use std::{
Expand Down Expand Up @@ -64,14 +64,16 @@ pub fn bundle_project(settings: &Settings) -> crate::Result<Vec<PathBuf>> {
arch
);
let package_name = format!("{}.deb", package_base_name);
common::print_bundling(&package_name)?;

let base_dir = settings.project_out_directory().join("bundle/deb");
let package_dir = base_dir.join(&package_base_name);
if package_dir.exists() {
fs::remove_dir_all(&package_dir)
.with_context(|| format!("Failed to remove old {}", package_base_name))?;
}
let package_path = base_dir.join(package_name);
let package_path = base_dir.join(&package_name);

info!(action = "Bundling"; "{} ({})", package_name, package_path.display());

let (data_dir, _) = generate_data(settings, &package_dir)
.with_context(|| "Failed to build data folders and files")?;
Expand Down
Loading

0 comments on commit 35f2147

Please sign in to comment.