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
use std::env;
use std::ffi::OsString;
use std::fs;
use std::os::unix::fs::symlink;
use std::path::Path;
use std::process::Command;
use std::time::Duration;

use crossbeam_channel::Sender;
use regex::Regex;
use serde_derive::Deserialize;

use crate::blocks::{Block, ConfigBlock, Update};
use crate::config::SharedConfig;
use crate::de::deserialize_duration;
use crate::errors::*;
use crate::formatting::value::Value;
use crate::formatting::FormatTemplate;
use crate::input::{I3BarEvent, MouseButton};
use crate::scheduler::Task;
use crate::util::has_command;
use crate::widgets::text::TextWidget;
use crate::widgets::{I3BarWidget, State};

pub struct Pacman {
    id: usize,
    output: TextWidget,
    update_interval: Duration,
    format: FormatTemplate,
    format_singular: FormatTemplate,
    format_up_to_date: FormatTemplate,
    warning_updates_regex: Option<Regex>,
    critical_updates_regex: Option<Regex>,
    watched: Watched,
    uptodate: bool,
    hide_when_uptodate: bool,
}

#[derive(Debug, PartialEq, Eq)]
pub enum Watched {
    None,
    Pacman,
    /// cf `Pacman::aur_command`
    AUR(String),
    /// cf `Pacman::aur_command`
    Both(String),
}

#[derive(Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields, default)]
pub struct PacmanConfig {
    /// Update interval in seconds
    #[serde(deserialize_with = "deserialize_duration")]
    pub interval: Duration,

    /// Format override
    pub format: String,

    /// Alternative format override for when exactly 1 update is available
    pub format_singular: String,

    /// Alternative format override for when no updates are available
    pub format_up_to_date: String,

    /// Indicate a `warning` state for the block if any pending update match the
    /// following regex. Default behaviour is that no package updates are deemed
    /// warning
    pub warning_updates_regex: Option<String>,

    /// Indicate a `critical` state for the block if any pending update match the following regex.
    /// Default behaviour is that no package updates are deemed critical
    pub critical_updates_regex: Option<String>,

    /// Optional AUR command, listing available updates
    pub aur_command: Option<String>,

    pub hide_when_uptodate: bool,
}

impl Default for PacmanConfig {
    fn default() -> Self {
        Self {
            interval: Duration::from_secs(600),
            format: "{pacman}".to_string(),
            format_singular: "{pacman}".to_string(),
            format_up_to_date: "{pacman}".to_string(),
            warning_updates_regex: None,
            critical_updates_regex: None,
            aur_command: None,
            hide_when_uptodate: false,
        }
    }
}

impl PacmanConfig {
    fn watched(
        format: &str,
        format_singular: &str,
        format_up_to_date: &str,
        aur_command: Option<String>,
    ) -> Result<Watched> {
        let aur_format = "{aur";
        let pacman_format = "{pacman";
        let both_format = "{both";
        let pacman_deprecated_format = "{count";
        let concatenated_format_str = format!("{}{}{}", format, format_singular, format_up_to_date);
        let aur = concatenated_format_str.contains(aur_format);
        let pacman = concatenated_format_str.contains(pacman_format)
            || concatenated_format_str.contains(pacman_deprecated_format);
        let both = concatenated_format_str.contains(both_format);
        if both || (pacman && aur) {
            let aur_command = aur_command.block_error(
                "pacman",
                "{aur} or {both} found in format string but no aur_command supplied",
            )?;
            Ok(Watched::Both(aur_command))
        } else if pacman && !aur {
            Ok(Watched::Pacman)
        } else if !pacman && aur {
            let aur_command = aur_command.block_error(
                "pacman",
                "{aur} found in format string but no aur_command supplied",
            )?;
            Ok(Watched::AUR(aur_command))
        } else {
            Ok(Watched::None)
        }
    }
}

impl ConfigBlock for Pacman {
    type Config = PacmanConfig;

