tix-tracker 0.4.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
use std::io::IsTerminal;
use std::path::Path;
use std::process::Command;

use crate::config::Config;
use crate::error::{Result, TixError};
use crate::model::Issue;

/// Read a single line from TTY with basic readline-style editing.
///
/// This replaces `std::io::stdin().read_line` for interactive prompts so
/// common editing shortcuts (Ctrl-A/E, arrows, delete/backspace) work.
pub fn read_tty_line(prompt: &str) -> Result<String> {
    if !std::io::stdin().is_terminal() {
        return Err(TixError::InvalidInput(
            "interactive input requires a TTY; pass an explicit argument instead".into(),
        ));
    }

    use reedline::{DefaultPrompt, DefaultPromptSegment, Reedline, Signal};

    let mut line_editor = Reedline::create();
    let prompt = DefaultPrompt::new(
        DefaultPromptSegment::Basic(prompt.to_string()),
        DefaultPromptSegment::Empty,
    );

    match line_editor.read_line(&prompt) {
        Ok(Signal::Success(input)) => Ok(input.trim().to_string()),
        Ok(Signal::CtrlC) | Ok(Signal::CtrlD) => {
            Err(TixError::InvalidInput("input cancelled".into()))
        }
        Err(e) => Err(TixError::Editor(format!("failed to read tty line: {e}"))),
    }
}

pub struct FieldEdits {
    pub title: Option<String>,
    pub status: Option<String>,
    pub priority: Option<String>,
    pub labels: Option<Vec<String>>,
    pub files: Option<Vec<String>>,
    pub assignee: Option<Option<String>>,
    pub estimate: Option<Option<String>>,
    pub commit: Option<Option<String>>,
    pub cycles: Option<Option<Vec<String>>>,
    pub milestones: Option<Option<Vec<String>>>,
    pub reviewer: Option<Option<String>>,
    pub start_date: Option<Option<String>>,
    pub due_date: Option<Option<String>>,
    /// The decomposition parent, as a **resolved issue number**.
    ///
    /// `Some(None)` clears it, mirroring `assignee` and every other optional field:
    /// an absent flag leaves it untouched, `--parent ""` removes it.
    ///
    /// A number, never a selector, because a title is not stable and a stored title
    /// would silently break every child on a retitle. Resolution happens in
    /// [`crate::commands::edit`] against the store, which `merge_fields` has no
    /// access to.
    ///
    /// **Out of map for WP03** (`src/editor.rs` is in no WP's `owned_files`; see tix
    /// #1374). The field lives here, rather than as a separate parameter, because
    /// that is exactly what `assignee` does: the value is merged so the merge stays
    /// uniform, and the side effect `merge_fields` cannot perform — here validating
    /// through the hierarchy service and appending the History event — happens
    /// around it in the caller. The alternative, a second write path in `edit` that
    /// bypasses the merge, is what `assignee`'s precedent argues against.
    pub parent: Option<Option<u32>>,
}

pub fn resolve_editor(pref: Option<&str>) -> Result<String> {
    resolve_editor_with_env(
        pref,
        std::env::var("EDITOR").ok(),
        std::env::var("VISUAL").ok(),
    )
}

pub fn resolve_agent(pref: Option<&str>) -> Result<String> {
    resolve_editor_with_env(
        pref,
        std::env::var("TIX_AGENT")
            .ok()
            .or_else(|| std::env::var("AGENT").ok()),
        std::env::var("VISUAL").ok(),
    )
}

fn resolve_editor_with_env(
    pref: Option<&str>,
    editor: Option<String>,
    visual: Option<String>,
) -> Result<String> {
    if let Some(e) = pref
        && !e.is_empty()
    {
        return Ok(e.to_string());
    }
    if let Some(e) = editor.filter(|v| !v.is_empty()) {
        return Ok(e);
    }
    if let Some(e) = visual.filter(|v| !v.is_empty()) {
        return Ok(e);
    }
    let fallbacks: &[&str] = if cfg!(target_os = "windows") {
        &["cmd", "nano", "vi"]
    } else {
        &["editor", "nano", "vi"]
    };
    for name in fallbacks {
        if which(name) {
            return Ok(name.to_string());
        }
    }
    Err(TixError::Editor("no editor found".into()))
}

