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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
//! Logic for dealing with tasks executed by up.
use self::task::CommandType;
use self::task::Task;
use self::TaskError as E;
use crate::config;
use crate::env::get_env;
use crate::tasks::task::TaskStatus;
use crate::utils::files;
use crate::utils::user::get_and_keep_sudo;
use camino::Utf8Path;
use camino::Utf8PathBuf;
use color_eyre::eyre::bail;
use color_eyre::eyre::eyre;
use color_eyre::eyre::Result;
use displaydoc::Display;
use itertools::Itertools;
use rayon::prelude::*;
use std::collections::HashMap;
use std::collections::HashSet;
use std::io;
use std::time::Duration;
use std::time::Instant;
use thiserror::Error;
use tracing::debug;
use tracing::error;
use tracing::info;
use tracing::trace;
use tracing::warn;

pub mod completions;
pub mod defaults;
pub mod git;
pub mod link;
pub mod task;
pub mod update_self;

// TODO(gib): If there's only one task left, stream output directly to the
// console and run sync.

// TODO(gib): Use https://lib.rs/crates/indicatif for progress bars.

// TODO(gib): use tui Terminal UI lib (https://crates.io/keywords/tui) for better UI.

/// Trait that tasks implement to specify how to replace environment variables in their
/// configuration.
pub trait ResolveEnv {
    /// Expand env vars in `self` by running `env_fn()` on its component
    /// strings.
    ///
    /// # Errors
    /// `resolve_env()` should return any errors returned by the `env_fn()`.
    fn resolve_env<F>(&mut self, _env_fn: F) -> Result<(), E>
    where
        F: Fn(&str) -> Result<String, E>,
    {
        Ok(())
    }
}

/// What to do with the tasks.
#[derive(Debug, Clone, Copy)]
pub enum TasksAction {
    /// Run tasks.
    Run,
    /// Just list the matching tasks.
    List,
}

/// Directory in which to find the tasks.
#[derive(Debug, Clone, Copy)]
pub enum TasksDir {
    /// Normal tasks to execute.
    Tasks,
    /// Generation tasks (that generate your main tasks).
    GenerateTasks,
}

impl TasksDir {
    /// The default directory names for task types.
    fn to_dir_name(self) -> String {
        match self {
            TasksDir::Tasks => "tasks".to_owned(),
            TasksDir::GenerateTasks => "generate_tasks".to_owned(),
        }
    }
}

/// Run a set of tasks specified in a subdir of the directory containing the up
/// config.
pub fn run(
    config: &config::UpConfig,
    tasks_dirname: TasksDir,
    tasks_action: TasksAction,
) -> Result<()> {
    // TODO(gib): Handle missing dir & move into config.
    let mut tasks_dir = config
        .up_yaml_path
        .as_ref()
        .ok_or(E::UnexpectedNone)?
        .clone();
    tasks_dir.pop();
    tasks_dir.push(tasks_dirname.to_dir_name());

    let env = get_env(
        config.config_yaml.inherit_env.as_ref(),
        config.config_yaml.env.as_ref(),
    )?;

    // If in macOS, don't let the display sleep until the command exits.
    #[cfg(target_os = "macos")]
    {
        use crate::cmd;
        _ = cmd!("caffeinate", "-ds", "-w", &std::process::id().to_string()).start()?;
    }

    // TODO(gib): Handle and filter by constraints.

    let bootstrap_tasks = match (config.bootstrap, &config.config_yaml.bootstrap_tasks) {
        (false, _) => Ok(Vec::new()),
        (true, None) => Err(eyre!(
            "Bootstrap flag set but no bootstrap_tasks specified in config."
        )),
        (true, Some(b_tasks)) => Ok(b_tasks.clone()),
    }?;

    let filter_tasks_set: Option<HashSet<String>> =
        config.tasks.clone().map(|v| v.into_iter().collect());
    debug!("Filter tasks set: {filter_tasks_set:?}");

    let excluded_tasks: HashSet<String> = config
        .exclude_tasks
        .clone()
        .map_or_else(HashSet::new, |v| v.into_iter().collect());
    debug!("Excluded tasks set: {excluded_tasks:?}");

    let mut tasks: HashMap<String, task::Task> = HashMap::new();
    for entry in tasks_dir.read_dir().map_err(|e| E::ReadDir {
        path: tasks_dir.clone(),
        source: e,
    })? {
        let entry = entry?;
        if entry.file_type()?.is_dir() {
            continue;
        }
        let path = Utf8PathBuf::try_from(entry.path())?;
        // If file is a broken symlink.
        if !path.exists() && path.symlink_metadata().is_ok() {
            files::remove_broken_symlink(&path)?;
            continue;
        }
        let task = task::Task::from(&path)?;
        let name = &task.name;

        if excluded_tasks.contains(name) {
            debug!(
                "Not running task '{name}' as it is in the excluded tasks set {excluded_tasks:?}"
            );
            continue;
        }

        if let Some(filter) = filter_tasks_set.as_ref() {
            if !filter.contains(name) {
                debug!("Not running task '{name}' as not in tasks filter {filter:?}",);
                continue;
            }
        }
        tasks.insert(name.clone(), task);
    }

    if matches!(tasks_action, TasksAction::Run)
        && tasks.values().any(|t| t.config.needs_sudo)
        && users::get_current_uid() != 0
    {
        get_and_keep_sudo(false)?;
    }

    debug!("Task count: {:?}", tasks.len());
    trace!("Task list: {tasks:#?}");

    match tasks_action {
        TasksAction::List => println!("{}", tasks.keys().join("\n")),
        TasksAction::Run => {
            let run_tempdir = config.temp_dir.join(format!(
                "runs/{start_time}",
                start_time = config.start_time.to_rfc3339()
            ));

            run_tasks(
                bootstrap_tasks,
                tasks,
                &env,
                &run_tempdir,
                config.keep_going,
            )?;
        }
    }
    Ok(())
}

