willdo 0.0.1

Task manager with DAG
Documentation
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
#![doc = include_str!("README.md")]

mod entry;
#[cfg(test)]
mod tests;
mod yaml;

use self::entry::Entry;
use self::yaml::*;
use crate::{execution::BoxError, job::Relation};
use core::str::FromStr as _;
use glob::Paths;
use log::{debug, info};
use serde::Deserialize as _;
use serde_content::Value;
use std::{env, ffi::OsStr, fs, os::unix::ffi::OsStrExt, path::PathBuf};
use url::Url;

/// Load configuration from given url/path
pub fn load(
    what: impl Into<String>,
) -> impl IntoIterator<Item = Result<impl ConfigurationEntry, LoadError>> {
    Loader::Init {
        namespace: vec![],
        what: what.into().into_boxed_str(),
    }
}

/// Load configuration from given reader, using source for subsequent includes
pub fn read(
    what: impl std::io::Read + 'static,
    source: impl Into<String>,
) -> impl IntoIterator<Item = Result<impl ConfigurationEntry, LoadError>> {
    let source = Url::from_str(&source.into()).expect("invalid url");
    Loader::Reading {
        namespace: vec![],
        glob: vec![],
        skip: vec![],
        reader: serde_yaml::Deserializer::from_reader(what),
        source,
    }
}

/// Represents an entry that can be applied to [Configuration]
pub trait ConfigurationEntry: core::fmt::Debug {
    /// Apply the entry
    fn configure<C: Configuration>(self, config: &mut C) -> Result<(), C::Error>;
}

/// Represents a WillDo configuration
pub trait Configuration {
    /// Configuration errors
    type Error: core::error::Error;

    /// Add project configuration
    fn configure_project(
        &mut self,
        namespace: &[Box<str>],
        name: Box<str>,
        source: Url,
    ) -> Result<(), Self::Error>;

    /// Add interpretter configuration
    fn configure_interpretter(
        &mut self,
        namespace: &[Box<str>],
        name: Box<str>,
        source: Box<str>,
        provider: Box<str>,
        spec: Value<'static>,
    ) -> Result<(), Self::Error>;

    /// Add job configuration
    fn configure_job(
        &mut self,
        namespace: &[Box<str>],
        name: Box<str>,
        source: Box<str>,
        script: Vec<Box<str>>,
        interpretter: Option<Box<str>>,
        relations: Vec<Relation>,
    ) -> Result<(), Self::Error>;
}

#[derive(Default)]
enum Loader {
    Init {
        namespace: Vec<Box<str>>,
        what: Box<str>,
    },
    Loading {
        namespace: Vec<Box<str>>,
        glob: Vec<(Url, GlobIncluder)>,
        skip: Vec<Url>,
    },
    Reading {
        namespace: Vec<Box<str>>,
        glob: Vec<(Url, GlobIncluder)>,
        skip: Vec<Url>,
        reader: serde_yaml::Deserializer<'static>,
        source: Url,
    },
    #[default]
    Empty,
}

/// Config loader specific errors
#[derive(Debug, thiserror::Error)]
#[allow(missing_docs)]
pub enum LoadError {
    #[error("Unsupported configuration file type {0:?} for {1:?}")]
    InvalidConfigurationFileType(Option<Box<str>>, PathBuf),
    #[error("Invalid include reference {reference:?} at {source_url}")]
    InvalidIncludeUrl {
        reference: Box<str>,
        source_url: Box<str>,
        source: url::ParseError,
    },
    #[error("Invalid include reference {reference:?} at {source_url}")]
    InvalidIncludeGlob {
        reference: Box<str>,
        source_url: Box<str>,
        source: glob::PatternError,
    },
    #[error("Invalid config document: {source} at {source_url}")]
    InvalidDocument {
        source_url: Box<str>,
        source: BoxError,
    },
    #[error("Could not find included config: {what:?} in {base:?}")]
    IncludeNotFound { base: Box<str>, what: Box<str> },
    #[error("Error including config: {what:?} in {base:?} - {source}")]
    IncludeGlobError {
        base: Box<str>,
        what: Box<str>,
        source: glob::GlobError,
    },
    #[error("Error including config: {path:?} - {source}")]
    ErrorReadingConfig {
        path: PathBuf,
        source: std::io::Error,
    },
}

