tix-tracker 0.7.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
//! GitLab adapter: shells out to the `glab` CLI under
//! `contracts/external-tools.md` (GitLab row). Every contract fabricate
//! template's command shape is reproduced; the only additions are `--output
//! json` (needed to parse the create/list responses) and the token env
//! injection.
//!
//! Tokens are env-only and scrubbed as `<token>` from any surfaced output.

use serde::Deserialize;

use crate::error::{Result, TixError};
use crate::sync::{CommandOutcome, CommandRunner, RemoteIssue, Tool, TrackerAdapter, scrub_secret};

/// The `glab` adapter. Spawns `glab issue <create|update|close|list>` with
/// the configured project and, when a secret is configured, the
/// `GITLAB_TOKEN` env pair.
pub struct GitLabAdapter {
    runner: Box<dyn CommandRunner>,
    token: Option<String>,
    base_url: Option<String>,
    project: String,
}

impl GitLabAdapter {
    pub fn new(
        runner: impl CommandRunner + 'static,
        token: Option<String>,
        base_url: Option<String>,
        project: String,
    ) -> Self {
        GitLabAdapter {
            runner: Box::new(runner),
            token,
            base_url,
            project,
        }
    }

    fn project_arg(&self) -> (String, String) {
        ("--project".to_string(), self.project.clone())
    }

    fn hostname_args(&self) -> Vec<String> {
        match &self.base_url {
            Some(url) => vec!["--hostname".to_string(), url.clone()],
            None => Vec::new(),
        }
    }

    /// Environment injected into every child: the token env pair when a
    /// secret is configured (native glab auth otherwise — no env at all).
    fn child_env(&self) -> Vec<(String, String)> {
        match &self.token {
            Some(token) => vec![("GITLAB_TOKEN".to_string(), token.clone())],
            None => Vec::new(),
        }
    }

    fn run(&self, args: &[String]) -> Result<CommandOutcome> {
        self.runner
            .run(Tool::GitLab.binary(), args, &self.child_env())
    }

    /// Build a [`TixError::External`] for a failed tool invocation, scrubbing
    /// the token from any surfaced output.
    fn external(&self, context: &str, outcome: &CommandOutcome) -> TixError {
        let mut message = format!("{context}: {}", outcome.text().trim());
        if let Some(secret) = &self.token {
            message = scrub_secret(&message, secret);
        }
        TixError::External(message)
    }

    /// Parse `glab issue create` stdout as `{"iid": n}`.
    fn parse_iid(&self, outcome: &CommandOutcome) -> Result<String> {
        let stdout = &outcome.stdout;
        serde_json::from_str::<serde_json::Value>(stdout)
            .ok()
            .and_then(|value| {
                value
                    .get("iid")
                    .and_then(serde_json::Value::as_i64)
                    .map(|iid| iid.to_string())
            })
            .ok_or_else(|| {
                TixError::External(format!(
                    "`glab issue create` did not return JSON with a numeric `iid` field (expected {{\"iid\":…}}): {}",
                    scrub_secret(stdout.trim(), self.token.as_deref().unwrap_or(""))
                ))
            })
    }
}

impl TrackerAdapter for GitLabAdapter {
    fn tool(&self) -> Tool {
        Tool::GitLab
    }

    fn create_issue(
        &mut self,
        title: &str,
        body: &str,
        labels: &[String],
        assignee: Option<&str>,
        _priority: Option<&str>,
        _status: &str,
    ) -> Result<String> {
        let mut args: Vec<String> = Vec::new();
        args.push("issue".to_string());
        args.push("create".to_string());
        let (k, v) = self.project_arg();
        args.push(k);
        args.push(v);
        args.extend(self.hostname_args());
        args.push("--title".to_string());
        args.push(title.to_string());
        args.push("--description".to_string());
        args.push(body.to_string());
        if !labels.is_empty() {
            args.push("--label".to_string());
            args.push(labels.join(","));
        }
        if let Some(name) = assignee {
            args.push("--assignee".to_string());
            args.push(format!("@{name}"));
        }
        args.push("--yes".to_string());
        args.push("--output".to_string());
        args.push("json".to_string());
        let outcome = self.run(&args)?;
        if !outcome.success {
            return Err(self.external("`glab issue create` failed", &outcome));
        }
        self.parse_iid(&outcome)
    }

