git-custom-cli 2.4.0

Fast, keyboard-driven terminal UI for dated Git commits
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
//! Release helpers: version tags and release notes (pure; used by the tag mode).

/// A parsed semantic version. `prefix` remembers a leading `v`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Semver {
    pub prefix: bool,
    pub major: u64,
    pub minor: u64,
    pub patch: u64,
    pub pre: Option<String>,
    pub build: Option<String>,
}

/// Parses `1.2.3`, `v1.2.3`, `v1.2.3-rc.1+b5`. Anything else (two parts, leading zeros,
/// empty pre-release, letters in the core) is None.
pub fn parse_semver(text: &str) -> Option<Semver> {
    let text = text.trim();
    let (prefix, rest) = match text.strip_prefix('v') {
        Some(rest) => (true, rest),
        None => (false, text),
    };
    let (rest, build) = match rest.split_once('+') {
        Some((core, build)) => (core, Some(build)),
        None => (rest, None),
    };
    let (core, pre) = match rest.split_once('-') {
        Some((core, pre)) => (core, Some(pre)),
        None => (rest, None),
    };
    let ident_ok = |s: &str| {
        !s.is_empty()
            && s.split('.')
                .all(|p| !p.is_empty() && p.chars().all(|c| c.is_ascii_alphanumeric() || c == '-'))
    };
    if pre.is_some_and(|p| !ident_ok(p)) || build.is_some_and(|b| !ident_ok(b)) {
        return None;
    }
    let mut nums = core.split('.').map(|part| {
        let digits = !part.is_empty() && part.chars().all(|c| c.is_ascii_digit());
        if !digits || (part.len() > 1 && part.starts_with('0')) {
            None
        } else {
            part.parse::<u64>().ok()
        }
    });
    let (major, minor, patch) = (nums.next()??, nums.next()??, nums.next()??);
    if nums.next().is_some() {
        return None;
    }
    Some(Semver {
        prefix,
        major,
        minor,
        patch,
        pre: pre.map(str::to_string),
        build: build.map(str::to_string),
    })
}

impl Semver {
    fn plain(&self, major: u64, minor: u64, patch: u64) -> Semver {
        Semver {
            prefix: self.prefix,
            major,
            minor,
            patch,
            pre: None,
            build: None,
        }
    }

    pub fn bump_major(&self) -> Semver {
        self.plain(self.major.saturating_add(1), 0, 0)
    }

    pub fn bump_minor(&self) -> Semver {
        self.plain(self.major, self.minor.saturating_add(1), 0)
    }

    pub fn bump_patch(&self) -> Semver {
        self.plain(self.major, self.minor, self.patch.saturating_add(1))
    }

    /// `1.2.3-rc.1+b5`, with a leading `v` when the parsed text had one.
    pub fn to_string_with_prefix(&self) -> String {
        let mut text = format!(
            "{}{}.{}.{}",
            if self.prefix { "v" } else { "" },
            self.major,
            self.minor,
            self.patch
        );
        if let Some(pre) = &self.pre {
            text.push('-');
            text.push_str(pre);
        }
        if let Some(build) = &self.build {
            text.push('+');
            text.push_str(build);
        }
        text
    }
}

/// One classified conventional commit.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Commit {
    /// Lowercase type (`feat`, `fix`, ...) or `other` when the subject is not conventional.
    pub kind: String,
    pub scope: Option<String>,
    pub breaking: bool,
    pub desc: String,
}

const KINDS: [&str; 10] = [
    "feat", "fix", "docs", "chore", "refactor", "perf", "test", "build", "ci", "revert",
];

pub fn classify_commit(subject: &str, body: &str) -> Commit {
    let subject = subject.trim();
    let footer_breaking = body.lines().any(|line| {
        let line = line.trim_start();
        line.starts_with("BREAKING CHANGE:") || line.starts_with("BREAKING-CHANGE:")
    });
    let conventional = subject.split_once(':').and_then(|(head, desc)| {
        let (head, bang) = match head.strip_suffix('!') {
            Some(h) => (h, true),
            None => (head, false),
        };
        let (kind, scope) = match head.split_once('(') {
            Some((kind, rest)) => {
                let scope = rest.strip_suffix(')')?;
                (
                    kind,
                    (!scope.trim().is_empty()).then(|| scope.trim().to_string()),
                )
            }
            None => (head, None),
        };
        let kind = kind.to_ascii_lowercase();
        KINDS
            .contains(&kind.as_str())
            .then(|| (kind, scope, bang, desc.trim().to_string()))
    });
    match conventional {
        Some((kind, scope, bang, desc)) => Commit {
            kind,
            scope,
            breaking: bang || footer_breaking,
            desc,
        },
        None => Commit {
            kind: "other".into(),
            scope: None,
            breaking: footer_breaking,
            desc: subject.to_string(),
        },
    }
}

