You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

68 lines
1.7 KiB

  1. use indicatif::{ProgressBar, ProgressStyle};
  2. use once_cell::sync::Lazy;
  3. use std::io::LineWriter;
  4. use std::sync::Mutex;
  5. pub static PROGRESS_BAR: Lazy<Mutex<Option<ProgressBar>>> = Lazy::new(|| Mutex::new(None));
  6. pub fn update_progress(position: u64) {
  7. let pb = PROGRESS_BAR.lock().unwrap();
  8. if let Some(pb) = pb.as_ref() {
  9. pb.set_position(position);
  10. }
  11. }
  12. pub fn create_progress_bar(total_size: u64) {
  13. let pb = ProgressBar::new(total_size);
  14. pb.enable_steady_tick(100);
  15. pb.set_style(ProgressStyle::default_bar()
  16. .template("{spinner:.green} [{elapsed_precise}] [{wide_bar:.cyan/blue}] {bytes}/{total_bytes} {msg} ({eta} remaining)")
  17. .progress_chars("=>-"));
  18. *PROGRESS_BAR.lock().unwrap() = Some(pb);
  19. }
  20. pub fn finish_progress_bar() {
  21. let mut pb = PROGRESS_BAR.lock().unwrap();
  22. if let Some(pb) = pb.as_ref() {
  23. pb.finish();
  24. }
  25. *pb = None;
  26. }
  27. pub struct PBWriter {}
  28. impl PBWriter {
  29. pub fn new() -> Self {
  30. PBWriter {}
  31. }
  32. }
  33. impl std::io::Write for PBWriter {
  34. fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
  35. let pb = PROGRESS_BAR.lock().unwrap();
  36. if let Some(pb) = pb.as_ref() {
  37. pb.println(std::str::from_utf8(buf).unwrap());
  38. Ok(buf.len())
  39. } else {
  40. std::io::stderr().write(buf)
  41. }
  42. }
  43. fn flush(&mut self) -> std::io::Result<()> {
  44. std::io::stderr().flush()
  45. }
  46. }
  47. pub fn setup_logging() {
  48. std::env::set_var(
  49. "RUST_LOG",
  50. std::env::var("RUST_LOG").unwrap_or("info".to_string()),
  51. );
  52. tracing_subscriber::fmt::fmt()
  53. .with_writer(move || -> Box<dyn std::io::Write> {
  54. Box::new(LineWriter::new(PBWriter::new()))
  55. })
  56. .init();
  57. }