onetaskgraph 0.3.4

One interface over the ticketing systems your work lives in.
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
//! `task create`, `project create`, `document create`, `task render`, `project render`,
//! `document render`, `task answers`, `project answers` and `document answers`: items created
//! from a body or a template, regenerated in place, and the answers stored beside them.
//!
//! What lives here is what only a command line has — the flags, the files and standard input
//! they are read from, and the prompts. Creating, regenerating and reading answers are the
//! engine's (`onetaskgraph_core::Engine::create_task` and its siblings), so a Rust caller and
//! this binary cannot do them differently.

use std::collections::{BTreeMap, HashSet};
use std::io::{self, Read as _, Write};
use std::path::{Path, PathBuf};
use std::str::FromStr as _;

use onetaskgraph_core::{
    Body, DocumentCreate, EngineError, Failure, GlobalId, Loaded, OutputFormat, ProjectCreate,
    RenderRequest, RenderTemplate, RenderedRecord, TaskCreate,
};
use onetaskgraph_plugin_api::{
    AssetName, AssetPayload, MetadataKey, NativeId, Repository, SourceName,
};
use serde_json::Value;

use crate::cli::{
    AnswersArgs, CreateBodyArgs, CreateItemArgs, DocumentCreateArgs, ProjectCreateArgs, RenderArgs,
    TaskCreateArgs,
};
use crate::template::{Refusal, answers_given, ask, input, refused};
use crate::{EXIT_OK, delivery_exit, emit, engine, json, qualified, render};

/// `task create`: create the task, then write its qualified id — or, under `--json`, the task
/// exactly as `task show --json` writes it.
pub(crate) async fn create_task(
    out: &mut impl Write,
    loaded: &Loaded,
    args: &TaskCreateArgs,
) -> Result<u8, Failure> {
    let item = match item(&args.item, loaded) {
        Ok(item) => item,
        Err(Refusal::Answers(message)) => return Ok(refused(&message)),
        Err(Refusal::Failed(failure)) => return Err(failure),
    };
    let depends_on = ids(&args.depends_on)?;
    let delivers = ids(&args.delivers)?;
    let assets = asset_files(&args.assets.asset)?;
    let engine = engine(loaded);
    let created = engine
        .create_task(&TaskCreate {
            source: item.source,
            project: item.project,
            title: args.item.title.clone(),
            body: item.body,
            status: args.status.map(|status| status.category()),
            labels: args.item.label.clone(),
            repositories: item.repositories,
            depends_on,
            delivers,
            metadata: item.metadata,
            assets,
        })
        .await
        .map_err(|error| Failure::from(&error))?;
    let id = created.task.id;
    match loaded.config.output() {
        OutputFormat::Text => emit(out, &id.to_string(), "the task's id")?,
        OutputFormat::Json => {
            let detail = engine
                .task_detail(&id)
                .await
                .map_err(|error| Failure::from(&error))?;
            emit(out, &json(&detail, "the task")?, "the task")?;
        }
    }
    Ok(delivery_exit(&created.delivered))
}

/// `document create`: create or replace the document, then write its qualified id — or,
/// under `--json`, the document exactly as `document show --json` writes it.
pub(crate) async fn create_document(
    out: &mut impl Write,
    loaded: &Loaded,
    args: &DocumentCreateArgs,
) -> Result<u8, Failure> {
    let item = match item(&args.item, loaded) {
        Ok(item) => item,
        Err(Refusal::Answers(message)) => return Ok(refused(&message)),
        Err(Refusal::Failed(failure)) => return Err(failure),
    };
    let assets = asset_files(&args.assets.asset)?;
    let engine = engine(loaded);
    let created = engine
        .create_document(&DocumentCreate {
            source: item.source,
            project: item.project,
            title: args.item.title.clone(),
            id: args.id.clone(),
            body: item.body,
            labels: args.item.label.clone(),
            repositories: item.repositories,
            metadata: item.metadata,
            assets,
        })
        .await
        .map_err(|error| Failure::from(&error))?;
    match loaded.config.output() {
        OutputFormat::Text => emit(out, &created.id.to_string(), "the document's id")?,
        OutputFormat::Json => {
            let detail = engine
                .document_detail(&created.id)
                .await
                .map_err(|error| Failure::from(&error))?;
            emit(out, &json(&detail, "the document")?, "the document")?;
        }
    }
    Ok(EXIT_OK)
}

