tony / oxwm

added caching to ShellBlock so it only re-executes the shell command when the interval has elapsed, returning the cached output otherwise Browse files
tonybtw committed 2025-12-23 parent 165e841 commit 84f46f68c001f5c657730e45827b5264801572fc
Showing 1 changed file with 29 additions and 5 deletions. UnifiedSplit
+29 −5 src/bar/blocks/shell.rs
@@ -1,13 +1,15 @@
1 use super::Block; 1 use super::Block;
2 use crate::errors::BlockError; 2 use crate::errors::BlockError;
3 use std::process::Command; 3 use std::process::Command;
4 -use std::time::Duration; 4 +use std::time::{Duration, Instant};
5 5
6 pub struct ShellBlock { 6 pub struct ShellBlock {
7 format: String, 7 format: String,
8 command: String, 8 command: String,
9 interval: Duration, 9 interval: Duration,
10 color: u32, 10 color: u32,
11 + cached_output: Option<String>,
12 + last_run: Option<Instant>,
11 } 13 }
12 14
13 impl ShellBlock { 15 impl ShellBlock {
@@ -17,12 +19,12 @@ impl ShellBlock {
17 command: command.to_string(), 19 command: command.to_string(),
18 interval: Duration::from_secs(interval_secs), 20 interval: Duration::from_secs(interval_secs),
19 color, 21 color,
22 + cached_output: None,
23 + last_run: None,
20 } 24 }
21 } 25 }
22 -}
23 26
24 -impl Block for ShellBlock { 27 + fn execute(&mut self) -> Result<String, BlockError> {
25 - fn content(&mut self) -> Result<String, BlockError> {
26 let output = Command::new("sh") 28 let output = Command::new("sh")
27 .arg("-c") 29 .arg("-c")
28 .arg(&self.command) 30 .arg(&self.command)
@@ -37,7 +39,29 @@ impl Block for ShellBlock {
37 } 39 }
38 40
39 let result = String::from_utf8_lossy(&output.stdout).trim().to_string(); 41 let result = String::from_utf8_lossy(&output.stdout).trim().to_string();
40 - Ok(self.format.replace("{}", &result)) 42 + let formatted = self.format.replace("{}", &result);
43 +
44 + self.cached_output = Some(formatted.clone());
45 + self.last_run = Some(Instant::now());
46 +
47 + Ok(formatted)
48 + }
49 +}
50 +
51 +impl Block for ShellBlock {
52 + fn content(&mut self) -> Result<String, BlockError> {
53 + let should_refresh = match self.last_run {
54 + None => true,
55 + Some(last) => last.elapsed() >= self.interval,
56 + };
57 +
58 + if should_refresh {
59 + return self.execute();
60 + }
61 +
62 + self.cached_output
63 + .clone()
64 + .ok_or_else(|| BlockError::CommandFailed("No cached output".to_string()))
41 } 65 }
42 66
43 fn interval(&self) -> Duration { 67 fn interval(&self) -> Duration {