build: fix version detection if there is no .git folder available

This path already handles if `git`, the binary, is missing. But we
should also check if this is building from a git checkout, hence having
a .git/ folder in the root. This would happen when building from a
source tarball for example.
This commit is contained in:
Matt Robenolt
2024-09-12 13:06:16 -07:00
parent 12bf107bcb
commit a8599c3bdc

View File

@ -19,8 +19,18 @@ branch: []const u8,
pub fn detect(b: *std.Build) !Version { pub fn detect(b: *std.Build) !Version {
// Execute a bunch of git commands to determine the automatic version. // Execute a bunch of git commands to determine the automatic version.
var code: u8 = 0; var code: u8 = 0;
const root_path = b.build_root.path orelse ".";
// Check that we're within a git checkout with a .git folder, if not, bail early.
const git_path = try std.fs.path.join(b.allocator, &[_][]const u8{ root_path, ".git" });
std.fs.cwd().access(git_path, .{}) catch |err| switch (err) {
error.FileNotFound => return error.GitNotFound,
else => return err,
};
const branch: []const u8 = b.runAllowFail( const branch: []const u8 = b.runAllowFail(
&[_][]const u8{ "git", "-C", b.build_root.path orelse ".", "rev-parse", "--abbrev-ref", "HEAD" }, &[_][]const u8{ "git", "-C", root_path, "rev-parse", "--abbrev-ref", "HEAD" },
&code, &code,
.Ignore, .Ignore,
) catch |err| switch (err) { ) catch |err| switch (err) {
@ -30,7 +40,7 @@ pub fn detect(b: *std.Build) !Version {
const short_hash = short_hash: { const short_hash = short_hash: {
const output = b.runAllowFail( const output = b.runAllowFail(
&[_][]const u8{ "git", "-C", b.build_root.path orelse ".", "log", "--pretty=format:%h", "-n", "1" }, &[_][]const u8{ "git", "-C", root_path, "log", "--pretty=format:%h", "-n", "1" },
&code, &code,
.Ignore, .Ignore,
) catch |err| switch (err) { ) catch |err| switch (err) {
@ -42,7 +52,7 @@ pub fn detect(b: *std.Build) !Version {
}; };
const tag = b.runAllowFail( const tag = b.runAllowFail(
&[_][]const u8{ "git", "-C", b.build_root.path orelse ".", "describe", "--exact-match", "--tags" }, &[_][]const u8{ "git", "-C", root_path, "describe", "--exact-match", "--tags" },
&code, &code,
.Ignore, .Ignore,
) catch |err| switch (err) { ) catch |err| switch (err) {
@ -54,7 +64,7 @@ pub fn detect(b: *std.Build) !Version {
_ = b.runAllowFail(&[_][]const u8{ _ = b.runAllowFail(&[_][]const u8{
"git", "git",
"-C", "-C",
b.build_root.path orelse ".", root_path,
"diff", "diff",
"--quiet", "--quiet",
"--exit-code", "--exit-code",