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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
//! Dust's built-in commands.
//!
//! When a tool in invoked in Dust, the input is checked against the inputs listed in its ToolInfo.
//! The input should then be double-checked by `Tool::check_input` when you implement `run`. The
//! purpose of the second check is to weed out mistakes in how the inputs were described in the
//! ToolInfo. The errors from the second check should only come up during development and should not //! be seen by the user.
//!
//! ## Writing macros
//!
//! - Snake case identifier, this is enforced by a test
//! - The description should be brief, it will display in the shell
//! - Recycle code that is already written and tested
//! - Write non-trivial tests, do not write tests just for the sake of writing them
//!
//! ## Usage
//!
//! Commands can be used in Rust by passing a Value to the run method.
//!
//! ```
//! # use dust_lib::{tools::collections::Count, Tool, Value};
//! let value = Value::List(vec![
//!     Value::Integer(1),
//!     Value::Integer(2),
//!     Value::Integer(3),
//! ]);
//! let count = Count
//!     .run(&value)
//!     .unwrap()
//!     .as_int()
//!     .unwrap();
//!
//! assert_eq!(count, 3);
//! ```

use crate::{Result, Value, ValueType};

pub mod collections;
pub mod command;
pub mod data_formats;
pub mod disks;
pub mod filesystem;
pub mod general;
pub mod gui;
pub mod logic;
pub mod network;
pub mod random;
pub mod system;
pub mod time;

/// Master list of all tools.
///
/// This list is used to match identifiers with tools and to provide info to the shell.
pub const TOOL_LIST: [&'static dyn Tool; 52] = [
    &collections::Count,
    &collections::CreateTable,
    &collections::Insert,
    &collections::Rows,
    &collections::Select,
    &collections::String,
    &collections::Sort,
    &collections::Replace,
    &collections::Transform,
    &collections::Where,
    &command::Bash,
    &command::Fish,
    &command::Raw,
    &command::Sh,
    &command::Zsh,
    &data_formats::FromCsv,
    &data_formats::ToCsv,
    &data_formats::FromJson,
    &data_formats::ToJson,
    &disks::ListDisks,
    &disks::Partition,
    &filesystem::Append,
    &filesystem::CreateDir,
    &filesystem::FileMetadata,
    &filesystem::MoveDir,
    &filesystem::ReadDir,
    &filesystem::ReadFile,
    &filesystem::RemoveDir,
    &filesystem::Trash,
    &filesystem::Watch,
    &filesystem::Write,
    &general::Help,
    &general::Run,
    &general::Output,
    &general::Repeat,
    &general::Wait,
    &gui::BarGraph,
    &gui::Plot,
    &logic::If,
    &logic::IfElse,
    &logic::Loop,
    &network::Download,
    &random::Random,
    &random::RandomBoolean,
    &random::RandomFloat,
    &random::RandomInteger,
    &random::RandomString,
    &system::Users,
    &logic::Assert,
    &logic::AssertEqual,
    &time::Local,
    &time::Now,
];

/// A whale macro function.
pub trait Tool: Sync + Send {
    fn info(&self) -> ToolInfo<'static>;
    fn run(&self, argument: &Value) -> Result<Value>;

    fn check_type<'a>(&self, argument: &'a Value) -> Result<&'a Value> {
        if self
            .info()
            .inputs
            .iter()
            .any(|value_type| &argument.value_type() == value_type)
        {
            Ok(argument)
        } else {
            Err(crate::Error::TypeCheckFailure {
                tool_info: self.info(),
                argument: argument.clone(),
            })
        }
    }

    fn fail(&self, argument: &Value) -> Result<Value> {
        Err(crate::Error::TypeCheckFailure {
            tool_info: self.info(),
            argument: argument.clone(),
        })
    }
}

/// Information needed for each macro.
#[derive(Clone, Debug, PartialEq)]
pub struct ToolInfo<'a> {
    /// Text pattern that triggers this macro.
    pub identifier: &'a str,

    /// User-facing information about how the macro works.
    pub description: &'a str,

    /// Category used to sort macros in the shell.
    pub group: &'a str,

    pub inputs: Vec<ValueType>,
}

// pub struct SystemInfo;

// impl Macro for SystemInfo {
//     fn info(&self) -> MacroInfo<'static> {
//         MacroInfo {
//             identifier: "system_info",
//             description: "Get information on the system.",
//         }
//     }

//     fn run(&self, argument: &Value) -> crate::Result<Value> {
//         argument.as_empty()?;

//         let mut map = VariableMap::new();

//         map.set_value("hostname", Value::String(hostname()?))?;

//         Ok(Value::Map(map))
//     }
// }

// pub struct Map;

// impl Macro for Map {
//     fn info(&self) -> MacroInfo<'static> {
//         MacroInfo {
//             identifier: "map",
//             description: "Create a map from a value.",
//         }
//     }

