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
use crate::dirs::WindshDirs;
use chrono::prelude::*;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::PathBuf;

#[derive(Deserialize, Serialize)]
pub struct HistoryItem {
    datetime: Option<String>,
    cmd: Option<String>,
}

#[derive(Clone)]
pub struct History {
    datetime: DateTime<Utc>,
    cmd: String,
}

impl History {
    pub fn new(cmd: &str) -> Self {
        Self {
            datetime: Utc::now(),
            cmd: String::from(cmd),
        }
    }

    pub fn save(&self, history_file: Option<&str>) {
        let mut history_file_path = PathBuf::new();

        #[cfg(unix)]
        if history_file == None {
            history_file_path.push(
                format!(
                    "{}/history.yml",
                    WindshDirs::load()
                        .config_dir()
                        .to_str()
                        .expect("Cannot convert config_dir path to str")
                )
                .as_str(),
            );
        } else {
            history_file_path
                .push(history_file.expect("Cannot get the history file"));
        }

        #[cfg(windows)]
        if history_file == None {
            history_file_path.push(
                format!(
                    "{}/history.yml",
                    WindshDirs::load()
                        .config_dir()
                        .to_str()
                        .expect("Cannot convert config_dir path to str")
                )
                .as_str(),
            );
        } else {
            history_file_path
                .push(history_file.expect("Cannot get the history file"));
        }

        if !history_file_path.exists() {
            fs::File::create(history_file_path.to_str().unwrap()).unwrap();
            let default_content: Vec<HistoryItem> = vec![HistoryItem {
                datetime: Some(String::from("DEFAULT")),
                cmd: Some(String::from("DEFAULT")),
            }];
            fs::write(
                &history_file_path,
                serde_yaml::to_string(&default_content).unwrap(),
            )
            .unwrap();
        }

        let content_raw =
            fs::read_to_string(&history_file_path.to_str().unwrap()).unwrap();

        let content_yaml: Vec<HistoryItem> =
            serde_yaml::from_str(content_raw.as_str()).unwrap();

        let mut history_vec: Vec<HistoryItem> = Vec::new();

        for item in content_yaml {
            history_vec.push(HistoryItem {
                datetime: item.datetime,
                cmd: item.cmd,
            })
        }

        history_vec.push(HistoryItem {
            datetime: Some(self.datetime.to_string()),
            cmd: Some(self.cmd.to_string()),
        });

        let all_history = serde_yaml::to_string(&history_vec).unwrap();

        fs::write(history_file_path, all_history).unwrap();
    }

    /// Set the datetime of history
    /// ```rust
    /// use windsh_core::history::History;
    /// use chrono::prelude::*;
    ///
    /// let mut my_history = History::new("print Hello, World!");
    ///
    /// my_history.set_datetime(Utc::now());
    /// ```
    pub fn set_datetime(&mut self, datetime: DateTime<Utc>) {
        self.datetime = datetime;
    }

    /// Set the cmd of history
    /// ```rust
    /// use windsh_core::history::History;
    /// use chrono::prelude::*;
    ///
    /// let mut my_history = History::new("ls -lsa");
    ///
    /// my_history.set_cmd("exec docker run -ti ubuntu:20.04 bash");
    /// ```
    pub fn set_cmd(&mut self, cmd: &str) {
        self.cmd = String::from(cmd);
    }

    pub fn get_datetime(&self) -> DateTime<Utc> {
        self.datetime
    }

    pub fn get_cmd(&self) -> String {
        self.cmd.clone()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::thread;
    use std::time;

    #[test]
    fn test_history_new() {
        let my_history = History::new("ls -lsa");

        assert_eq!(my_history.cmd, "ls -lsa");
        assert_ne!(my_history.cmd, "ls -lsa ");

        thread::sleep(time::Duration::from_millis(50));
        assert_ne!(my_history.datetime, Utc::now());
    }

    #[test]
    fn test_set_datetime() {
        let mut my_history = History::new("print Hello, World!");
        let datetime = Utc::now();

        my_history.set_datetime(datetime);

        assert_eq!(my_history.datetime, datetime);
    }

    #[test]
    fn test_set_cmd() {
        let mut my_history = History::new("print Hello, World!");

        my_history.set_cmd("print This is awesome");
        assert_eq!(my_history.cmd, "print This is awesome");

        my_history.set_cmd("ls -lsa \n");
        assert_eq!(my_history.cmd, "ls -lsa \n");
    }

    #[test]
    fn test_get_datetime() {
        let mut my_history = History::new("ls -lsa");

        let datetime = Utc::now();
        my_history.datetime = datetime;

        assert_eq!(my_history.datetime, datetime);

        thread::sleep(time::Duration::from_millis(50));
        assert_ne!(my_history.datetime, Utc::now());
    }

    #[test]
    fn test_get_cmd() {
        let mut my_history = History::new("ls -lsa");

        assert_eq!(my_history.cmd, "ls -lsa");

        my_history.cmd = String::from("");

        assert_eq!(my_history.cmd, "");
        assert_ne!(my_history.cmd, "\n");
    }
}