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
use ansi_term::ANSIString;
use anyhow::Result;
use itertools::Itertools;
use path_absolutize::Absolutize;
use std::path::PathBuf;
use std::{env, path::Path};
use toml_edit::Item;

use crate::{
    colors::{BLUE, RED, YELLOW},
    filter::FilterOptions,
    output::{ErrorCode, Output},
    saucefile::Saucefile,
    settings::Settings,
    shell::{actions, Shell},
    target::Target,
    toml::value_from_string,
};

#[derive(Debug)]
pub struct Context<'a> {
    filter_options: FilterOptions<'a>,

    data_dir: PathBuf,
    config_dir: PathBuf,
    home_dir: PathBuf,

    path: PathBuf,
    pub sauce_path: PathBuf,

    _settings: Option<Settings>,
    _saucefile: Option<Saucefile>,
}

impl<'a> Context<'a> {
    pub fn new(
        data_dir: PathBuf,
        config_dir: PathBuf,
        home_dir: PathBuf,
        filter_options: FilterOptions<'a>,
        path: Option<&'a str>,
        file: Option<&'a str>,
    ) -> Result<Self> {
        let (path, sauce_path, data_dir) = match file {
            // The default case, where no `file` is supplied. We perform normal
            // path lookup and saucefile cascading behavior.
            None => {
                let path = if let Some(path) = path {
                    Path::new(path).to_path_buf()
                } else {
                    env::current_dir()?
                };

                let path = path.absolutize()?;

                let relative_path = path.strip_prefix(&home_dir)?;
                let sauce_path = data_dir.join(relative_path).with_extension("toml");
                (path.to_path_buf(), sauce_path, data_dir)
            }
            // The default case, where no `file` is supplied. We perform normal
            // path lookup and saucefile cascading behavior.
            Some(file) => {
                let file = Path::new(file).absolutize()?.to_path_buf();

                (file.clone(), file, "".into())
            }
        };
        Ok(Self {
            data_dir,
            config_dir,
            home_dir,
            filter_options,
            path,
            sauce_path,
            _saucefile: None,
            _settings: None,
        })
    }

    fn load_saucefile(&mut self, output: &mut Output) {
        if self._saucefile.is_none() {
            self._saucefile = Some(Saucefile::read(
                output,
                &self.sauce_path,
                self.cascade_paths(),
            ));
        }
    }

    fn saucefile(&self) -> &Saucefile {
        self._saucefile.as_ref().unwrap()
    }

    fn saucefile_mut(&mut self) -> &mut Saucefile {
        self._saucefile.as_mut().unwrap()
    }

    pub fn set_settings(&mut self, settings: Settings) {
        self._settings = Some(settings);
    }

    pub fn load_settings(&mut self, output: &mut Output) {
        if self._settings.is_none() {
            self._settings = Some(Settings::load(&self.config_dir, output));
        }
    }

    pub fn settings(&self) -> &Settings {
        self._settings.as_ref().unwrap()
    }

    pub fn settings_mut(&mut self) -> &mut Settings {
        self._settings.as_mut().unwrap()
    }

    pub fn init_shell(&mut self, shell_kind: &dyn Shell, output: &mut Output) {
        self.load_settings(output);
        let autoload_hook = self.settings().autoload_hook.unwrap_or(false);
        actions::init(output, shell_kind, autoload_hook)
    }

    pub fn execute_shell_command(
        &mut self,
        shell_kind: &dyn Shell,
        command: &str,
        output: &mut Output,
    ) {
        actions::execute_shell_command(output, shell_kind, command)
    }

    pub fn create_saucefile(&mut self, output: &mut Output) {
        actions::create_saucefile(output, &self.sauce_path);
    }

    pub fn move_saucefile(&self, output: &mut Output, destination: &Path, copy: bool) {
        let source = &self.sauce_path;

        let destination = match destination.absolutize() {
            Ok(d) => d,
            Err(_) => {
                output.notify_error(
                    ErrorCode::WriteError,
                    &[RED.paint("Path is not relative to the home directory")],
                );
                return;
            }
        };
        if let Ok(relative_path) = destination.strip_prefix(&self.home_dir) {
            let dest = self.data_dir.join(relative_path).with_extension("toml");
            actions::move_saucefile(output, source, &dest, copy);
        } else {
            output.notify_error(
                ErrorCode::WriteError,
                &[RED.paint("Path is not relative to the home directory")],
            );
        }
    }

    pub fn edit_saucefile(&mut self, shell_kind: &dyn Shell, output: &mut Output) {
        actions::edit(output, shell_kind, &self.sauce_path);
    }

    pub fn show(&mut self, target: Target, output: &mut Output) {
        self.load_saucefile(output);
        actions::show(output, &self.filter_options, target, self.saucefile());
    }

    pub fn clear(&mut self, shell_kind: &dyn Shell, output: &mut Output) {
        self.load_settings(output);
        self.load_saucefile(output);

        actions::clear(
            output,
            shell_kind,
            self.saucefile(),
            self.settings(),
            &self.filter_options,
        );
    }