/// `project create`: create or replace the project, then write its qualified id — or, under
/// `--json`, the project exactly as `project show --json` writes it.
pub(crate) async fn create_project(
    out: &mut impl Write,
    loaded: &Loaded,
    args: &ProjectCreateArgs,
) -> Result<u8, Failure> {
    let request = match project(args, loaded) {
        Ok(request) => request,
        Err(Refusal::Answers(message)) => return Ok(refused(&message)),
        Err(Refusal::Failed(failure)) => return Err(failure),
    };
    let engine = engine(loaded);
    let created = engine
        .create_project(&request)
        .await
        .map_err(|error| Failure::from(&error))?;
    match loaded.config.output() {
        OutputFormat::Text => emit(out, &created.id.to_string(), "the project's id")?,
        OutputFormat::Json => {
            let response = engine
                .project(&created.id)
                .await
                .map_err(|error| Failure::from(&error))?;
            emit(out, &json(&response, "the project")?, "the project")?;
        }
    }
    Ok(EXIT_OK)
}

/// `task render`, `project render` and `document render`: regenerate the item in place, asking — when
/// interactive — for what its base and the given answers leave unanswered.
///
/// A refusal of the answers — required variables left unanswered, an answer to no declared
/// variable or of the wrong type — is the invocation's mistake, and exits `2`.
pub(crate) async fn regenerate(
    out: &mut impl Write,
    loaded: &Loaded,
    record: RenderedRecord,
    args: &RenderArgs,
    assets: &[PathBuf],
) -> Result<u8, Failure> {
    let id = qualified(&args.id)?;
    let assets = asset_files(assets)?;
    match regenerated(out, loaded, record, &id, args, assets).await {
        Ok(()) => Ok(EXIT_OK),
        Err(Refusal::Answers(message)) => Ok(refused(&message)),
        Err(Refusal::Failed(failure)) => Err(failure),
    }
}

async fn regenerated(
    out: &mut impl Write,
    loaded: &Loaded,
    record: RenderedRecord,
    id: &GlobalId,
    args: &RenderArgs,
    assets: Vec<AssetPayload>,
) -> Result<(), Refusal> {
    let template = input(
        args.template.as_deref(),
        &args.search_path,
        args.template_loader.as_deref(),
        args.answers.as_deref(),
    )?;
    let engine = engine(loaded);
    let regeneration = engine
        .regeneration(
            record,
            id,
            &RenderRequest {
                template: template.map_or_else(
                    || RenderTemplate::Recorded {
                        search_path: args.search_path.clone(),
                    },
                    RenderTemplate::Given,
                ),
                assets,
                ..RenderRequest::default()
            },
        )
        .await
        .map_err(refusal)?;
    // An unset of a name the template does not declare would drop nothing and say nothing.
    let declared: Vec<&str> = regeneration
        .template()
        .variables()
        .iter()
        .map(|variable| variable.name())
        .collect();
    if let Some(undeclared) = args
        .unset
        .iter()
        .find(|name| !declared.contains(&name.as_str()))
    {
        return Err(Refusal::Answers(format!(
            "--unset {undeclared}: the template declares no variable of that name, so there is \
             no answer to drop\n\
             next: unset one of {}, or leave the flag out.",
            declared.join(", ")
        )));
    }
    let mut given = answers_given(args.answers.as_deref(), &args.var)?;
    for name in &args.unset {
        given.unset(name.clone());
    }
    // Nothing the base settles, and nothing a caller unset, is asked for again: the first is
    // this item's own answer, and the second is a caller asking for the default.
    let settled: HashSet<String> = regeneration
        .settled()
        .map(str::to_owned)
        .chain(args.unset.iter().cloned())
        .collect();
    let answers = ask(
        loaded,
        regeneration.template(),
        regeneration.base().overlay(&given),
        &settled,
    )?;
    let regenerated = engine
        .regenerate(&regeneration, &answers, args.dry_run)
        .await
        .map_err(refusal)?;
    let rendered = match loaded.config.output() {
        OutputFormat::Text => render::regenerated(&regenerated, args.dry_run),
        OutputFormat::Json => json(&regenerated, "the rendering")?,
    };
    emit(out, rendered.trim_end(), "the rendering")?;
    Ok(())
}

