tix-tracker 0.2.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
//! Assignee identities and filesystem-safe directory segments.
//!
//! WP01 foundation for assignee-grouped storage (FR-028–FR-031, NFR-009).
//! [`git_identity`] reads the git author identity by shelling out to
//! `git config --get user.name` / `user.email` (D-11), best-effort: any
//! failure or an unconfigured `user.name` yields [`None`] so downstream
//! callers can fall back to `unassigned` (FR-028). [`derive_segment`] maps
//! any assignee value to a deterministic, filesystem-safe directory segment
//! (kebab-cased via [`crate::slug::slugify`], a single safe path component
//! by construction).

use std::process::Command;

/// The git author identity used as the default assignee on create (FR-028).
///
/// `email` is optional: when `user.name` is configured but `user.email` is
/// not, the identity still carries the name, and segment derivation works via
/// the name slug (D-11).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AuthorIdentity {
    pub name: String,
    pub email: Option<String>,
}

impl std::fmt::Display for AuthorIdentity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.email {
            Some(email) => write!(f, "{} <{email}>", self.name),
            None => write!(f, "{}", self.name),
        }
    }
}

/// Read the git author identity from `git config`, best-effort.
///
/// Shells out to `git config --get user.name` then `git config --get
/// user.email` (D-11), matching the sync adapters' shell-out seam. Returns
/// [`None`] when `git` is missing, either call fails, or `user.name` is
/// unconfigured/empty. When `user.name` is present but `user.email` is not,
/// the returned identity has `email: None`. Never errors downstream (FR-028).
pub fn git_identity() -> Option<AuthorIdentity> {
    git_identity_for("git")
}

/// The spawn seam behind [`git_identity`]: `program` defaults to `"git"` but
/// tests point it at a fake binary. Failures surface as [`None`], never an
/// error.
fn git_identity_for(program: &str) -> Option<AuthorIdentity> {
    let name = git_config_get(program, "user.name")?;
    let email = git_config_get(program, "user.email");
    Some(AuthorIdentity { name, email })
}

/// Run `git config --get <key>` via `program` and return the trimmed value.
fn git_config_get(program: &str, key: &str) -> Option<String> {
    let stdout = run_git(program, &["config", "--get", key])?;
    let value = stdout.trim();
    if value.is_empty() {
        None
    } else {
        Some(value.to_string())
    }
}

/// The injectable subprocess runner used by the reader.
///
/// An unset key makes `git config --get` exit 1, so any non-zero status is
/// treated as "no value". Reads stdout lossily and untrimmed; trimming is the
/// caller's job.
fn run_git(program: &str, args: &[&str]) -> Option<String> {
    let output = Command::new(program).args(args).output().ok()?;
    if !output.status.success() {
        return None;
    }
    Some(String::from_utf8_lossy(&output.stdout).into_owned())
}

/// Parse an assignee value into its canonical in-memory form (FR-027).
///
/// Accepts a full `Name <email>` identity (returned verbatim, trimmed), a
/// bare or `@`-prefixed handle (`@alice` / `alice` → `alice`), and a full
/// identity with an empty name part (→ the email's local part). Empty /
/// whitespace-only input → [`None`].
pub fn parse_assignee(raw: &str) -> Option<String> {
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return None;
    }
    if let Some((name, email)) = parse_full_identity(trimmed) {
        if name.is_empty() {
            return email_local_part(&email);
        }
        return Some(trimmed.to_string());
    }
    let handle = trimmed.strip_prefix('@').unwrap_or(trimmed).trim();
    if handle.is_empty() {
        return None;
    }
    Some(handle.to_string())
}

/// Resolve the `@me` / `me` shorthand to the git author identity.
///
/// When `raw` parses to the handle `"me"` (case-insensitive) and a git
/// identity is available, returns the full `Name <email>` identity string.
/// Otherwise returns `parse_assignee(raw)` unchanged. Empty / whitespace
/// → [`None`].
pub fn resolve_me(raw: &str, identity: Option<&AuthorIdentity>) -> Option<String> {
    let parsed = parse_assignee(raw)?;
    if parsed.eq_ignore_ascii_case("me")
        && let Some(id) = identity
    {
        return Some(id.to_string());
    }
    Some(parsed)
}

