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
use std::{
collections::{HashMap, HashSet},
io,
path::PathBuf,
process::Command,
thread, time,
};
use anyhow::{anyhow, Context, Result};
use displaydoc::Display;
use log::{debug, error, info, trace, warn};
use thiserror::Error;
use self::TasksError as E;
use crate::{config, env::get_env};
pub mod defaults;
pub mod git;
pub mod link;
pub mod task;
pub mod update_self;
pub trait ResolveEnv {
fn resolve_env<F>(&mut self, _env_fn: F) -> Result<()>
where
F: Fn(&str) -> Result<String>,
{
Ok(())
}
}
#[derive(Error, Debug)]
pub enum TaskError {
#[error("Env lookup error, please define '{}' in your up.toml:", var)]
ResolveEnv { var: String, source: anyhow::Error },
}
pub fn run(config: &config::UpConfig, tasks_dirname: &str) -> Result<()> {
let mut tasks_dir = config.up_toml_path.as_ref().ok_or(E::None {})?.clone();
tasks_dir.pop();
tasks_dir.push(tasks_dirname);
let env = get_env(
config.config_toml.inherit_env.as_ref(),
config.config_toml.env.as_ref(),
)?;
if config.config_toml.needs_sudo {
debug!("Prompting for superuser privileges with 'sudo -v'");
Command::new("sudo").arg("-v").output()?;
}
#[cfg(target_os = "macos")]
Command::new("caffeinate")
.args(&["-ds", "-w", &std::process::id().to_string()])
.spawn()?;
let mut bootstrap_tasks = match (config.bootstrap, &config.config_toml.bootstrap_tasks) {
(false, _) => Ok(Vec::new()),
(true, None) => Err(anyhow!(
"Bootstrap flag set but no bootstrap_tasks specified in config."
)),
(true, Some(b_tasks)) => Ok(b_tasks.clone()),
}?;
bootstrap_tasks.reverse();
let filter_tasks_set: Option<HashSet<String>> =
config.tasks.clone().map(|v| v.into_iter().collect());
#[allow(clippy::filter_map)]
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 = entry.path();
if !path.exists() && path.symlink_metadata().is_ok() {
warn!(
"Failed to read task, broken symlink or file permissions issue? {}",
path.display()
);
continue;
}
let task = task::Task::from(&path)?;
if let Some(filter) = filter_tasks_set.as_ref() {
if !filter.contains(&task.name) {
debug!(
"Not running task '{}' as not in tasks filter {:?}",
&task.name, &filter
);
continue;
}
}
tasks.insert(task.name.clone(), task);
}
debug!("Task count: {:?}", tasks.len());
trace!("Task list: {:#?}", tasks);
run_tasks(bootstrap_tasks, tasks, &env)
}
fn run_tasks(
mut bootstrap_tasks: Vec<String>,
mut tasks: HashMap<String, task::Task>,
env: &HashMap<String, String>,
) -> Result<()> {
let env_fn = &|s: &str| {
let out = shellexpand::full_with_context(s, dirs::home_dir, |k| {
env.get(k)
.ok_or_else(|| anyhow!("Value not found"))
.map(Some)
})
.map(std::borrow::Cow::into_owned)
.map_err(|e| TaskError::ResolveEnv {
var: e.var_name,
source: e.cause,
})?;
Ok(out)
};
#[allow(clippy::filter_map)]
let post_bootstrap_tasks_to_run: Vec<String> = tasks
.iter()
.filter(|(_, task)| task.config.auto_run.unwrap_or(true))
.map(|(name, _)| name.clone())
.collect();
let mut bootstrap = !bootstrap_tasks.is_empty();
let mut tasks_to_run: HashSet<String> = HashSet::new();
if let Some(task) = bootstrap_tasks.pop() {
tasks_to_run.insert(task);
} else {
tasks_to_run.extend(post_bootstrap_tasks_to_run.iter().cloned())
}
let mut tasks_passed = Vec::new();
let mut tasks_skipped = Vec::new();
let mut tasks_failed = Vec::new();
let mut task_errors: Vec<anyhow::Error> = Vec::new();
let mut tasks_to_run_completed = Vec::new();
while !tasks_to_run.is_empty() {
thread::sleep(time::Duration::from_millis(10));
for name in &tasks_to_run {
let task = tasks
.get_mut(name)
.ok_or_else(|| anyhow!("Task '{}' was missing.", name))?;
match task.status {
task::TaskStatus::New => {
task.try_start(env_fn, env)?;
}
task::TaskStatus::Blocked => {
}
task::TaskStatus::Running(_, _) => {
task.try_finish()?;
}
task::TaskStatus::Failed(ref mut e) => {
tasks_to_run_completed.push(name.clone());
tasks_failed.push(name.clone());
let extracted_error = std::mem::replace(e, anyhow!(""));
task_errors.push(extracted_error);
}
task::TaskStatus::Passed => {
tasks_to_run_completed.push(name.clone());
tasks_passed.push(name.clone());
}
task::TaskStatus::Skipped => {
tasks_to_run_completed.push(name.clone());
tasks_skipped.push(name.clone());
}
}
}
for name in tasks_to_run_completed.drain(..) {
tasks_to_run.remove(&name);
}
if tasks_to_run.is_empty() {
if let Some(task) = bootstrap_tasks.pop() {
tasks_to_run.insert(task);
} else if bootstrap {
bootstrap = false;
tasks_to_run.extend(post_bootstrap_tasks_to_run.iter().cloned())
} else {
}
}
}
info!(
"Ran {} tasks, {} passed, {} failed, {} skipped",
tasks.len(),
tasks_passed.len(),
tasks_failed.len(),
tasks_skipped.len()
);
if !tasks_passed.is_empty() {
info!("Tasks passed: {:?}", tasks_passed);
}
if !tasks_skipped.is_empty() {
info!("Tasks skipped: {:?}", tasks_skipped);
}
if !tasks_failed.is_empty() {
error!("Tasks failed: {:#?}", tasks_failed);
error!("One or more tasks failed, exiting.");
return Err(anyhow!("")).with_context(|| {
let task_errors_string = task_errors
.into_iter()
.fold(String::new(), |acc, e| acc + &format!("\n- {:?}", e));
anyhow!("Task errors: {}", task_errors_string)
});
}
Ok(())
}
#[derive(Error, Debug, Display)]
pub enum TasksError {
ReadDir { path: PathBuf, source: io::Error },
ReadFile { path: PathBuf, source: io::Error },
EnvLookup { var: String, source: anyhow::Error },
MissingCmd { name: String },
CheckCmdFailed {
name: String,
source: io::Error,
cmd: Vec<String>,
},
None {},
InvalidToml {
path: PathBuf,
source: toml::de::Error,
},
}