tix-tracker 0.12.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
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
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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
//! The pure template resolver: registry + explicit scope + user input →
//! **one normal create request** (`contracts/resolver.md`, data-model §6).
//!
//! Resolution is a pure function. It borrows the [`Config`] (which owns the
//! [`TemplateRegistry`]), reads nothing else, and returns a
//! [`TemplateResolution`] — the created-by-nobody request plus provenance, or
//! the complete set of [`TemplateDiagnostic`] values that prevented one. It
//! never reads `stdin`, launches an editor, mutates the registry, or writes an
//! issue (C-005).
//!
//! # Merge policy (deterministic)
//!
//! For every field in [`CREATE_FIELDS`], in declaration order, the resolved
//! value is the first of:
//!
//! 1. the user's input value, even when blank (an explicit override wins);
//! 2. the field's prompt `default`, when a prompt declares one;
//! 3. the template's `defaults` value.
//!
//! A list-valued field (`labels`, `files`, `cycles`, `milestones`,
//! `related_issues`) is replaced wholesale rather than appended to, using the
//! same comma-separated rule the create core applies. Defaults are applied
//! before user input; user input reaches only documented create fields because
//! [`TemplateInput`] *is* the create-field shape.
//!
//! # Request shape
//!
//! [`CreateRequest`] has exactly the parameters of
//! [`crate::commands::create::create`], so applying a resolution is a direct
//! call into the shared create core — there is no second issue schema and no
//! second writer (C-001/C-007/NFR-002). Status-column and date validation stay
//! in that core, which runs them **before** `Store::create`; this module does
//! not restate them, so the two paths cannot drift.

use std::fmt;

use crate::config::Config;
use crate::model::{Priority, Status};

use super::registry::{
    CREATE_FIELDS, Template, TemplateDefaults, TemplateScope, TemplateScopeKind,
};
use super::validation::{self, DiagnosticKind, TemplateDiagnostic};

/// Which template to resolve and the scope the caller explicitly selected.
///
/// Both are required: the ID is immutable identity (C-002) and the scope is an
/// explicit, visible selection (C-003/FR-005). A display name is never identity
/// — see [`resolve`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TemplateSelection {
    /// The stable template ID.
    pub id: String,
    /// The scope the caller selected; must equal the template's own scope.
    pub scope: TemplateScope,
}

impl TemplateSelection {
    /// Build a selection from a stable ID and an explicit scope.
    pub fn new(id: impl Into<String>, scope: TemplateScope) -> Self {
        Self {
            id: id.into(),
            scope,
        }
    }
}

/// The caller's normal create-field values.
///
/// This mirrors the shared create arguments one-for-one — the same
/// comma-separated string shape the CLI passes — so a surface cannot smuggle a
/// field the create model does not understand. Every field is optional: an
/// absent field means "not provided" (the template default, if any, applies),
/// while `Some("")` is an explicit blank override.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TemplateInput {
    /// Issue title.
    pub title: Option<String>,
    /// Issue body (Markdown).
    pub body: Option<String>,
    /// Status column.
    pub status: Option<String>,
    /// Priority (`''`/`low`/`medium`/`high`).
    pub priority: Option<String>,
    /// Assignee identity.
    pub assignee: Option<String>,
    /// Comma-separated labels.
    pub labels: Option<String>,
    /// Comma-separated file paths.
    pub files: Option<String>,
    /// Estimate.
    pub estimate: Option<String>,
    /// Comma-separated cycle names.
    pub cycles: Option<String>,
    /// Comma-separated milestone names.
    pub milestones: Option<String>,
    /// Reviewer.
    pub reviewer: Option<String>,
    /// Start date (`YYYY-MM-DD`).
    pub start_date: Option<String>,
    /// Due date (`YYYY-MM-DD`).
    pub due_date: Option<String>,
    /// Parent selector.
    pub parent: Option<String>,
    /// Comma-separated cross-repository references.
    pub related_issues: Option<String>,
    /// Issue type (the create core's `type`).
    pub type_: Option<String>,
}

impl TemplateInput {
    /// The raw value for a create-field key, mapping the TOML key `type` onto
    /// the Rust field `type_`.
    #[must_use]
    pub fn get(&self, field: &str) -> Option<&str> {
        match field {
            "title" => self.title.as_deref(),
            "body" => self.body.as_deref(),
            "status" => self.status.as_deref(),
            "priority" => self.priority.as_deref(),
            "assignee" => self.assignee.as_deref(),
            "labels" => self.labels.as_deref(),
            "files" => self.files.as_deref(),
            "estimate" => self.estimate.as_deref(),
            "cycles" => self.cycles.as_deref(),
            "milestones" => self.milestones.as_deref(),
            "reviewer" => self.reviewer.as_deref(),
            "start_date" => self.start_date.as_deref(),
            "due_date" => self.due_date.as_deref(),
            "parent" => self.parent.as_deref(),
            "related_issues" => self.related_issues.as_deref(),
            "type" => self.type_.as_deref(),
            _ => None,
        }
    }
}

