Skip to content

Commit

Permalink
refactor: Refactor memory_usage module to use module config. (starshi…
Browse files Browse the repository at this point in the history
…p#515)

Also addresses a number of bugs:
- the percent sign not displaying correctly on some terminal emulators, including kitty
- changing the symbol in the configuration file didn't do anything
- swap being shown even if the system didn't have any
  • Loading branch information
matiaskotlik authored and matchai committed Oct 20, 2019
1 parent e3f1a76 commit 86bb923
Show file tree
Hide file tree
Showing 4 changed files with 83 additions and 57 deletions.
2 changes: 1 addition & 1 deletion docs/config/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -691,7 +691,7 @@ To enable it, set `disabled` to `false` in your configuration file.
| Variable | Default | Description |
| ----------------- | ------------------------ | ------------------------------------------------------------- |
| `show_percentage` | `false` | Display memory usage as a percentage of the available memory. |
| `show_swap` | when total swap non-zero | Display swap usage. |
| `show_swap` | `true` | Display swap usage if total swap is non-zero. |
| `threshold` | `75` | Hide the memory usage unless it exceeds this percentage. |
| `symbol` | `"🐏 "` | The symbol used before displaying the memory usage. |
| `style` | `"bold dimmed white"` | The style for the module. |
Expand Down
29 changes: 29 additions & 0 deletions src/configs/memory_usage.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
use crate::config::{ModuleConfig, RootModuleConfig, SegmentConfig};

use ansi_term::{Color, Style};
use starship_module_config_derive::ModuleConfig;

#[derive(Clone, ModuleConfig)]
pub struct MemoryConfig<'a> {
pub show_percentage: bool,
pub show_swap: bool,
pub threshold: i64,
pub symbol: SegmentConfig<'a>,
pub display: SegmentConfig<'a>,
pub style: Style,
pub disabled: bool,
}

impl<'a> RootModuleConfig<'a> for MemoryConfig<'a> {
fn new() -> Self {
MemoryConfig {
show_percentage: false,
show_swap: true,
threshold: 75,
display: SegmentConfig::default(),
symbol: SegmentConfig::new("🐏 "),
style: Color::White.bold().dimmed(),
disabled: true,
}
}
}
1 change: 1 addition & 0 deletions src/configs/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ pub mod go;
pub mod hostname;
pub mod jobs;
pub mod kubernetes;
pub mod memory_usage;
pub mod nodejs;
pub mod package;
pub mod python;
Expand Down
108 changes: 52 additions & 56 deletions src/modules/memory_usage.rs
Original file line number Diff line number Diff line change
@@ -1,90 +1,86 @@
use ansi_term::Color;

use super::{Context, Module};
use byte_unit::{Byte, ByteUnit};
use sysinfo::{RefreshKind, SystemExt};

use super::{Context, Module, RootModuleConfig};

use crate::configs::memory_usage::MemoryConfig;

fn format_kib(n_kib: u64) -> String {
let byte = Byte::from_unit(n_kib as f64, ByteUnit::KiB).unwrap_or_else(|_| Byte::from_bytes(0));
let mut display_bytes = byte.get_appropriate_unit(true).format(0);
display_bytes.retain(|c| c != ' ');
display_bytes
}

/// Creates a module with system memory usage information
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
const DEFAULT_THRESHOLD: i64 = 75;
const DEFAULT_SHOW_PERCENTAGE: bool = false;
const RAM_CHAR: &str = "🐏 ";

let mut module = context.new_module("memory_usage");
let config = MemoryConfig::try_load(module.config);

// TODO: Update when v1.0 printing refactor is implemented to only
// print escapes in a prompt context.
let shell = std::env::var("STARSHIP_SHELL").unwrap_or_default();
let percent_sign = match shell.as_str() {
"zsh" => "%%", // % is an escape in zsh, see PROMPT in `man zshmisc`
"powershell" => "`%",
_ => "%",
};

if module.config_value_bool("disabled").unwrap_or(true) {
if config.disabled {
return None;
}

let module_style = module
.config_value_style("style")
.unwrap_or_else(|| Color::White.bold().dimmed());
module.set_style(config.style);

let system = sysinfo::System::new_with_specifics(RefreshKind::new().with_system());

let used_memory_kib = system.get_used_memory();
let total_memory_kib = system.get_total_memory();
let used_swap_kib = system.get_used_swap();
let total_swap_kib = system.get_total_swap();

let percent_mem_used = (used_memory_kib as f64 / total_memory_kib as f64) * 100.;
let percent_swap_used = (used_swap_kib as f64 / total_swap_kib as f64) * 100.;

let threshold = module
.config_value_i64("threshold")
.unwrap_or(DEFAULT_THRESHOLD);
let threshold = config.threshold;

if percent_mem_used.round() < threshold as f64 {
return None;
}

let show_percentage = module
.config_value_bool("show_percentage")
.unwrap_or(DEFAULT_SHOW_PERCENTAGE);
let show_percentage = config.show_percentage;

let (display_mem, display_swap) = if show_percentage {
(
format!("{:.0}%", percent_mem_used),
format!("{:.0}%", percent_swap_used),
)
let mut display = if show_percentage {
format!("{:.0}{}", percent_mem_used, percent_sign)
} else {
fn format_kib(n_kib: u64) -> String {
let byte = Byte::from_unit(n_kib as f64, ByteUnit::KiB)
.unwrap_or_else(|_| Byte::from_bytes(0));
let mut display_bytes = byte.get_appropriate_unit(true).format(0);
display_bytes.retain(|c| c != ' ');
display_bytes
}
(
format!(
"{}/{}",
format_kib(used_memory_kib),
format_kib(total_memory_kib)
),
format!(
"{}/{}",
format_kib(used_swap_kib),
format_kib(total_swap_kib)
),
format!(
"{}/{}",
format_kib(used_memory_kib),
format_kib(total_memory_kib)
)
};

let show_swap = module
.config_value_bool("show_swap")
.unwrap_or(total_swap_kib != 0);

module.new_segment("symbol", RAM_CHAR);

module.set_style(module_style);
if show_swap {
module.new_segment(
"memory_usage",
&format!("{} | {}", display_mem, display_swap),
// swap only shown if enabled and there is swap on the system
let total_swap_kib = system.get_total_swap();
if config.show_swap && total_swap_kib > 0 {
let used_swap_kib = system.get_used_swap();
let percent_swap_used = (used_swap_kib as f64 / total_swap_kib as f64) * 100.;

display = format!(
"{} | {}",
display,
if show_percentage {
format!("{:.0}{}", percent_swap_used, percent_sign)
} else {
format!(
"{}/{}",
format_kib(used_swap_kib),
format_kib(total_swap_kib)
)
}
);
} else {
module.new_segment("memory_usage", &display_mem);
}

module.create_segment("symbol", &config.symbol);
module.create_segment("memory_usage", &config.display.with_value(&display));

module.get_prefix().set_value("");

Some(module)
Expand Down

0 comments on commit 86bb923

Please sign in to comment.