Skip to content

Commit

Permalink
Simplify echo!() output (#898)
Browse files Browse the repository at this point in the history
* Simplify `echo!()` output

* Alternative syntax for echo

---------

Co-authored-by: Armin Ronacher <[email protected]>
  • Loading branch information
j178 and mitsuhiko committed Mar 19, 2024
1 parent 913e8a6 commit 4a99f58
Show file tree
Hide file tree
Showing 8 changed files with 87 additions and 110 deletions.
81 changes: 28 additions & 53 deletions rye/src/bootstrap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,9 +102,7 @@ pub fn ensure_self_venv_with_toolchain(
Ok(venv_dir) => return Ok(venv_dir),
Err((venv_dir, SelfVenvStatus::DoesNotExist)) => venv_dir,
Err((venv_dir, SelfVenvStatus::NotUpToDate)) => {
if output != CommandOutput::Quiet {
echo!("Detected outdated rye internals. Refreshing");
}
echo!(if output, "Detected outdated rye internals. Refreshing");
fs::remove_dir_all(&venv_dir)
.path_context(&venv_dir, "could not remove self-venv for update")?;

Expand All @@ -118,9 +116,7 @@ pub fn ensure_self_venv_with_toolchain(
}
};

if output != CommandOutput::Quiet {
echo!("Bootstrapping rye internals");
}
echo!(if output, "Bootstrapping rye internals");

// Ensure we have uv
let uv = UvBuilder::new()
Expand Down Expand Up @@ -300,12 +296,11 @@ fn ensure_latest_self_toolchain(output: CommandOutput) -> Result<PythonVersion,
.into_iter()
.max()
{
if output != CommandOutput::Quiet {
echo!(
"Found a compatible Python version: {}",
style(&version).cyan()
);
}
echo!(
if output,
"Found a compatible Python version: {}",
style(&version).cyan()
);
Ok(version)
} else {
fetch(&SELF_PYTHON_TARGET_VERSION, output, false)
Expand All @@ -326,20 +321,18 @@ fn ensure_specific_self_toolchain(
);
}
if !get_toolchain_python_bin(&toolchain_version)?.is_file() {
if output != CommandOutput::Quiet {
echo!(
"Fetching requested internal toolchain '{}'",
toolchain_version
);
}
echo!(
if output,
"Fetching requested internal toolchain '{}'",
toolchain_version
);
fetch(&toolchain_version.into(), output, false)
} else {
if output != CommandOutput::Quiet {
echo!(
"Found a compatible Python version: {}",
style(&toolchain_version).cyan()
);
}
echo!(
if output,
"Found a compatible Python version: {}",
style(&toolchain_version).cyan()
);
Ok(toolchain_version)
}
}
Expand All @@ -353,9 +346,7 @@ pub fn fetch(
if let Ok(version) = PythonVersion::try_from(version.clone()) {
let py_bin = get_toolchain_python_bin(&version)?;
if !force && py_bin.is_file() {
if output == CommandOutput::Verbose {
echo!("Python version already downloaded. Skipping.");
}
echo!(if verbose output, "Python version already downloaded. Skipping.");
return Ok(version);
}
}
Expand All @@ -367,46 +358,32 @@ pub fn fetch(

let target_dir = get_canonical_py_path(&version)?;
let target_py_bin = get_toolchain_python_bin(&version)?;
if output == CommandOutput::Verbose {
echo!("target dir: {}", target_dir.display());
}
echo!(if verbose output, "target dir: {}", target_dir.display());
if target_dir.is_dir() && target_py_bin.is_file() {
if !force {
if output == CommandOutput::Verbose {
echo!("Python version already downloaded. Skipping.");
}
echo!(if verbose output, "Python version already downloaded. Skipping.");
return Ok(version);
}
if output != CommandOutput::Quiet {
echo!("Removing the existing Python version");
}
echo!(if output, "Removing the existing Python version");
fs::remove_dir_all(&target_dir)
.with_context(|| format!("failed to remove target folder {}", target_dir.display()))?;
}

fs::create_dir_all(&target_dir).path_context(&target_dir, "failed to create target folder")?;

if output == CommandOutput::Verbose {
echo!("download url: {}", url);
}
if output != CommandOutput::Quiet {
echo!("{} {}", style("Downloading").cyan(), version);
}
echo!(if verbose output, "download url: {}", url);
echo!(if output, "{} {}", style("Downloading").cyan(), version);
let archive_buffer = download_url(url, output)?;

if let Some(sha256) = sha256 {
if output != CommandOutput::Quiet {
echo!("{} {}", style("Checking").cyan(), "checksum");
}
echo!(if output, "{} {}", style("Checking").cyan(), "checksum");
check_checksum(&archive_buffer, sha256)
.with_context(|| format!("Checksum check of {} failed", &url))?;
} else if output != CommandOutput::Quiet {
echo!("Checksum check skipped (no hash available)");
} else {
echo!(if output, "Checksum check skipped (no hash available)");
}

if output != CommandOutput::Quiet {
echo!("{}", style("Unpacking").cyan());
}
echo!(if output, "{}", style("Unpacking").cyan());
unpack_archive(&archive_buffer, &target_dir, 1).with_context(|| {
format!(
"unpacking of downloaded tarball {} to '{}' failed",
Expand All @@ -415,9 +392,7 @@ pub fn fetch(
)
})?;

if output != CommandOutput::Quiet {
echo!("{} {}", style("Downloaded").green(), version);
}
echo!(if output, "{} {}", style("Downloaded").green(), version);

Ok(version)
}
Expand Down
8 changes: 5 additions & 3 deletions rye/src/cli/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,11 @@ pub fn execute(cmd: Args) -> Result<(), Error> {
continue;
}

if output != CommandOutput::Quiet {
echo!("building {}", style(project.normalized_name()?).cyan());
}
echo!(
if output,
"building {}",
style(project.normalized_name()?).cyan()
);

let mut build_cmd = Command::new(get_venv_python_bin(&venv));
build_cmd
Expand Down
17 changes: 8 additions & 9 deletions rye/src/cli/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -444,15 +444,14 @@ pub fn execute(cmd: Args) -> Result<(), Error> {
}
}

if output != CommandOutput::Quiet {
echo!(
"{} Initialized {}project in {}",
style("success:").green(),
if is_virtual { "virtual " } else { "" },
dir.display()
);
echo!(" Run `rye sync` to get started");
}
echo!(
if output,
"{} Initialized {}project in {}",
style("success:").green(),
if is_virtual { "virtual " } else { "" },
dir.display()
);
echo!(if output, " Run `rye sync` to get started");

Ok(())
}
Expand Down
4 changes: 2 additions & 2 deletions rye/src/cli/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,9 @@ pub fn execute(cmd: Args) -> Result<(), Error> {
for (idx, project) in projects.iter().enumerate() {
if output != CommandOutput::Quiet {
if idx > 0 {
println!();
echo!();
}
println!(
echo!(
"Running tests for {} ({})",
style(project.name().unwrap_or("<unknown>")).cyan(),
style(project.root_path().display()).dim()
Expand Down
8 changes: 2 additions & 6 deletions rye/src/lock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,9 +137,7 @@ pub fn update_workspace_lockfile(
sources: &ExpandedSources,
lock_options: &LockOptions,
) -> Result<(), Error> {
if output != CommandOutput::Quiet {
echo!("Generating {} lockfile: {}", lock_mode, lockfile.display());
}
echo!(if output, "Generating {} lockfile: {}", lock_mode, lockfile.display());

let lock_options = restore_lock_options(lockfile, lock_options)?;
let features_by_project = collect_workspace_features(&lock_options);
Expand Down Expand Up @@ -319,9 +317,7 @@ pub fn update_single_project_lockfile(
sources: &ExpandedSources,
lock_options: &LockOptions,
) -> Result<(), Error> {
if output != CommandOutput::Quiet {
echo!("Generating {} lockfile: {}", lock_mode, lockfile.display());
}
echo!(if output, "Generating {} lockfile: {}", lock_mode, lockfile.display());

let lock_options = restore_lock_options(lockfile, lock_options)?;
let mut req_file = NamedTempFile::new()?;
Expand Down
4 changes: 1 addition & 3 deletions rye/src/piptools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,7 @@ fn get_pip_tools_bin(py_ver: &PythonVersion, output: CommandOutput) -> Result<Pa
.path_context(&venv, "unable to wipe old virtualenv for pip-tools")?;
}

if output != CommandOutput::Quiet {
echo!("Creating virtualenv for pip-tools");
}
echo!(if output, "Creating virtualenv for pip-tools");
create_virtualenv(output, &self_venv, py_ver, &venv, "pip-tools")?;

let mut cmd = Command::new(self_venv.join(VENV_BIN).join("pip"));
Expand Down
57 changes: 24 additions & 33 deletions rye/src/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,33 +115,29 @@ pub fn sync(mut cmd: SyncOptions) -> Result<(), Error> {
if venv.is_dir() {
if let Some(marker) = read_venv_marker(&venv) {
if marker.python != py_ver {
if cmd.output != CommandOutput::Quiet {
echo!(
"Python version mismatch (found {}, expected {}), recreating.",
marker.python,
py_ver
);
}
echo!(
if cmd.output,
"Python version mismatch (found {}, expected {}), recreating.",
marker.python,
py_ver
);
recreate = true;
} else if let Some(ref venv_path) = marker.venv_path {
// for virtualenvs that have a location identifier, check if we need to
// recreate it. On IO error we know that one of the paths is gone, so
// something needs recreation.
if !is_same_file(&venv, venv_path).unwrap_or(false) {
if cmd.output != CommandOutput::Quiet {
echo!(
"Detected relocated virtualenv ({} => {}), recreating.",
venv_path.display(),
venv.display(),
);
}
echo!(
if cmd.output,
"Detected relocated virtualenv ({} => {}), recreating.",
venv_path.display(),
venv.display(),
);
recreate = true;
}
}
} else if cmd.force {
if cmd.output != CommandOutput::Quiet {
echo!("Forcing re-creation of non-rye managed virtualenv");
}
echo!(if cmd.output, "Forcing re-creation of non-rye managed virtualenv");
recreate = true;
} else if cmd.mode == SyncMode::PythonOnly {
// in python-only sync mode, don't complain about foreign venvs
Expand All @@ -162,19 +158,16 @@ pub fn sync(mut cmd: SyncOptions) -> Result<(), Error> {

if venv.is_dir() {
// we only care about this output if regular syncs are used
if !matches!(cmd.mode, SyncMode::PythonOnly | SyncMode::LockOnly)
&& output != CommandOutput::Quiet
{
echo!("Reusing already existing virtualenv");
if !matches!(cmd.mode, SyncMode::PythonOnly | SyncMode::LockOnly) {
echo!(if output, "Reusing already existing virtualenv");
}
} else {
if output != CommandOutput::Quiet {
echo!(
"Initializing new virtualenv in {}",
style(venv.display()).cyan()
);
echo!("Python version: {}", style(&py_ver).cyan());
}
echo!(
if output,
"Initializing new virtualenv in {}",
style(venv.display()).cyan()
);
echo!(if output, "Python version: {}", style(&py_ver).cyan());
let prompt = pyproject.name().unwrap_or("venv");
create_virtualenv(output, &self_venv, &py_ver, &venv, prompt)
.context("failed creating virtualenv ahead of sync")?;
Expand Down Expand Up @@ -242,9 +235,7 @@ pub fn sync(mut cmd: SyncOptions) -> Result<(), Error> {

// run pip install with the lockfile.
if cmd.mode != SyncMode::LockOnly {
if output != CommandOutput::Quiet {
echo!("Installing dependencies");
}
echo!(if output, "Installing dependencies");

let target_lockfile = if cmd.dev && dev_lockfile.is_file() {
dev_lockfile
Expand Down Expand Up @@ -311,8 +302,8 @@ pub fn sync(mut cmd: SyncOptions) -> Result<(), Error> {
};
}

if output != CommandOutput::Quiet && cmd.mode != SyncMode::PythonOnly {
echo!("Done!");
if cmd.mode != SyncMode::PythonOnly {
echo!(if output, "Done!");
}

Ok(())
Expand Down
18 changes: 17 additions & 1 deletion rye/src/tui.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,27 @@ macro_rules! echo {
() => {
$crate::tui::_print(format_args!(""))
};
(if verbose $out:expr, $($arg:tt)+) => {
match $out {
$crate::utils::CommandOutput::Verbose => {
$crate::tui::_print(format_args!($($arg)*))
}
_ => {}
}
};
(if $out:expr, $($arg:tt)+) => {
match $out {
$crate::utils::CommandOutput::Normal | $crate::utils::CommandOutput::Verbose => {
$crate::tui::_print(format_args!($($arg)*))
}
_ => {}
}
};
($($arg:tt)+) => {
// TODO: this is bloaty, but this way capturing of outputs
// for stdout works in tests still.
$crate::tui::_print(format_args!($($arg)*))
}
};
}

/// Like echo but always goes to stderr.
Expand Down

0 comments on commit 4a99f58

Please sign in to comment.