/// Runs a set of tasks.
fn run_tasks(
    bootstrap_tasks: Vec<String>,
    mut tasks: HashMap<String, task::Task>,
    env: &HashMap<String, String>,
    temp_dir: &Utf8Path,
    keep_going: bool,
) -> Result<()> {
    let mut completed_tasks = Vec::new();
    if !bootstrap_tasks.is_empty() {
        for task_name in bootstrap_tasks {
            let task_tempdir = create_task_tempdir(temp_dir, &task_name)?;

            let task = run_task(
                tasks
                    .remove(&task_name)
                    .ok_or_else(|| eyre!("Task '{task_name}' was missing."))?,
                env,
                &task_tempdir,
            );
            if !keep_going {
                if let TaskStatus::Failed(e) = task.status {
                    bail!(e);
                }
            }
            completed_tasks.push(task);
        }
    }

    completed_tasks.extend(
        tasks
            .into_par_iter()
            .filter(|(_, task)| task.config.auto_run.unwrap_or(true))
            .map(|(_, task)| {
                let task_name = task.name.as_str();
                let _span = tracing::info_span!("task", task = task_name).entered();
                let task_tempdir = create_task_tempdir(temp_dir, task_name)?;
                Ok(run_task(task, env, &task_tempdir))
            })
            .collect::<Result<Vec<Task>>>()?,
    );
    let completed_tasks_len = completed_tasks.len();

    let mut tasks_passed = Vec::new();
    let mut tasks_skipped = Vec::new();
    let mut tasks_failed = Vec::new();
    let mut tasks_incomplete = Vec::new();

    for task in completed_tasks {
        match task.status {
            TaskStatus::Failed(_) => {
                tasks_failed.push(task);
            }
            TaskStatus::Passed => tasks_passed.push(task),
            TaskStatus::Skipped => tasks_skipped.push(task),
            TaskStatus::Incomplete => tasks_incomplete.push(task),
        }
    }

    info!(
        "Ran {completed_tasks_len} tasks, {} passed, {} failed, {} skipped",
        tasks_passed.len(),
        tasks_failed.len(),
        tasks_skipped.len()
    );
    if !tasks_passed.is_empty() {
        info!(
            "Tasks passed: {:?}",
            tasks_passed.iter().map(|t| &t.name).collect::<Vec<_>>()
        );
    }
    if !tasks_skipped.is_empty() {
        info!(
            "Tasks skipped: {:?}",
            tasks_skipped.iter().map(|t| &t.name).collect::<Vec<_>>()
        );
    }

    if !tasks_failed.is_empty() {
        error!("One or more tasks failed, exiting.");

        error!(
            "Tasks failed: {:#?}",
            tasks_failed.iter().map(|t| &t.name).collect::<Vec<_>>()
        );

        let mut tasks_failed_iter = tasks_failed.into_iter().filter_map(|t| match t.status {
            TaskStatus::Failed(e) => Some(e),
            _ => None,
        });
        let err = tasks_failed_iter.next().ok_or(E::UnexpectedNone)?;
        let err = eyre!(err);
        tasks_failed_iter.fold(Err(err), color_eyre::Help::error)?;
    }

    Ok(())
}