/// The next version: breaking -> major (minor while major is 0), feat -> minor, else patch.
pub fn suggest_bump(commits: &[Commit], current: &Semver) -> Semver {
    if commits.iter().any(|c| c.breaking) {
        if current.major == 0 {
            current.bump_minor()
        } else {
            current.bump_major()
        }
    } else if commits.iter().any(|c| c.kind == "feat") {
        current.bump_minor()
    } else {
        current.bump_patch()
    }
}

/// Like `suggest_bump`, but with no previous version it proposes `v0.1.0`.
pub fn suggest_next(commits: &[Commit], current: Option<&Semver>) -> Semver {
    match current {
        Some(current) => suggest_bump(commits, current),
        None => Semver {
            prefix: true,
            major: 0,
            minor: 1,
            patch: 0,
            pre: None,
            build: None,
        },
    }
}

/// Markdown notes grouped Breaking changes / Features / Fixes / Other (empty groups skipped).
pub fn render_changelog(commits: &[Commit]) -> String {
    let line = |c: &Commit| match &c.scope {
        Some(scope) => format!("- {scope}: {}", c.desc),
        None => format!("- {}", c.desc),
    };
    let groups: [(&str, Vec<&Commit>); 4] = [
        (
            "Breaking changes",
            commits.iter().filter(|c| c.breaking).collect(),
        ),
        (
            "Features",
            commits
                .iter()
                .filter(|c| !c.breaking && c.kind == "feat")
                .collect(),
        ),
        (
            "Fixes",
            commits
                .iter()
                .filter(|c| !c.breaking && c.kind == "fix")
                .collect(),
        ),
        (
            "Other",
            commits
                .iter()
                .filter(|c| !c.breaking && c.kind != "feat" && c.kind != "fix")
                .collect(),
        ),
    ];
    let sections: Vec<String> = groups
        .iter()
        .filter(|(_, items)| !items.is_empty())
        .map(|(title, items)| {
            let body: Vec<String> = items.iter().map(|c| line(c)).collect();
            format!("### {title}\n{}", body.join("\n"))
        })
        .collect();
    sections.join("\n\n")
}

