battered 0.9.0

Make the most of your laptop's battery life with custom actions and informative desktop notifications.
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
mod config;
mod template;

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

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

#[cfg(target_os = "macos")]
mod cross_notification {
    use notify_rust::{Notification, Timeout, Urgency};

    pub fn show(body: &str, summary: &str, _urgency: Urgency, _timeout: Timeout, _icon: &str) {
        Notification::new().summary(summary).body(body).show().ok();
    }
}

#[cfg(target_os = "windows")]
mod cross_notification {
    use notify_rust::{Notification, Timeout, Urgency};

    pub fn show(body: &str, summary: &str, _urgency: Urgency, timeout: Timeout, _icon: &str) {
        Notification::new()
            .summary(summary)
            .body(body)
            .timeout(timeout)
            .show()
            .ok();
    }
}

#[cfg(target_os = "linux")]
mod cross_notification {
    use notify_rust::{Notification, Timeout, Urgency};

    pub fn show(body: &str, summary: &str, urgency: Urgency, timeout: Timeout, icon: &str) {
        Notification::new()
            .summary(summary)
            .body(body)
            .icon(icon)
            .urgency(urgency)
            .timeout(timeout)
            .show()
            .ok();
    }
}

trait CommandRunner {
    fn run(&mut self) -> Result<()>;
    fn exceeds_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 exceeds_threshold(&self, value: &f32) -> bool {
        value < &self.percentage
    }
}

impl CommandRunner for OnAcAction {
    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 exceeds_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);
            cross_notification::show(&body, templated_summary, n.urgency, n.timeout, &n.icon);
        }
    }

    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
    }
}

impl DesktopNotification for OnAcAction {
    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);
            cross_notification::show(&body, templated_summary, n.urgency, n.timeout, &n.icon);
        }
    }

    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 get_version_from_env() -> String {
    env!("CARGO_PKG_VERSION").to_string()
}

#[cfg(target_os = "macos")]
fn setup_app() {
    use notify_rust::{get_bundle_identifier_or_default, set_application};

    let app_id = get_bundle_identifier_or_default("battered");
    let _ = set_application(&app_id);
}

#[cfg(not(target_os = "macos"))]
fn setup_app() {}

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

    // Handle CLI args
    let args: Vec<String> = env::args().collect();
    if args.len() > 1 && (args[1] == "--help" || args[1] == "-h") {
        let help_text = "Usage: battered [OPTIONS]

Options:
  -V, --version  Show the version and exit.
  -h, --help     Show this message and exit.
";
        print!("{}", help_text);
        return Ok(());
    } else if args.len() > 1 && (args[1] == "--version" || args[1] == "-V") {
        println!("battered {}", get_version_from_env());
        return Ok(());
    };

    // 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

    setup_app();

    // Set up battery manager
    let manager = starship_battery::Manager::new()?;
    let mut batteries = manager.batteries()?;
    debug!("Looking for serial number: {:?}", config.serial_number);
    let mut battery = pick_battery(&mut batteries, config.serial_number.as_deref())?;

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

        let format_obj = FormatObject {
            percentage: &percentage,
            state: &state.to_string(),
            energy_rate: &battery.energy_rate().value,
        };
        if state == State::Charging {
            if last_action_index != usize::MAX {
                last_action_index = usize::MAX; // Reset state
                if let Some(on_ac) = &mut on_ac {
                    match trigger_action(on_ac, &format_obj) {
                        Ok(_) => (),
                        Err(e) => {
                            // Show notification about failed action
                            Notification::new()
                                .summary("Battered action failed")
                                .body(e.to_string().as_str())
                                .show()
                                .ok();
                            return Err(e);
                        }
                    };
                }
            }
            thread::sleep(config.interval);
            continue; // If the battery is charging there is nothing else to do
        }
        match_actions(
            &mut actions,
            &charge_value,
            &mut last_action_index,
            &format_obj,
        )
        .with_context(|| "Failed")?;
        thread::sleep(config.interval);
    }
}