/// Runs a specific task.
fn run_task(mut task: Task, env: &HashMap<String, String>, task_tempdir: &Utf8Path) -> Task {
    let env_fn = &|s: &str| {
        let home_dir = files::home_dir().map_err(|e| E::EyreError { source: e })?;
        let out = shellexpand::full_with_context(
            s,
            || Some(home_dir),
            |k| env.get(k).ok_or_else(|| eyre!("Value not found")).map(Some),
        )
        .map(std::borrow::Cow::into_owned)
        .map_err(|e| E::ResolveEnv {
            var: e.var_name,
            source: e.cause,
        })?;

        Ok(out)
    };

    let now = Instant::now();
    task.run(env_fn, env, task_tempdir);
    let elapsed_time = now.elapsed();
    if elapsed_time > Duration::from_secs(60) {
        warn!("Task took {elapsed_time:?}");
    }
    task
}

/// Create a subdir of the current temporary directory for the task.
fn create_task_tempdir(temp_dir: &Utf8Path, task_name: &str) -> Result<Utf8PathBuf> {
    let task_tempdir = temp_dir.join(task_name);
    files::create_dir_all(&task_tempdir)?;
    Ok(task_tempdir)
}

#[allow(clippy::doc_markdown)]
#[derive(Error, Debug, Display)]
/// Errors thrown by this file.
pub enum TaskError {
    /// Task `{name}` {lib} failed.
    TaskError {
        /// Source error.
        source: color_eyre::eyre::Error,
        /// The task library we were running.
        lib: String,
        /// The task name.
        name: String,
    },
    /// Error walking directory `{path}`:
    ReadDir {
        /// The path we failed to walk.
        path: Utf8PathBuf,
        /// Source error.
        source: io::Error,
    },
    /// Error reading file `{path}`:
    ReadFile {
        /// The path we failed to read.
        path: Utf8PathBuf,
        /// Source error.
        source: io::Error,
    },
    /// Env lookup error, please define `{var}` in your up.yaml:"
    EnvLookup {
        /// The env var we couldn't find.
        var: String,
        /// Source error.
        source: color_eyre::eyre::Error,
    },
    /// Commmand was empty.
    EmptyCmd,
    /// Task `{name}` had no run command.
    MissingCmd {
        /// The task name.
        name: String,
    },
    /**
    Task `{name}` {command_type} failed.Command: {cmd:?}.{suggestion}
    */
    CmdFailed {
        /// The type of command that failed (check or run).
        command_type: CommandType,
        /// Task name.
        name: String,
        /// Source error.
        source: io::Error,
        /// The command itself.
        cmd: Vec<String>,
        /// Suggestion for how to fix it.
        suggestion: String,
    },
    /**
    Task `{name}` {command_type} failed with exit code {code}. Command: {cmd:?}.
      Output: {output_file}
    */
    CmdNonZero {
        /// The type of command that failed (check or run).
        command_type: CommandType,
        /// Task name.
        name: String,
        /// The command itself.
        cmd: Vec<String>,
        /// Error code.
        code: i32,
        /// File containing stdout and stderr of the file.
        output_file: Utf8PathBuf,
    },
    /**
    Task `{name}` {command_type} was terminated. Command: {cmd:?}, output: {output_file}.
      Output: {output_file}
    */
    CmdTerminated {
        /// The type of command that failed (check or run).
        command_type: CommandType,
        /// Task name.
        name: String,
        /// The command itself.
        cmd: Vec<String>,
        /// File containing stdout and stderr of the file.
        output_file: Utf8PathBuf,
    },
    /// Unexpectedly empty option found.
    UnexpectedNone,
    /// Invalid yaml at `{path}`:
    InvalidYaml {
        /// Path that contained invalid yaml.
        path: Utf8PathBuf,
        /// Source error.
        source: serde_yaml::Error,
    },
    /// Unable to calculate the current user's home directory.
    MissingHomeDir,
    /// Env lookup error, please define `{var}` in your up.yaml
    ResolveEnv {
        /// Env var we couldn't find.
        var: String,
        /// Source error.
        source: color_eyre::eyre::Error,
    },
    /// Task {task} must have data.
    TaskDataRequired {
        /// Task name.
        task: String,
    },
    /// Failed to parse the config.
    DeserializeError {
        /// Source error.
        source: serde_yaml::Error,
    },
    /// Task error.
    EyreError {
        /// Source error.
        source: color_eyre::Report,
    },
}