battered 0.6.1

Regularly polls battery levels and sends notifications on crossing certain thresholds.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
mod config;
mod template;

#[macro_use]
extern crate log;
extern crate starship_battery;
use anyhow::{Context, Result};
use config::{xdg_config_home, Action, Config};
use notify_rust::{Notification, Urgency};
use starship_battery::State;
use template::{FormatObject, Template};

use std::path::PathBuf;
use std::process::Command;
use std::thread;

trait CommandRunner {
    fn run(&mut self) -> Result<()>;
    fn below_threshold(&self, value: f32) -> bool;
}

impl CommandRunner for Action {
    fn run(&mut self) -> Result<()> {
        let command = self.command.as_ref();
        match command {
            Some(cmd) => {
                let status = Command::new(&cmd[0])
                    .args(&cmd[1..])
                    .status()
                    .with_context(|| format!("Failed to execute '{}'", cmd.join(" ")))?;
                if !status.success() {
                    return Err(anyhow::anyhow!("Command failed: {}", status));
                }
                Ok(())
            }
            _ => Ok(()),
        }
    }
    fn below_threshold(&self, value: f32) -> bool {
        value < self.percentage
    }
}

trait DesktopNotification {
    fn show(&mut self, format_obj: &FormatObject);
    fn has_notify(&self) -> bool;
    fn fill_template<T: Template>(&self, input_string: String, format_obj: &T) -> String;
}

impl DesktopNotification for Action {
    fn show(&mut self, format_obj: &FormatObject) {
        if let Some(n) = &self.notify {
            let templated_summary = &self.fill_template(n.summary.clone(), format_obj);
            let mut body = n.body.clone().unwrap_or(String::from(""));
            body = self.fill_template(body, format_obj);
            Notification::new()
                .summary(templated_summary)
                .body(body.as_str())
                .icon(n.icon.as_str())
                .urgency(n.urgency)
                .timeout(n.timeout)
                .show()
                .ok();
        }
    }

    fn has_notify(&self) -> bool {
        self.notify.is_some()
    }

    fn fill_template<T: Template>(&self, input_string: String, format_obj: &T) -> String {
        let mut result = input_string;
        let format_string = format_obj.to_template();

        // Replace template vars with templated values from FormatObject
        for line in format_string.lines() {
            let parts: Vec<&str> = line.split(": ").collect();
            if parts.len() == 2 {
                let placeholder = format!("${}", parts[0]);
                result = result.replace(&placeholder, parts[1]);
            }
        }
        result
    }
}

fn main() -> Result<()> {
    env_logger::init();

    // Config
    let config_path = xdg_config_home().join("battered/config.toml");
    let config = get_config(&config_path).with_context(|| "Failed to read config")?;
    let mut actions = config.action;
    actions.sort_by(|a, b| {
        a.percentage
            .partial_cmp(&b.percentage)
            .expect("Failed to sort actions by percentage")
    }); // Sort by percentage

    // Set up battery
    let manager = starship_battery::Manager::new()?;
    let mut first_battery = manager
        .batteries()?
        .next()
        .with_context(|| "Failed to access battery information")??;

    // Check and act on battery levels
    let mut last_action_index: usize = usize::MAX;
    loop {
        manager.refresh(&mut first_battery)?;
        let charge_value = first_battery.state_of_charge().value;
        let state = first_battery.state();
        info!("Charge: {:.2}", charge_value);
        info!("State:  {}", state);

        if state == State::Charging {
            last_action_index = usize::MAX; // Reset state
            thread::sleep(config.interval);
            continue; // If the battery is charging there is nothing to do
        }
        match_actions(&mut actions, charge_value, &mut last_action_index)
            .with_context(|| "Failed")?;
        thread::sleep(config.interval);
    }
}

