util.rs 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::io::Write;
  19. use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor};
  20. use fud::resource::{ResourceStatus, ResourceType};
  21. const UNITS: [&str; 7] = ["B", "KB", "MB", "GB", "TB", "PB", "EB"];
  22. pub fn status_to_colorspec(status: &ResourceStatus) -> ColorSpec {
  23. ColorSpec::new()
  24. .set_fg(match status {
  25. ResourceStatus::Downloading => Some(Color::Blue),
  26. ResourceStatus::Seeding => Some(Color::Green),
  27. ResourceStatus::Discovering => Some(Color::Magenta),
  28. ResourceStatus::Incomplete => Some(Color::Red),
  29. ResourceStatus::Verifying => Some(Color::Yellow),
  30. })
  31. .set_bold(true)
  32. .clone()
  33. }
  34. pub fn type_to_colorspec(rtype: &ResourceType) -> ColorSpec {
  35. ColorSpec::new()
  36. .set_fg(match rtype {
  37. ResourceType::File => Some(Color::Blue),
  38. ResourceType::Directory => Some(Color::Magenta),
  39. ResourceType::Unknown => None,
  40. })
  41. .set_bold(true)
  42. .clone()
  43. }
  44. pub fn format_bytes(bytes: u64) -> String {
  45. let mut size = bytes as f64;
  46. let mut unit_index = 0;
  47. while size >= 1024.0 && unit_index < UNITS.len() - 1 {
  48. size /= 1024.0;
  49. unit_index += 1;
  50. }
  51. format!("{size:.1} {}", UNITS[unit_index])
  52. }
  53. pub fn format_progress_bytes(current: u64, total: u64) -> String {
  54. let mut total = total as f64;
  55. let mut unit_index = 0;
  56. while total >= 1024.0 && unit_index < UNITS.len() - 1 {
  57. total /= 1024.0;
  58. unit_index += 1;
  59. }
  60. let current = (current as f64) / 1024_f64.powi(unit_index as i32);
  61. format!("{current:.1}/{total:.1} {}", UNITS[unit_index])
  62. }
  63. /// Returns a formated string from the duration.
  64. /// - 1 -> 1s
  65. /// - 60 -> 1m
  66. /// - 90 -> 1m30s
  67. pub fn format_duration(seconds: u64) -> String {
  68. if seconds == 0 {
  69. return "0s".to_string();
  70. }
  71. let units = [
  72. (86400, "d"), // days
  73. (3600, "h"), // hours
  74. (60, "m"), // minutes
  75. (1, "s"), // seconds
  76. ];
  77. for (i, (unit_seconds, unit_symbol)) in units.iter().enumerate() {
  78. if seconds >= *unit_seconds {
  79. let first = seconds / unit_seconds;
  80. let remaining = seconds % unit_seconds;
  81. if remaining > 0 && i < units.len() - 1 {
  82. let (next_unit_seconds, next_unit_symbol) = units[i + 1];
  83. let second = remaining / next_unit_seconds;
  84. return format!("{first}{unit_symbol}{second}{next_unit_symbol}");
  85. }
  86. return format!("{first}{unit_symbol}");
  87. }
  88. }
  89. "0s".to_string()
  90. }
  91. /// Tree only used for printing.
  92. #[derive(Debug)]
  93. pub struct TreeNode<K> {
  94. pub key: K,
  95. pub value: Option<String>,
  96. pub color: Option<ColorSpec>,
  97. pub children: Vec<TreeNode<K>>,
  98. }
  99. impl<K> TreeNode<K> {
  100. /// Key only
  101. pub fn key(key: K) -> Self {
  102. Self { key, value: None, color: None, children: vec![] }
  103. }
  104. /// Key + value
  105. pub fn kv(key: K, value: String) -> Self {
  106. Self { key, value: Some(value), color: None, children: vec![] }
  107. }
  108. /// Key + value + color
  109. pub fn kvc(key: K, value: String, color: ColorSpec) -> Self {
  110. Self { key, value: Some(value), color: Some(color), children: vec![] }
  111. }
  112. }
  113. pub fn print_tree<K: AsRef<str> + std::fmt::Display>(root: &str, items: &[TreeNode<K>]) {
  114. fn print_node<K: AsRef<str> + std::fmt::Display>(
  115. node: &TreeNode<K>,
  116. is_last: bool,
  117. prefix: &str,
  118. ) {
  119. let mut stdout = StandardStream::stdout(ColorChoice::Auto);
  120. write!(&mut stdout, "{}{} {}", prefix, if is_last { "└─" } else { "├─" }, node.key)
  121. .unwrap();
  122. if let Some(value) = &node.value {
  123. write!(&mut stdout, ": ").unwrap();
  124. if let Some(spec) = &node.color {
  125. stdout.set_color(spec).unwrap();
  126. }
  127. write!(&mut stdout, "{value}").unwrap();
  128. stdout.reset().unwrap();
  129. }
  130. writeln!(&mut stdout).unwrap();
  131. let new_prefix = format!("{}{}", prefix, if is_last { " " } else { "│ " });
  132. for (i, child) in node.children.iter().enumerate() {
  133. print_node(child, i == node.children.len() - 1, &new_prefix);
  134. }
  135. }
  136. let mut stdout = StandardStream::stdout(ColorChoice::Auto);
  137. stdout.set_color(ColorSpec::new().set_bold(true)).unwrap();
  138. writeln!(&mut stdout, "{root}").unwrap();
  139. stdout.reset().unwrap();
  140. for (i, item) in items.iter().enumerate() {
  141. print_node(item, i == items.len() - 1, "");
  142. }
  143. }
  144. macro_rules! optional_value {
  145. ($value:expr) => {
  146. match $value {
  147. 0 => "?".to_string(),
  148. x => x.to_string(),
  149. }
  150. };
  151. ($value:expr, $formatter:expr) => {
  152. match $value {
  153. 0 => "?".to_string(),
  154. x => $formatter(x),
  155. }
  156. };
  157. }
  158. pub(crate) use optional_value;