/// (tag name, object id) from `git ls-remote --tags` output; peeled `^{}` lines are dropped.
/// An annotated tag's id is the tag object's, which is what a backup must keep.
pub fn parse_ls_remote_oids(text: &str) -> Vec<(String, String)> {
    let mut found: Vec<(String, String)> = Vec::new();
    for line in text.lines() {
        let Some((oid, name)) = line.trim_end().split_once(['\t', ' ']) else {
            continue;
        };
        let Some(name) = name.trim().strip_prefix("refs/tags/") else {
            continue;
        };
        if name.is_empty() || name.ends_with("^{}") || oid.is_empty() {
            continue;
        }
        if !found.iter().any(|(n, _)| n == name) {
            found.push((name.to_string(), oid.to_string()));
        }
    }
    found
}

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

    #[test]
    fn ls_remote_oids_parse() {
        let text = "aaa\trefs/tags/v1\r\nbbb\trefs/tags/v2\nccc\trefs/tags/v2^{}\nddd\trefs/heads/main\nbad\n";
        assert_eq!(
            parse_ls_remote_oids(text),
            [
                ("v1".to_string(), "aaa".to_string()),
                ("v2".to_string(), "bbb".to_string())
            ]
        );
        assert!(parse_ls_remote_oids("").is_empty());
    }

    fn v(text: &str) -> Semver {
        parse_semver(text).unwrap()
    }

    fn commit(subject: &str) -> Commit {
        classify_commit(subject, "")
    }

    #[test]
    fn parse_table() {
        let ok = [
            ("1.2.3", false, (1, 2, 3), None, None),
            ("v1.2.3", true, (1, 2, 3), None, None),
            ("v1.2.3-rc.1+b5", true, (1, 2, 3), Some("rc.1"), Some("b5")),
            ("0.0.0+build", false, (0, 0, 0), None, Some("build")),
            (" v10.20.30 ", true, (10, 20, 30), None, None),
        ];
        for (text, prefix, (a, b, c), pre, build) in ok {
            let s = v(text);
            assert_eq!(
                (s.prefix, s.major, s.minor, s.patch),
                (prefix, a, b, c),
                "{text}"
            );
            assert_eq!(s.pre.as_deref(), pre, "{text}");
            assert_eq!(s.build.as_deref(), build, "{text}");
        }
        for bad in [
            "",
            "v",
            "1.2",
            "1.2.3.4",
            "a.b.c",
            "01.2.3",
            "1.2.x",
            "v1.2.3-",
            "1.2.3+",
            "release",
            "1..3",
            "-1.2.3",
            "1.2.3-a..b",
            "99999999999999999999.0.0",
        ] {
            assert!(parse_semver(bad).is_none(), "{bad:?} should be rejected");
        }
    }

    #[test]
    fn bump_and_print() {
        let s = v("v1.2.3-rc.1+b5");
        assert_eq!(s.to_string_with_prefix(), "v1.2.3-rc.1+b5");
        assert_eq!(s.bump_patch().to_string_with_prefix(), "v1.2.4");
        assert_eq!(s.bump_minor().to_string_with_prefix(), "v1.3.0");
        assert_eq!(s.bump_major().to_string_with_prefix(), "v2.0.0");
        assert_eq!(v("1.9.9").bump_minor().to_string_with_prefix(), "1.10.0");
    }

    #[test]
    fn classify_table() {
        let c = commit("feat(ui)!: new menu");
        assert_eq!(
            (c.kind.as_str(), c.scope.as_deref(), c.breaking),
            ("feat", Some("ui"), true)
        );
        assert_eq!(c.desc, "new menu");
        let c = commit("fix: crash on empty repo");
        assert_eq!(
            (c.kind.as_str(), c.scope.clone(), c.breaking),
            ("fix", None, false)
        );
        let c = classify_commit("refactor: split", "text\n\nBREAKING CHANGE: api gone");
        assert!(c.breaking && c.kind == "refactor");
        let c = commit("Merge branch 'x'");
        assert_eq!(
            (c.kind.as_str(), c.desc.as_str()),
            ("other", "Merge branch 'x'")
        );
        assert_eq!(commit("wip: thing").kind, "other");
        assert_eq!(commit("FEAT: loud").kind, "feat");
        assert_eq!(commit("fix(: broken").kind, "other");
        for kind in KINDS {
            assert_eq!(commit(&format!("{kind}: x")).kind, kind);
        }
        assert_eq!(commit("feat(): x").scope, None);
        assert_eq!(commit("Ünï: ключ").kind, "other");
    }

    #[test]
    fn suggest_rules() {
        let cur = v("v1.4.2");
        assert_eq!(
            suggest_bump(&[commit("fix: a")], &cur).to_string_with_prefix(),
            "v1.4.3"
        );
        assert_eq!(suggest_bump(&[], &cur).to_string_with_prefix(), "v1.4.3");
        assert_eq!(
            suggest_bump(&[commit("fix: a"), commit("feat: b")], &cur).to_string_with_prefix(),
            "v1.5.0"
        );
        assert_eq!(
            suggest_bump(&[commit("fix!: a")], &cur).to_string_with_prefix(),
            "v2.0.0"
        );
        let zero = v("0.3.1");
        assert_eq!(
            suggest_bump(&[commit("feat!: a")], &zero).to_string_with_prefix(),
            "0.4.0"
        );
        assert_eq!(
            suggest_next(&[commit("feat: a")], None).to_string_with_prefix(),
            "v0.1.0"
        );
    }

    #[test]
    fn changelog_snapshot() {
        let commits = vec![
            commit("feat(ui): menu"),
            commit("fix: crash"),
            commit("chore: deps"),
            commit("refactor!: drop api"),
            commit("plain subject"),
        ];
        let expected = "### Breaking changes\n- drop api\n\n### Features\n- ui: menu\n\n### Fixes\n- crash\n\n### Other\n- deps\n- plain subject";
        assert_eq!(render_changelog(&commits), expected);
        assert_eq!(render_changelog(&[]), "");
    }

    #[test]
    fn ls_remote_oids_unicode_and_noise() {
        let text =
            "aaa\trefs/tags/v1\nddd\trefs/heads/main\n\nbad line\neee\trefs/tags/release/é\n";
        let names: Vec<String> = parse_ls_remote_oids(text)
            .into_iter()
            .map(|(n, _)| n)
            .collect();
        assert_eq!(names, ["v1", "release/é"]);
    }
}