Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add progress bar to install command #1028

Merged
merged 8 commits into from
May 25, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/show-download-progress.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"fnm": minor
---

Show a progress bar when downloading and extracting node
73 changes: 71 additions & 2 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ sysinfo = "0.29.3"
thiserror = "1.0.44"
clap_complete = "4.3.1"
anyhow = "1.0.71"
indicatif = "0.17.6"

[dev-dependencies]
pretty_assertions = "1.4.0"
Expand Down
3 changes: 3 additions & 0 deletions docs/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,9 @@ Options:
--latest
Install latest version

--no-progress
Do not display a progress bar

--log-level <LOG_LEVEL>
The log level of fnm commands

Expand Down
12 changes: 12 additions & 0 deletions src/commands/install.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ pub struct Install {
/// Install latest version
#[clap(long, conflicts_with_all = &["version", "lts"])]
pub latest: bool,

/// Do not display a progress bar
#[clap(long)]
pub no_progress: bool,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think clap has a way to add --progress/--no-progress to enable or disable a flag, just made a progress bar the default.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fyi, I'm gonna change that before releasing to --progress=never, and will have --progress=auto|always so auto will be based on the log level :blob_thumbs_up:

}

impl Install {
Expand All @@ -34,16 +38,19 @@ impl Install {
version: v,
lts: false,
latest: false,
no_progress: _,
} => Ok(v),
Self {
version: None,
lts: true,
latest: false,
no_progress: _,
} => Ok(Some(UserVersion::Full(Version::Lts(LtsType::Latest)))),
Self {
version: None,
lts: false,
latest: true,
no_progress: _,
} => Ok(Some(UserVersion::Full(Version::Latest))),
_ => Err(Error::TooManyVersionsProvided),
}
Expand All @@ -56,6 +63,8 @@ impl Command for Install {
fn apply(self, config: &FnmConfig) -> Result<(), Self::Error> {
let current_dir = std::env::current_dir().unwrap();

let show_progress = !self.no_progress;

let current_version = self
.version()?
.or_else(|| get_user_version_for_directory(current_dir, config))
Expand Down Expand Up @@ -131,6 +140,7 @@ impl Command for Install {
&config.node_dist_mirror,
config.installations_dir(),
safe_arch,
show_progress,
) {
Err(err @ DownloaderError::VersionAlreadyInstalled { .. }) => {
outln!(config, Error, "{} {}", "warning:".bold().yellow(), err);
Expand Down Expand Up @@ -225,6 +235,7 @@ mod tests {
version: UserVersion::from_str("12.0.0").ok(),
lts: false,
latest: false,
no_progress: true,
}
.apply(&config)
.expect("Can't install");
Expand All @@ -250,6 +261,7 @@ mod tests {
version: None,
lts: false,
latest: true,
no_progress: true,
}
.apply(&config)
.expect("Can't install");
Expand Down
17 changes: 11 additions & 6 deletions src/downloader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ use crate::arch::Arch;
use crate::archive;
use crate::archive::{Error as ExtractError, Extract};
use crate::directory_portal::DirectoryPortal;
use crate::progress::ResponseProgress;
use crate::version::Version;
use log::debug;
use std::io::Read;
use std::path::Path;
use std::path::PathBuf;
use thiserror::Error;
Expand Down Expand Up @@ -63,10 +65,7 @@ fn download_url(base_url: &Url, version: &Version, arch: &Arch) -> Url {
.unwrap()
}

pub fn extract_archive_into<P: AsRef<Path>>(
path: P,
response: crate::http::Response,
) -> Result<(), Error> {
fn extract_archive_into<P: AsRef<Path>, R: Read>(path: P, response: R) -> Result<(), Error> {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

:interesting:

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

just a thought (not important, can be done in a different PR): what do you think about starting to use impl instead of generic constraints? seems more readable right?

Suggested change
fn extract_archive_into<P: AsRef<Path>, R: Read>(path: P, response: R) -> Result<(), Error> {
fn extract_archive_into(path: impl AsRef<Path>, response: impl Read) -> Result<(), Error> {

#[cfg(unix)]
let extractor = archive::TarXz::new(response);
#[cfg(windows)]
Expand All @@ -81,6 +80,7 @@ pub fn install_node_dist<P: AsRef<Path>>(
node_dist_mirror: &Url,
installations_dir: P,
arch: &Arch,
show_progress: bool,
) -> Result<(), Error> {
let installation_dir = PathBuf::from(installations_dir.as_ref()).join(version.v_str());

Expand Down Expand Up @@ -109,7 +109,11 @@ pub fn install_node_dist<P: AsRef<Path>>(
}

debug!("Extracting response...");
extract_archive_into(&portal, response)?;
if show_progress {
extract_archive_into(&portal, ResponseProgress::new(response))?;
} else {
extract_archive_into(&portal, response)?;
}
debug!("Extraction completed");

let installed_directory = std::fs::read_dir(&portal)?
Expand Down Expand Up @@ -171,7 +175,8 @@ mod tests {
let version = Version::parse("12.0.0").unwrap();
let arch = Arch::X64;
let node_dist_mirror = Url::parse("https://nodejs.org/dist/").unwrap();
install_node_dist(&version, &node_dist_mirror, path, &arch).expect("Can't install Node 12");
install_node_dist(&version, &node_dist_mirror, path, &arch, false)
.expect("Can't install Node 12");

let mut location_path = path.join(version.v_str()).join("installation");

Expand Down
1 change: 1 addition & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ mod installed_versions;
mod lts;
mod package_json;
mod path_ext;
mod progress;
mod remote_node_index;
mod shell;
mod system_info;
Expand Down
55 changes: 55 additions & 0 deletions src/progress.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
use std::io::Read;

use indicatif::{ProgressBar, ProgressStyle};
use reqwest::blocking::Response;

pub struct ResponseProgress {
progress: Option<ProgressBar>,
response: Response,
}

fn make_progress_bar(size: u64) -> ProgressBar {
let bar = ProgressBar::new(size);

bar.set_style(
ProgressStyle::default_bar()
.template("[{elapsed_precise}] [{bar:40}] {bytes}/{total_bytes} ({bytes_per_sec}, {eta})")
.unwrap()
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This can return a TemplateError from indicatif when the template has a syntax issue. Unwrapping because it's a static template.

.progress_chars("#>-")
);

bar
}

impl ResponseProgress {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you think we should unit test this somehow?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added a test to ensure we still read from the underlying response with the progress wrapper. Also added a indicatif::TermLike impl that captures the progress bar activity and saves all the activity into a String, then checks for "#" characters in the string after reading all the data.

The mock impl is a bit verbose so I added it in a separate commit to revert it easily. Let me know if you'd prefer to just test the read operations pass through.

pub fn new(response: Response) -> Self {
Self {
progress: response.content_length().map(make_progress_bar),
response,
}
}

pub fn finish(&self) {
if let Some(ref bar) = self.progress {
bar.finish();
}
}
}

impl Read for ResponseProgress {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let size = self.response.read(buf)?;

if let Some(ref bar) = self.progress {
bar.inc(size as u64);
}

Ok(size)
}
}

impl Drop for ResponseProgress {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using Drop because the XzDecoder takes ownership of the reader. Ensures the progress bar is finalized once the download is completed. Not sure if there's a better way of doing this.

fn drop(&mut self) {
self.finish()
}
}