onetaskgraph 0.2.25

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
//! What a person sees.
//!
//! Machine-readable output is the response types themselves, serialised — a stable
//! contract an SDK is generated from, and validated in the journeys against the schema
//! this binary emits. Everything in this file is the *other* output: minimal, aligned,
//! and deliberately not a second contract. Nothing here reshapes a response; it renders
//! one.
//!
//! Every vocabulary a line spells — a status category, a predicate, a dependency kind —
//! is taken from the type's own `Serialize`, never from a `match` written out again
//! here. A second spelling of `in-progress` in this file would be a second place for it
//! to drift from the one a filter compares against.

use onetaskgraph_core::{
    CopyReport, Predicate, Qualified, QualifiedEdge, QueryPlan, SearchHit, SourceListing,
    SourceState,
};
use onetaskgraph_plugin_api::{Capabilities, Document, Label, Location, Project, Support, Task};
use serde::Serialize;

/// One value as the wire spells it — `in-progress`, `search-title`, `blocks`.
///
/// Every caller passes a unit-like enum of the contract, which serialises to a quoted
/// string and cannot fail; stripping the quotes is the whole of the work. Taking the
/// spelling from `Serialize` rather than from a `match` written out again here is what
/// stops a second spelling of `in-progress` existing to drift from the one a filter
/// compares against.
fn wire(value: &impl Serialize) -> String {
    serde_json::to_string(value)
        .expect("a contract enum serialises")
        .trim_matches('"')
        .to_owned()
}

/// Lay `rows` out as aligned columns, one line each.
///
/// The last column is never padded, so nothing trails a line with blanks that a shell
/// pipeline would then have to strip.
fn columns(rows: &[Vec<String>]) -> String {
    let width = rows.iter().map(Vec::len).max().unwrap_or(0);
    let widths: Vec<usize> = (0..width)
        .map(|column| {
            rows.iter()
                .filter_map(|row| row.get(column))
                .map(|cell| cell.chars().count())
                .max()
                .unwrap_or(0)
        })
        .collect();

    let mut rendered = String::new();
    for row in rows {
        let last = row.len().saturating_sub(1);
        for (index, cell) in row.iter().enumerate() {
            if index == last {
                rendered.push_str(cell);
            } else {
                let pad = widths[index].saturating_sub(cell.chars().count());
                rendered.push_str(cell);
                rendered.push_str(&" ".repeat(pad));
                rendered.push_str("  ");
            }
        }
        rendered.push('\n');
    }
    rendered
}

/// One line per task: qualified id, normalised status, title.
///
/// The normalised category rather than the source's own wording, because this list
/// crosses sources and the category is the one vocabulary they share — and it is what
/// `--status` compares against. `task show` prints both.
pub fn tasks(items: &[Qualified<Task>]) -> String {
    columns(
        &items
            .iter()
            .map(|task| {
                vec![
                    task.id.to_string(),
                    wire(&task.item.status.category),
                    task.item.title.clone(),
                ]
            })
            .collect::<Vec<_>>(),
    )
}

/// Where an entity is, as one cell: which kind of place, then the place itself.
///
/// The key is the kind, read off the type's own `Serialize` rather than written out again
/// in a `match`, for the reason [`wire`] gives: `Location` is externally tagged with
/// exactly two variants, so what a consumer branches on in JSON is what a reader sees here.
fn located(location: &Location) -> String {
    let rendered = serde_json::to_value(location).expect("a contract enum serialises");
    let (kind, place) = rendered
        .as_object()
        .and_then(|object| object.iter().next())
        .expect("an externally tagged enum is an object of exactly one member");
    format!("{kind} {}", place.as_str().unwrap_or_default())
}

/// One line per document: qualified id, where it is, title.
///
/// Where a task list prints the normalised status, this prints the location: a document
/// has no status, and where it is is what a reader does something with — open the link, or
/// read the file out. A document whose source did not say prints `-`, which is not the
/// same as saying it is nowhere.
pub fn documents(items: &[Qualified<Document>]) -> String {
    columns(
        &items
            .iter()
            .map(|document| {
                vec![
                    document.id.to_string(),
                    document
                        .item
                        .location
                        .as_ref()
                        .map_or_else(|| "-".to_owned(), located),
                    document.item.title.clone(),
                ]
            })
            .collect::<Vec<_>>(),
    )
}

