service_install/install/init/cron/
teardown.rs

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
use std::iter;
use std::path::PathBuf;
use std::str::FromStr;

use itertools::Itertools;

use crate::install::init::extract_path;
use crate::install::init::{autogenerated_comment, ExeLocation, RSteps, TearDownError};
use crate::install::{Mode, Tense};
use crate::install::{RemoveError, RemoveStep};

use super::Line;
use super::{current_crontab, set_crontab, GetCrontabError};

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("Could not get the current crontab")]
    GetCrontab(#[from] #[source] GetCrontabError),
    #[error("Comment for previous install at the end of the crontab")]
    CrontabCorrupt,
    #[error(transparent)]
    CrontabChanged(#[from] CrontabChanged),
    #[error("Rule in crontab corrupt, too short")]
    CorruptTooShort,
}

pub(crate) fn path_from_rule(rule: &str) -> PathBuf {
    let command = if let Some(command) = rule.strip_prefix("@reboot") {
        command.to_string()
    } else {
        rule.splitn(5 + 1, char::is_whitespace).skip(5).collect()
    };
    let command = match command.split_once("&&") {
        Some((_cd, command)) => command.to_string(),
        None => command,
    };

    let command = command.trim_start();
    let command = extract_path::split_unescaped_whitespace_once(command);

    PathBuf::from_str(&command).expect("infallible")
}

#[cfg(test)]
mod test {
    use std::path::Path;

    use super::*;

    #[test]
    fn test_from_rule() {
        let case = "10 10 * * *  '/home/david/.local/hi bin/cron_only'";
        assert_eq!(
            &path_from_rule(case),
            Path::new("/home/david/.local/hi bin/cron_only")
        )
    }
}

pub(crate) fn tear_down_steps(
    bin_name: &str,
    mode: Mode,
    user: Option<&str>,
) -> Result<Option<(RSteps, ExeLocation)>, TearDownError> {
    assert!(
        !(mode.is_user() && user.is_some()),
        "need to run as system to set a different users crontab"
    );

    let current = current_crontab(user).map_err(Error::GetCrontab)?;
    let landmark_comment = autogenerated_comment(bin_name);

    let to_remove = current
        .windows(landmark_comment.lines().count() + 1)
        .map(|w| w.split_last().expect("window size always >= 2"))
        .find(|(_, comments)| comments.iter().map(Line::text).eq(landmark_comment.lines()));

    let Some((rule, comment)) = to_remove else {
        return Ok(None);
    };

    let install_path = path_from_rule(&rule.text);
    let step = Box::new(RemoveInstalled {
        comments: comment.to_vec(),
        rule: rule.clone(),
        user: user.map(str::to_owned),
    }) as Box<dyn RemoveStep>;
    Ok(Some((vec![step], install_path)))
}

struct RemoveInstalled {
    user: Option<String>,
    comments: Vec<Line>,
    rule: Line,
}

impl RemoveStep for RemoveInstalled {
    fn describe(&self, tense: Tense) -> String {
        let verb = match tense {
            Tense::Past => "Removed",
            Tense::Questioning => "Remove",
            Tense::Future => "Will remove",
            Tense::Active => "Removing",
        };
        let user = self
            .user
            .as_ref()
            .map(|n| format!("{n}'s "))
            .unwrap_or_default();
        format!("{verb} the installs comment and rule from {user}crontab")
    }

    fn describe_detailed(&self, tense: Tense) -> String {
        let verb = match tense {
            Tense::Past => "Removed",
            Tense::Questioning => "Remove",
            Tense::Future => "Will remove",
            Tense::Active => "Removing",
        };
        let user = self
            .user
            .as_ref()
            .map(|n| format!("{n}'s "))
            .unwrap_or_default();
        #[allow(clippy::format_collect)]
        let comment: String = self
            .comments
            .iter()
            .map(|Line { pos, text }| format!("\n|\t{pos}: {text}"))
            .collect();
        let rule = format!("|\t{}: {}", self.rule.pos, self.rule.text);
        format!("{verb} the installs comment and rule from {user}crontab:\n| comment:{comment}\n| rule:\n{rule}")
    }

    fn perform(&mut self) -> Result<(), RemoveError> {
        let Self {
            comments,
            rule,
            user,
        } = self;
        let current_crontab = current_crontab(user.as_deref())?;
        let new_lines = filter_out(&current_crontab, rule, comments)?;

        let new_crontab: String = new_lines
            .into_iter()
            .interleave_shortest(iter::once("\n").cycle())
            .collect();
        set_crontab(&new_crontab, user.as_deref())?;

        Ok(())
    }
}

#[derive(Debug, thiserror::Error)]
#[error(
    "Crontab was modified between preparation and running this step, you should manually verify it"
)]
pub struct CrontabChanged;

pub(super) fn filter_out<'a>(
    current_crontab: &'a [Line],
    rule: &Line,
    comments: &[Line],
) -> Result<Vec<&'a str>, CrontabChanged> {
    // someone could store the steps and execute later, if
    // anything changed refuse to remove lines and abort
    let mut output = Vec::new();
    let mut to_remove = comments.iter().chain(iter::once(rule)).fuse();
    let mut next_to_remove = to_remove.next();
    for line in current_crontab {
        if let Some(next) = next_to_remove {
            if line.pos != next.pos {
                continue;
            }

            if line.text != next.text {
                return Err(CrontabChanged);
            }

            next_to_remove = to_remove.next();
            continue;
        }
        output.push(line.text.as_str());
    }

    Ok(output)
}