    pub fn execute(&mut self, shell_kind: &dyn Shell, autoload: bool, output: &mut Output) {
        self.load_saucefile(output);
        self.load_settings(output);

        let saucefile = self.saucefile();
        let sauced = actions::execute(
            output,
            shell_kind,
            saucefile,
            self.settings(),
            &self.filter_options,
            autoload,
        );

        if !sauced {
            // We may sometimes opt to *not* execute, i.e. certain autoload scenarios.
            return;
        }

        let message = materialize_path_message("Sauced", &self.data_dir, saucefile.paths());
        output.notify(&message);
    }

    pub fn cascade_paths(&self) -> impl Iterator<Item = PathBuf> {
        self.sauce_path
            .ancestors()
            .filter(|p| {
                if self.data_dir.with_extension("toml") == *p {
                    true
                } else {
                    p.strip_prefix(&self.data_dir).is_ok()
                }
            })
            .map(|p| p.with_extension("toml"))
            .collect::<Vec<PathBuf>>()
            .into_iter()
            .rev()
    }

    pub fn set_var<T: AsRef<str>>(&mut self, raw_values: &[(T, T)], output: &mut Output) {
        self.load_saucefile(output);

        let values = raw_values
            .iter()
            .map(|(name, raw_value)| (name, value_from_string(raw_value.as_ref())))
            .collect::<Vec<_>>();

        self.set_values(output, "environment", values);
    }

    pub fn set_alias<T: AsRef<str>>(&mut self, raw_values: &[(T, T)], output: &mut Output) {
        self.load_saucefile(output);

        let values = raw_values
            .iter()
            .map(|(name, raw_value)| (name, value_from_string(raw_value.as_ref())))
            .collect::<Vec<_>>();

        self.set_values(output, "alias", values);
    }

    pub fn set_function(&mut self, name: &str, body: &str, output: &mut Output) {
        self.load_saucefile(output);
        let values = vec![(name, value_from_string(body))];

        self.set_values(output, "function", values);
    }

    fn set_values<I, T>(&mut self, output: &mut Output, section: &str, values: I)
    where
        I: IntoIterator<Item = (T, Item)>,
        T: AsRef<str>,
    {
        let path = &self.sauce_path.clone();
        let document = &mut self.saucefile_mut().document;

        output.write_toml(path, document, section, values);
    }

    pub fn set_config<T: AsRef<str>>(
        &mut self,
        values: &[(T, T)],
        global: bool,
        output: &mut Output,
    ) {
        if global {
            self.load_settings(output);
            self.settings_mut().set_values(&values, output);
        } else {
            self.load_saucefile(output);
            let settings = self.saucefile().settings();
            settings.set_values(&values, output);
        };
    }
}

fn materialize_path_message<'a>(
    action: &'a str,
    data_dir: &'a Path,
    paths: impl Iterator<Item = &'a PathBuf>,
) -> Vec<ANSIString<'a>> {
    let parent_dir = &data_dir.parent().unwrap_or(data_dir);
    let paths = paths
        .filter_map(|p| p.strip_prefix(parent_dir).ok())
        .map(|p| p.to_string_lossy())
        .join(", ");

    let mut result = Vec::new();

    if paths.is_empty() {
        result.push(RED.bold().paint("No saucefiles exist"));
        return result;
    }

    result.push(BLUE.bold().paint(format!("{} ", action)));
    result.push(YELLOW.paint(paths.clone()));

    if !paths.starts_with(data_dir.to_string_lossy().as_ref()) {
        result.push(BLUE.bold().paint(" from "));
        result.push(YELLOW.paint(data_dir.to_string_lossy()));
    }
    result
}

impl<'a> Default for Context<'a> {
    fn default() -> Self {
        Self {
            filter_options: FilterOptions::default(),
            data_dir: PathBuf::new(),
            config_dir: PathBuf::new(),
            home_dir: PathBuf::new(),
            path: PathBuf::new(),
            sauce_path: PathBuf::new(),
            _saucefile: None,
            _settings: None,
        }
    }
}

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

    mod cascade_paths {
        use super::super::*;
        use super::*;
        use pretty_assertions::assert_eq;

        #[test]
        fn test_home() {
            let mut context = Context::default();
            context.data_dir = "~/.local/share/sauce".into();
            context.sauce_path = "~/.local/share/sauce".into();

            let paths: Vec<_> = context.cascade_paths().collect();

            let expected: Vec<PathBuf> = vec!["~/.local/share/sauce.toml".into()];
            assert_eq!(paths, expected);
        }

        #[test]
        fn test_nested_subdir() {
            let mut context = Context::default();
            context.data_dir = "~/.local/share/sauce".into();
            context.sauce_path = "~/.local/share/sauce/meow/meow/kitty.toml".into();

            let paths: Vec<_> = context.cascade_paths().collect();

            let expected: Vec<PathBuf> = vec![
                "~/.local/share/sauce.toml".into(),
                "~/.local/share/sauce/meow.toml".into(),
                "~/.local/share/sauce/meow/meow.toml".into(),
                "~/.local/share/sauce/meow/meow/kitty.toml".into(),
            ];
            assert_eq!(paths, expected);
        }
    }
}