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
use std::{
    collections::HashMap,
    fs,
    io::Read,
    path::{Path, PathBuf},
    process::{Child, Command, ExitStatus, Output, Stdio},
    time::{Duration, Instant},
};

use anyhow::{anyhow, bail, Result};
use log::{debug, info, log, trace, Level};
use serde_derive::{Deserialize, Serialize};

use crate::{
    args::{GenerateGitConfig, LinkOptions, UpdateSelfOptions},
    generate, tasks,
    tasks::{defaults::DefaultsConfig, git::GitConfig, ResolveEnv, TasksError},
};

#[derive(Debug)]
pub enum TaskStatus {
    /// We haven't checked this task yet.
    New,
    /// Not yet ready to run as some requires still haven't finished.
    Blocked,
    /// In progress.
    Running(Child, Instant),
    /// Skipped.
    Skipped,
    /// Completed successfully.
    Passed,
    /// Completed unsuccessfully.
    Failed(anyhow::Error),
}

#[derive(Debug)]
pub struct Task {
    pub name: String,
    pub path: PathBuf,
    pub config: TaskConfig,
    pub start_time: Instant,
    pub status: TaskStatus,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TaskConfig {
    /// Task name, defaults to file name (minus extension) if unset.
    pub name: Option<String>,
    /// Set of Constraints that will cause the task to be run.
    pub constraints: Option<HashMap<String, String>>,
    /// Tasks that must have been executed beforehand.
    pub requires: Option<Vec<String>>,
    /// Whether to run this by default, or only if required.
    pub auto_run: Option<bool>,
    /// Run library: up-rs library to use for this task. Either use this or
    /// `run_cmd` + `check_cmd`.
    pub run_lib: Option<String>,
    /// Check command: only run the `run_cmd` if this command returns a non-zero
    /// exit code.
    pub check_cmd: Option<Vec<String>>,
    /// Run command: command to run to perform the update.
    pub run_cmd: Option<Vec<String>>,
    /// Set of data provided to the Run library.
    pub data: Option<toml::Value>,
    /// Description of the task.
    pub description: Option<String>,
}

/// Shell commands we run.
#[derive(Debug)]
pub enum CommandType {
    /// check_cmd field in the toml.
    Check,
    /// run_cmd field in the toml.
    Run,
}

impl Task {
    pub fn from(path: &Path) -> Result<Self> {
        let start_time = Instant::now();
        let s = fs::read_to_string(&path).map_err(|e| TasksError::ReadFile {
            path: path.to_owned(),
            source: e,
        })?;
        trace!("Task '{:?}' contents: <<<{}>>>", &path, &s);
        let config = toml::from_str::<TaskConfig>(&s).map_err(|e| TasksError::InvalidToml {
            path: path.to_owned(),
            source: e,
        })?;
        let name = match &config.name {
            Some(n) => n.clone(),
            None => path
                .file_stem()
                .ok_or_else(|| anyhow!("Task had no path."))?
                .to_str()
                .ok_or(TasksError::None {})?
                .to_owned(),
        };
        let status = TaskStatus::New;
        let task = Self {
            name,
            path: path.to_owned(),
            config,
            status,
            start_time,
        };
        debug!("Task '{}': {:?}", &task.name, task);
        Ok(task)
    }

    pub fn try_start<F>(&mut self, env_fn: F, env: &HashMap<String, String>) -> Result<()>
    where
        F: Fn(&str) -> Result<String>,
    {
        // TODO(gib): actually check whether we're blocked.

        self.status = TaskStatus::Blocked;
        self.start(env_fn, env)
    }

    // TODO(gib): Test for this (using basic config).
    pub fn start<F>(&mut self, env_fn: F, env: &HashMap<String, String>) -> Result<()>
    where
        F: Fn(&str) -> Result<String>,
    {
        info!("Running task '{}'", &self.name);
        self.status = TaskStatus::Passed;

        if let Some(lib) = &self.config.run_lib {
            let run_lib_result = match lib.as_str() {
                "link" => {
                    let mut data = self
                        .config
                        .data
                        .as_ref()
                        .ok_or_else(|| anyhow!("Task '{}' data had no value.", &self.name))?
                        .clone()
                        .try_into::<LinkOptions>()?;
                    data.resolve_env(env_fn)?;
                    tasks::link::run(data)
                }
                "git" => {
                    let mut data = self
                        .config
                        .data
                        .as_ref()
                        .ok_or_else(|| anyhow!("Task '{}' data had no value.", &self.name))?
                        .clone()
                        .try_into::<Vec<GitConfig>>()?;
                    data.resolve_env(env_fn)?;
                    tasks::git::run(data)
                }
                "generate_git" => {
                    let mut data = self
                        .config
                        .data
                        .as_ref()
                        .ok_or_else(|| anyhow!("Task '{}' data had no value.", &self.name))?
                        .clone()
                        .try_into::<Vec<GenerateGitConfig>>()?;
                    data.resolve_env(env_fn)?;
                    generate::git::run(&data)
                }
                "defaults" => {
                    let mut data = self
                        .config
                        .data
                        .as_ref()
                        .ok_or_else(|| anyhow!("Task '{}' data had no value.", &self.name))?
                        .clone()
                        .try_into::<DefaultsConfig>()?;
                    data.resolve_env(env_fn)?;
                    tasks::defaults::run(data)
                }
                "self" => {
                    let options = if let Some(raw_data) = self.config.data.as_ref() {
                        let mut raw_opts = raw_data.clone().try_into::<UpdateSelfOptions>()?;
                        raw_opts.resolve_env(env_fn)?;
                        raw_opts
                    } else {
                        UpdateSelfOptions::default()
                    };
                    tasks::update_self::run(&options)
                }
                _ => Err(anyhow!("This run_lib is invalid or not yet implemented.")),
            };
            if let Err(e) = run_lib_result {
                self.status = TaskStatus::Failed(e);
            } else {
                self.status = TaskStatus::Passed;
            }
            return Ok(());
        }

        if let Some(mut cmd) = self.config.check_cmd.clone() {
            debug!("Running '{}' check command.", &self.name);
            for s in &mut cmd {
                *s = env_fn(s)?;
            }
            let check_output = self.run_check_cmd(&cmd, env)?;
            // TODO(gib): Allow choosing how to validate check_cmd output (stdout, zero exit
            // code, non-zero exit code).
            if check_output.status.success() {
                debug!("Skipping task '{}' as check command passed.", &self.name);
                self.status = TaskStatus::Skipped;
                return Ok(());
            }
        } else {
            // TODO(gib): Make a warning and allow silencing by setting check_cmd to boolean
            // false.
            debug!(
                "You haven't specified a check command for '{}', so it will always be run",
                &self.name
            )
        }

        if let Some(mut cmd) = self.config.run_cmd.clone() {
            debug!("Running '{}' run command.", &self.name);
            for s in &mut cmd {
                *s = env_fn(s)?;
            }
            let (child, start_time) = Self::start_command(&cmd, env)?;
            self.status = TaskStatus::Running(child, start_time);
            return Ok(());
        }

        bail!(TasksError::MissingCmd {
            name: self.name.clone()
        });
    }

