stax 0.50.2

Fast stacked Git branches and PRs
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
use crate::git::GitRepo;
use anyhow::{Context, Result};
use colored::Colorize;
use regex::Regex;
use serde::Serialize;
use std::env;
use std::path::{Path, PathBuf};
use std::process::Command;

/// A single commit entry in the changelog
#[derive(Debug, Clone, Serialize)]
struct CommitEntry {
    hash: String,
    short_hash: String,
    message: String,
    author: String,
    pr_number: Option<u64>,
}

/// JSON output structure for changelog
#[derive(Serialize)]
struct ChangelogJson {
    from: String,
    to: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    resolved_from: Option<String>,
    path: Option<String>,
    commit_count: usize,
    commits: Vec<CommitEntry>,
}

/// Pick the first tag from `git tag --sort=-creatordate` output that matches
/// the optional prefix. Pure function over the raw stdout string so it can be
/// unit-tested without a real repo.
fn pick_latest_tag(git_tag_output: &str, prefix: Option<&str>) -> Result<String> {
    let tag = git_tag_output
        .lines()
        .map(|l| l.trim())
        .filter(|l| !l.is_empty())
        .find(|l| match prefix {
            Some(p) => l.starts_with(p),
            None => true,
        });

    match tag {
        Some(t) => Ok(t.to_string()),
        None => match prefix {
            Some(p) => anyhow::bail!("No tags found matching prefix '{}'", p),
            None => anyhow::bail!("No tags found in this repository"),
        },
    }
}

/// Resolve the latest tag in the repo, optionally filtered by prefix.
fn resolve_latest_tag(workdir: &Path, prefix: Option<&str>) -> Result<String> {
    let output = Command::new("git")
        .args(["tag", "--sort=-creatordate"])
        .current_dir(workdir)
        .output()
        .context("Failed to run git tag")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("git tag failed: {}", stderr.trim());
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    pick_latest_tag(&stdout, prefix)
}

pub fn run(
    from: Option<String>,
    to: String,
    tag_prefix: Option<String>,
    path: Option<String>,
    json: bool,
) -> Result<()> {
    let repo = GitRepo::open()?;
    let workdir = repo.workdir()?;

    let (from, auto_resolved) = match from {
        Some(f) => (f, false),
        None => {
            let tag = resolve_latest_tag(workdir, tag_prefix.as_deref())?;
            (tag, true)
        }
    };

    // Resolve path filter relative to current directory and make it relative to repo root
    let resolved_path = if let Some(p) = path.as_ref() {
        let current_dir = env::current_dir().context("Failed to get current directory")?;
        let path_buf = PathBuf::from(p);

        // Make path absolute if it's relative
        let abs_path = if path_buf.is_absolute() {
            path_buf
        } else {
            current_dir.join(path_buf)
        };

        // Make it relative to the repo root
        let rel_path = abs_path
            .strip_prefix(workdir)
            .context("Path is outside repository")?;

        Some(rel_path.to_string_lossy().to_string())
    } else {
        None
    };

    // Build git log command
    // Use %x00 (NULL byte) as delimiter to handle messages with special characters
    // %aN gives us the author name from git config (user.name)
    let range = format!("{}..{}", from, to);
    let mut args = vec![
        "log".to_string(),
        "--format=%H%x00%s%x00%aN".to_string(),
        range.clone(),
    ];

    // Add path filter if specified
    if let Some(ref p) = resolved_path {
        args.push("--".to_string());
        args.push(p.clone());
    }

    let output = Command::new("git")
        .args(&args)
        .current_dir(workdir)
        .output()
        .context("Failed to run git log")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("git log failed: {}", stderr.trim());
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let commits = parse_commits(&stdout)?;

    if json {
        let output = ChangelogJson {
            from: from.clone(),
            to: to.clone(),
            resolved_from: if auto_resolved {
                Some(from.clone())
            } else {
                None
            },
            path: resolved_path.clone(),
            commit_count: commits.len(),
            commits,
        };
        println!("{}", serde_json::to_string_pretty(&output)?);
        return Ok(());
    }

    // Pretty output
    print_changelog(&from, &to, &resolved_path, &commits);

    Ok(())
}

