git-std 0.11.11

Standard git workflow — commits, versioning, hooks
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
//! Read-only git queries implemented via `git` CLI subprocess calls.

use std::path::Path;

use super::cmd::{GitError, git};

/// Read a git config value.
pub fn config_value(dir: &Path, key: &str) -> Result<String, GitError> {
    git(dir, &["config", key])
}

/// Return the full SHA of HEAD.
pub fn head_oid(dir: &Path) -> Result<String, GitError> {
    git(dir, &["rev-parse", "HEAD"])
}

/// Return the current branch name (e.g. `main`).
pub fn current_branch(dir: &Path) -> Result<String, GitError> {
    git(dir, &["rev-parse", "--abbrev-ref", "HEAD"])
}

/// Resolve an arbitrary revision spec to a full SHA.
pub fn resolve_rev(dir: &Path, rev: &str) -> Result<String, GitError> {
    git(dir, &["rev-parse", "--verify", rev])
}

/// Detect the repository host (GitHub, GitLab, etc.) from the `origin` remote URL.
pub fn detect_host(dir: &Path) -> standard_changelog::RepoHost {
    match git(dir, &["remote", "get-url", "origin"]) {
        Ok(url) => standard_changelog::detect_host(&url),
        Err(_) => standard_changelog::RepoHost::Unknown,
    }
}

/// Return the staged diff (`git diff --staged`).
///
/// Returns an empty string when there is nothing staged.
pub fn staged_diff(dir: &Path) -> Result<String, GitError> {
    git(dir, &["diff", "--staged"])
}

/// Return `git status --short` output.
///
/// Returns an empty string when the working tree is clean.
pub fn short_status(dir: &Path) -> Result<String, GitError> {
    git(dir, &["status", "--short"])
}

/// Return the list of staged file paths (`git diff --cached --name-only`).
///
/// Returns an empty vector when there is nothing staged.
pub fn staged_files(dir: &Path) -> Result<Vec<String>, GitError> {
    let output = git(dir, &["diff", "--cached", "--name-only"])?;
    Ok(output
        .lines()
        .map(str::to_owned)
        .filter(|s| !s.is_empty())
        .collect())
}

/// Walk commits from `from` (inclusive) back to `until` (exclusive).
///
/// Returns `(full_sha, commit_message)` pairs in topological order.
pub fn walk_commits(
    dir: &Path,
    from: &str,
    until: Option<&str>,
) -> Result<Vec<(String, String)>, GitError> {
    let range = match until {
        Some(u) => format!("{u}..{from}"),
        None => from.to_string(),
    };

    let output = git(
        dir,
        &["log", "--format=%H%x00%B%x00", "--topo-order", &range, "--"],
    )?;
    Ok(parse_nul_delimited_log(&output))
}

/// Walk commits in a revision range string (e.g. `v1.0.0..v2.0.0`).
pub fn walk_range(dir: &Path, range: &str) -> Result<Vec<(String, String)>, GitError> {
    let output = git(
        dir,
        &["log", "--format=%H%x00%B%x00", "--topo-order", range, "--"],
    )?;
    Ok(parse_nul_delimited_log(&output))
}

/// Walk commits from `from` (inclusive) back to `until` (exclusive),
/// filtered to only those touching the given paths.
///
/// Returns `(full_sha, commit_message)` pairs in topological order.
/// Branch commits merged via pull requests are included — the path filter
/// already limits results to commits that actually touched the given paths.
pub fn walk_commits_for_path(
    dir: &Path,
    from: &str,
    until: Option<&str>,
    paths: &[&str],
) -> Result<Vec<(String, String)>, GitError> {
    let range = match until {
        Some(u) => format!("{u}..{from}"),
        None => from.to_string(),
    };

    let mut args = vec!["log", "--format=%H%x00%B%x00", "--topo-order", &range, "--"];
    args.extend(paths);

    let output = git(dir, &args)?;
    Ok(parse_nul_delimited_log(&output))
}

/// Parse NUL-delimited `git log` output into `(sha, message)` pairs.
fn parse_nul_delimited_log(output: &str) -> Vec<(String, String)> {
    let mut commits = Vec::new();
    let parts: Vec<&str> = output.split('\0').collect();
    // The format produces: SHA\0BODY\0 SHA\0BODY\0 ...
    // After split we get pairs with possible leading newlines.
    let mut i = 0;
    while i + 1 < parts.len() {
        let sha_part = parts[i].trim();
        let msg_part = parts[i + 1].trim();
        if !sha_part.is_empty() && sha_part.len() >= 40 {
            // The SHA is the last 40+ hex chars of sha_part (could have leading newline from previous record).
            let sha = if let Some(pos) = sha_part.rfind('\n') {
                &sha_part[pos + 1..]
            } else {
                sha_part
            };
            if sha.len() >= 40 {
                commits.push((sha.to_string(), msg_part.to_string()));
            }
        }
        i += 2;
    }
    commits
}