pub fn run_editor(editor: &str, path: &Path, _config: &Config) -> Result<()> {
    let status = Command::new(editor)
        .arg(path)
        .status()
        .map_err(|e| TixError::Editor(format!("failed to launch {editor}: {e}")))?;
    if !status.success() {
        return Err(TixError::Editor(format!(
            "editor {editor} exited with {status}"
        )));
    }
    let contents = std::fs::read_to_string(path)
        .map_err(|e| TixError::Editor(format!("cannot read file after edit: {e}")))?;
    if Issue::parse(&contents).is_err() {
        return Err(TixError::Editor("file not valid after edit".into()));
    }
    Ok(())
}

pub fn merge_fields(issue: &Issue, edits: &FieldEdits) -> Issue {
    let mut result = issue.clone();
    if let Some(ref title) = edits.title {
        result.title = title.clone();
    }
    if let Some(ref status) = edits.status {
        result.status = crate::model::Status::new(status);
    }
    if let Some(ref priority) = edits.priority {
        result.priority = priority.parse().unwrap_or_default();
    }
    if let Some(ref labels) = edits.labels {
        result.labels = labels.clone();
    }
    if let Some(ref files) = edits.files {
        result.files = files.clone();
    }
    if let Some(ref assignee) = edits.assignee {
        result.assignee = assignee.clone();
    }
    if let Some(ref estimate) = edits.estimate {
        result.estimate = estimate.clone();
    }
    if let Some(ref commit) = edits.commit {
        result.commit = commit.clone();
    }
    if let Some(ref cycles) = edits.cycles {
        result.cycles = cycles.clone();
    }
    if let Some(ref milestones) = edits.milestones {
        result.milestones = milestones.clone();
    }
    if let Some(ref reviewer) = edits.reviewer {
        result.reviewer = reviewer.clone();
    }
    if let Some(ref start_date) = edits.start_date {
        result.start_date = start_date.clone();
    }
    if let Some(ref due_date) = edits.due_date {
        result.due_date = due_date.clone();
    }
    if let Some(ref parent) = edits.parent {
        result.parent = *parent;
    }
    result
}