    fn update_issue(
        &mut self,
        remote_ref: &str,
        title: &str,
        body: &str,
        labels: &[String],
        assignee: Option<&str>,
        _priority: Option<&str>,
        _status: &str,
    ) -> Result<()> {
        let mut args: Vec<String> = Vec::new();
        args.push("issue".to_string());
        args.push("update".to_string());
        args.push(remote_ref.to_string());
        let (k, v) = self.project_arg();
        args.push(k);
        args.push(v);
        args.extend(self.hostname_args());
        args.push("--title".to_string());
        args.push(title.to_string());
        args.push("--description".to_string());
        args.push(body.to_string());
        if !labels.is_empty() {
            args.push("--label".to_string());
            args.push(labels.join(","));
        }
        if let Some(name) = assignee {
            args.push("--assignee".to_string());
            args.push(format!("@{name}"));
        }
        let outcome = self.run(&args)?;
        if !outcome.success {
            return Err(self.external("`glab issue update` failed", &outcome));
        }
        Ok(())
    }

    fn mark_done(&mut self, remote_ref: &str) -> Result<()> {
        let mut args: Vec<String> = Vec::new();
        args.push("issue".to_string());
        args.push("close".to_string());
        args.push(remote_ref.to_string());
        let (k, v) = self.project_arg();
        args.push(k);
        args.push(v);
        args.extend(self.hostname_args());
        let outcome = self.run(&args)?;
        if !outcome.success {
            return Err(self.external("`glab issue close` failed", &outcome));
        }
        Ok(())
    }

    fn list_open(&mut self) -> Result<Vec<RemoteIssue>> {
        let mut args: Vec<String> = Vec::new();
        args.push("issue".to_string());
        args.push("list".to_string());
        let (k, v) = self.project_arg();
        args.push(k);
        args.push(v);
        args.extend(self.hostname_args());
        args.push("--output".to_string());
        args.push("json".to_string());
        let outcome = self.run(&args)?;
        if !outcome.success {
            return Err(self.external("`glab issue list` failed", &outcome));
        }
        let issues: Vec<GlabIssue> = serde_json::from_str(&outcome.stdout).map_err(|e| {
            TixError::External(format!(
                "`glab issue list` did not return a JSON array: {e}\n{}",
                scrub_secret(&outcome.stdout, self.token.as_deref().unwrap_or(""))
            ))
        })?;
        Ok(issues
            .into_iter()
            .map(RemoteIssue::from)
            .filter(|i| i.state != "closed")
            .collect())
    }

    fn done_via_status(&self) -> bool {
        false
    }

    /// `glab issue update <ref> --blocking <refs>` (WP07 T030).
    ///
    /// The only relation affordance `glab` exposes on an issue update is
    /// `--blocking`, so a `blocks` edge is the only thing that can leave the
    /// machine — and that is decided by the shared seam, not here. What arrives
    /// is already filtered; this method only renders it.
    ///
    /// `--blocking` is not additive in `glab`: it *replaces* the issue's blocked-by
    /// set. So the full set is sent in one call rather than one call per edge,
    /// which is also one fewer chance to leave the remote half-configured.
    fn set_relations(
        &mut self,
        remote_ref: &str,
        relations: &[super::MappedRelation],
    ) -> Result<()> {
        let blocking: Vec<String> = relations
            .iter()
            .filter_map(|r| match r {
                super::MappedRelation::Remote { value, .. } => Some(value.clone()),
                super::MappedRelation::Unsupported(_) => None,
            })
            .collect();
        if blocking.is_empty() {
            // Nothing expressible. Sending an empty `--blocking` would *clear* the
            // remote's set, which is the opposite of leaving it alone — so a run
            // that cannot express anything must send nothing at all.
            return Ok(());
        }
        let mut args: Vec<String> = vec!["issue".into(), "update".into(), remote_ref.to_string()];
        let (k, v) = self.project_arg();
        args.push(k);
        args.push(v);
        args.extend(self.hostname_args());
        args.push("--blocking".to_string());
        args.push(blocking.join(","));
        let outcome = self.run(&args)?;
        if !outcome.success {
            return Err(self.external("`glab issue update --blocking` failed", &outcome));
        }
        Ok(())
    }
}

/// A single entry from `glab issue list --output json`.
#[derive(Debug, Deserialize)]
struct GlabIssue {
    iid: i64,
    #[serde(default)]
    title: String,
    #[serde(default)]
    description: Option<String>,
    #[serde(default)]
    labels: Vec<GlabLabel>,
    #[serde(default)]
    state: String,
    #[serde(default)]
    updated_at: Option<String>,
    #[serde(default)]
    assignees: Vec<GlabAssignee>,
    /// The parent epic's iid, when the remote reported one.
    ///
    /// GitLab's issue hierarchy is a **closed** field — an issue belongs to one
    /// epic or to none — so a single id is the whole of it.
    ///
    /// **Neither spelling is verified.** GitLab's payloads have carried both
    /// `epic_iid` and `parent_iid` depending on version and endpoint, and this
    /// repository cannot run `glab` to see which. Accepting either, under one field
    /// name, is the honest form: it does not assert a spelling it cannot check,
    /// and a payload that uses neither simply reports no parent. The wire verb
    /// stays gated behind `PARENT_WIRE_VERIFIED` regardless — reading a field is
    /// not the same claim as sending one.
    #[serde(default, alias = "epic_iid", alias = "parent_iid")]
    parent: Option<i64>,
}