//     fn run(&self, argument: &Value) -> Result<Value> {
//         match argument {
//             Value::String(_) => todo!(),
//             Value::Float(_) => todo!(),
//             Value::Integer(_) => todo!(),
//             Value::Boolean(_) => todo!(),
//             Value::List(_) => todo!(),
//             Value::Map(_) => todo!(),
//             Value::Table(table) => Ok(Value::Map(VariableMap::from(table))),
//             Value::Function(_) => todo!(),
//             Value::Empty => todo!(),
//         }
//     }
// }

// pub struct Status;

// impl Macro for Status {
//     fn info(&self) -> MacroInfo<'static> {
//         MacroInfo {
//             identifier: "git_status",
//             description: "Get the repository status for the current directory.",
//         }
//     }

//     fn run(&self, argument: &Value) -> Result<Value> {
//         argument.as_empty()?;

//         let repo = Repository::open(".")?;
//         let mut table = Table::new(vec![
//             "path".to_string(),
//             "status".to_string(),
//             "staged".to_string(),
//         ]);

//         for entry in repo.statuses(None)?.into_iter() {
//             let (status, staged) = {
//                 if entry.status().is_wt_new() {
//                     ("created".to_string(), false)
//                 } else if entry.status().is_wt_deleted() {
//                     ("deleted".to_string(), false)
//                 } else if entry.status().is_wt_modified() {
//                     ("modified".to_string(), false)
//                 } else if entry.status().is_index_new() {
//                     ("created".to_string(), true)
//                 } else if entry.status().is_index_deleted() {
//                     ("deleted".to_string(), true)
//                 } else if entry.status().is_index_modified() {
//                     ("modified".to_string(), true)
//                 } else if entry.status().is_ignored() {
//                     continue;
//                 } else {
//                     ("".to_string(), false)
//                 }
//             };
//             let path = entry.path().unwrap().to_string();

//             table.insert(vec![
//                 Value::String(path),
//                 Value::String(status),
//                 Value::Boolean(staged),
//             ])?;
//         }

//         Ok(Value::Table(table))
//     }
// }

// pub struct DocumentConvert;

// impl Macro for DocumentConvert {
//     fn info(&self) -> MacroInfo<'static> {
//         MacroInfo {
//             identifier: "convert_document",
//             description: "Convert a file's contents to a format and set the extension.",
//         }
//     }

//     fn run(&self, argument: &Value) -> Result<Value> {
//         let argument = argument.as_list()?;

//         if argument.len() != 3 {
//             return Err(Error::WrongFunctionArgumentAmount {
//                 expected: 3,
//                 actual: argument.len(),
//             });
//         }

//         let (path, from, to) = (
//             argument[0].as_string()?,
//             argument[1].as_string()?,
//             argument[2].as_string()?,
//         );
//         let mut file_name = PathBuf::from(&path);
//         file_name.set_extension(to);
//         let new_file_name = file_name.to_str().unwrap();
//         let script = format!("pandoc --from {from} --to {to} --output {new_file_name} {path}");

//         Command::new("fish").arg("-c").arg(script).spawn()?.wait()?;

//         Ok(Value::Empty)
//     }
// }

// pub struct Trash;

// impl Macro for Trash {
//     fn info(&self) -> MacroInfo<'static> {
//         MacroInfo {
//             identifier: "trash_dir",
//             description: "Move a directory to the trash.",
//         }
//     }

//     fn run(&self, argument: &Value) -> Result<Value> {
//         let path = argument.as_string()?;

//         trash::delete(path)?;

//         Ok(Value::Empty)
//     }
// }

// pub struct Get;

// impl Macro for Get {
//     fn info(&self) -> MacroInfo<'static> {
//         MacroInfo {
//             identifier: "get",
//             description: "Extract a value from a collection.",
//         }
//     }

//     fn run(&self, argument: &Value) -> Result<Value> {
//         let argument_list = argument.as_list()?;
//         let collection = &argument_list[0];
//         let index = &argument_list[1];

//         if let Ok(list) = collection.as_list() {
//             let index = index.as_int()?;
//             let value = list.get(index as usize).unwrap_or(&Value::Empty);

//             return Ok(value.clone());
//         }

//         if let Ok(table) = collection.as_table() {
//             let index = index.as_int()?;
//             let get_row = table.get(index as usize);

//             if let Some(row) = get_row {
//                 return Ok(Value::List(row.clone()));
//             }
//         }

//         Err(Error::TypeError {
//             expected: &[
//                 ValueType::List,
//                 ValueType::Map,
//                 ValueType::Table,
//                 ValueType::String,
//             ],
//             actual: collection.clone(),
//         })
//     }
// }

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

    #[test]
    fn tool_identifier_formatting() {
        for function in TOOL_LIST {
            let identifier = function.info().identifier;

            assert_eq!(identifier.to_lowercase(), identifier);
            assert!(identifier.is_ascii());
            assert!(!identifier.is_empty());
            assert!(!identifier.contains(' '));
            assert!(!identifier.contains(':'));
            assert!(!identifier.contains('.'));
            assert!(!identifier.contains('-'));
        }
    }

    #[test]
    fn tool_inputs_exist() {
        for function in TOOL_LIST {
            let identifier = function.info().identifier;
            let input_count = function.info().inputs.len();

            assert!(input_count > 0, "{} has no inputs declared", identifier);
        }
    }
}