/// The image assets `paths` name, each read whole and named by its file's base name.
///
/// Refused by name before anything is built or asked: a base name that is not an asset name —
/// an extension outside .png, .jpg, .jpeg, .gif and .webp among them — two paths with one base
/// name, and a file that cannot be read.
fn asset_files(paths: &[PathBuf]) -> Result<Vec<AssetPayload>, Failure> {
    let mut assets: Vec<AssetPayload> = Vec::with_capacity(paths.len());
    for path in paths {
        let base = path
            .file_name()
            .and_then(|name| name.to_str())
            .unwrap_or_default();
        let name = AssetName::new(base).map_err(|problem| {
            Failure::decided(
                "asset-name",
                format!(
                    "--asset {}: {problem}\n\
                     next: rename the file to a bare name ending in one of those extensions, \
                     and reference it as `![alt](./<name>)`.",
                    path.display()
                ),
            )
        })?;
        if let Some(earlier) = assets.iter().position(|held| held.name == name) {
            return Err(Failure::decided(
                "asset-given-twice",
                format!(
                    "--asset {} and --asset {} have one base name, {name}, and an asset is \
                     stored under its base name\n\
                     next: rename one of the two files.",
                    paths[earlier].display(),
                    path.display()
                ),
            ));
        }
        let bytes = std::fs::read(path).map_err(|error| {
            Failure::decided(
                "asset-unreadable",
                format!(
                    "--asset {}: the file could not be read: {error}\n\
                     next: name an image file this process can read.",
                    path.display()
                ),
            )
        })?;
        assets.push(AssetPayload::of(name, bytes));
    }
    Ok(assets)
}

/// `task answers`, `project answers` and `document answers`: the answers stored beside the item, as YAML — or,
/// under `--json`, as one JSON object.
pub(crate) async fn stored(
    out: &mut impl Write,
    loaded: &Loaded,
    record: RenderedRecord,
    args: &AnswersArgs,
) -> Result<u8, Failure> {
    let id = qualified(&args.id)?;
    let answers = engine(loaded)
        .template_answers(record, &id)
        .await
        .map_err(|error| Failure::from(&error))?;
    let rendered = match loaded.config.output() {
        OutputFormat::Json => json(&answers, "the answers")?,
        OutputFormat::Text => answers.to_yaml().map_err(|error| {
            Failure::decided("render", format!("could not render the answers: {error}"))
        })?,
    };
    emit(out, rendered.trim_end(), "the answers")?;
    Ok(EXIT_OK)
}

/// A refusal of the answers exits `2`; every other engine refusal is the command failing.
fn refusal(error: EngineError) -> Refusal {
    match &error {
        EngineError::MissingAnswers { .. } => Refusal::Answers(error.to_string()),
        EngineError::Template { error } if error.refuses_answers() => {
            Refusal::Answers(error.to_string())
        }
        _ => Refusal::Failed(Failure::from(&error)),
    }
}

/// What every create names, read and checked before any source is built.
struct Item {
    source: SourceName,
    project: NativeId,
    body: Body,
    repositories: Vec<Repository>,
    metadata: BTreeMap<MetadataKey, Value>,
}

/// Read a create's item: its source, project, repositories and metadata checked, and its
/// body rendered — asking, when interactive, for what the answers leave unanswered.
fn item(args: &CreateItemArgs, loaded: &Loaded) -> Result<Item, Refusal> {
    let source = source_name(&args.source)?;
    // Qualified with the source it is created in, a project is that source's own; qualified
    // with any other configured source it names a project the item cannot be filed under, and is
    // refused rather than read as a native id full of colons. A prefix naming no configured
    // source is part of a native id, as `task list --project` reads one.
    let project = match GlobalId::from_str(&args.project) {
        Ok(id) if id.source == source => id.native,
        Ok(id) if loaded.config.sources().contains_key(&id.source) => {
            return Err(Refusal::Failed(Failure::decided(
                "project-in-another-source",
                format!(
                    "--project {}: that project is in source {}, and this creates in {source}; an \
                     item is filed under a project of its own source\n\
                     next: name a project of {source}, or create the item in {}.",
                    args.project, id.source, id.source
                ),
            )));
        }
        Ok(_) | Err(_) => NativeId::from(args.project.as_str()),
    };
    let repositories = repositories(&args.repository)?;
    let metadata = metadata(&args.metadata)?;
    let body = body(&args.body, loaded)?;
    Ok(Item {
        source,
        project,
        body,
        repositories,
        metadata,
    })
}

/// Read a project create: its source, repositories and metadata checked, and its body
/// rendered — asking, when interactive, for what the answers leave unanswered. A label or a
/// repository given replaces what a project being replaced holds, and none given keeps it.
fn project(args: &ProjectCreateArgs, loaded: &Loaded) -> Result<ProjectCreate, Refusal> {
    let source = source_name(&args.source)?;
    let repositories = repositories(&args.repository)?;
    let metadata = metadata(&args.metadata)?;
    let body = body(&args.body, loaded)?;
    Ok(ProjectCreate {
        source,
        id: args.id.clone(),
        title: args.title.clone(),
        body,
        status: args.status.map(|status| status.category()),
        labels: (!args.label.is_empty()).then(|| args.label.clone()),
        repositories: (!repositories.is_empty()).then_some(repositories),
        metadata,
    })
}