impl Iterator for Loader {
    type Item = Result<Entry, LoadError>;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            let mut job = None;
            *self = match core::mem::take(self) {
                empty @ Loader::Empty => empty,
                Loader::Init { namespace, what } => {
                    let cwd = env::current_dir().expect("CWD");
                    let cwd = cwd.to_str().expect("CWD");
                    let cwd = Url::parse(&format!("file://{cwd}/")).expect("CWD");
                    let mut glob = vec![];
                    let skip = vec![];
                    if let Err(e) = discover_config(&mut glob, &cwd, what) {
                        return Some(Err(e));
                    }
                    Loader::Loading {
                        namespace,
                        glob,
                        skip,
                    }
                }
                Loader::Loading {
                    namespace,
                    mut glob,
                    skip,
                } => {
                    let (base, entry) = loop {
                        let (base, paths) = glob.last_mut()?;
                        let Some(entry) = paths.next() else {
                            glob.pop();
                            continue;
                        };
                        break (base, entry);
                    };
                    let path = match entry {
                        Ok(p) => p,
                        Err(e) => return Some(Err(e)),
                    };
                    let source = base
                        .join(path.to_str().expect("config URL"))
                        .expect("config URL");
                    match load_config(namespace, glob, skip, source) {
                        Err(e) => return Some(Err(e)),
                        Ok(it) => it,
                    }
                }
                Loader::Reading {
                    namespace,
                    mut glob,
                    skip,
                    mut reader,
                    source,
                } => match reader.next() {
                    None => Loader::Loading {
                        namespace,
                        glob,
                        skip,
                    },
                    Some(document) => {
                        let doc = match Doc::deserialize(document) {
                            Ok(doc) => doc,
                            Err(e) => {
                                return Some(Err(LoadError::InvalidDocument {
                                    source_url: source.as_str().into(),
                                    source: e.into(),
                                }))
                            }
                        };

                        job = match doc {
                            Doc::Job(job) => Some(Entry::job(&namespace, &source, job)),
                            Doc::Interpretter(interpretter) => {
                                Some(Entry::interpretter(&namespace, &source, interpretter))
                            }
                            Doc::Empty => None,
                            Doc::Project { project } => {
                                Some(Entry::project(&namespace, &source, project))
                            }
                            Doc::Include(references) => {
                                for reference in references.into_iter().rev() {
                                    if let Err(e) = discover_config(&mut glob, &source, reference) {
                                        return Some(Err(e));
                                    }
                                }
                                None
                            }
                        };
                        Loader::Reading {
                            namespace,
                            glob,
                            skip,
                            reader,
                            source,
                        }
                    }
                },
            };
            if let Some(job) = job {
                break Some(Ok(job));
            }
            if let Loader::Empty = self {
                break None;
            }
        }
    }
}

fn load_config(
    namespace: Vec<Box<str>>,
    mut glob: Vec<(Url, GlobIncluder)>,
    mut skip: Vec<Url>,
    source: Url,
) -> Result<Loader, LoadError> {
    if skip.contains(&source) {
        return Ok(Loader::Loading {
            namespace,
            glob,
            skip,
        });
    }
    skip.push(source.clone());

    if source.scheme() != "file" {
        todo!("other means of configuration - {}", source.scheme())
    }

    let mut path = PathBuf::from(source.path());

    if path.is_dir() {
        path.push("*.willdo.*");
        let glob_includer = GlobIncluder::new(
            path.to_str().expect("dir path glob"),
            path.to_str().unwrap_or_default(),
            &source,
        );
        glob.push((source, glob_includer?));
        return Ok(Loader::Loading {
            namespace,
            glob,
            skip,
        });
    }

    let extension = path
        .extension()
        .and_then(OsStr::to_str)
        .map(str::to_ascii_lowercase)
        .map(Into::<Box<str>>::into);
    let reader: serde_yaml::Deserializer<'_> = match extension {
        Some(ext) => match ext.as_ref() {
            "yml" | "yaml" => {
                info!("loading {source}");
                let reader = fs::File::open(&path)
                    .map_err(|source| LoadError::ErrorReadingConfig { path, source })?;

                serde_yaml::Deserializer::from_reader(reader)
            }
            _ => return Err(LoadError::InvalidConfigurationFileType(Some(ext), path)),
        },
        None => return Err(LoadError::InvalidConfigurationFileType(None, path)),
    };
    Ok(Loader::Reading {
        namespace,
        glob,
        skip,
        reader,
        source,
    })
}
fn discover_config(
    glob: &mut Vec<(Url, GlobIncluder)>,
    base: &Url,
    what: Box<str>,
) -> Result<(), LoadError> {
    let url = Url::options()
        .base_url(Some(base))
        .parse(&what)
        .map_err(|source| LoadError::InvalidIncludeUrl {
            source_url: base.as_str().into(),
            reference: what.clone(),
            source,
        })?;

    if url.scheme() == "file" {
        debug!("discovering {what:?} in {base:?}");
        glob.push((base.clone(), GlobIncluder::new(url.path(), &what, base)?));
    } else {
        todo!("other means of configuration - {}", url.scheme())
    }
    Ok(())
}

struct GlobIncluder {
    paths: Paths,
    some: bool,
    what: Box<str>,
    base: Box<str>,
}

impl GlobIncluder {
    pub fn new(pattern: &str, what: &str, base: &Url) -> Result<Self, LoadError> {
        let opts = glob::MatchOptions {
            case_sensitive: true,
            require_literal_separator: true,
            require_literal_leading_dot: true,
        };

        Ok(Self {
            paths: glob::glob_with(pattern, opts).map_err(|source| {
                LoadError::InvalidIncludeGlob {
                    source,
                    reference: what.into(),
                    source_url: base.as_str().into(),
                }
            })?,
            some: false,
            what: what.into(),
            base: base.as_str().into(),
        })
    }
}
impl Iterator for GlobIncluder {
    type Item = Result<PathBuf, LoadError>;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            let next = self.paths.next().map(|r| match r {
                Ok(p) => Ok(p),
                Err(source) => Err(LoadError::IncludeGlobError {
                    source,
                    base: self.base.clone(),
                    what: self.what.clone(),
                }),
            });
            break match next {
                Some(Ok(ref path)) => {
                    match path
                        .as_os_str()
                        .as_bytes()
                        .windows(3)
                        .last()
                        .unwrap_or_default()
                    {
                        [_, b'/', b'.'] | [b'.', b'.'] | [b'/', b'.', b'.'] => {
                            debug!("skipping {:?}", path);
                            continue;
                        }
                        _ => {
                            info!("discovered {path:?}",);
                            self.some = true;
                            next
                        }
                    }
                }
                Some(Err(e)) => Some(Err(e)),
                None if self.some => None,
                None => Some(Err(LoadError::IncludeNotFound {
                    base: self.base.clone(),
                    what: self.what.clone(),
                })),
            };
        }
    }
}