/// Labels arrive either as plain strings or as `{"id":..,"name":".."}`.
#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum GlabLabel {
    Name(String),
    Named { name: String },
}

#[derive(Debug, Deserialize)]
struct GlabAssignee {
    #[serde(default)]
    username: String,
}

impl From<GlabIssue> for RemoteIssue {
    fn from(issue: GlabIssue) -> Self {
        RemoteIssue {
            id: issue.iid.to_string(),
            title: issue.title,
            description: issue.description.unwrap_or_default(),
            labels: issue
                .labels
                .into_iter()
                .map(|l| match l {
                    GlabLabel::Name(name) | GlabLabel::Named { name } => name,
                })
                .collect(),
            state: issue.state,
            updated_at: issue.updated_at,
            parent: issue.parent.map(|iid| iid.to_string()),
            assignee: issue
                .assignees
                .into_iter()
                .next()
                .map(|a| a.username)
                .filter(|u| !u.is_empty()),
        }
    }
}

/// A recorded adapter call: the argv plus the env pairs it was spawned with.
pub type RecordedCall = (Vec<String>, Vec<(String, String)>);

/// A fake runner for adapter unit tests: records argv plus env (for the
/// token scrub/injection assertions) and returns configured outcomes in
/// order, falling back to an empty success.
#[derive(Default)]
pub struct FakeRunner {
    calls: std::sync::Mutex<Vec<RecordedCall>>,
    responses: std::sync::Mutex<Vec<CommandOutcome>>,
}

impl FakeRunner {
    #[must_use]
    pub fn new(responses: Vec<CommandOutcome>) -> Self {
        FakeRunner {
            responses: std::sync::Mutex::new(responses),
            ..FakeRunner::default()
        }
    }

    pub fn take_calls(&self) -> Vec<RecordedCall> {
        self.calls.lock().unwrap().clone()
    }
}