/// One line per project: qualified id, normalised status, title.
pub fn projects(items: &[Qualified<Project>]) -> String {
    columns(
        &items
            .iter()
            .map(|project| {
                vec![
                    project.id.to_string(),
                    wire(&project.item.status.category),
                    project.item.title.clone(),
                ]
            })
            .collect::<Vec<_>>(),
    )
}

/// One line per item a copy considered: where it came from, where it went, what happened.
///
/// A dry run that would create has no destination id to print, because nothing was
/// created and inventing one would be a claim about an id the destination never issued.
pub fn copied(report: &CopyReport) -> String {
    columns(
        &report
            .items
            .iter()
            .map(|outcome| {
                vec![
                    outcome.source.to_string(),
                    outcome
                        .destination()
                        .map_or_else(|| "-".to_owned(), ToString::to_string),
                    outcome.action.name(),
                ]
            })
            .collect::<Vec<_>>(),
    )
}

/// One line per label: qualified id and the name a filter types.
pub fn labels(items: &[Qualified<Label>]) -> String {
    columns(
        &items
            .iter()
            .map(|label| vec![label.id.to_string(), label.item.name.clone()])
            .collect::<Vec<_>>(),
    )
}

/// One line per edge: where it starts, what it means, where it points.
pub fn edges(items: &[QualifiedEdge]) -> String {
    columns(
        &items
            .iter()
            .map(|edge| {
                vec![
                    format!("{} {}", wire(&edge.from.kind), edge.from.id),
                    wire(&edge.kind),
                    format!("{} {}", wire(&edge.to.kind), edge.to.id),
                ]
            })
            .collect::<Vec<_>>(),
    )
}

/// One line per hit, saying which entity matched.
pub fn hits(items: &[SearchHit]) -> String {
    columns(
        &items
            .iter()
            .map(|hit| match hit {
                SearchHit::Task(task) => vec![
                    "task".to_owned(),
                    task.id.to_string(),
                    task.item.title.clone(),
                ],
                SearchHit::Project(project) => vec![
                    "project".to_owned(),
                    project.id.to_string(),
                    project.item.title.clone(),
                ],
            })
            .collect::<Vec<_>>(),
    )
}

/// One task in full, body last.
pub fn task_detail(task: &Qualified<Task>) -> String {
    let item = &task.item;
    let mut fields = vec![
        ("id", task.id.to_string()),
        ("title", item.title.clone()),
        (
            "status",
            format!("{} ({})", wire(&item.status.category), item.status.name),
        ),
    ];
    fields.push((
        "project",
        match &item.project {
            Some(project) => format!("{}:{project}", task.id.source),
            None => "none".to_owned(),
        },
    ));
    detail(
        &mut fields,
        &item.labels,
        item.url.as_deref(),
        item.location.as_ref(),
    );
    body(&fields, item.content.as_deref())
}

/// One document in full, body last.
///
/// No status line, because a document has none — and no dependency line, because it is in
/// no graph. What it has that a task does not print above its body is the same `location`
/// every entity now carries.
pub fn document_detail(document: &Qualified<Document>) -> String {
    let item = &document.item;
    let mut fields = vec![
        ("id", document.id.to_string()),
        ("title", item.title.clone()),
        (
            "project",
            match &item.project {
                Some(project) => format!("{}:{project}", document.id.source),
                None => "none".to_owned(),
            },
        ),
    ];
    detail(
        &mut fields,
        &item.labels,
        item.url.as_deref(),
        item.location.as_ref(),
    );
    body(&fields, item.content.as_deref())
}

/// One project in full, body last.
pub fn project_detail(project: &Qualified<Project>) -> String {
    let item = &project.item;
    let mut fields = vec![
        ("id", project.id.to_string()),
        ("title", item.title.clone()),
        (
            "status",
            format!("{} ({})", wire(&item.status.category), item.status.name),
        ),
    ];
    detail(
        &mut fields,
        &item.labels,
        item.url.as_deref(),
        item.location.as_ref(),
    );
    body(&fields, item.content.as_deref())
}

