aboutsummaryrefslogtreecommitdiff

swift2nix

Build Swift packages inside Nix builds.

Usage

Install with niv:

niv init
niv add git --name swift2nix --repo https://git.euandreh.xyz/swift2nix

Create a default.nix with:

let
  niv-sources = import ./nix/sources.nix;
  pkgs = import niv-sources.nixpkgs { };
  src = pkgs.nix-gitignore.gitignoreSource [ ] ./.;
  swift2nix = pkgs.callPackage niv-sources.swift2nix {
    package-resolved = ./Package.resolved;
  };
in pkgs.stdenv.mkDerivation {
  inherit src;
  name = "swift-test";
  buildInputs = with pkgs; [ swift ];
  phases = [ "unpackPhase" "buildPhase" ];
  buildPhase = ''
    # Setup dependencies path to satisfy SwiftPM
    mkdir .build
    ln -s ${swift2nix.env.dependencies-state-json} .build/dependencies-state.json
    ln -s ${swift2nix.env.checkouts} .build/checkouts

    # Run the tests
    swift test
    touch $out
  '';
}

And than run nix-build:

nix-build

Demo

You may also try the demo repository:

pushd "$(mktemp -d)"
git clone https://git.euandreh.xyz/swift2nix-demo
cd swift2nix-demo/
nix-build

Limitations

The swift2nix function (the contents of default.nix) only tries to replicate the minimum environment and make it available so you can add it to a build.

This is only a proof-of-concept. I've managed to make it work for my projects, but I have not looked if the Swift Package Manager provides a better API for exposing its internals, or makes any promises on the shape of the .build/ directory.

Contributing

Patches welcome! Send them to my public-inbox[^1] via the git send-email command (see git-send-email.io for a friendly tutorial).

[^1]: I haven't set up a dedicated mailing list for this project, due to it being so small. Feedback is welcome.