/// The normal create request a resolution produced.
///
/// The fields are exactly the parameters of
/// [`crate::commands::create::create`], in the same order and with the same
/// types; a caller destructures this straight into the shared core. Nothing
/// here is derived from a template-specific schema — a template can only ever
/// pre-fill these documented fields.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CreateRequest {
    /// `create(..., title, ...)`: always non-blank on a successful resolution.
    pub title: String,
    /// `create(..., body, ...)`.
    pub body: Option<String>,
    /// `create(..., status, ...)`.
    pub status: Option<Status>,
    /// `create(..., priority, ...)`.
    pub priority: Option<Priority>,
    /// `create(..., assignee, ...)`.
    pub assignee: Option<String>,
    /// `create(..., labels, ...)`, comma-separated.
    pub labels: Option<String>,
    /// `create(..., files, ...)`, comma-separated.
    pub files: Option<String>,
    /// `create(..., estimate, ...)`.
    pub estimate: Option<String>,
    /// `create(..., cycles, ...)`, comma-separated.
    pub cycles: Option<String>,
    /// `create(..., milestones, ...)`, comma-separated.
    pub milestones: Option<String>,
    /// `create(..., reviewer, ...)`.
    pub reviewer: Option<String>,
    /// `create(..., start_date, ...)`.
    pub start_date: Option<String>,
    /// `create(..., due_date, ...)`.
    pub due_date: Option<String>,
    /// `create(..., parent, ...)`.
    pub parent: Option<String>,
    /// `create(..., related_issues, ...)`, comma-separated.
    pub related_issues: Option<String>,
    /// `create(..., type_, ...)`.
    pub type_: Option<String>,
}

/// The pure result of applying a template to user input (data-model §6).
///
/// `request` is present **iff** `diagnostics` is empty: a failed resolution
/// never yields a partial request, and the template/config it read is
/// untouched.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TemplateResolution {
    template_id: String,
    scope: TemplateScope,
    provided_fields: Vec<String>,
    diagnostics: Vec<TemplateDiagnostic>,
    request: Option<CreateRequest>,
}

impl TemplateResolution {
    /// The selected template's stable ID (provenance, even on failure).
    #[must_use]
    pub fn template_id(&self) -> &str {
        &self.template_id
    }

    /// The resolved (explicitly selected) scope.
    #[must_use]
    pub fn scope(&self) -> &TemplateScope {
        &self.scope
    }

    /// The create fields that received a value, in [`CREATE_FIELDS`] order.
    #[must_use]
    pub fn provided_fields(&self) -> &[String] {
        &self.provided_fields
    }

    /// Every validation diagnostic, in deterministic order.
    ///
    /// Non-empty exactly when [`Self::request`] is `None`.
    #[must_use]
    pub fn diagnostics(&self) -> &[TemplateDiagnostic] {
        &self.diagnostics
    }

    /// The normal create request, present only on success.
    #[must_use]
    pub fn request(&self) -> Option<&CreateRequest> {
        self.request.as_ref()
    }

    /// Whether resolution succeeded and a request is available.
    #[must_use]
    pub fn is_ok(&self) -> bool {
        self.request.is_some()
    }

    /// Consume the resolution, yielding the request when it succeeded.
    #[must_use]
    pub fn into_request(self) -> Option<CreateRequest> {
        self.request
    }

    /// A failed (or early-rejected) resolution.
    fn rejected(
        template_id: &str,
        scope: &TemplateScope,
        diagnostics: Vec<TemplateDiagnostic>,
    ) -> Self {
        Self {
            template_id: template_id.to_string(),
            scope: scope.clone(),
            provided_fields: Vec::new(),
            diagnostics,
            request: None,
        }
    }
}

impl fmt::Display for TemplateResolution {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.is_ok() {
            write!(
                f,
                "template `{}` at scope `{}` resolved",
                self.template_id, self.scope
            )
        } else {
            write!(
                f,
                "template `{}` at scope `{}` did not resolve ({} diagnostic(s))",
                self.template_id,
                self.scope,
                self.diagnostics.len()
            )
        }
    }
}