/// Parse git log output into CommitEntry structs
/// Uses NULL byte (\0) as delimiter to handle messages with special characters
fn parse_commits(output: &str) -> Result<Vec<CommitEntry>> {
    let pr_regex = Regex::new(r"\(#(\d+)\)").unwrap();
    let mut commits = Vec::new();

    for line in output.lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }

        let parts: Vec<&str> = line.splitn(3, '\0').collect();
        if parts.len() < 3 {
            continue;
        }

        let hash = parts[0].to_string();
        let short_hash = hash.chars().take(7).collect();
        let message = parts[1].to_string();
        let author = parts[2].to_string();

        // Extract PR number from message (e.g., "feat: add thing (#123)")
        let pr_number = pr_regex
            .captures(&message)
            .and_then(|caps| caps.get(1))
            .and_then(|m| m.as_str().parse::<u64>().ok());

        commits.push(CommitEntry {
            hash,
            short_hash,
            message,
            author,
            pr_number,
        });
    }

    Ok(commits)
}

/// Print a pretty, colorful changelog
fn print_changelog(from: &str, to: &str, path: &Option<String>, commits: &[CommitEntry]) {
    let commit_word = if commits.len() == 1 {
        "commit"
    } else {
        "commits"
    };

    // Header
    println!(
        "{}",
        format!(
            "Changelog: {} → {} ({} {})",
            from,
            to,
            commits.len(),
            commit_word
        )
        .bold()
    );

    // Path filter indicator
    if let Some(p) = path {
        println!("{}", format!("Filtered to: {}", p).dimmed());
    }

    println!("{}", "─".repeat(50).dimmed());
    println!();

    if commits.is_empty() {
        println!("{}", "No commits found in this range.".dimmed());
        return;
    }

    // Calculate column width for PR number alignment
    let max_pr_width = commits
        .iter()
        .filter_map(|c| c.pr_number)
        .map(|n| format!("#{}", n).len())
        .max()
        .unwrap_or(1)
        .max(1);

    for commit in commits {
        let hash = &commit.short_hash;

        let pr_col = if let Some(n) = commit.pr_number {
            let raw = format!("{:<width$}", format!("#{}", n), width = max_pr_width);
            raw.bright_magenta().to_string()
        } else {
            let raw = " ".repeat(max_pr_width);
            raw.dimmed().to_string()
        };

        let clean_message = remove_pr_suffix(&commit.message);

        println!(
            "    {} {} {} {}",
            hash.bright_yellow(),
            pr_col,
            clean_message,
            format!("(@{})", commit.author).cyan().dimmed(),
        );
    }

    println!();
}

