1# Crystal {#crystal} 2 3## Building a Crystal package {#building-a-crystal-package} 4 5This section uses [Mint](https://github.com/mint-lang/mint) as an example for how to build a Crystal package. 6 7If the Crystal project has any dependencies, the first step is to get a `shards.nix` file encoding those. Get a copy of the project and go to its root directory such that its `shard.lock` file is in the current directory. Executable projects should usually commit the `shard.lock` file, but sometimes that's not the case, which means you need to generate it yourself. With an existing `shard.lock` file, `crystal2nix` can be run. 8```bash 9$ git clone https://github.com/mint-lang/mint 10$ cd mint 11$ git checkout 0.5.0 12$ if [ ! -f shard.lock ]; then nix-shell -p shards --run "shards lock"; fi 13$ nix-shell -p crystal2nix --run crystal2nix 14``` 15 16This should have generated a `shards.nix` file. 17 18Next create a Nix file for your derivation and use `pkgs.crystal.buildCrystalPackage` as follows: 19 20```nix 21with import <nixpkgs> { }; 22crystal.buildCrystalPackage rec { 23 pname = "mint"; 24 version = "0.5.0"; 25 26 src = fetchFromGitHub { 27 owner = "mint-lang"; 28 repo = "mint"; 29 rev = version; 30 hash = "sha256-dFN9l5fgrM/TtOPqlQvUYgixE4KPr629aBmkwdDoq28="; 31 }; 32 33 # Insert the path to your shards.nix file here 34 shardsFile = ./shards.nix; 35 36 # ... 37} 38``` 39 40This won't build anything yet, because we haven't told it what files build. We can specify a mapping from binary names to source files with the `crystalBinaries` attribute. The project's compilation instructions should show this. For Mint, the binary is called "mint", which is compiled from the source file `src/mint.cr`, so we'll specify this as follows: 41 42```nix 43{ 44 crystalBinaries.mint.src = "src/mint.cr"; 45 46 # ... 47} 48``` 49 50Additionally you can override the default `crystal build` options (which are currently `--release --progress --no-debug --verbose`) with 51 52```nix 53{ 54 crystalBinaries.mint.options = [ 55 "--release" 56 "--verbose" 57 ]; 58} 59``` 60 61Depending on the project, you might need additional steps to get it to compile successfully. In Mint's case, we need to link against openssl, so in the end the Nix file looks as follows: 62 63```nix 64with import <nixpkgs> { }; 65crystal.buildCrystalPackage rec { 66 version = "0.5.0"; 67 pname = "mint"; 68 src = fetchFromGitHub { 69 owner = "mint-lang"; 70 repo = "mint"; 71 rev = version; 72 hash = "sha256-dFN9l5fgrM/TtOPqlQvUYgixE4KPr629aBmkwdDoq28="; 73 }; 74 75 shardsFile = ./shards.nix; 76 crystalBinaries.mint.src = "src/mint.cr"; 77 78 buildInputs = [ openssl ]; 79} 80```