/// Resolve `selection` against the registry in `config`, merging `input`.
///
/// Pure: no I/O, no registry mutation, no prompting. A successful result
/// carries a [`CreateRequest`] and gives the caller one normal create request;
/// a failed result carries **all** actionable diagnostics — every missing
/// required prompt, every unknown reference — and no request.
///
/// Rejections, in order:
///
/// * a blank selection ID, or an ID the registry does not contain (a display
///   name is diagnosed with the stable ID to use instead — names are labels,
///   not identity);
/// * an explicit scope that is malformed or names an unknown board/team;
/// * an explicit scope that differs from the template's own scope;
/// * a structurally invalid template (a safety net; the registry validates on
///   load/save);
/// * missing required prompts/title, invalid values, unknown references.
#[must_use]
pub fn resolve(
    config: &Config,
    selection: &TemplateSelection,
    input: &TemplateInput,
) -> TemplateResolution {
    let id = selection.id.trim().to_string();
    if id.is_empty() {
        return TemplateResolution::rejected(
            &id,
            &selection.scope,
            vec![TemplateDiagnostic::new(
                DiagnosticKind::UnknownTemplate,
                "template_id",
                "a template id is required (a display name is not identity)",
            )],
        );
    }
    let Some(template) = config.issue_templates.get(&id) else {
        return TemplateResolution::rejected(
            &id,
            &selection.scope,
            vec![TemplateDiagnostic::new(
                DiagnosticKind::UnknownTemplate,
                "template_id",
                unknown_template_message(config, &id),
            )],
        );
    };
    // Safety net: the registry validates on load and save, but resolution is
    // the last gate before a write, so a structurally broken template is
    // diagnosed here rather than merged.
    if let Err(error) = template.validate(&id, config) {
        return TemplateResolution::rejected(
            &id,
            &selection.scope,
            vec![TemplateDiagnostic::new(
                DiagnosticKind::InvalidValue,
                "template",
                error.to_string(),
            )],
        );
    }
    let scope_diagnostics = scope_diagnostics(config, &id, selection, template);
    if !scope_diagnostics.is_empty() {
        return TemplateResolution::rejected(&id, &selection.scope, scope_diagnostics);
    }
    let merged = merge(template, input);
    let mut diagnostics = validation::missing_required(template, &merged);
    diagnostics.extend(validation::invalid_values(&merged));
    diagnostics.extend(validation::validate_references(config, template, &merged));
    let provided_fields = merged
        .iter()
        .map(|(field, _)| field.to_string())
        .collect::<Vec<_>>();
    let request = diagnostics.is_empty().then(|| build_request(&merged));
    TemplateResolution {
        template_id: id,
        scope: selection.scope.clone(),
        provided_fields,
        diagnostics,
        request,
    }
}

/// The diagnostic for an ID the registry does not contain, naming the stable
/// ID when the caller passed a display name.
fn unknown_template_message(config: &Config, id: &str) -> String {
    if let Some((stable, _)) = config
        .issue_templates
        .iter()
        .find(|(_, template)| template.display_name("") == id)
    {
        return format!("`{id}` is a display name, not a stable id; use `{stable}`");
    }
    let known = config.issue_templates.ids().collect::<Vec<_>>();
    let list = if known.is_empty() {
        "none configured".to_string()
    } else {
        known.join(", ")
    };
    format!("unknown template id `{id}` — known ids: {list}")
}

/// Validate the explicit selection scope, then require it to be the template's.
fn scope_diagnostics(
    config: &Config,
    id: &str,
    selection: &TemplateSelection,
    template: &Template,
) -> Vec<TemplateDiagnostic> {
    let requested = &selection.scope;
    let mut out = Vec::new();
    let qualifier = requested.qualifier().unwrap_or_default().trim();
    match requested.kind() {
        TemplateScopeKind::Repository => {}
        TemplateScopeKind::Board if qualifier.is_empty() => out.push(TemplateDiagnostic::new(
            DiagnosticKind::InvalidScope,
            "scope",
            "a board scope must name its board as `board:<name>`",
        )),
        TemplateScopeKind::Board => {
            if !config.kanban.configurations.contains_key(qualifier) {
                out.push(TemplateDiagnostic::new(
                    DiagnosticKind::InvalidScope,
                    "scope",
                    format!("references unknown board `{qualifier}`"),
                ));
            }
        }
        TemplateScopeKind::Team if qualifier.is_empty() => out.push(TemplateDiagnostic::new(
            DiagnosticKind::InvalidScope,
            "scope",
            "a team scope must name its team as `team:<label>`",
        )),
        TemplateScopeKind::Team => {
            if !config.teams.contains_key(qualifier) {
                out.push(TemplateDiagnostic::new(
                    DiagnosticKind::InvalidScope,
                    "scope",
                    format!("references unknown team `{qualifier}`"),
                ));
            }
        }
    }
    if out.is_empty() && requested != &template.scope {
        out.push(TemplateDiagnostic::new(
            DiagnosticKind::ScopeMismatch,
            "scope",
            format!(
                "template `{id}` is scoped to `{}`, not `{}`",
                template.scope, requested
            ),
        ));
    }
    out
}