    fn new(
        id: usize,
        block_config: Self::Config,
        shared_config: SharedConfig,
        _tx_update_request: Sender<Task>,
    ) -> Result<Self> {
        let output = TextWidget::new(id, 0, shared_config).with_icon("update")?;

        Ok(Pacman {
            id,
            update_interval: block_config.interval,
            format: FormatTemplate::from_string(&block_config.format)
                .block_error("pacman", "Invalid format specified for pacman::format")?,
            format_singular: FormatTemplate::from_string(&block_config.format_singular)
                .block_error(
                    "pacman",
                    "Invalid format specified for pacman::format_singular",
                )?,
            format_up_to_date: FormatTemplate::from_string(&block_config.format_up_to_date)
                .block_error(
                    "pacman",
                    "Invalid format specified for pacman::format_up_to_date",
                )?,
            output,
            warning_updates_regex: match block_config.warning_updates_regex {
                None => None, // no regex configured
                Some(regex_str) => {
                    let regex = Regex::new(regex_str.as_ref()).map_err(|_| {
                        ConfigurationError(
                            "pacman".to_string(),
                            "invalid warning updates regex".to_string(),
                        )
                    })?;
                    Some(regex)
                }
            },
            critical_updates_regex: match block_config.critical_updates_regex {
                None => None, // no regex configured
                Some(regex_str) => {
                    let regex = Regex::new(regex_str.as_ref()).map_err(|_| {
                        ConfigurationError(
                            "pacman".to_string(),
                            "invalid critical updates regex".to_string(),
                        )
                    })?;
                    Some(regex)
                }
            },
            watched: PacmanConfig::watched(
                &block_config.format,
                &block_config.format_singular,
                &block_config.format_up_to_date,
                block_config.aur_command,
            )?,
            uptodate: false,
            hide_when_uptodate: block_config.hide_when_uptodate,
        })
    }
}

fn run_command(var: &str) -> Result<()> {
    Command::new("sh")
        .args(&["-c", var])
        .spawn()
        .block_error("pacman", &format!("Failed to run command '{}'", var))?
        .wait()
        .block_error("pacman", &format!("Failed to wait for command '{}'", var))
        .map(|_| ())
}

fn has_fake_root() -> Result<bool> {
    has_command("pacman", "fakeroot")
}

fn check_fakeroot_command_exists() -> Result<()> {
    if !has_fake_root()? {
        Err(BlockError(
            "pacman".to_string(),
            "fakeroot not found".to_string(),
        ))
    } else {
        Ok(())
    }
}

fn get_updates_db_dir() -> Result<String> {
    let tmp_dir = env::temp_dir()
        .into_os_string()
        .into_string()
        .block_error("pacman", "There's something wrong with your $TMP variable")?;
    let user = env::var_os("USER")
        .unwrap_or_else(|| OsString::from(""))
        .into_string()
        .block_error("pacman", "There's a problem with your $USER")?;
    env::var_os("CHECKUPDATES_DB")
        .unwrap_or_else(|| OsString::from(format!("{}/checkup-db-{}", tmp_dir, user)))
        .into_string()
        .block_error("pacman", "There's a problem with your $CHECKUPDATES_DB")
}

fn get_pacman_available_updates() -> Result<String> {
    let updates_db = get_updates_db_dir()?;

    // Determine pacman database path
    let db_path = env::var_os("DBPath")
        .map(Into::into)
        .unwrap_or_else(|| Path::new("/var/lib/pacman/").to_path_buf());

    // Create the determined `checkup-db` path recursively
    fs::create_dir_all(&updates_db).block_error(
        "pacman",
        &format!("Failed to create checkup-db path '{}'", updates_db),
    )?;

    // Create symlink to local cache in `checkup-db` if required
    let local_cache = Path::new(&updates_db).join("local");
    if !local_cache.exists() {
        symlink(db_path.join("local"), local_cache)
            .block_error("pacman", "Failed to created required symlink")?;
    }

    // Update database
    run_command(&format!(
        "fakeroot -- pacman -Sy --dbpath \"{}\" --logfile /dev/null &> /dev/null",
        updates_db
    ))?;

    // Get update count
    String::from_utf8(
        Command::new("sh")
            .env("LC_ALL", "C")
            .args(&[
                "-c",
                &format!("fakeroot pacman -Qu --dbpath \"{}\"", updates_db),
            ])
            .output()
            .block_error("pacman", "There was a problem running the pacman commands")?
            .stdout,
    )
    .block_error(
        "pacman",
        "There was a problem while converting the output of the pacman command to a string",
    )
}