/// The configured source a create names, refused naming the problem.
fn source_name(name: &str) -> Result<SourceName, Refusal> {
    SourceName::new(name.to_owned()).map_err(|error| {
        Refusal::Failed(Failure::decided(
            "invalid-source-name",
            format!(
                "{name}: {error}\n\
                 next: name a configured source — `onetaskgraph sources list` reports them."
            ),
        ))
    })
}

/// Every `--repository`, each refused unless it is a normalized origin.
fn repositories(given: &[String]) -> Result<Vec<Repository>, Refusal> {
    given
        .iter()
        .map(|origin| {
            Repository::try_from(origin.clone()).map_err(|error| {
                Refusal::Failed(Failure::decided(
                    "invalid-repository",
                    format!(
                        "--repository {origin}: {error}\n\
                         next: name it by its normalized origin, such as \
                         github.com/owner/name."
                    ),
                ))
            })
        })
        .collect()
}

/// Every `--metadata KEY=JSON`, each refused naming the problem.
fn metadata(given: &[String]) -> Result<BTreeMap<MetadataKey, Value>, Refusal> {
    given
        .iter()
        .map(|entry| metadata_entry(entry).map_err(Refusal::Failed))
        .collect()
}

/// One `--metadata KEY=JSON`: a caller's own key, and exactly one JSON value.
pub(crate) fn metadata_entry(entry: &str) -> Result<(MetadataKey, Value), Failure> {
    let Some((key, value)) = entry.split_once('=') else {
        return Err(Failure::decided(
            "invalid-metadata-key",
            format!(
                "--metadata {entry}: that is not KEY=JSON\n\
                 next: write it as --metadata myapp.key='\"value\"'."
            ),
        ));
    };
    let key = MetadataKey::new(key).map_err(|message| {
        Failure::decided(
            "invalid-metadata-key",
            format!("--metadata {entry}: {message}"),
        )
    })?;
    let value = serde_json::from_str(value).map_err(|error| {
        Failure::decided(
            "invalid-metadata-value",
            format!(
                "--metadata {entry}: the value is not JSON: {error}\n\
                 next: pass exactly one JSON value — quote a string as '\"text\"'."
            ),
        )
    })?;
    Ok((key, value))
}

/// A create's body: rendered from a template or a loader document, read from `--body-file`,
/// or read from standard input.
fn body(args: &CreateBodyArgs, loaded: &Loaded) -> Result<Body, Refusal> {
    if let Some(input) = input(
        args.template.as_deref(),
        &args.search_path,
        args.template_loader.as_deref(),
        args.answers.as_deref(),
    )? {
        let template = input.load()?;
        let answers = ask(
            loaded,
            &template,
            answers_given(args.answers.as_deref(), &args.var)?,
            &HashSet::new(),
        )?;
        let rendered = template.render(&answers)?;
        return Ok(Body::rendered(&input, rendered)?);
    }
    plain(args.body_file.as_deref()).map(Body::plain)
}

/// A plain body, byte for byte from `path`, or from standard input without one.
fn plain(path: Option<&Path>) -> Result<String, Refusal> {
    let (bytes, from) = match path {
        Some(path) => (
            std::fs::read(path).map_err(|error| {
                Refusal::Failed(Failure::decided(
                    "body-file",
                    format!(
                        "--body-file {}: could not read it: {error}\n\
                         next: name a readable file, or leave --body-file out and pass the body \
                         on standard input.",
                        path.display()
                    ),
                ))
            })?,
            format!("--body-file {}", path.display()),
        ),
        None => {
            let mut bytes = Vec::new();
            io::stdin().read_to_end(&mut bytes).map_err(|error| {
                Refusal::Failed(Failure::decided(
                    "body-file",
                    format!(
                        "could not read the body from standard input: {error}\n\
                         next: pass the body with --body-file PATH, or render it with \
                         --template FILE."
                    ),
                ))
            })?;
            (bytes, "standard input".to_owned())
        }
    };
    String::from_utf8(bytes).map_err(|error| {
        Refusal::Failed(Failure::decided(
            "body-file",
            format!(
                "the body on {from} is not UTF-8 text: {error}\n\
                 next: save the body as UTF-8 and pass it again."
            ),
        ))
    })
}

/// Every `--depends-on` or `--delivers`, refused before any source is built unless each is
/// qualified: a bare id would be read as naming a task of the source being created in, which a
/// caller copying another source's id did not mean.
fn ids(given: &[String]) -> Result<Vec<GlobalId>, Failure> {
    given.iter().map(|id| qualified(id)).collect()
}