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
#![warn(clippy::pedantic)]
use regex::{Regex, RegexSet, RegexSetBuilder};
use std::collections::HashMap;
use std::env::args_os;
use std::error;
use std::fmt;
use std::io::{self, Write};
use std::path::PathBuf;
use std::result;
use tempfile::NamedTempFile;

type Error = Box<dyn error::Error + Send + Sync>;
type Result<T> = result::Result<T, Error>;

macro_rules! err {
    ($($tt:tt)*) => {
        Err(Error::from(format!($($tt)*)))
    }
}

/// IGNORES should not be included in the final history unless they are in EXCEPTIONS
const IGNORES: &[&str] = &[
    // short things
    "^.{1,3}$",
    // cd / ls with relative directories
    "^cd [^~/]",
    "^ls [^~/]",
    // annoying if accidentally re-executed at a later date
    "^(sudo)? reboot",
    "^(sudo)? shutdown",
    "^(sudo)? halt",
    // mouse esc codes
    "^0",
    // commands explicitly hidden by user
    "^ ",
    // frequent typos (see .aliases)

    // Sensitive looking lines
    "(api|token|key|secret|pass)",
];

/// EXCEPTIONS should be included in the history even if they also match IGNORES
const EXCEPTIONS: &[&str] = &[
    // password retrieval to clipboard
    "^pass -c",
];

#[derive(PartialEq, Eq)]
struct HistoryCommand {
    timestamp: u32,
    command: String,
}

/// `HistoryCommand` should be sorted by timestamp then alphabetically
impl PartialOrd for HistoryCommand {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(
            self.timestamp
                .cmp(&other.timestamp)
                .then_with(|| self.command.cmp(&other.command)),
        )
    }
}

impl Ord for HistoryCommand {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.partial_cmp(other).unwrap()
    }
}

struct HistoryIterator<'a> {
    data: std::str::Lines<'a>,
    timestamp_regex: Regex,
    next_timestamp: Option<&'a str>,
}

impl<'a> From<&'a str> for HistoryIterator<'a> {
    fn from(s: &'a str) -> Self {
        Self {
            data: s.lines(),
            timestamp_regex: Regex::new(r"^#\d+$")
                .expect("You've got a bad regex there."),
            next_timestamp: None,
        }
    }
}

impl Iterator for HistoryIterator<'_> {
    type Item = Result<HistoryCommand>;
    fn next(&mut self) -> Option<Self::Item> {
        let mut command = String::new();
        let timestamp = loop {
            match self.data.next() {
                // Either new or duplicate timestamp, take the last while command is empty
                Some(line)
                    if self.timestamp_regex.is_match(line)
                        && command.is_empty() =>
                {
                    self.next_timestamp = Some(line);
                }
                // New timestamp, return a completed command
                Some(line)
                    if self.timestamp_regex.is_match(line)
                        && !command.is_empty() =>
                {
                    break self.next_timestamp.replace(line);
                }
                // Accumulate lines of command (if multiple)
                Some(line) => {
                    let trimmed_line = line.trim();
                    if !trimmed_line.is_empty() {
                        command += trimmed_line;
                        command += "; ";
                    }
                }
                // End of file
                None => {
                    break self.next_timestamp.take();
                }
            };
        };

        let timestamp: Option<Result<u32>> = timestamp.map(|v| {
            v.trim().trim_start_matches('#').parse().map_err(Into::into)
        });

        // Get rid of differences in whitespace
        let command = command
            .split_whitespace()
            .collect::<Vec<_>>()
            .join(" ")
            .trim_end_matches(';')
            .to_owned();

        match (timestamp, command) {
            (Some(Ok(timestamp)), command) if command.is_empty() => {
                Some(err!("command was empty for timestamp {}", timestamp))
            }
            (Some(Ok(timestamp)), command) => {
                Some(Ok(HistoryCommand { timestamp, command }))
            }
            (Some(Err(e)), command) => Some(err!("{}, {}", e, command)),
            (None, command) if !command.is_empty() => {
                Some(err!("missing timestamp for command: {}", command))
            }
            (None, _) => None,
        }
    }
}

/// Write the usage to stderr
/// # Errors
///
/// Returns an error if it fails to wroute to stderr.
pub fn usage() -> io::Result<()> {
    writeln!(
        io::stderr(),
        "cleanup-history :: Deduplicate bash history file\
        \n    USAGE: cleanup-history historyfile\
        "
    )
}

/// Ensure script was called with only one argument and parse the arg to path
fn parse_args<T, U>(args: &mut T) -> Result<PathBuf>
where
    T: Iterator<Item = U>,
    U: std::convert::AsRef<std::ffi::OsStr>,
{
    let _script = args.next();
    let history_file = args.next().ok_or_else(|| {
        Error::from("please supply the path to the bash_history file")
    })?;
    if args.next().is_some() {
        err!("this script only accepts one argument")?;
    }

    if let Some(s) = history_file.as_ref().to_str() {
        if ["-h", "--help"].contains(&s) {
            usage()?;
            std::process::exit(0);
        }
    }

    let path = PathBuf::from(&history_file);
    Ok(path)
}

fn is_valid(line: &str, exceptions: &RegexSet, ignores: &RegexSet) -> bool {
    if exceptions.is_match(line) {
        return true;
    } else if ignores.is_match(line) {
        return false;
    }
    true
}

struct HistoryCommands(Vec<HistoryCommand>);

impl fmt::Display for HistoryCommands {
    fn fmt(
        &self,
        f: &mut fmt::Formatter<'_>,
    ) -> result::Result<(), fmt::Error> {
        for hc in &self.0 {
            writeln!(f, "#{}", hc.timestamp)?;
            writeln!(f, "{}", hc.command)?;
        }
        Ok(())
    }
}

fn clean_history(input: &str) -> Result<HistoryCommands> {
    let ignore_regex = RegexSetBuilder::new(IGNORES)
        .case_insensitive(true)
        .build()?;
    let exception_regex = RegexSetBuilder::new(EXCEPTIONS)
        .case_insensitive(true)
        .build()?;

    let mut history = <HashMap<String, u32>>::new();
    let iter = HistoryIterator::from(input);
    for hc in iter {
        match hc {
            Ok(hc) => {
                if is_valid(&hc.command, &exception_regex, &ignore_regex) {
                    let ts = history.entry(hc.command).or_insert(hc.timestamp);
                    if *ts < hc.timestamp {
                        *ts = hc.timestamp;
                    }
                }
            }
            Err(e) => writeln!(io::stderr(), "{}", e)?,
        }
    }

    let mut new_commands = HistoryCommands(
        history
            .into_iter()
            .map(|(command, timestamp)| HistoryCommand { timestamp, command })
            .collect(),
    );

    if new_commands.0.is_empty() {
        return err!("no valid commands");
    }

    new_commands.0.sort();
    Ok(new_commands)
}

fn write_history(
    history_file: &PathBuf,
    history: &HistoryCommands,
) -> Result<()> {
    let cwd = std::env::current_dir()?;
    let dir = history_file.parent().unwrap_or(cwd.as_path());
    let mut file = NamedTempFile::new_in(dir)?;
    write!(file, "{}", history)?;
    file.persist(history_file)?;
    Ok(())
}

/// Expose a runner for the command line tool
/// # Errors
///
/// Returns an error if it fails to parse the history file or if it is empty.
pub fn run() -> Result<()> {
    let mut args = args_os();
    let history_file = parse_args(&mut args)?;
    let input = std::fs::read_to_string(&history_file)?;
    let history = clean_history(&input)?;
    write_history(&history_file, &history)
}

#[cfg(test)]
mod tests;