/// A short display label for an assignee value, suitable for the board.
///
/// Full identities show just the name part; bare handles are `@`-prefixed.
pub fn assignee_display(assignee: &str) -> String {
    if let Some((name, _)) = parse_full_identity(assignee)
        && !name.is_empty()
    {
        return name;
    }
    let stripped = assignee.strip_prefix('@').unwrap_or(assignee);
    format!("@{stripped}")
}

/// Derive the filesystem-safe directory segment for an assignee (FR-029,
/// FR-030, NFR-009).
///
/// - `None` or empty → `"unassigned"`.
/// - `Name <email>` → slug of the name part.
/// - ` <email>` / bare `user@host` → slug of the email local part.
/// - bare `alice` / `@alice` → slug of the handle text.
///
/// The output is deterministic kebab-case from [`crate::slug::slugify`] plus
/// the literal `unassigned`, so it is always a single safe path component
/// (no spaces or separators, never `.`/`..`, no control characters).
pub fn derive_segment(assignee: Option<&str>) -> String {
    let raw = assignee.map(str::trim).unwrap_or("");
    if raw.is_empty() {
        return "unassigned".to_string();
    }
    if let Some((name, email)) = parse_full_identity(raw) {
        if name.is_empty() {
            return email_local_part(&email)
                .map(|local| crate::slug::slugify(&local))
                .unwrap_or_else(|| "unassigned".to_string());
        }
        return crate::slug::slugify(&name);
    }
    let bare = raw.strip_prefix('@').unwrap_or(raw).trim();
    if bare.is_empty() {
        return "unassigned".to_string();
    }
    let component = if bare.contains('@') {
        email_local_part(bare)
    } else {
        Some(bare.to_string())
    };
    component
        .map(|part| crate::slug::slugify(&part))
        .unwrap_or_else(|| "unassigned".to_string())
}

/// Split `Name <email>` into `(name, email)`. The name may be empty when an
/// identity carries only an angle-bracketed email. Anything else → [`None`].
fn parse_full_identity(raw: &str) -> Option<(String, String)> {
    let open = raw.find('<')?;
    let close = raw.rfind('>')?;
    if close < open {
        return None;
    }
    let name = raw[..open].trim();
    let email = raw[open + 1..close].trim();
    if email.is_empty() {
        return None;
    }
    Some((name.to_string(), email.to_string()))
}