/// Return the commit date of a revision as `YYYY-MM-DD`.
pub fn commit_date(dir: &Path, rev: &str) -> Result<String, GitError> {
    let output = git(dir, &["log", "-1", "--format=%ai", rev, "--"])?;
    // %ai produces "2024-03-16 12:34:56 +0000", take first 10 chars.
    if output.len() < 10 {
        return Err(GitError {
            message: format!("unexpected date format: '{output}'"),
        });
    }
    Ok(output[..10].to_string())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicI64, Ordering};

    static COMMIT_TIME: AtomicI64 = AtomicI64::new(1_700_000_000);

    fn next_timestamp() -> String {
        let ts = COMMIT_TIME.fetch_add(1, Ordering::SeqCst);
        format!("{ts} +0000")
    }

    fn init_repo(dir: &Path) {
        std::process::Command::new("git")
            .current_dir(dir)
            .args(["init"])
            .output()
            .unwrap();
        std::process::Command::new("git")
            .current_dir(dir)
            .args(["config", "user.name", "Test"])
            .output()
            .unwrap();
        std::process::Command::new("git")
            .current_dir(dir)
            .args(["config", "user.email", "test@test.com"])
            .output()
            .unwrap();
    }

    fn commit(dir: &Path, message: &str) -> String {
        let ts = next_timestamp();
        let filename = format!("file-{}.txt", &ts[..10]);
        std::fs::write(dir.join(&filename), message).unwrap();
        std::process::Command::new("git")
            .current_dir(dir)
            .args(["add", &filename])
            .output()
            .unwrap();
        let output = std::process::Command::new("git")
            .current_dir(dir)
            .args(["commit", "-m", message])
            .env("GIT_COMMITTER_DATE", &ts)
            .env("GIT_AUTHOR_DATE", &ts)
            .output()
            .unwrap();
        assert!(
            output.status.success(),
            "git commit failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        git(dir, &["rev-parse", "HEAD"]).unwrap()
    }

    /// Create a file in a specific subdirectory and commit it.
    fn commit_in_path(dir: &Path, subdir: &str, message: &str) -> String {
        let ts = next_timestamp();
        let full_dir = dir.join(subdir);
        std::fs::create_dir_all(&full_dir).unwrap();
        let filename = format!("{subdir}/file-{}.txt", &ts[..10]);
        std::fs::write(dir.join(&filename), message).unwrap();
        std::process::Command::new("git")
            .current_dir(dir)
            .args(["add", &filename])
            .output()
            .unwrap();
        let output = std::process::Command::new("git")
            .current_dir(dir)
            .args(["commit", "-m", message])
            .env("GIT_COMMITTER_DATE", &ts)
            .env("GIT_AUTHOR_DATE", &ts)
            .output()
            .unwrap();
        assert!(
            output.status.success(),
            "git commit failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        git(dir, &["rev-parse", "HEAD"]).unwrap()
    }

    #[test]
    fn walk_commits_returns_topological_order() {
        let dir = tempfile::tempdir().unwrap();
        init_repo(dir.path());
        commit(dir.path(), "chore: init");
        let start = git(dir.path(), &["rev-parse", "HEAD"]).unwrap();
        commit(dir.path(), "feat: A");
        commit(dir.path(), "feat: B");
        let head = git(dir.path(), &["rev-parse", "HEAD"]).unwrap();

        let commits = walk_commits(dir.path(), &head, Some(&start)).unwrap();
        assert_eq!(commits.len(), 2);
        // Topological order: newest first.
        assert_eq!(commits[0].1, "feat: B");
        assert_eq!(commits[1].1, "feat: A");
    }

    #[test]
    fn walk_commits_for_path_filters_by_directory() {
        let dir = tempfile::tempdir().unwrap();
        init_repo(dir.path());
        let base = commit(dir.path(), "chore: init");
        commit_in_path(dir.path(), "crates/core", "feat: core feature");
        commit_in_path(dir.path(), "crates/cli", "feat: cli feature");
        commit_in_path(dir.path(), "crates/core", "fix: core fix");
        let head = head_oid(dir.path()).unwrap();

        // Only core commits
        let core_commits =
            walk_commits_for_path(dir.path(), &head, Some(&base), &["crates/core"]).unwrap();
        assert_eq!(core_commits.len(), 2);
        assert_eq!(core_commits[0].1, "fix: core fix");
        assert_eq!(core_commits[1].1, "feat: core feature");

        // Only cli commits
        let cli_commits =
            walk_commits_for_path(dir.path(), &head, Some(&base), &["crates/cli"]).unwrap();
        assert_eq!(cli_commits.len(), 1);
        assert_eq!(cli_commits[0].1, "feat: cli feature");
    }

    #[test]
    fn walk_commits_for_path_multi_package_commit_appears_in_both() {
        let dir = tempfile::tempdir().unwrap();
        init_repo(dir.path());
        let base = commit(dir.path(), "chore: init");

        // Create a commit that touches both core and cli
        let ts = next_timestamp();
        std::fs::create_dir_all(dir.path().join("crates/core")).unwrap();
        std::fs::create_dir_all(dir.path().join("crates/cli")).unwrap();
        std::fs::write(dir.path().join("crates/core/shared.txt"), "shared").unwrap();
        std::fs::write(dir.path().join("crates/cli/shared.txt"), "shared").unwrap();
        std::process::Command::new("git")
            .current_dir(dir.path())
            .args(["add", "."])
            .output()
            .unwrap();
        std::process::Command::new("git")
            .current_dir(dir.path())
            .args(["commit", "-m", "feat: shared change"])
            .env("GIT_COMMITTER_DATE", &ts)
            .env("GIT_AUTHOR_DATE", &ts)
            .output()
            .unwrap();
        let head = head_oid(dir.path()).unwrap();

        let core_commits =
            walk_commits_for_path(dir.path(), &head, Some(&base), &["crates/core"]).unwrap();
        let cli_commits =
            walk_commits_for_path(dir.path(), &head, Some(&base), &["crates/cli"]).unwrap();

        assert_eq!(core_commits.len(), 1);
        assert_eq!(cli_commits.len(), 1);
        assert_eq!(core_commits[0].1, "feat: shared change");
        assert_eq!(cli_commits[0].1, "feat: shared change");
    }

    #[test]
    fn walk_commits_for_path_empty_when_no_matching_commits() {
        let dir = tempfile::tempdir().unwrap();
        init_repo(dir.path());
        let base = commit(dir.path(), "chore: init");
        commit_in_path(dir.path(), "crates/core", "feat: core only");
        let head = head_oid(dir.path()).unwrap();

        let commits =
            walk_commits_for_path(dir.path(), &head, Some(&base), &["crates/cli"]).unwrap();
        assert!(commits.is_empty());
    }

    #[test]
    fn walk_commits_for_path_without_until() {
        let dir = tempfile::tempdir().unwrap();
        init_repo(dir.path());
        commit_in_path(dir.path(), "crates/core", "feat: core feature");
        commit_in_path(dir.path(), "crates/cli", "feat: cli feature");
        let head = head_oid(dir.path()).unwrap();

        // Without until, returns all matching commits from HEAD back
        let core_commits =
            walk_commits_for_path(dir.path(), &head, None, &["crates/core"]).unwrap();
        assert_eq!(core_commits.len(), 1);
        assert_eq!(core_commits[0].1, "feat: core feature");
    }

    /// Regression: branch commits merged via a PR must be visible to
    /// `walk_commits_for_path`. Previously `--first-parent` caused git to skip
    /// the feature-branch commits entirely, so the path-filtered query returned
    /// an empty result even though conventional commits existed for the path.
    #[test]
    fn walk_commits_for_path_includes_merged_branch_commits() {
        let dir = tempfile::tempdir().unwrap();
        init_repo(dir.path());
        let base = commit(dir.path(), "chore: init");

        // Simulate a feature branch: create a detached branch from base, add a
        // commit touching crates/core, then merge it into main.
        std::process::Command::new("git")
            .current_dir(dir.path())
            .args(["checkout", "-b", "feature"])
            .output()
            .unwrap();
        let ts = next_timestamp();
        std::fs::create_dir_all(dir.path().join("crates/core")).unwrap();
        std::fs::write(dir.path().join("crates/core/f.txt"), "x").unwrap();
        std::process::Command::new("git")
            .current_dir(dir.path())
            .args(["add", "crates/core/f.txt"])
            .output()
            .unwrap();
        std::process::Command::new("git")
            .current_dir(dir.path())
            .args(["commit", "-m", "feat: core feature on branch"])
            .env("GIT_COMMITTER_DATE", &ts)
            .env("GIT_AUTHOR_DATE", &ts)
            .output()
            .unwrap();

        // Switch back to main and merge (creates a merge commit).
        std::process::Command::new("git")
            .current_dir(dir.path())
            .args(["checkout", "-"])
            .output()
            .unwrap();
        let ts2 = next_timestamp();
        std::process::Command::new("git")
            .current_dir(dir.path())
            .args([
                "merge",
                "--no-ff",
                "feature",
                "-m",
                "Merge branch 'feature'",
            ])
            .env("GIT_COMMITTER_DATE", &ts2)
            .env("GIT_AUTHOR_DATE", &ts2)
            .output()
            .unwrap();

        let head = head_oid(dir.path()).unwrap();
        let commits =
            walk_commits_for_path(dir.path(), &head, Some(&base), &["crates/core"]).unwrap();

        assert_eq!(
            commits.len(),
            1,
            "branch commit must be visible after merge"
        );
        assert_eq!(commits[0].1, "feat: core feature on branch");
    }
}