fn get_aur_available_updates(aur_command: &str) -> Result<String> {
    String::from_utf8(
        Command::new("sh")
            .args(&["-c", aur_command])
            .output()
            .block_error("pacman", &format!("aur command: {} failed", aur_command))?
            .stdout,
    )
    .block_error(
        "pacman",
        "There was a problem while converting the aur command output to a string",
    )
}

fn get_update_count(updates: &str) -> usize {
    updates
        .lines()
        .filter(|line| !line.contains("[ignored]"))
        .count()
}

fn has_warning_update(updates: &str, regex: &Regex) -> bool {
    updates.lines().filter(|line| regex.is_match(line)).count() > 0
}

fn has_critical_update(updates: &str, regex: &Regex) -> bool {
    updates.lines().filter(|line| regex.is_match(line)).count() > 0
}

impl Block for Pacman {
    fn id(&self) -> usize {
        self.id
    }

    fn view(&self) -> Vec<&dyn I3BarWidget> {
        if self.uptodate && self.hide_when_uptodate {
            vec![]
        } else {
            vec![&self.output]
        }
    }

    fn update(&mut self) -> Result<Option<Update>> {
        let (formatting_map, warning, critical, cum_count) = match &self.watched {
            Watched::Pacman => {
                check_fakeroot_command_exists()?;
                let pacman_available_updates = get_pacman_available_updates()?;
                let pacman_count = get_update_count(&pacman_available_updates);
                let formatting_map = map!(
                    "count" => Value::from_integer(pacman_count as i64),
                    "pacman" => Value::from_integer(pacman_count as i64),
                );

                let warning = self.warning_updates_regex.as_ref().map_or(false, |regex| {
                    has_warning_update(&pacman_available_updates, regex)
                });
                let critical = self.critical_updates_regex.as_ref().map_or(false, |regex| {
                    has_critical_update(&pacman_available_updates, regex)
                });

                (formatting_map, warning, critical, pacman_count)
            }
            Watched::AUR(aur_command) => {
                let aur_available_updates = get_aur_available_updates(&aur_command)?;
                let aur_count = get_update_count(&aur_available_updates);
                let formatting_map = map!(
                    "aur" => Value::from_integer(aur_count as i64)
                );

                let warning = self.warning_updates_regex.as_ref().map_or(false, |regex| {
                    has_warning_update(&aur_available_updates, regex)
                });
                let critical = self.critical_updates_regex.as_ref().map_or(false, |regex| {
                    has_critical_update(&aur_available_updates, regex)
                });

                (formatting_map, warning, critical, aur_count)
            }
            Watched::Both(aur_command) => {
                check_fakeroot_command_exists()?;
                let pacman_available_updates = get_pacman_available_updates()?;
                let aur_available_updates = get_aur_available_updates(&aur_command)?;
                let pacman_count = get_update_count(&pacman_available_updates);
                let aur_count = get_update_count(&aur_available_updates);
                let formatting_map = map!(
                    "count" =>  Value::from_integer(pacman_count as i64),
                    "pacman" => Value::from_integer(pacman_count as i64),
                    "aur" =>    Value::from_integer(aur_count as i64),
                    "both" =>   Value::from_integer((pacman_count + aur_count) as i64),
                );

                let warning = self.warning_updates_regex.as_ref().map_or(false, |regex| {
                    has_warning_update(&aur_available_updates, regex)
                        || has_warning_update(&pacman_available_updates, regex)
                });
                let critical = self.critical_updates_regex.as_ref().map_or(false, |regex| {
                    has_critical_update(&aur_available_updates, regex)
                        || has_critical_update(&pacman_available_updates, regex)
                });

                (formatting_map, warning, critical, pacman_count + aur_count)
            }
            Watched::None => (std::collections::HashMap::new(), false, false, 0),
        };
        self.output.set_text(match cum_count {
            0 => self.format_up_to_date.render(&formatting_map)?,
            1 => self.format_singular.render(&formatting_map)?,
            _ => self.format.render(&formatting_map)?,
        });
        self.output.set_state(match cum_count {
            0 => State::Idle,
            _ => {
                if critical {
                    State::Critical
                } else if warning {
                    State::Warning
                } else {
                    State::Info
                }
            }
        });
        self.uptodate = cum_count == 0;
        Ok(Some(self.update_interval.into()))
    }