/// The part of `email` before the first `@`, trimmed; [`None`] when empty.
fn email_local_part(email: &str) -> Option<String> {
    let local = email.split('@').next().unwrap_or("").trim();
    if local.is_empty() {
        None
    } else {
        Some(local.to_string())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::os::unix::fs::PermissionsExt;
    use tempfile::TempDir;

    /// Write an executable fake `git` script into `dir` and return its path.
    fn fake_git(dir: &TempDir, script: &str) -> String {
        let path = dir.path().join("fake-git");
        std::fs::write(&path, script).unwrap();
        let mut perms = std::fs::metadata(&path).unwrap().permissions();
        perms.set_mode(0o755);
        std::fs::set_permissions(&path, perms).unwrap();
        path.display().to_string()
    }

    /// Build a `git config` responder body: `$3` is the queried key; a
    /// `Some(value)` echoes it, `None` exits 1 (unconfigured key).
    fn fake_script(cases: &[(&str, Option<&str>)]) -> String {
        let mut body = String::from("#!/bin/sh\ncase \"$3\" in\n");
        for (key, value) in cases {
            match value {
                Some(value) => body.push_str(&format!("\"{key}\") printf '%s\\n' '{value}';;\n")),
                None => body.push_str(&format!("\"{key}\") exit 1;;\n")),
            }
        }
        body.push_str("*) exit 1;;\nesac\n");
        body
    }

    #[test]
    fn configured_identity_reads_name_and_email() {
        let tmp = TempDir::new().unwrap();
        let script = fake_script(&[
            ("user.name", Some("Herbert Maschke")),
            ("user.email", Some("thyseus@pm.me")),
        ]);
        let id = git_identity_for(&fake_git(&tmp, &script)).expect("identity expected");
        assert_eq!(id.name, "Herbert Maschke");
        assert_eq!(id.email.as_deref(), Some("thyseus@pm.me"));
        assert_eq!(id.to_string(), "Herbert Maschke <thyseus@pm.me>");
        assert_eq!(format!("{id}"), "Herbert Maschke <thyseus@pm.me>");
    }

    #[test]
    fn name_only_survives_unconfigured_email() {
        let tmp = TempDir::new().unwrap();
        let script = fake_script(&[("user.name", Some("Herbert Maschke")), ("user.email", None)]);
        let id = git_identity_for(&fake_git(&tmp, &script)).expect("identity expected");
        assert_eq!(id.name, "Herbert Maschke");
        assert_eq!(id.email, None);
        assert_eq!(id.to_string(), "Herbert Maschke");
    }

    #[test]
    fn exit_code_1_on_unconfigured_user_name_is_none() {
        let tmp = TempDir::new().unwrap();
        let script = fake_script(&[("user.name", None)]);
        assert_eq!(git_identity_for(&fake_git(&tmp, &script)), None);
    }

    #[test]
    fn missing_binary_is_none() {
        let tmp = TempDir::new().unwrap();
        let absent = tmp.path().join("no-such-git").display().to_string();
        assert_eq!(git_identity_for(&absent), None);
        assert_eq!(git_identity_for("/nonexistent/git-binary"), None);
    }

    #[test]
    fn stdout_is_trimmed_of_stray_whitespace() {
        let tmp = TempDir::new().unwrap();
        let script = "#!/bin/sh\ncase \"$3\" in\n\"user.name\") printf '  Herbert Maschke  \\n';;\n*) exit 1;;\nesac\n";
        let id = git_identity_for(&fake_git(&tmp, script)).expect("identity expected");
        assert_eq!(id.name, "Herbert Maschke");
    }

    #[test]
    fn resolve_me_with_identity_returns_full_identity() {
        let identity = AuthorIdentity {
            name: "Herbert Maschke".into(),
            email: Some("thyseus@pm.me".into()),
        };
        assert_eq!(
            resolve_me("@me", Some(&identity)),
            Some("Herbert Maschke <thyseus@pm.me>".into())
        );
        assert_eq!(
            resolve_me("me", Some(&identity)),
            Some("Herbert Maschke <thyseus@pm.me>".into())
        );
        assert_eq!(
            resolve_me("Me", Some(&identity)),
            Some("Herbert Maschke <thyseus@pm.me>".into())
        );
        assert_eq!(
            resolve_me("@ME", Some(&identity)),
            Some("Herbert Maschke <thyseus@pm.me>".into())
        );
    }

    #[test]
    fn resolve_me_without_identity_returns_handle() {
        assert_eq!(resolve_me("@me", None), Some("me".into()));
        assert_eq!(resolve_me("me", None), Some("me".into()));
    }

    #[test]
    fn resolve_me_non_me_handles_unchanged() {
        let identity = AuthorIdentity {
            name: "Herb".into(),
            email: Some("herb@example.com".into()),
        };
        assert_eq!(resolve_me("@alice", Some(&identity)), Some("alice".into()));
        assert_eq!(
            resolve_me("Herbert Maschke <thyseus@pm.me>", Some(&identity)),
            Some("Herbert Maschke <thyseus@pm.me>".into())
        );
    }

    #[test]
    fn resolve_me_empty_input() {
        assert_eq!(resolve_me("", None), None);
        assert_eq!(resolve_me("   ", None), None);
    }

    #[test]
    fn assignee_display_shows_name_for_identities() {
        assert_eq!(
            assignee_display("Herbert Maschke <thyseus@pm.me>"),
            "Herbert Maschke"
        );
        assert_eq!(assignee_display(" <thyseus@pm.me>"), "@ <thyseus@pm.me>");
    }

    #[test]
    fn assignee_display_prefixes_handles() {
        assert_eq!(assignee_display("alice"), "@alice");
        assert_eq!(assignee_display("@alice"), "@alice");
    }

    #[test]
    fn parse_assignee_normalizes_handles_and_identities() {
        assert_eq!(parse_assignee("@alice"), Some("alice".to_string()));
        assert_eq!(parse_assignee("alice"), Some("alice".to_string()));
        assert_eq!(parse_assignee("  alice  "), Some("alice".to_string()));
        assert_eq!(
            parse_assignee("Herbert Maschke <thyseus@pm.me>"),
            Some("Herbert Maschke <thyseus@pm.me>".to_string())
        );
        assert_eq!(
            parse_assignee(" <thyseus@pm.me>"),
            Some("thyseus".to_string())
        );
        assert_eq!(parse_assignee(""), None);
        assert_eq!(parse_assignee("   "), None);
        assert_eq!(parse_assignee("@"), None);
    }

    #[test]
    fn segment_matrix_is_deterministic_and_safe() {
        let cases: &[(Option<&str>, &str)] = &[
            (None, "unassigned"),
            (Some(""), "unassigned"),
            (Some("   "), "unassigned"),
            (Some("Herbert Maschke <thyseus@pm.me>"), "herbert-maschke"),
            (Some("herbert.maschke@pm.me"), "herbert-maschke"),
            (Some(" <thyseus@pm.me>"), "thyseus"),
            (Some("alice"), "alice"),
            (Some("@alice"), "alice"),
            (Some("André Möller"), "andr-m-ller"),
            (Some("A_B_C"), "a-b-c"),
            (Some("!!Leading##"), "leading"),
            (Some("Alice: the Great!"), "alice-the-great"),
            (Some("Ünïcødé <weird@example.com>"), "n-c-d"),
        ];
        for (input, expected) in cases {
            assert_eq!(derive_segment(*input), *expected, "input: {input:?}");
        }
    }

    #[test]
    fn every_segment_is_a_single_safe_path_component() {
        let inputs: &[Option<&str>] = &[
            None,
            Some(""),
            Some("Herbert Maschke <thyseus@pm.me>"),
            Some(" <thyseus@pm.me>"),
            Some("../../etc/passwd"),
            Some("@../x"),
            Some(".."),
            Some("a b<c>d"),
            Some("control\u{7}char"),
            Some("back\\slash/name"),
        ];
        for input in inputs {
            let segment = derive_segment(*input);
            assert!(!segment.is_empty(), "input {input:?} gave empty");
            assert!(
                !segment.contains('/') && !segment.contains('\\') && !segment.contains(' '),
                "unsafe segment {segment:?} from {input:?}"
            );
            assert!(
                !segment.chars().any(char::is_control),
                "control char in {segment:?}"
            );
            assert_ne!(segment, ".");
            assert_ne!(segment, "..");
            assert!(
                segment
                    .chars()
                    .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-'),
                "unexpected characters in {segment:?}"
            );
        }
    }

    #[test]
    fn derivation_is_stable_across_repeated_calls() {
        let inputs: &[Option<&str>] = &[
            Some("Herbert Maschke <thyseus@pm.me>"),
            Some(" <thyseus@pm.me>"),
            Some("@alice"),
            Some("André Möller"),
            Some("herbert.maschke@pm.me"),
            None,
        ];
        for input in inputs {
            let first = derive_segment(*input);
            for _ in 0..100 {
                assert_eq!(derive_segment(*input), first, "nondeterministic: {input:?}");
            }
        }
    }

    #[test]
    fn full_identity_splits_name_and_email() {
        assert_eq!(
            parse_full_identity("Herbert Maschke <thyseus@pm.me>"),
            Some(("Herbert Maschke".to_string(), "thyseus@pm.me".to_string()))
        );
        assert_eq!(parse_full_identity("alice"), None);
        assert_eq!(parse_full_identity("a<>"), None);
    }

    #[test]
    fn email_local_part_splits_on_at() {
        assert_eq!(
            email_local_part("thyseus@pm.me"),
            Some("thyseus".to_string())
        );
        assert_eq!(email_local_part("@pm.me"), None);
        assert_eq!(email_local_part("a@b@c"), Some("a".to_string()));
    }
}