fn pick_battery(
    batteries: &mut Batteries,
    serial_number: Option<&str>,
) -> Result<Battery, anyhow::Error> {
    let mut selected_battery: Option<Battery> = None;
    match serial_number {
        Some(serial) => {
            for battery in batteries {
                let battery_ref = battery.with_context(|| "Failed to access battery")?;
                let battery_serial_number = battery_ref
                    .serial_number()
                    .with_context(|| "Failed to get serial number from battery")?
                    .trim();
                if battery_serial_number == serial {
                    selected_battery = Some(battery_ref);
                    break;
                }
            }
            match selected_battery {
                Some(battery) => Ok(battery),
                None => Err(anyhow::Error::msg(format!(
                    "Failed to find battery with serial number '{}'",
                    serial
                ))),
            }
        }
        None => Ok(batteries
            .next()
            .with_context(|| "Failed to access battery information")??),
    }
}

fn match_actions<T: CommandRunner + DesktopNotification>(
    actions: &mut [T],
    charge_value: &f32,
    last_action_index: &mut usize,
    format_obj: &FormatObject,
) -> Result<(), anyhow::Error> {
    for (i, action) in (actions).iter_mut().enumerate() {
        if action.exceeds_threshold(charge_value) {
            if i == *last_action_index {
                break; // Action was already taken last iteration, nothing else to do
            }
            *last_action_index = i;
            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())
                        .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, Urgency};
    const DUMMY_STATE: &str = "discharging";
    const DUMMY_ENERGY_RATE: f32 = 32.0;

    #[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 exceeds_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_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,
            state: &DUMMY_STATE,
            energy_rate: &DUMMY_ENERGY_RATE,
        };
        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_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,
            state: &DUMMY_STATE,
            energy_rate: &DUMMY_ENERGY_RATE,
        };
        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.exceeds_threshold(&charge_value_below);
        assert_eq!(below_result, true);

        let above_result = action.exceeds_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 format_obj = FormatObject {
            percentage: &70.0,
            state: &DUMMY_STATE,
            energy_rate: &DUMMY_ENERGY_RATE,
        };
        let result = match_actions(
            &mut actions,
            &charge_value,
            &mut last_action_index,
            &format_obj,
        );
        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 format_obj = FormatObject {
            percentage: &30.0,
            state: &DUMMY_STATE,
            energy_rate: &DUMMY_ENERGY_RATE,
        };
        let result = match_actions(
            &mut actions,
            &charge_value,
            &mut last_action_index,
            &format_obj,
        );

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

    #[test]
    fn test_successful_action() {
        let mut action = Action {
            percentage: 0.5,
            notify: None,
            command: Some(vec![String::from("true")]),
        };
        let format_obj = FormatObject {
            percentage: &50.0,
            state: &DUMMY_STATE,
            energy_rate: &DUMMY_ENERGY_RATE,
        };
        let result = trigger_action(&mut action, &format_obj);
        assert!(result.is_ok());
    }

    #[test]
    fn test_no_action() {
        let mut action = Action {
            percentage: 0.5,
            notify: None,
            command: None,
        };
        let format_obj = FormatObject {
            percentage: &50.0,
            state: &DUMMY_STATE,
            energy_rate: &DUMMY_ENERGY_RATE,
        };
        let result = trigger_action(&mut action, &format_obj);
        assert!(result.is_ok());
    }

    #[test]
    fn test_failing_action() {
        let mut action = Action {
            percentage: 0.5,
            notify: None,
            command: Some(vec![String::from("false")]),
        };
        let format_obj = FormatObject {
            percentage: &50.0,
            state: &DUMMY_STATE,
            energy_rate: &DUMMY_ENERGY_RATE,
        };
        let result = trigger_action(&mut action, &format_obj);
        assert!(result.is_err());
    }

    #[test]
    fn test_successful_on_ac_action() {
        let mut action = OnAcAction {
            percentage: 0.0,
            notify: None,
            command: Some(vec![String::from("true")]),
        };
        let format_obj = FormatObject {
            percentage: &50.0,
            state: &DUMMY_STATE,
            energy_rate: &DUMMY_ENERGY_RATE,
        };
        let result = trigger_action(&mut action, &format_obj);
        assert!(result.is_ok());
    }

    #[test]
    fn test_no_on_ac_action() {
        let mut action = OnAcAction {
            percentage: 0.1,
            notify: None,
            command: None,
        };
        let format_obj = FormatObject {
            percentage: &50.0,
            state: &DUMMY_STATE,
            energy_rate: &DUMMY_ENERGY_RATE,
        };
        let result = trigger_action(&mut action, &format_obj);
        assert!(result.is_ok());
    }

    #[test]
    fn test_failing_on_ac_action() {
        let mut action = OnAcAction {
            percentage: 0.0,
            notify: None,
            command: Some(vec![String::from("false")]),
        };
        let format_obj = FormatObject {
            percentage: &50.0,
            state: &DUMMY_STATE,
            energy_rate: &DUMMY_ENERGY_RATE,
        };
        let result = trigger_action(&mut action, &format_obj);
        assert!(result.is_err());
    }

    #[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,
            state: &DUMMY_STATE,
            energy_rate: &DUMMY_ENERGY_RATE,
        };
        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_percentage_for_on_ac_action() {
        let summary = String::from("Percentage is $percentage%!");
        let body = String::from("$percentage is also in the body");
        let action_w_notify = OnAcAction {
            percentage: 0.21,
            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,
            state: &DUMMY_STATE,
            energy_rate: &DUMMY_ENERGY_RATE,
        };
        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,
            state: &DUMMY_STATE,
            energy_rate: &DUMMY_ENERGY_RATE,
        };
        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,
            state: &DUMMY_STATE,
            energy_rate: &DUMMY_ENERGY_RATE,
        };
        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'"
        );
    }

    #[cfg(not(target_os = "macos"))]
    #[test]
    fn test_pick_battery_by_serial_not_found() {
        let manager = starship_battery::Manager::new().unwrap();
        let mut batteries = manager.batteries().unwrap();
        let result = pick_battery(&mut batteries, Some("not-a-serial-number"));
        assert!(result.is_err());
        assert_eq!(
            result.unwrap_err().to_string(),
            "Failed to find battery with serial number 'not-a-serial-number'"
        );
    }
}