    fn click(&mut self, event: &I3BarEvent) -> Result<()> {
        if let MouseButton::Left = event.button {
            self.update()?;
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use crate::blocks::pacman::{
        get_aur_available_updates, get_update_count, PacmanConfig, Watched,
    };

    #[test]
    fn test_get_update_count() {
        let no_update = "";
        assert_eq!(get_update_count(no_update), 0);
        let two_updates_available = concat!(
            "systemd 245.4-2 -> 245.5-1\n",
            "systemd-libs 245.4-2 -> 245.5-1\n"
        );
        assert_eq!(get_update_count(two_updates_available), 2);
    }

    #[test]
    fn test_watched() {
        let watched = PacmanConfig::watched("foo {count} bar", "foo {count} bar", "", None);
        assert!(watched.is_ok());
        assert_eq!(watched.unwrap(), Watched::Pacman);
        let watched = PacmanConfig::watched("foo {pacman} bar", "foo {pacman} bar", "", None);
        assert!(watched.is_ok());
        assert_eq!(watched.unwrap(), Watched::Pacman);
        let watched = PacmanConfig::watched("foo bar", "foo bar", "", None);
        assert!(watched.is_ok()); // missing formatter should not cause an error
        let watched = PacmanConfig::watched("foo bar", "foo bar", "", Some("aur cmd".to_string()));
        assert!(watched.is_ok()); // missing formatter should not cause an error
        let watched = PacmanConfig::watched(
            "foo {aur} bar",
            "foo {aur} bar",
            "",
            Some("aur cmd".to_string()),
        );
        assert!(watched.is_ok());
        assert_eq!(watched.unwrap(), Watched::AUR("aur cmd".to_string()));
        let watched = PacmanConfig::watched(
            "foo {pacman} {aur} bar",
            "foo {pacman} {aur} bar",
            "",
            Some("aur cmd".to_string()),
        );
        assert!(watched.is_ok());
        assert_eq!(watched.unwrap(), Watched::Both("aur cmd".to_string()));
        let watched =
            PacmanConfig::watched("foo {pacman} {aur} bar", "foo {pacman} {aur} bar", "", None);
        assert!(watched.is_err()); // missing aur command
        let watched = PacmanConfig::watched("foo {both} bar", "foo {both} bar", "", None);
        assert!(watched.is_err()); // missing aur command
        let watched = PacmanConfig::watched(
            "foo {both} bar",
            "foo {both} bar",
            "",
            Some("aur cmd".to_string()),
        );
        assert!(watched.is_ok());
        assert_eq!(watched.unwrap(), Watched::Both("aur cmd".to_string()));
    }

    #[test]
    fn test_get_aur_available_updates() {
        // aur_command should behave as echo -ne "foo x.x -> y.y\n"
        let updates = "foo x.x -> y.y\nbar x.x -> y.y\n";
        let aur_command = format!("printf '{}'", updates);
        let available_updates = get_aur_available_updates(&aur_command);
        assert!(available_updates.is_ok());
        assert_eq!(available_updates.unwrap(), updates);
    }
}