/// The merged view of every create field: the value each field resolved to,
/// in [`CREATE_FIELDS`] order. Fields with no value are absent.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct MergedFields {
    entries: Vec<(&'static str, String)>,
}

impl MergedFields {
    /// Record `field`'s resolved value. Callers insert in [`CREATE_FIELDS`]
    /// order, so the entries stay ordered.
    fn set(&mut self, field: &'static str, value: String) {
        self.entries.push((field, value));
    }

    /// The resolved value for `field`, if any. A blank string is a value: an
    /// explicit blank override.
    pub(crate) fn get(&self, field: &str) -> Option<&str> {
        self.entries
            .iter()
            .find(|(key, _)| *key == field)
            .map(|(_, value)| value.as_str())
    }

    /// Whether `field` resolved to nothing, or to a blank string.
    pub(crate) fn is_blank(&self, field: &str) -> bool {
        self.get(field).is_none_or(|value| value.trim().is_empty())
    }

    /// The resolved fields and their values, in order.
    pub(crate) fn iter(&self) -> impl Iterator<Item = (&'static str, &str)> {
        self.entries
            .iter()
            .map(|(field, value)| (*field, value.as_str()))
    }
}

/// Merge defaults, prompt defaults and user input per the module's documented
/// precedence, in [`CREATE_FIELDS`] order.
fn merge(template: &Template, input: &TemplateInput) -> MergedFields {
    let mut merged = MergedFields::default();
    for field in CREATE_FIELDS {
        let value = input
            .get(field)
            .map(str::to_string)
            .or_else(|| prompt_default(template, field))
            .or_else(|| defaults_value(&template.defaults, field));
        if let Some(value) = value {
            merged.set(field, value);
        }
    }
    merged
}

/// A prompt's own `default` for `field`, when a prompt declares one.
fn prompt_default(template: &Template, field: &str) -> Option<String> {
    template
        .prompts
        .iter()
        .find(|prompt| prompt.key == field)
        .and_then(|prompt| non_blank(&prompt.default))
}

/// The template defaults value for `field`, as the create core's argument
/// shape (list fields join with the shared comma rule).
fn defaults_value(defaults: &TemplateDefaults, field: &str) -> Option<String> {
    let scalar = match field {
        "title" => &defaults.title,
        "body" => &defaults.body,
        "status" => &defaults.status,
        "priority" => &defaults.priority,
        "assignee" => &defaults.assignee,
        "estimate" => &defaults.estimate,
        "reviewer" => &defaults.reviewer,
        "start_date" => &defaults.start_date,
        "due_date" => &defaults.due_date,
        "parent" => &defaults.parent,
        "type" => &defaults.type_,
        _ => return list_default(defaults, field),
    };
    scalar.clone()
}

/// The comma-joined value of a list default, or `None` when empty.
fn list_default(defaults: &TemplateDefaults, field: &str) -> Option<String> {
    let values = match field {
        "labels" => &defaults.labels,
        "files" => &defaults.files,
        "cycles" => &defaults.cycles,
        "milestones" => &defaults.milestones,
        "related_issues" => &defaults.related_issues,
        _ => return None,
    };
    let joined = values
        .iter()
        .filter(|value| !value.trim().is_empty())
        .cloned()
        .collect::<Vec<_>>()
        .join(",");
    if joined.is_empty() {
        None
    } else {
        Some(joined)
    }
}

/// A prompt default, filtering a blank one out (the registry refuses these).
fn non_blank(value: &Option<String>) -> Option<String> {
    value
        .as_deref()
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .map(str::to_string)
}

/// The resolved field's value, as `Option<String>`.
impl MergedFields {
    fn owned(&self, field: &str) -> Option<String> {
        self.get(field).map(str::to_string)
    }
}

/// Build the normal create request from the merged fields.
///
/// Priority is parsed with the shared strict parser; a failure is already a
/// diagnostic, so `.ok()` here cannot silently drop a bad value on a successful
/// resolution.
fn build_request(merged: &MergedFields) -> CreateRequest {
    CreateRequest {
        title: merged.get("title").unwrap_or_default().trim().to_string(),
        body: merged.owned("body"),
        status: merged.owned("status").map(Status::new),
        priority: merged
            .get("priority")
            .and_then(|raw| crate::commands::parse_priority(raw.trim()).ok()),
        assignee: merged.owned("assignee"),
        labels: merged.owned("labels"),
        files: merged.owned("files"),
        estimate: merged.owned("estimate"),
        cycles: merged.owned("cycles"),
        milestones: merged.owned("milestones"),
        reviewer: merged.owned("reviewer"),
        start_date: merged.owned("start_date"),
        due_date: merged.owned("due_date"),
        parent: merged.owned("parent"),
        related_issues: merged.owned("related_issues"),
        type_: merged.owned("type"),
    }
}