diff options
Diffstat (limited to 'src/diff.zig')
| -rw-r--r-- | src/diff.zig | 24 |
1 files changed, 24 insertions, 0 deletions
diff --git a/src/diff.zig b/src/diff.zig index ed54c149..659576d3 100644 --- a/src/diff.zig +++ b/src/diff.zig @@ -8,6 +8,21 @@ //! taken for a file header. const std = @import("std"); +/// The commit named by git show, format-patch or jj show's leading header. +pub fn commitHash(content: []const u8) ?[]const u8 { + const line = content[0 .. std.mem.indexOfScalar(u8, content, '\n') orelse content.len]; + inline for (.{ "commit ", "From ", "Commit ID: " }) |prefix| { + if (std.mem.startsWith(u8, line, prefix)) { + var words = std.mem.tokenizeAny(u8, line[prefix.len..], " \t\r"); + const hash = words.next() orelse return null; + if (hash.len < 7 or hash.len > 64) return null; + for (hash) |c| if (!std.ascii.isHex(c)) return null; + return hash; + } + } + return null; +} + pub const Kind = enum { /// Anything outside a file header and a hunk: a commit message, /// `Only in ...`, a mail's headers. @@ -653,3 +668,12 @@ test "diff a section's paths are the repository's names under every prefix git w try testing.expectEqualStrings("/dev/null", made[0]); try testing.expectEqualStrings("n.zig", made[1]); } + +test "diff commit headers retain the full hash, not message or hunk text" { + const hash = "0123456789abcdef0123456789abcdef01234567"; + try std.testing.expectEqualStrings(hash, commitHash("commit " ++ hash ++ " (HEAD -> main)\nmessage").?); + try std.testing.expectEqualStrings(hash, commitHash("From " ++ hash ++ " Mon Sep 17 00:00:00 2001\n").?); + try std.testing.expectEqualStrings(hash, commitHash("Commit ID: " ++ hash ++ "\nChange ID: xyz").?); + inline for (.{ "commit ", "commit nope123", "From 1234\n", "@@ -1 +1 @@\n+commit " ++ hash }) |text| + try std.testing.expectEqual(@as(?[]const u8, null), commitHash(text)); +} |
