Skip to content

Commit

Permalink
Add new ProgressStyle::with_template() constructor
Browse files Browse the repository at this point in the history
  • Loading branch information
djc committed Feb 22, 2022
1 parent a3c1829 commit b1d2e46
Show file tree
Hide file tree
Showing 15 changed files with 50 additions and 58 deletions.
11 changes: 6 additions & 5 deletions examples/cargo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,16 +42,17 @@ fn main() {
// mimic cargo progress bar although it behaves a bit different
let pb = ProgressBar::new(CRATES.len() as u64);
pb.set_style(
ProgressStyle::default_bar()
ProgressStyle::with_template(
// note that bar size is fixed unlike cargo which is dynamic
// and also the truncation in cargo uses trailers (`...`)
.template(if Term::stdout().size().1 > 80 {
if Term::stdout().size().1 > 80 {
"{prefix:>12.cyan.bold} [{bar:57}] {pos}/{len} {wide_msg}"
} else {
"{prefix:>12.cyan.bold} [{bar:57}] {pos}/{len}"
})
.unwrap()
.progress_chars("=> "),
},
)
.unwrap()
.progress_chars("=> "),
);
pb.set_prefix("Building");

Expand Down
7 changes: 3 additions & 4 deletions examples/cargowrap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,9 @@ pub fn main() {
let pb = ProgressBar::new_spinner();
pb.enable_steady_tick(Duration::from_millis(200));
pb.set_style(
ProgressStyle::default_spinner()
.tick_chars("/|\\- ")
.template("{spinner:.dim.bold} cargo: {wide_msg}")
.unwrap(),
ProgressStyle::with_template("{spinner:.dim.bold} cargo: {wide_msg}")
.unwrap()
.tick_chars("/|\\- "),
);

let mut p = process::Command::new("cargo")
Expand Down
9 changes: 5 additions & 4 deletions examples/download-continued.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,11 @@ fn main() {

let pb = ProgressBar::new(total_size);
pb.set_style(
ProgressStyle::default_bar()
.template("{spinner:.green} [{wide_bar:.cyan/blue}] {bytes}/{total_bytes} ({eta})")
.unwrap()
.progress_chars("#>-"),
ProgressStyle::with_template(
"{spinner:.green} [{wide_bar:.cyan/blue}] {bytes}/{total_bytes} ({eta})",
)
.unwrap()
.progress_chars("#>-"),
);
pb.set_position(downloaded);
pb.reset_eta();
Expand Down
3 changes: 1 addition & 2 deletions examples/download-speed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@ fn main() {
let total_size = 231231231;

let pb = ProgressBar::new(total_size);
pb.set_style(ProgressStyle::default_bar()
.template("{spinner:.green} [{elapsed_precise}] [{wide_bar:.cyan/blue}] {bytes}/{total_bytes} ({bytes_per_sec}, {eta})")
pb.set_style(ProgressStyle::with_template("{spinner:.green} [{elapsed_precise}] [{wide_bar:.cyan/blue}] {bytes}/{total_bytes} ({bytes_per_sec}, {eta})")
.unwrap()
.progress_chars("#>-"));

Expand Down
3 changes: 1 addition & 2 deletions examples/download.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@ fn main() {
let total_size = 231231231;

let pb = ProgressBar::new(total_size);
pb.set_style(ProgressStyle::default_bar()
.template("{spinner:.green} [{elapsed_precise}] [{wide_bar:.cyan/blue}] {bytes}/{total_bytes} ({eta})")
pb.set_style(ProgressStyle::with_template("{spinner:.green} [{elapsed_precise}] [{wide_bar:.cyan/blue}] {bytes}/{total_bytes} ({eta})")
.unwrap()
.with_key("eta", |state| format!("{:.1}s", state.eta().as_secs_f64()))
.progress_chars("#>-"));
Expand Down
3 changes: 1 addition & 2 deletions examples/finebars.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@ fn main() {
.map(|s| {
let pb = m.add(ProgressBar::new(512));
pb.set_style(
ProgressStyle::default_bar()
.template(&format!("{{prefix:.bold}}▕{{bar:.{}}}▏{{msg}}", s.2))
ProgressStyle::with_template(&format!("{{prefix:.bold}}▕{{bar:.{}}}▏{{msg}}", s.2))
.unwrap()
.progress_chars(s.1),
);
Expand Down
9 changes: 6 additions & 3 deletions examples/iterator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,12 @@ fn main() {

// Provide a custom bar style
let pb = ProgressBar::new(1000);
pb.set_style(ProgressStyle::default_bar().template(
"{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] ({pos}/{len}, ETA {eta})",
).unwrap());
pb.set_style(
ProgressStyle::with_template(
"{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] ({pos}/{len}, ETA {eta})",
)
.unwrap(),
);
for _ in (0..1000).progress_with(pb) {
// ...
thread::sleep(Duration::from_millis(5));
Expand Down
7 changes: 3 additions & 4 deletions examples/long-spinner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ fn main() {
let pb = ProgressBar::new_spinner();
pb.enable_steady_tick(Duration::from_millis(120));
pb.set_style(
ProgressStyle::default_spinner()
ProgressStyle::with_template("{spinner:.blue} {msg}")
.unwrap()
// For more spinners check out the cli-spinners project:
// https://github.com/sindresorhus/cli-spinners/blob/master/spinners.json
.tick_strings(&[
Expand All @@ -18,9 +19,7 @@ fn main() {
"▹▹▹▸▹",
"▹▹▹▹▸",
"▪▪▪▪▪",
])
.template("{spinner:.blue} {msg}")
.unwrap(),
]),
);
pb.set_message("Calculating...");
thread::sleep(Duration::from_secs(5));
Expand Down
4 changes: 1 addition & 3 deletions examples/morebars.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@ use indicatif::{MultiProgress, ProgressBar, ProgressStyle};

fn main() {
let m = Arc::new(MultiProgress::new());
let sty = ProgressStyle::default_bar()
.template("{bar:40.green/yellow} {pos:>7}/{len:7}")
.unwrap();
let sty = ProgressStyle::with_template("{bar:40.green/yellow} {pos:>7}/{len:7}").unwrap();

let pb = m.add(ProgressBar::new(5));
pb.set_style(sty.clone());
Expand Down
13 changes: 4 additions & 9 deletions examples/multi-tree-ext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,15 +184,10 @@ pub fn main() {
MultiProgressAlignment::Top
};
mp.set_alignment(alignment);
let sty_main = ProgressStyle::default_bar()
.template("{bar:40.green/yellow} {pos:>4}/{len:4}")
.unwrap();
let sty_aux = ProgressStyle::default_bar()
.template("[{pos:>2}/{len:2}] {prefix}{spinner:.green} {msg}")
.unwrap();
let sty_fin = ProgressStyle::default_bar()
.template("[{pos:>2}/{len:2}] {prefix}{msg}")
.unwrap();
let sty_main = ProgressStyle::with_template("{bar:40.green/yellow} {pos:>4}/{len:4}").unwrap();
let sty_aux =
ProgressStyle::with_template("[{pos:>2}/{len:2}] {prefix}{spinner:.green} {msg}").unwrap();
let sty_fin = ProgressStyle::with_template("[{pos:>2}/{len:2}] {prefix}{msg}").unwrap();

let pb_main = mp.add(ProgressBar::new(
ELEMENTS
Expand Down
8 changes: 2 additions & 6 deletions examples/multi-tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,12 +86,8 @@ static ELEMENTS: Lazy<[Elem; 9]> = Lazy::new(|| {
/// complete, the function returns `None`, which finishes the loop.
fn main() {
let mp = Arc::new(MultiProgress::new());
let sty_main = ProgressStyle::default_bar()
.template("{bar:40.green/yellow} {pos:>4}/{len:4}")
.unwrap();
let sty_aux = ProgressStyle::default_bar()
.template("{spinner:.green} {msg} {pos:>4}/{len:4}")
.unwrap();
let sty_main = ProgressStyle::with_template("{bar:40.green/yellow} {pos:>4}/{len:4}").unwrap();
let sty_aux = ProgressStyle::with_template("{spinner:.green} {msg} {pos:>4}/{len:4}").unwrap();

let pb_main = mp.add(ProgressBar::new(
ELEMENTS.iter().map(|e| e.progress_bar.length()).sum(),
Expand Down
9 changes: 5 additions & 4 deletions examples/multi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@ use indicatif::{MultiProgress, ProgressBar, ProgressStyle};

fn main() {
let m = MultiProgress::new();
let sty = ProgressStyle::default_bar()
.template("[{elapsed_precise}] {bar:40.cyan/blue} {pos:>7}/{len:7} {msg}")
.unwrap()
.progress_chars("##-");
let sty = ProgressStyle::with_template(
"[{elapsed_precise}] {bar:40.cyan/blue} {pos:>7}/{len:7} {msg}",
)
.unwrap()
.progress_chars("##-");

let pb = m.add(ProgressBar::new(128));
pb.set_style(sty.clone());
Expand Down
7 changes: 3 additions & 4 deletions examples/yarnish.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,9 @@ static SPARKLE: Emoji<'_, '_> = Emoji("✨ ", ":-)");
pub fn main() {
let mut rng = rand::thread_rng();
let started = Instant::now();
let spinner_style = ProgressStyle::default_spinner()
.tick_chars("⠁⠂⠄⡀⢀⠠⠐⠈ ")
.template("{prefix:.bold.dim} {spinner} {wide_msg}")
.unwrap();
let spinner_style = ProgressStyle::with_template("{prefix:.bold.dim} {spinner} {wide_msg}")
.unwrap()
.tick_chars("⠁⠂⠄⡀⢀⠠⠐⠈ ");

println!(
"{} {}Resolving packages...",
Expand Down
3 changes: 1 addition & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,8 +151,7 @@
//! ```rust
//! # use indicatif::{ProgressBar, ProgressStyle};
//! # let bar = ProgressBar::new(0);
//! bar.set_style(ProgressStyle::default_bar()
//! .template("[{elapsed_precise}] {bar:40.cyan/blue} {pos:>7}/{len:7} {msg}")
//! bar.set_style(ProgressStyle::with_template("[{elapsed_precise}] {bar:40.cyan/blue} {pos:>7}/{len:7} {msg}")
//! .unwrap()
//! .progress_chars("##-"));
//! ```
Expand Down
12 changes: 8 additions & 4 deletions src/style.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,15 +65,19 @@ fn width(c: &[Box<str>]) -> usize {
impl ProgressStyle {
/// Returns the default progress bar style for bars
pub fn default_bar() -> ProgressStyle {
Self::new("{wide_bar} {pos}/{len}")
Self::new(Template::from_str("{wide_bar} {pos}/{len}").unwrap())
}

/// Returns the default progress bar style for spinners
pub fn default_spinner() -> Self {
Self::new("{spinner} {msg}")
Self::new(Template::from_str("{spinner} {msg}").unwrap())
}

fn new(template: &str) -> Self {
pub fn with_template(template: &str) -> Result<Self, TemplateError> {
Ok(Self::new(Template::from_str(template)?))
}

fn new(template: Template) -> Self {
let progress_chars = segment("█░");
let char_width = width(&progress_chars);
Self {
Expand All @@ -85,7 +89,7 @@ impl ProgressStyle {
.collect(),
progress_chars,
char_width,
template: Template::from_str(template).unwrap(),
template,
format_map: HashMap::default(),
}
}
Expand Down

0 comments on commit b1d2e46

Please sign in to comment.