zed: Read ZED_COMMIT_SHA from env var when building (#51115)

Jakub Konka created

Quality-of-life improvement for us Nix users - Zed built via `nix build`
will now correctly the git commit sha in its version

<img width="433" height="298" alt="image"
src="https://github.com/user-attachments/assets/b940ee4a-6914-4410-ba20-b50391282a4e"
/>

Release Notes:

- N/A

Change summary

crates/zed/build.rs | 26 +++++++++++++++++++++-----
nix/build.nix       |  7 ++++++-
nix/toolchain.nix   |  1 +
3 files changed, 28 insertions(+), 6 deletions(-)

Detailed changes

crates/zed/build.rs 🔗

@@ -43,12 +43,28 @@ fn main() {
         "cargo:rustc-env=TARGET={}",
         std::env::var("TARGET").unwrap()
     );
-    if let Ok(output) = Command::new("git").args(["rev-parse", "HEAD"]).output()
-        && output.status.success()
-    {
-        let git_sha = String::from_utf8_lossy(&output.stdout);
-        let git_sha = git_sha.trim();
 
+    let git_sha = match std::env::var("ZED_COMMIT_SHA").ok() {
+        Some(git_sha) => {
+            // In deterministic build environments such as Nix, we inject the commit sha into the build script.
+            Some(git_sha)
+        }
+        None => {
+            if let Some(output) = Command::new("git")
+                .args(["rev-parse", "HEAD"])
+                .output()
+                .ok()
+                && output.status.success()
+            {
+                let git_sha = String::from_utf8_lossy(&output.stdout);
+                Some(git_sha.trim().to_string())
+            } else {
+                None
+            }
+        }
+    };
+
+    if let Some(git_sha) = git_sha {
         println!("cargo:rustc-env=ZED_COMMIT_SHA={git_sha}");
 
         if let Some(build_identifier) = option_env!("GITHUB_RUN_NUMBER") {

nix/build.nix 🔗

@@ -52,6 +52,7 @@
 
   withGLES ? false,
   profile ? "release",
+  commitSha ? null,
 }:
 assert withGLES -> stdenv.hostPlatform.isLinux;
 let
@@ -84,7 +85,10 @@ let
     in
     rec {
       pname = "zed-editor";
-      version = zedCargoLock.package.version + "-nightly";
+      version =
+        zedCargoLock.package.version
+        + "-nightly"
+        + lib.optionalString (commitSha != null) "+${builtins.substring 0 7 commitSha}";
       src = builtins.path {
         path = ../.;
         filter = mkIncludeFilter ../.;
@@ -220,6 +224,7 @@ let
         };
         ZED_UPDATE_EXPLANATION = "Zed has been installed using Nix. Auto-updates have thus been disabled.";
         RELEASE_VERSION = version;
+        ZED_COMMIT_SHA = commitSha;
         LK_CUSTOM_WEBRTC = pkgs.callPackage ./livekit-libwebrtc/package.nix { };
         PROTOC = "${protobuf}/bin/protoc";
 

nix/toolchain.nix 🔗

@@ -6,4 +6,5 @@ in
 pkgs.callPackage ./build.nix {
   crane = inputs.crane.mkLib pkgs;
   rustToolchain = rustBin.fromRustupToolchainFile ../rust-toolchain.toml;
+  commitSha = inputs.self.rev or null;
 }