/// The fields a task, a project and a document share below their own.
///
/// `location` is a line of its own rather than folded into `url`, and it says which kind
/// of place it names: a reader handed one has to know whether to open a link or read a
/// file out, and the two are different actions. It does not replace `url` — a source that
/// reports one goes on reporting it, and both lines appear when a source gives both.
fn detail(
    fields: &mut Vec<(&'static str, String)>,
    item_labels: &[Label],
    url: Option<&str>,
    location: Option<&Location>,
) {
    if !item_labels.is_empty() {
        fields.push((
            "labels",
            item_labels
                .iter()
                .map(|label| label.name.clone())
                .collect::<Vec<_>>()
                .join(", "),
        ));
    }
    if let Some(url) = url {
        fields.push(("url", url.to_owned()));
    }
    if let Some(location) = location {
        fields.push(("location", located(location)));
    }
}

/// The field table, then the long-form body under a blank line.
fn body(fields: &[(&'static str, String)], content: Option<&str>) -> String {
    let mut rendered = columns(
        &fields
            .iter()
            .map(|(name, value)| vec![format!("{name}:"), value.clone()])
            .collect::<Vec<_>>(),
    );
    if let Some(content) = content.map(str::trim).filter(|body| !body.is_empty()) {
        rendered.push('\n');
        rendered.push_str(content);
        rendered.push('\n');
    }
    rendered
}

/// One line per configured source: what it is, and what it says it can do.
pub fn sources(listings: &[SourceListing]) -> String {
    columns(
        &listings
            .iter()
            .map(|listing| {
                vec![
                    listing.source.to_string(),
                    listing.kind.clone(),
                    match &listing.state {
                        SourceState::Available { capabilities } => declared(capabilities),
                        SourceState::Unavailable { error } => {
                            format!("unavailable — {error}")
                        }
                    },
                ]
            })
            .collect::<Vec<_>>(),
    )
}

/// What one source applies itself, in one line.
fn declared(capabilities: &Capabilities) -> String {
    let native: Vec<&str> = [
        ("label", capabilities.filter_by_label),
        ("status", capabilities.filter_by_status),
        ("search-title", capabilities.search_title),
        ("search-content", capabilities.search_content),
        ("project", capabilities.projects),
        ("orphan-tasks", capabilities.orphan_tasks),
    ]
    .into_iter()
    .filter(|(_, support)| *support == Support::Native)
    .map(|(name, _)| name)
    .collect();

    format!(
        "native: {}; deps: task {}, project {}; page <= {}",
        if native.is_empty() {
            "none".to_owned()
        } else {
            native.join(", ")
        },
        wire(&capabilities.task_dependencies),
        wire(&capabilities.project_dependencies),
        capabilities.max_page_size,
    )
}

/// The plan, per source, with only the lines that have something to say.
///
/// This is the whole reason capability declaration exists: two sources answer the same
/// query by two different plans and both answers are correct, and without this a caller
/// could only guess which of the two they got.
pub fn plan(plan: &QueryPlan) -> String {
    let mut rendered = String::from("plan:\n");
    if plan.per_source.is_empty() {
        rendered.push_str("  (no source was addressed)\n");
        return rendered;
    }
    for source in &plan.per_source {
        rendered.push_str(&format!(
            "  {} ({})  {} page(s)\n",
            source.source, source.kind, source.pages_fetched
        ));
        for (label, predicates) in [
            ("pushed down", &source.pushed_down),
            ("applied locally", &source.applied_locally),
            ("emulated", &source.emulated),
            ("unavailable", &source.unavailable),
        ] {
            if predicates.is_empty() {
                continue;
            }
            rendered.push_str(&format!("    {label}: {}\n", predicate_list(predicates)));
        }
    }
    rendered
}

/// Predicate names, in the wire spelling `--json` publishes.
fn predicate_list(predicates: &[Predicate]) -> String {
    predicates.iter().map(wire).collect::<Vec<_>>().join(", ")
}