added caching to ShellBlock so it only re-executes the shell command when the interval has elapsed, returning the cached output otherwise
Browse files
+29 −5 src/bar/blocks/shell.rs
| @@ -1,13 +1,15 @@ | ||
| 1 | 1 | use super::Block; |
| 2 | 2 | use crate::errors::BlockError; |
| 3 | 3 | use std::process::Command; |
| 4 | -use std::time::Duration; | |
| 4 | +use std::time::{Duration, Instant}; | |
| 5 | 5 | |
| 6 | 6 | pub struct ShellBlock { |
| 7 | 7 | format: String, |
| 8 | 8 | command: String, |
| 9 | 9 | interval: Duration, |
| 10 | 10 | color: u32, |
| 11 | + cached_output: Option<String>, | |
| 12 | + last_run: Option<Instant>, | |
| 11 | 13 | } |
| 12 | 14 | |
| 13 | 15 | impl ShellBlock { |
| @@ -17,12 +19,12 @@ impl ShellBlock { | ||
| 17 | 19 | command: command.to_string(), |
| 18 | 20 | interval: Duration::from_secs(interval_secs), |
| 19 | 21 | color, |
| 22 | + cached_output: None, | |
| 23 | + last_run: None, | |
| 20 | 24 | } |
| 21 | 25 | } |
| 22 | -} | |
| 23 | 26 | |
| 24 | -impl Block for ShellBlock { | |
| 25 | - fn content(&mut self) -> Result<String, BlockError> { | |
| 27 | + fn execute(&mut self) -> Result<String, BlockError> { | |
| 26 | 28 | let output = Command::new("sh") |
| 27 | 29 | .arg("-c") |
| 28 | 30 | .arg(&self.command) |
| @@ -37,7 +39,29 @@ impl Block for ShellBlock { | ||
| 37 | 39 | } |
| 38 | 40 | |
| 39 | 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 | 67 | fn interval(&self) -> Duration { |