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
//! ## History
//!
//! `History` provides an API for the shell History

/*
*
*   Copyright (C) 2020 Christian Visintin - christian.visintin1997@gmail.com
*
* 	This file is part of "Pyc"
*
*   Pyc is free software: you can redistribute it and/or modify
*   it under the terms of the GNU General Public License as published by
*   the Free Software Foundation, either version 3 of the License, or
*   (at your option) any later version.
*
*   Pyc is distributed in the hope that it will be useful,
*   but WITHOUT ANY WARRANTY; without even the implied warranty of
*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*   GNU General Public License for more details.
*
*   You should have received a copy of the GNU General Public License
*   along with Pyc.  If not, see <http://www.gnu.org/licenses/>.
*
*/

use std::collections::VecDeque;

pub struct ShellHistory {
    history: VecDeque<String>
}

impl ShellHistory {

    /// ### new
    /// 
    /// Instantiate a new ShellHistory
    pub fn new() -> ShellHistory {
        ShellHistory {
            history: VecDeque::with_capacity(2048)
        }
    }

    /// ### at
    /// 
    /// Get the command at a certain index of the history
    /// None is returned in case index is out of range
    pub fn at(&self, index: usize) -> Option<String> {
        match self.history.get(index) {
            Some(s) => Some(s.clone()),
            None => None
        }
    }

    /// ### clear
    /// 
    /// Clear history
    pub fn clear(&mut self) {
        self.history.clear();
    }

    /// ### dump
    /// 
    /// Dump history
    pub fn dump(&mut self) -> Vec<String> {
        let mut history: Vec<String> = Vec::with_capacity(self.history.len());
        for entry in self.history.iter().rev() {
            history.push(entry.clone());
        }
        history
    }

    /// ### len
    /// 
    /// Returns history len
    pub fn len(&self) -> usize {
        self.history.len()
    }

    /// ### load
    /// 
    /// Load history
    /// NOTE: the maximum history size will still be the size provided at constructor
    pub fn load(&mut self, lines: Vec<String>) {
        //Clear current history
        self.clear();
        //Parse file
        for line in lines.iter() {
            self.push(line.clone());
        }
    }

    /// ### push
    /// 
    /// Push a new entry to the history.
    /// The entry is stored at the front of the history. The first the newest
    pub fn push(&mut self, mut line: String) {
        //@! Remove newline
        while line.ends_with("\n") {
            line.pop();
        }
        //Ignore empty lines
        if line.is_empty() {
            return;
        }
        //Duplicates not allowed
        if let Some(last_line) = self.at(0) {
            if last_line == line {
                return
            }
        }
        //Check if history overflows the size
        let size: usize = (self.history.capacity() + 1) / 2;
        if self.history.len() + 1 > size {
            self.history.pop_back();
        }
        self.history.push_front(line);
    }

}

//@! Test module

#[cfg(test)]
mod tests {

    use super::*;

    #[test]
    fn test_shell_history() {
        let mut history: ShellHistory = ShellHistory::new();
        assert_eq!(history.history.capacity(), (2048 * 2 - 1)); //2048 * 2 - 1
        //Load history
        history.load(vec![String::from("ls"), String::from("cd /tmp/")]);
        assert_eq!(history.len(), 2);
        //History at
        assert_eq!(history.at(0).unwrap(), String::from("cd /tmp/"));
        assert_eq!(history.at(1).unwrap(), String::from("ls"));
        assert!(history.at(2).is_none());
        //Push element
        history.push(String::from("pwd\n\n\n")); //@! Newlines must be removed
        assert_eq!(history.len(), 3);
        assert_eq!(history.at(0).unwrap(), String::from("pwd"));
        //Duplicates are not allowed
        history.push(String::from("pwd"));
        assert_eq!(history.len(), 3);
        //Empty lines are not allowed
        history.push(String::from("\n"));
        assert_eq!(history.len(), 3);
        //Fill history with 2048 elements
        let mut history_vec: Vec<String> = Vec::with_capacity(2048);
        for i in 0..2048 {
            history_vec.push(format!("echo {}", i));
        }
        history.load(history_vec);
        assert_eq!(history.len(), 2048);
        assert_eq!(history.at(0).unwrap(), String::from("echo 2047"));
        assert_eq!(history.at(2047).unwrap(), String::from("echo 0"));
        //Push element
        history.push(String::from("echo 2048"));
        assert_eq!(history.len(), 2048);
        assert_eq!(history.at(0).unwrap(), String::from("echo 2048"));
        assert_eq!(history.at(2047).unwrap(), String::from("echo 1"));
        //Clear
        history.clear();
        assert_eq!(history.len(), 0);
        //Push element
        history.push(String::from("ls -l"));
        history.push(String::from("cd /tmp/"));
        //Dump history
        let dump: Vec<String> = history.dump();
        assert_eq!(dump.len(), 2);
        //Older commands first
        assert_eq!(*dump.get(0).unwrap(), String::from("ls -l"));
        assert_eq!(*dump.get(1).unwrap(), String::from("cd /tmp/"));
    }

}