impl CommandRunner for FakeRunner {
    fn run(
        &self,
        program: &str,
        args: &[String],
        env: &[(String, String)],
    ) -> Result<CommandOutcome> {
        self.calls.lock().unwrap().push((
            std::iter::once(program.to_string())
                .chain(args.iter().cloned())
                .collect(),
            env.to_vec(),
        ));
        let outcome = self
            .responses
            .lock()
            .unwrap()
            .pop()
            .unwrap_or(CommandOutcome {
                success: true,
                status: Some(0),
                stdout: String::new(),
                stderr: String::new(),
            });
        Ok(outcome)
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

/// Response helpers shaped like `glab` JSON output.
impl CommandOutcome {
    #[must_use]
    pub fn glab_created(iid: i64) -> CommandOutcome {
        CommandOutcome {
            success: true,
            status: Some(0),
            stdout: format!(
                "{{\"iid\": {iid}, \"web_url\": \"https://gitlab.example/acme/tix/-/issues/{iid}\"}}"
            ),
            stderr: String::new(),
        }
    }

    #[must_use]
    pub fn glab_list(payload: &str) -> CommandOutcome {
        CommandOutcome {
            success: true,
            status: Some(0),
            stdout: payload.to_string(),
            stderr: String::new(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn adapter_with(
        runner: FakeRunner,
        token: Option<&str>,
        base_url: Option<&str>,
    ) -> GitLabAdapter {
        GitLabAdapter::new(
            runner,
            token.map(String::from),
            base_url.map(String::from),
            "acme/tix".into(),
        )
    }

    /// Read the recorded calls through the owned runner's downcast hook.
    fn recorded(adapter: &GitLabAdapter) -> Vec<RecordedCall> {
        adapter
            .runner
            .as_any()
            .downcast_ref::<FakeRunner>()
            .expect("adapter must hold a FakeRunner")
            .take_calls()
    }

    #[test]
    fn create_records_env_token_and_full_shape() {
        let runner = FakeRunner::new(vec![CommandOutcome::glab_created(42)]);
        let mut adapter = adapter_with(runner, Some("gl-token"), None);
        let id = adapter
            .create_issue(
                "Fix login",
                "body here",
                &["bug".into(), "auth".into()],
                Some("alice"),
                None,
                "opened",
            )
            .unwrap();
        assert_eq!(id, "42");
        let calls = recorded(&adapter);
        let (argv, env) = &calls[0];
        assert_eq!(argv[0], "glab");
        assert_eq!(argv[1], "issue");
        assert_eq!(argv[2], "create");
        let joined = argv.join(" ");
        assert!(joined.contains("--project acme/tix"));
        assert!(joined.contains("--title Fix login"));
        assert!(joined.contains("--description body here"));
        assert!(joined.contains("--label bug,auth"));
        assert!(joined.contains("--assignee @alice"));
        assert!(joined.contains("--yes"));
        assert!(joined.contains("--output json"));
        assert_eq!(env, &[("GITLAB_TOKEN".to_string(), "gl-token".to_string())]);
    }

    #[test]
    fn create_with_hostname_includes_hostname_flag() {
        let runner = FakeRunner::new(vec![CommandOutcome::glab_created(7)]);
        let mut adapter = adapter_with(runner, None, Some("gitlab.example.com"));
        adapter
            .create_issue("T", "b", &[], None, None, "opened")
            .unwrap();
        let joined = recorded(&adapter)[0].0.join(" ");
        assert!(joined.contains("--hostname gitlab.example.com"));
    }

    #[test]
    fn create_json_without_iid_is_a_parse_error() {
        let runner = FakeRunner::new(vec![CommandOutcome::glab_list("{}")]);
        let mut adapter = adapter_with(runner, None, None);
        let err = adapter
            .create_issue("T", "b", &[], None, None, "opened")
            .unwrap_err();
        assert!(matches!(err, TixError::External(_)));
        assert!(err.to_string().contains("iid"));
    }

    #[test]
    fn update_uses_iid_position_and_project() {
        let runner = FakeRunner::new(vec![]);
        let mut adapter = adapter_with(runner, None, None);
        adapter
            .update_issue("777", "New title", "new body", &[], None, None, "opened")
            .unwrap();
        let argv = &recorded(&adapter)[0].0;
        let joined = argv.join(" ");
        assert!(joined.starts_with("glab issue update 777 "));
        assert!(joined.contains("--project acme/tix"));
        assert!(joined.contains("--title New title"));
        assert!(joined.contains("--description new body"));
    }

    #[test]
    fn mark_done_calls_close() {
        let runner = FakeRunner::new(vec![]);
        let mut adapter = adapter_with(runner, None, None);
        adapter.mark_done("777").unwrap();
        let argv = &recorded(&adapter)[0].0;
        assert_eq!(
            argv,
            &["glab", "issue", "close", "777", "--project", "acme/tix"]
        );
    }

    #[test]
    fn list_open_parses_json_and_filters_closed() {
        let payload = r#"[
          {"iid":1,"title":"T1","description":"d1","labels":[{"name":"bug"}],"state":"opened","updated_at":"2026-05-11T10:00:00Z","assignees":[{"username":"alice"}]},
          {"iid":2,"title":"T2","state":"closed"}
        ]"#;
        let runner = FakeRunner::new(vec![CommandOutcome::glab_list(payload)]);
        let mut adapter = adapter_with(runner, None, None);
        let issues = adapter.list_open().unwrap();
        assert_eq!(issues.len(), 1);
        assert_eq!(issues[0].id, "1");
        assert_eq!(issues[0].title, "T1");
        assert_eq!(issues[0].labels, ["bug"]);
        assert_eq!(issues[0].state, "opened");
        assert_eq!(
            issues[0].updated_at.as_deref(),
            Some("2026-05-11T10:00:00Z")
        );
        assert_eq!(issues[0].assignee.as_deref(), Some("alice"));
    }

    #[test]
    fn list_accepts_string_labels_too() {
        let runner = FakeRunner::new(vec![CommandOutcome::glab_list(
            r#"[{"iid":9,"title":"T","labels":["docs","ops"],"state":"opened"}]"#,
        )]);
        let mut adapter = adapter_with(runner, None, None);
        let issues = adapter.list_open().unwrap();
        assert_eq!(issues[0].labels, ["docs", "ops"]);
    }

    #[test]
    fn failure_message_scrubs_token_from_tool_output() {
        let runner = FakeRunner::new(vec![CommandOutcome {
            success: false,
            status: Some(1),
            stdout: String::new(),
            stderr: "GITLAB_TOKEN=gl-token leaked".into(),
        }]);
        let mut adapter = adapter_with(runner, Some("gl-token"), None);
        let err = adapter
            .create_issue("T", "b", &[], None, None, "opened")
            .unwrap_err();
        let text = err.to_string();
        assert!(text.contains("<token>"), "expected redaction, got: {text}");
        assert!(!text.contains("gl-token"), "secret leaked: {text}");
    }
}