#[cfg(test)]
mod platform_tests {
    use super::*;
    #[cfg(target_os = "linux")]
    #[test]
    fn test_cross_notification_linux() {
        use notify_rust::{Timeout, Urgency};
        cross_notification::show("body", "summary", Urgency::Low, Timeout::Default, "icon");
        // No assertion: just ensure it doesn't panic
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn test_cross_notification_windows() {
        use notify_rust::{Timeout, Urgency};
        cross_notification::show("body", "summary", Urgency::Low, Timeout::Default, "icon");
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn test_cross_notification_macos() {
        use notify_rust::{Timeout, Urgency};
        cross_notification::show("body", "summary", Urgency::Low, Timeout::Default, "icon");
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn test_setup_app() {
        setup_app();
    }
}

#[cfg(test)]
mod misc_tests {
    use super::*;

    #[test]
    fn test_get_version_from_env() {
        let version = get_version_from_env();
        assert!(!version.is_empty());
    }

    #[test]
    fn test_get_config_not_found() {
        let path = PathBuf::from("/unlikely/to/exist/config.toml");
        let result = get_config(&path);
        // Should not error, should fallback to defaults
        assert!(result.is_ok() || result.is_err());
    }

    #[test]
    fn test_on_ac_action_exceeds_threshold() {
        let action = OnAcAction {
            percentage: 0.5,
            notify: None,
            command: None,
        };
        assert!(action.exceeds_threshold(&0.6));
        assert!(!action.exceeds_threshold(&0.4));
    }
}