1{
  2  lib,
  3  stdenv,
  4
  5  apple-sdk_15,
  6  darwin,
  7  darwinMinVersionHook,
  8
  9  cargo-about,
 10  cargo-bundle,
 11  crane,
 12  rustPlatform,
 13  rustToolchain,
 14
 15  copyDesktopItems,
 16  envsubst,
 17  fetchFromGitHub,
 18  makeFontsConf,
 19  makeWrapper,
 20
 21  alsa-lib,
 22  cmake,
 23  curl,
 24  fontconfig,
 25  freetype,
 26  git,
 27  libgit2,
 28  libglvnd,
 29  libxkbcommon,
 30  livekit-libwebrtc,
 31  nodejs_22,
 32  openssl,
 33  perl,
 34  pkg-config,
 35  protobuf,
 36  sqlite,
 37  vulkan-loader,
 38  wayland,
 39  xorg,
 40  zlib,
 41  zstd,
 42
 43  withGLES ? false,
 44  profile ? "release",
 45}:
 46assert withGLES -> stdenv.hostPlatform.isLinux;
 47let
 48  mkIncludeFilter =
 49    root': path: type:
 50    let
 51      # note: under lazy-trees this introduces an extra copy
 52      root = toString root' + "/";
 53      relPath = lib.removePrefix root path;
 54      topLevelIncludes = [
 55        "crates"
 56        "assets"
 57        "extensions"
 58        "script"
 59        "tooling"
 60        "Cargo.toml"
 61        ".config" # nextest?
 62        ".cargo"
 63      ];
 64      firstComp = builtins.head (lib.path.subpath.components relPath);
 65    in
 66    builtins.elem firstComp topLevelIncludes;
 67
 68  craneLib = crane.overrideToolchain rustToolchain;
 69  gpu-lib = if withGLES then libglvnd else vulkan-loader;
 70  commonArgs =
 71    let
 72      zedCargoLock = builtins.fromTOML (builtins.readFile ../crates/zed/Cargo.toml);
 73      stdenv' = stdenv;
 74    in
 75    rec {
 76      pname = "zed-editor";
 77      version = zedCargoLock.package.version + "-nightly";
 78      src = builtins.path {
 79        path = ../.;
 80        filter = mkIncludeFilter ../.;
 81        name = "source";
 82      };
 83
 84      cargoLock = ../Cargo.lock;
 85
 86      nativeBuildInputs =
 87        [
 88          cmake
 89          copyDesktopItems
 90          curl
 91          perl
 92          pkg-config
 93          protobuf
 94          cargo-about
 95          rustPlatform.bindgenHook
 96        ]
 97        ++ lib.optionals stdenv'.hostPlatform.isLinux [ makeWrapper ]
 98        ++ lib.optionals stdenv'.hostPlatform.isDarwin [
 99          (cargo-bundle.overrideAttrs (
100            new: old: {
101              version = "0.6.1-zed";
102              src = fetchFromGitHub {
103                owner = "zed-industries";
104                repo = "cargo-bundle";
105                rev = "2be2669972dff3ddd4daf89a2cb29d2d06cad7c7";
106                hash = "sha256-cSvW0ND148AGdIGWg/ku0yIacVgW+9f1Nsi+kAQxVrI=";
107              };
108              cargoHash = "sha256-urn+A3yuw2uAO4HGmvQnKvWtHqvG9KHxNCCWTiytE4k=";
109
110              # NOTE: can drop once upstream uses `finalAttrs` here:
111              # https://github.com/NixOS/nixpkgs/blob/10214747f5e6e7cb5b9bdf9e018a3c7b3032f5af/pkgs/build-support/rust/build-rust-package/default.nix#L104
112              #
113              # See (for context): https://github.com/NixOS/nixpkgs/pull/382550
114              cargoDeps = rustPlatform.fetchCargoVendor {
115                inherit (new) src;
116                hash = new.cargoHash;
117                patches = new.cargoPatches or [];
118                name = new.cargoDepsName or new.finalPackage.name;
119              };
120            }
121          ))
122        ];
123
124      buildInputs =
125        [
126          curl
127          fontconfig
128          freetype
129          # TODO: need staticlib of this for linking the musl remote server.
130          # should make it a separate derivation/flake output
131          # see https://crane.dev/examples/cross-musl.html
132          libgit2
133          openssl
134          sqlite
135          zlib
136          zstd
137        ]
138        ++ lib.optionals stdenv'.hostPlatform.isLinux [
139          alsa-lib
140          libxkbcommon
141          wayland
142          gpu-lib
143          xorg.libX11
144          xorg.libxcb
145        ]
146        ++ lib.optionals stdenv'.hostPlatform.isDarwin [
147          apple-sdk_15
148          (darwinMinVersionHook "10.15")
149        ];
150
151      cargoExtraArgs = "-p zed -p cli --locked --features=gpui/runtime_shaders";
152
153      stdenv =
154        pkgs:
155        let
156          base = pkgs.llvmPackages.stdenv;
157          addBinTools = old: {
158            cc = old.cc.override {
159              inherit (pkgs.llvmPackages) bintools;
160            };
161          };
162          custom = lib.pipe base [
163            (stdenv: stdenv.override addBinTools)
164            pkgs.stdenvAdapters.useMoldLinker
165          ];
166        in
167        if stdenv'.hostPlatform.isLinux then custom else base;
168
169      env = {
170        ZSTD_SYS_USE_PKG_CONFIG = true;
171        FONTCONFIG_FILE = makeFontsConf {
172          fontDirectories = [
173            ../assets/fonts/lilex
174            ../assets/fonts/ibm-plex-sans
175          ];
176        };
177        ZED_UPDATE_EXPLANATION = "Zed has been installed using Nix. Auto-updates have thus been disabled.";
178        RELEASE_VERSION = version;
179        LK_CUSTOM_WEBRTC = livekit-libwebrtc;
180
181        CARGO_PROFILE = profile;
182        # need to handle some profiles specially https://github.com/rust-lang/cargo/issues/11053
183        TARGET_DIR = "target/" + (if profile == "dev" then "debug" else profile);
184
185        # for some reason these deps being in buildInputs isn't enough, the only thing
186        # about them that's special is that they're manually dlopened at runtime
187        NIX_LDFLAGS = lib.optionalString stdenv'.hostPlatform.isLinux "-rpath ${
188          lib.makeLibraryPath [
189            gpu-lib
190            wayland
191          ]
192        }";
193
194        NIX_OUTPATH_USED_AS_RANDOM_SEED = "norebuilds";
195      };
196
197      # prevent nix from removing the "unused" wayland/gpu-lib rpaths
198      dontPatchELF = stdenv'.hostPlatform.isLinux;
199
200      # TODO: try craneLib.cargoNextest separate output
201      # for now we're not worried about running our test suite (or tests for deps) in the nix sandbox
202      doCheck = false;
203
204      cargoVendorDir = craneLib.vendorCargoDeps {
205        inherit src cargoLock;
206        overrideVendorGitCheckout =
207          let
208            hasWebRtcSys = builtins.any (crate: crate.name == "webrtc-sys");
209            # we can't set $RUSTFLAGS because that clobbers the cargo config
210            # see https://github.com/rust-lang/cargo/issues/5376#issuecomment-2163350032
211            glesConfig = builtins.toFile "config.toml" ''
212              [target.'cfg(all())']
213              rustflags = ["--cfg", "gles"]
214            '';
215
216            # `webrtc-sys` expects a staticlib; nixpkgs' `livekit-webrtc` has been patched to
217            # produce a `dylib`... patching `webrtc-sys`'s build script is the easier option
218            # TODO: send livekit sdk a PR to make this configurable
219            postPatch =
220              ''
221                substituteInPlace webrtc-sys/build.rs --replace-fail \
222                  "cargo:rustc-link-lib=static=webrtc" "cargo:rustc-link-lib=dylib=webrtc"
223              ''
224              + lib.optionalString withGLES ''
225                cat ${glesConfig} >> .cargo/config/config.toml
226              '';
227          in
228          crates: drv:
229          if hasWebRtcSys crates then
230            drv.overrideAttrs (o: {
231              postPatch = (o.postPatch or "") + postPatch;
232            })
233          else
234            drv;
235      };
236    };
237  cargoArtifacts = craneLib.buildDepsOnly commonArgs;
238in
239craneLib.buildPackage (
240  lib.recursiveUpdate commonArgs {
241    inherit cargoArtifacts;
242
243    dontUseCmakeConfigure = true;
244
245    # without the env var generate-licenses fails due to crane's fetchCargoVendor, see:
246    # https://github.com/zed-industries/zed/issues/19971#issuecomment-2688455390
247    # TODO: put this in a separate derivation that depends on src to avoid running it on every build
248    preBuild = ''
249      ALLOW_MISSING_LICENSES=yes bash script/generate-licenses
250      echo nightly > crates/zed/RELEASE_CHANNEL
251    '';
252
253    installPhase =
254      if stdenv.hostPlatform.isDarwin then
255        ''
256          runHook preInstall
257
258          pushd crates/zed
259          sed -i "s/package.metadata.bundle-nightly/package.metadata.bundle/" Cargo.toml
260          export CARGO_BUNDLE_SKIP_BUILD=true
261          app_path="$(cargo bundle --profile $CARGO_PROFILE | xargs)"
262          popd
263
264          mkdir -p $out/Applications $out/bin
265          # Zed expects git next to its own binary
266          ln -s ${git}/bin/git "$app_path/Contents/MacOS/git"
267          mv $TARGET_DIR/cli "$app_path/Contents/MacOS/cli"
268          mv "$app_path" $out/Applications/
269
270          # Physical location of the CLI must be inside the app bundle as this is used
271          # to determine which app to start
272          ln -s "$out/Applications/Zed Nightly.app/Contents/MacOS/cli" $out/bin/zed
273
274          runHook postInstall
275        ''
276      else
277        ''
278          runHook preInstall
279
280          mkdir -p $out/bin $out/libexec
281          cp $TARGET_DIR/zed $out/libexec/zed-editor
282          cp $TARGET_DIR/cli  $out/bin/zed
283          ln -s $out/bin/zed $out/bin/zeditor  # home-manager expects the CLI binary to be here
284
285
286          install -D "crates/zed/resources/app-icon-nightly@2x.png" \
287            "$out/share/icons/hicolor/1024x1024@2x/apps/zed.png"
288          install -D crates/zed/resources/app-icon-nightly.png \
289            $out/share/icons/hicolor/512x512/apps/zed.png
290
291          # TODO: icons should probably be named "zed-nightly"
292          (
293            export DO_STARTUP_NOTIFY="true"
294            export APP_CLI="zed"
295            export APP_ICON="zed"
296            export APP_NAME="Zed Nightly"
297            export APP_ARGS="%U"
298            mkdir -p "$out/share/applications"
299            ${lib.getExe envsubst} < "crates/zed/resources/zed.desktop.in" > "$out/share/applications/dev.zed.Zed-Nightly.desktop"
300            chmod +x "$out/share/applications/dev.zed.Zed-Nightly.desktop"
301          )
302
303          runHook postInstall
304        '';
305
306    # TODO: why isn't this also done on macOS?
307    postFixup = lib.optionalString stdenv.hostPlatform.isLinux ''
308      wrapProgram $out/libexec/zed-editor --suffix PATH : ${lib.makeBinPath [ nodejs_22 ]}
309    '';
310
311    meta = {
312      description = "High-performance, multiplayer code editor from the creators of Atom and Tree-sitter";
313      homepage = "https://zed.dev";
314      changelog = "https://zed.dev/releases/preview";
315      license = lib.licenses.gpl3Only;
316      mainProgram = "zed";
317      platforms = lib.platforms.linux ++ lib.platforms.darwin;
318    };
319  }
320)