fn which(name: &str) -> bool {
    let output = Command::new("which")
        .arg(name)
        .output()
        .map(|o| o.status.success());
    output.unwrap_or(false)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::{Priority, Status};
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn resolve_editor_pref_wins() {
        let result = resolve_editor_with_env(Some("nvim"), None, None).unwrap();
        assert_eq!(result, "nvim");
    }

    #[test]
    fn resolve_editor_pref_empty_falls_through() {
        let result = resolve_editor_with_env(Some(""), Some("vim".into()), None).unwrap();
        assert_eq!(result, "vim");
    }

    #[test]
    fn resolve_editor_editor_env() {
        let result = resolve_editor_with_env(None, Some("emacs".into()), None).unwrap();
        assert_eq!(result, "emacs");
    }

    #[test]
    fn resolve_editor_visual_env() {
        let result = resolve_editor_with_env(None, None, Some("helix".into())).unwrap();
        assert_eq!(result, "helix");
    }

    #[test]
    fn resolve_editor_editor_beats_visual() {
        let result =
            resolve_editor_with_env(None, Some("vim".into()), Some("helix".into())).unwrap();
        assert_eq!(result, "vim");
    }

    #[test]
    fn resolve_editor_empty_env_falls_through_to_fallback() {
        let result = resolve_editor_with_env(None, Some("".into()), None);
        // Either a fallback editor resolves, or a clear error is returned.
        match result {
            Ok(name) => assert!(!name.is_empty()),
            Err(TixError::Editor(_)) => {}
            Err(other) => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn run_editor_success() {
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("issue.md");
        fs::write(
            &file,
            "---\nnumber: 1\ntitle: T\nstatus: todo\nlabels: []\npriority: medium\ncreated: \"2026-01-01\"\nupdated: \"2026-01-01\"\n---\n\nbody",
        )
        .unwrap();
        let script = tmp.path().join("edit.sh");
        fs::write(&script, "#!/bin/sh\necho 'done' > /dev/null\n").unwrap();
        Command::new("chmod")
            .arg("+x")
            .arg(&script)
            .status()
            .unwrap();
        let config = Config::default();
        run_editor(script.to_str().unwrap(), &file, &config).unwrap();
    }

    #[test]
    fn run_editor_non_zero_exits_with_error() {
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("issue.md");
        fs::write(
            &file,
            "---\nnumber: 1\ntitle: T\nstatus: todo\nlabels: []\npriority: medium\ncreated: \"2026-01-01\"\nupdated: \"2026-01-01\"\n---\n\nbody",
        )
        .unwrap();
        let script = tmp.path().join("fail.sh");
        fs::write(&script, "#!/bin/sh\nexit 1\n").unwrap();
        Command::new("chmod")
            .arg("+x")
            .arg(&script)
            .status()
            .unwrap();
        let config = Config::default();
        let err = run_editor(script.to_str().unwrap(), &file, &config).unwrap_err();
        assert!(matches!(err, TixError::Editor(_)));
    }

    #[test]
    fn merge_fields_flag_driven() {
        let issue = Issue {
            number: 1,
            title: "Old".into(),
            status: Status::new("todo"),
            labels: vec![],
            priority: Priority::Low,
            assignee: Some("alice".into()),
            estimate: Some("2".into()),
            commit: None,
            gitlab_id: None,
            linear_id: None,
            mission: None,
            task: None,
            relationships: vec![],
            files: vec![],
            cycles: None,
            milestones: None,
            reviewer: None,
            start_date: None,
            due_date: None,
            created: "2026-01-01".into(),
            updated: "2026-01-01".into(),
            filename: String::new(),
            body: "original body".into(),
            history: crate::model::History::new(),
            has_retired_links_key: false,
            parent: None,
            extra_frontmatter: std::collections::BTreeMap::new(),
            archived: false,
            entered_at: None,
            source: None,
        };
        let edits = FieldEdits {
            title: Some("New".into()),
            status: None,
            priority: None,
            labels: None,
            files: None,
            assignee: None,
            estimate: None,
            commit: None,
            cycles: None,
            milestones: None,
            reviewer: None,
            start_date: None,
            due_date: None,
            parent: None,
        };
        let merged = merge_fields(&issue, &edits);
        assert_eq!(merged.title, "New");
        assert_eq!(merged.status.display(), "todo");
        assert_eq!(merged.body, "original body");
        assert_eq!(merged.assignee.as_deref(), Some("alice"));
    }

    #[test]
    fn merge_fields_commit_clear() {
        let issue = Issue {
            number: 1,
            title: "T".into(),
            status: Status::new("done"),
            labels: vec![],
            priority: Priority::default(),
            assignee: None,
            estimate: None,
            commit: Some("abc".into()),
            gitlab_id: None,
            linear_id: None,
            mission: None,
            task: None,
            relationships: vec![],
            files: vec![],
            cycles: None,
            milestones: None,
            reviewer: None,
            start_date: None,
            due_date: None,
            created: "2026-01-01".into(),
            updated: "2026-01-01".into(),
            filename: String::new(),
            body: String::new(),
            history: crate::model::History::new(),
            has_retired_links_key: false,
            parent: None,
            extra_frontmatter: std::collections::BTreeMap::new(),
            archived: false,
            entered_at: None,
            source: None,
        };
        let edits = FieldEdits {
            title: None,
            status: Some("in progress".into()),
            priority: None,
            labels: None,
            files: None,
            assignee: None,
            estimate: None,
            commit: Some(None),
            cycles: None,
            milestones: None,
            reviewer: None,
            start_date: None,
            due_date: None,
            parent: None,
        };
        let merged = merge_fields(&issue, &edits);
        assert!(merged.commit.is_none());
        assert_eq!(merged.status.display(), "in progress");
    }

    #[test]
    fn merge_fields_body_never_altered() {
        let issue = Issue {
            number: 1,
            title: "T".into(),
            status: Status::new("todo"),
            labels: vec![],
            priority: Priority::default(),
            assignee: None,
            estimate: None,
            commit: None,
            gitlab_id: None,
            linear_id: None,
            mission: None,
            task: None,
            relationships: vec![],
            history: crate::model::History::new(),
            has_retired_links_key: false,
            parent: None,
            files: vec![],
            cycles: None,
            milestones: None,
            reviewer: None,
            start_date: None,
            due_date: None,
            created: "2026-01-01".into(),
            updated: "2026-01-01".into(),
            filename: String::new(),
            body: "important body".into(),
            extra_frontmatter: std::collections::BTreeMap::new(),
            archived: false,
            entered_at: None,
            source: None,
        };
        let edits = FieldEdits {
            title: Some("Changed".into()),
            status: Some("done".into()),
            priority: Some("high".into()),
            labels: Some(vec!["bug".into()]),
            files: Some(vec!["specs/s.md".into()]),
            assignee: Some(Some("bob".into())),
            estimate: Some(Some("3".into())),
            commit: Some(Some("def".into())),
            cycles: Some(Some(vec!["c1".into()])),
            milestones: None,
            reviewer: Some(Some("renata".into())),
            start_date: None,
            due_date: None,
            parent: None,
        };
        let merged = merge_fields(&issue, &edits);
        assert_eq!(merged.body, "important body");
    }
}