    /// If command has completed set output state.
    pub fn try_finish(&mut self) -> Result<()> {
        let (child, start_time) = match &mut self.status {
            TaskStatus::Running(child, start_time) => (child, start_time),
            _ => bail!(anyhow!("Can't finish non-running task.")),
        };

        if let Some(status) = child.try_wait()? {
            debug!("Task '{}' complete.", &self.name);
            let elapsed_time = start_time.elapsed();

            let mut stdout = String::new();
            child
                .stdout
                .as_mut()
                .ok_or_else(|| anyhow!("Missing stdout"))?
                .read_to_string(&mut stdout)?;

            let mut stderr = String::new();
            child
                .stderr
                .as_mut()
                .ok_or_else(|| anyhow!("Missing stderr"))?
                .read_to_string(&mut stderr)?;

            self.log_command_output(CommandType::Run, status, &stdout, &stderr, elapsed_time);
            if status.success() {
                self.status = TaskStatus::Passed;
            } else {
                // TODO(gib): Error should include an easy way to see the task logs.
                self.status = TaskStatus::Failed(anyhow!("Task {} failed.", self.name));
            }
        } else {
            // Still running.
            // trace!("Task '{}' still in progress.", &self.name);
        }

        Ok(())
    }

    pub fn run_check_cmd(&self, cmd: &[String], env: &HashMap<String, String>) -> Result<Output> {
        let mut command = Self::get_command(cmd, env)?;

        let now = Instant::now();
        let output = command.output().map_err(|e| TasksError::CheckCmdFailed {
            name: self.name.clone(),
            cmd: cmd.into(),
            source: e,
        })?;

        let elapsed_time = now.elapsed();
        let stdout = String::from_utf8_lossy(&output.stdout);
        let stderr = String::from_utf8_lossy(&output.stderr);

        self.log_command_output(
            CommandType::Check,
            output.status,
            &stdout,
            &stderr,
            elapsed_time,
        );
        Ok(output)
    }

    pub fn start_command(
        cmd: &[String],
        env: &HashMap<String, String>,
    ) -> Result<(Child, Instant)> {
        let command = Self::get_command(cmd, env);
        let now = Instant::now();
        let child = command?
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()?;
        Ok((child, now))
    }

    pub fn get_command(cmd: &[String], env: &HashMap<String, String>) -> Result<Command> {
        // TODO(gib): set current dir.
        let mut command = Command::new(
            &cmd.get(0)
                .ok_or_else(|| anyhow!("Task '{}' command was empty."))?,
        );
        command
            .args(cmd.get(1..).unwrap_or(&[]))
            .env_clear()
            .envs(env.iter())
            .stdin(Stdio::inherit());
        trace!("Running command: {:?}", &command);
        Ok(command)
    }

    pub fn log_command_output(
        &self,
        command_type: CommandType,
        status: ExitStatus,
        stdout: &str,
        stderr: &str,
        elapsed_time: Duration,
    ) {
        // | Command | Result | Status  | Stdout/Stderr |
        // | ---     | ---    | ---     | ---           |
        // | Check   | passes | `debug` | `debug`       |
        // | Run     | passes | `debug` | `debug`       |
        // | Check   | fails  | `info`  | `debug`       |
        // | Run     | fails  | `error` | `error`       |
        let (level, stdout_stderr_level) = match (command_type, status.success()) {
            (_, true) => (Level::Debug, Level::Debug),
            (CommandType::Run, false) => (Level::Error, Level::Error),
            (CommandType::Check, false) => (Level::Info, Level::Debug),
        };

        // TODO(gib): How do we separate out the task output?
        // TODO(gib): Document error codes.
        log!(
            level,
            "Task '{}' command ran in {:?} with status: {}",
            &self.name,
            elapsed_time,
            status
        );
        if !stdout.is_empty() {
            log!(
                stdout_stderr_level,
                "Task '{}' command stdout:\n<<<\n{}>>>\n",
                &self.name,
                stdout,
            );
        }
        if !stderr.is_empty() {
            log!(
                stdout_stderr_level,
                "Task '{}' command stderr:\n<<<\n{}>>>\n",
                &self.name,
                stderr
            );
        }
    }
}