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
/// A commit message: the title, then the body as its own paragraph.
pub(crate) fn message(title: &str, body: Option<&str>) -> String {
    match body {
        Some(body) => format!("{title}\n\n{body}"),
        None => title.to_owned(),
    }
}

/// The finished task's description. The commit message leads and its
/// trailers stay last, so they still parse as trailers, with the task's
/// spec kept between them under a `Task:` line.
pub fn finished_message(message: &str, spec: &str) -> String {
    let mut paragraphs = paragraphs(message.trim());
    let trailers = match paragraphs.as_slice() {
        [_, .., last] if is_trailers(last) => paragraphs.pop(),
        _ => None,
    };
    let (title, body) = match spec.trim().split_once('\n') {
        Some((title, body)) => (title, Some(body)),
        None => (spec.trim(), None),
    };
    let mut parts: Vec<String> = paragraphs.into_iter().map(str::to_owned).collect();
    parts.push(format!("Task: {title}"));
    parts.extend(body.map(|body| indent(body.trim())));
    parts.extend(trailers.map(str::to_owned));
    parts.join("\n\n")
}

// Splits trimmed text on runs of two or more newlines.
fn paragraphs(text: &str) -> Vec<&str> {
    let mut pieces = Vec::new();
    if text.is_empty() {
        return pieces;
    }
    let mut rest = text;
    while let Some(start) = rest.find("\n\n") {
        let (piece, tail) = rest.split_at(start);
        pieces.push(piece);
        rest = tail.trim_start_matches('\n');
    }
    pieces.push(rest);
    pieces
}

fn is_trailers(paragraph: &str) -> bool {
    let mut lines = paragraph.lines();
    lines.next().is_some_and(is_trailer) && lines.all(|l| is_trailer(l) || is_continuation(l))
}

/// `Key: value`, where the key is letters, digits, and dashes.
fn is_trailer(line: &str) -> bool {
    let key_end = line
        .find(|c: char| !(c.is_ascii_alphanumeric() || c == '-'))
        .unwrap_or(line.len());
    key_end > 0
        && line
            .get(key_end..)
            .and_then(|rest| rest.strip_prefix(": "))
            .and_then(|value| value.chars().next())
            .is_some_and(|c| !c.is_whitespace())
}

/// A wrapped trailer value: indented, then text.
fn is_continuation(line: &str) -> bool {
    let text = line.trim_start();
    text.len() < line.len() && text.chars().next().is_some_and(|c| !c.is_whitespace())
}

fn indent(text: &str) -> String {
    text.split_inclusive('\n')
        .map(|line| {
            if line.trim().is_empty() {
                "\n".to_owned()
            } else {
                format!("  {line}")
            }
        })
        .collect()
}

/// The short ID in jj's "Created new commit" line.
pub(crate) fn created_commit(stderr: &str) -> Option<&str> {
    let (_, rest) = stderr.split_once("Created new commit ")?;
    let end = rest
        .find(|c: char| !(c.is_alphanumeric() || c == '_'))
        .unwrap_or(rest.len());
    rest.get(..end).filter(|id| !id.is_empty())
}

/// The first `len` characters of a change ID.
pub(crate) fn short(id: &str, len: usize) -> &str {
    id.get(..len).unwrap_or(id)
}

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

    #[test]
    fn message_puts_the_body_after_a_blank_line() {
        assert_eq!(message("T", None), "T");
        assert_eq!(message("T", Some("b")), "T\n\nb");
    }

    #[test]
    fn finished_message_keeps_trailers_last() {
        assert_eq!(
            finished_message(
                "area: do A\n\nBecause.\n\nAssisted-by: Claude\nSigned-off-by: Someone\n",
                "A\n\n- one\n- two\n\nthen three\n"
            ),
            "area: do A\n\nBecause.\n\nTask: A\n\n  - one\n  - two\n\n  then three\n\nAssisted-by: Claude\nSigned-off-by: Someone"
        );
    }

    #[test]
    fn an_empty_message_leaves_only_the_spec() {
        assert_eq!(finished_message("", "A"), "Task: A");
    }

    #[test]
    fn a_lone_paragraph_is_never_trailers() {
        assert_eq!(
            finished_message("Key: value", "A\n"),
            "Key: value\n\nTask: A"
        );
    }

    #[test]
    fn trailers_may_wrap() {
        assert_eq!(
            finished_message("do A\n\nKey: one\n  two\n\n\n", "A"),
            "do A\n\nTask: A\n\nKey: one\n  two"
        );
    }

    #[test]
    fn a_list_isnt_trailers() {
        assert_eq!(
            finished_message("do A\n\n- a list\n  wrapped", "A\n"),
            "do A\n\n- a list\n  wrapped\n\nTask: A"
        );
        assert!(!is_trailer("Key:value"));
        assert!(!is_trailer(": value"));
        assert!(!is_trailer("Key:  value"));
        assert!(!is_continuation("text"));
        assert!(!is_continuation("   "));
    }

    #[test]
    fn created_commit_finds_the_short_id() {
        assert_eq!(
            created_commit("Created new commit abcd 1234 (empty) T\n"),
            Some("abcd")
        );
        assert_eq!(created_commit("Created new commit abcd"), Some("abcd"));
        assert_eq!(created_commit("Created new commit  x"), None);
        assert_eq!(created_commit("nothing"), None);
    }

    #[test]
    fn short_truncates_only_long_ids() {
        assert_eq!(short("abcdefghij", 8), "abcdefgh");
        assert_eq!(short("abc", 8), "abc");
    }
}