/// Remove the PR number suffix from a commit message for cleaner display
fn remove_pr_suffix(message: &str) -> String {
    let pr_regex = Regex::new(r"\s*\(#\d+\)\s*$").unwrap();
    pr_regex.replace(message, "").trim().to_string()
}

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

    #[test]
    fn test_parse_commits_basic() {
        // Uses NULL byte as delimiter (matches git log --format=%H%x00%s%x00%aN)
        // %aN gives author name from git config (user.name)
        let output =
            "abc1234567890\0feat: add feature\0John Doe\ndef9876543210\0fix: bug fix\0Jane Smith";
        let commits = parse_commits(output).unwrap();

        assert_eq!(commits.len(), 2);
        assert_eq!(commits[0].short_hash, "abc1234");
        assert_eq!(commits[0].message, "feat: add feature");
        assert_eq!(commits[0].author, "John Doe");
        assert_eq!(commits[0].pr_number, None);
    }

    #[test]
    fn test_parse_commits_with_pr() {
        let output = "abc1234567890\0feat: add feature (#42)\0John Doe";
        let commits = parse_commits(output).unwrap();

        assert_eq!(commits.len(), 1);
        assert_eq!(commits[0].pr_number, Some(42));
    }

    #[test]
    fn test_parse_commits_empty() {
        let output = "";
        let commits = parse_commits(output).unwrap();
        assert_eq!(commits.len(), 0);
    }

    #[test]
    fn test_parse_commits_with_special_chars_in_message() {
        // NULL byte delimiter allows pipes and other special chars in message
        let output = "abc1234567890\0feat: add foo|bar feature\0John Doe";
        let commits = parse_commits(output).unwrap();

        assert_eq!(commits.len(), 1);
        assert_eq!(commits[0].message, "feat: add foo|bar feature");
    }

    #[test]
    fn test_remove_pr_suffix() {
        assert_eq!(
            remove_pr_suffix("feat: add thing (#123)"),
            "feat: add thing"
        );
        assert_eq!(remove_pr_suffix("fix: bug (#42)  "), "fix: bug");
        assert_eq!(remove_pr_suffix("no pr here"), "no pr here");
        assert_eq!(
            remove_pr_suffix("mentions #42 but not at end"),
            "mentions #42 but not at end"
        );
    }

    #[test]
    fn test_commit_entry_serialization() {
        let entry = CommitEntry {
            hash: "abc1234567890".to_string(),
            short_hash: "abc1234".to_string(),
            message: "feat: test".to_string(),
            author: "Test Author".to_string(),
            pr_number: Some(42),
        };

        let json = serde_json::to_string(&entry).unwrap();
        assert!(json.contains("\"pr_number\":42"));
        assert!(json.contains("\"short_hash\":\"abc1234\""));
    }

    #[test]
    fn test_changelog_json_serialization() {
        let output = ChangelogJson {
            from: "v1.0.0".to_string(),
            to: "HEAD".to_string(),
            resolved_from: None,
            path: Some("src/".to_string()),
            commit_count: 1,
            commits: vec![CommitEntry {
                hash: "abc123".to_string(),
                short_hash: "abc123".to_string(),
                message: "test".to_string(),
                author: "Test User".to_string(),
                pr_number: None,
            }],
        };

        let json = serde_json::to_string_pretty(&output).unwrap();
        assert!(json.contains("\"from\": \"v1.0.0\""));
        assert!(json.contains("\"path\": \"src/\""));
        assert!(json.contains("\"commit_count\": 1"));
        assert!(!json.contains("resolved_from"));
    }

    #[test]
    fn test_changelog_json_with_resolved_from() {
        let output = ChangelogJson {
            from: "v2.0.0".to_string(),
            to: "HEAD".to_string(),
            resolved_from: Some("v2.0.0".to_string()),
            path: None,
            commit_count: 0,
            commits: vec![],
        };

        let json = serde_json::to_string_pretty(&output).unwrap();
        assert!(json.contains("\"resolved_from\": \"v2.0.0\""));
    }

    #[test]
    fn test_pick_latest_tag_returns_first() {
        let output = "v3.0.0\nv2.0.0\nv1.0.0\n";
        assert_eq!(pick_latest_tag(output, None).unwrap(), "v3.0.0");
    }

    #[test]
    fn test_pick_latest_tag_with_prefix() {
        let output = "release/android/v2.0.0\nrelease/ios/v1.1.0\nrelease/ios/v1.0.0\nrelease/android/v1.0.0\n";
        assert_eq!(
            pick_latest_tag(output, Some("release/ios")).unwrap(),
            "release/ios/v1.1.0"
        );
    }

    #[test]
    fn test_pick_latest_tag_prefix_no_match() {
        let output = "release/android/v1.0.0\nv1.0.0\n";
        let err = pick_latest_tag(output, Some("release/ios")).unwrap_err();
        assert!(err.to_string().contains("release/ios"));
    }

    #[test]
    fn test_pick_latest_tag_empty_output() {
        let err = pick_latest_tag("", None).unwrap_err();
        assert!(err.to_string().contains("No tags found"));
    }

    #[test]
    fn test_pick_latest_tag_whitespace_only() {
        let err = pick_latest_tag("  \n  \n", None).unwrap_err();
        assert!(err.to_string().contains("No tags found"));
    }
}