fn match_actions<T: CommandRunner + DesktopNotification>(
    actions: &mut [T],
    charge_value: f32,
    last_action_index: &mut usize,
) -> Result<(), anyhow::Error> {
    for (i, action) in (actions).iter_mut().enumerate() {
        if action.below_threshold(charge_value) {
            if i == *last_action_index {
                break; // Action was already taken last iteration, nothing else to do
            }
            *last_action_index = i;
            let percentage = (charge_value * 100.0).floor();
            let format_obj = FormatObject {
                percentage: &percentage,
            };
            match trigger_action(action, &format_obj) {
                Ok(_) => (),
                Err(e) => {
                    // Show notification about failed action
                    Notification::new()
                        .summary("Battered action failed")
                        .body(e.to_string().as_str())
                        .urgency(Urgency::Critical)
                        .show()
                        .ok();
                    return Err(e);
                }
            };
            break;
        };
    }
    Ok(())
}

fn trigger_action<A: CommandRunner + DesktopNotification>(
    action: &mut A,
    format_obj: &FormatObject,
) -> Result<()> {
    if action.has_notify() {
        action.show(format_obj); // Show notification
    }
    action.run() // Run command
}

fn get_config(config_path: &PathBuf) -> Result<Config, anyhow::Error> {
    let config_values = match std::fs::read_to_string(config_path) {
        Ok(config_values) => config_values,
        Err(e) => {
            if e.kind() == std::io::ErrorKind::NotFound {
                warn!(
                    "Config file not found at '{}'; falling back to defaults",
                    config_path.display()
                );
                String::new()
            } else {
                return Err(anyhow::Error::from(e));
            }
        }
    };
    let config: Config = toml::from_str(&config_values)
        .with_context(|| format!("Failed to parse config at '{}'", config_path.display()))?;
    Ok(config)
}

#[cfg(test)]
mod tests {
    use super::*;
    use config::Notify;
    use notify_rust::Timeout;

    #[derive(Copy, Clone)]
    struct MockNotify {}

    #[derive(Copy, Clone)]
    struct MockAction {
        show_call_count: usize,
        run_call_count: usize,
        notify: Option<MockNotify>,
        percentage: f32,
    }

    impl DesktopNotification for MockAction {
        fn show(&mut self, _format_obj: &FormatObject) {
            self.show_call_count += 1;
        }
        fn has_notify(&self) -> bool {
            self.notify.is_some()
        }
        fn fill_template<T: Template>(&self, _input_string: String, _format_obj: &T) -> String {
            String::from("")
        }
    }

    impl CommandRunner for MockAction {
        fn run(&mut self) -> Result<()> {
            self.run_call_count += 1;
            Ok(())
        }
        fn below_threshold(&self, value: f32) -> bool {
            value < self.percentage
        }
    }

    #[test]
    fn test_has_notify() {
        let action_w_notify = Action {
            percentage: 0.5,
            command: None,
            notify: Some(Notify {
                summary: String::from(""),
                body: None,
                urgency: Urgency::Low,
                icon: String::from(""),
                timeout: Timeout::Default,
            }),
        };
        let has_notify = action_w_notify.has_notify();
        assert_eq!(has_notify, true);
    }

    #[test]
    fn test_has_no_notify() {
        let action_w_notify = Action {
            percentage: 0.5,
            command: None,
            notify: None,
        };
        let has_notify = action_w_notify.has_notify();
        assert_eq!(has_notify, false);
    }

    #[test]
    fn test_handle_threshold_without_notification() {
        let mut action = MockAction {
            show_call_count: 0,
            run_call_count: 0,
            percentage: 0.5,
            notify: None,
        };
        let format_obj = FormatObject { percentage: &50.0 };
        let result = trigger_action(&mut action, &format_obj);
        assert!(result.is_ok());
        assert_eq!(action.show_call_count, 0);
        assert_eq!(action.run_call_count, 1);
    }

    #[test]
    fn test_handle_threshold_with_notification() {
        let mock_notify = MockNotify {};
        let mut action = MockAction {
            run_call_count: 0,
            show_call_count: 0,
            percentage: 0.5,
            notify: Some(mock_notify),
        };

        let format_obj = FormatObject { percentage: &50.0 };
        let result = trigger_action(&mut action, &format_obj);
        assert!(result.is_ok());
        assert_eq!(action.show_call_count, 1);
        assert_eq!(action.run_call_count, 1);
    }

