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
use regex::{Regex, RegexSet, RegexSetBuilder};
use std::collections::HashMap;
use std::env::args_os;
use std::error::Error;
use std::fmt;
use std::io::{self, Write};
use std::path::PathBuf;
use std::result;
use tempfile::NamedTempFile;

type Result<T> = result::Result<T, Box<dyn Error>>;

macro_rules! err {
    ($($tt:tt)*) => {
        Err(Box::<dyn 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, Ord)]
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)),
        )
    }
}

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: Option<&str>;
        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() => {
                    timestamp = self.next_timestamp;
                    self.next_timestamp = Some(line);
                    break;
                }
                // Accumulate lines of command (if multiple)
                Some(line) => command += line,

                None => {
                    timestamp = self.next_timestamp;
                    self.next_timestamp = None;
                    break;
                }
            };
        }

        let timestamp: Result<u32> = match timestamp {
            None => return None,
            Some(v) => v
                .trim()
                .trim_start_matches('#')
                .parse()
                .map_err(|e: std::num::ParseIntError| e.into()),
        };

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

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

/// Write the usage 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 = match args.next() {
        Some(path) => path,
        _ => return err!("please supply the path to the bash_history file"),
    };
    if args.next().is_some() {
        return err!("this script only accepts one argument");
    }

    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.iter() {
            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 = input.into();
    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 { command, timestamp })
            .collect(),
    );
    new_commands.0.sort();
    Ok(new_commands)
}

fn write_history(history_file: &PathBuf, history: &HistoryCommands) -> Result<()> {
    let mut file = NamedTempFile::new()?;
    write!(file, "{}", history)?;
    file.persist(history_file)?;
    Ok(())
}

/// Expose a runner for the command line tool
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;