    #[test]
    fn test_threshold_below_threshold_fn() {
        let action = Action {
            percentage: 0.5,
            command: None,
            notify: None,
        };
        let charge_value_below = 0.3; // Value below percentage threshold
        let charge_value_above = 0.8; // Value below percentage threshold

        let below_result = action.below_threshold(charge_value_below);
        assert_eq!(below_result, true);

        let above_result = action.below_threshold(charge_value_above);
        assert_eq!(above_result, false);
    }

    #[test]
    fn test_threshold_action_above_threshold() {
        let mock_notify = MockNotify {};
        let action = MockAction {
            run_call_count: 0,
            show_call_count: 0,
            percentage: 0.5,
            notify: Some(mock_notify),
        };
        let charge_value = 0.7; // Value above percentage threshold

        let mut actions = vec![action];
        let mut last_action_index: usize = 0;
        let result = match_actions(&mut actions, charge_value, &mut last_action_index);
        assert!(result.is_ok());
        assert_eq!(action.show_call_count, 0);
        assert_eq!(action.run_call_count, 0);
    }

    #[test]
    fn test_threshold_action_below_threshold() {
        let action = MockAction {
            run_call_count: 0,
            show_call_count: 0,
            percentage: 0.5,
            notify: None,
        };
        let charge_value = 0.3; // Value below percentage threshold

        let mut actions = vec![action]; // Creates a copy
        let mut last_action_index = usize::MAX;
        let result = match_actions(&mut actions, charge_value, &mut last_action_index);

        let result_action = actions[0];
        assert!(result.is_ok());
        assert_eq!(result_action.run_call_count, 1);
    }

    #[test]
    fn test_template_replaces_percentage() {
        let summary = String::from("Percentage is $percentage%!");
        let body = String::from("$percentage is also in the body");
        let action_w_notify = Action {
            percentage: 0.5,
            command: None,
            notify: Some(Notify {
                summary: summary.clone(),
                body: Some(body.clone()),
                urgency: Urgency::Low,
                icon: String::from(""),
                timeout: Timeout::Default,
            }),
        };
        let format_obj = FormatObject { percentage: &42.0 };
        let summary_result = action_w_notify.fill_template(summary, &format_obj);
        assert_eq!(summary_result, "Percentage is 42%!");
        let body_result = action_w_notify.fill_template(body, &format_obj);
        assert_eq!(body_result, "42 is also in the body");
    }

    #[test]
    fn test_template_replaces_nothing() {
        let summary = String::from("No percentage to replace here!");
        let action_w_notify = Action {
            percentage: 0.5,
            command: None,
            notify: Some(Notify {
                summary: summary.clone(),
                body: None,
                urgency: Urgency::Low,
                icon: String::from(""),
                timeout: Timeout::Default,
            }),
        };
        let format_obj = FormatObject { percentage: &42.0 };
        let result = action_w_notify.fill_template(summary, &format_obj);
        assert_eq!(result, "No percentage to replace here!");
    }

    #[test]
    fn test_template_does_not_replace_unknown() {
        let summary = String::from("No $value to replace here!");
        let action_w_notify = Action {
            percentage: 0.5,
            command: None,
            notify: Some(Notify {
                summary: summary.clone(),
                body: None,
                urgency: Urgency::Low,
                icon: String::from(""),
                timeout: Timeout::Default,
            }),
        };
        let format_obj = FormatObject { percentage: &42.0 };
        let result = action_w_notify.fill_template(summary, &format_obj);
        assert_eq!(result, "No $value to replace here!");
    }

    #[test]
    fn test_get_config_from_invalid_path() {
        let result = get_config(&PathBuf::from("/dev/null"));
        assert!(result.is_err());
        assert_eq!(
            result.unwrap_err().to_string(),
            "Failed to parse config at '/dev/null'"
        );
    }
}