Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .github/workflows/check-static.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
name: "Check Static Build"

on:
workflow_dispatch:

jobs:
check:
runs-on: "ubuntu-latest"

steps:
- name: "Checkout Codebase"
uses: "actions/checkout@v6"

- name: "Build Static Exectutable"
run: |
bash ./build-static.sh
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: "Check, Test and Build Codebase"
name: "Check, Lint, Test and Build Codebase"

on:
pull_request:
Expand All @@ -10,14 +10,18 @@ jobs:

steps:
- name: "Checkout Codebase"
uses: "actions/checkout@v4"
uses: "actions/checkout@v6"

- name: "Install Nix"
uses: "DeterminateSystems/nix-installer-action@v17"
uses: "DeterminateSystems/nix-installer-action@v21"

- name: "Check, Test and Build"
- name: "Prepare CI devShell"
run: |
nix develop --command bash -c "cabal update --ignore-project && cabal dev-test-build"
nix develop .#ci --command true

- name: "Verify Codebase"
run: |
nix develop .#ci --command cabal verify

- name: "Build Docker Image"
run: |
Expand Down
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
*~
/.direnv
/.envrc
/.stack-work
/dist
/dist-newstyle
/result
/stack.yaml.lock
/tmp
2 changes: 1 addition & 1 deletion .prettierignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
LICENSE.md
dist-newstyle/
dist/
*.md
17 changes: 16 additions & 1 deletion .prettierrc.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,21 @@
{
"tabWidth": 2,
"printWidth": 120,
"singleQuote": false,
"trailingComma": "es5",
"printWidth": 120
"overrides": [
{
"files": "*.md",
"options": {
"printWidth": 80,
"proseWrap": "always"
}
},
{
"files": "package.yaml",
"options": {
"singleQuote": true
}
}
]
}
6 changes: 3 additions & 3 deletions .stan.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@
# In serveral places Stack uses 4-tuples and in one place Stack uses a
# 5-tuple.
[[check]]
id = "STAN-0302"
scope = "all"
type = "Exclude"
id = "STAN-0302"
scope = "all"
type = "Exclude"
25 changes: 25 additions & 0 deletions .taplo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#:schema taplo://taplo.toml

include = ["*.toml"]
exclude = []

[formatting]

align_entries = false # Align entries vertically. Entries that have table headers, comments, or blank lines between them are not aligned.(default false)
align_comments = true # Align consecutive comments after entries and items vertically. This applies to comments that are after entries or array items.(default true)
array_trailing_comma = true # Put trailing commas for multiline arrays.(default true)
array_auto_expand = true # Automatically expand arrays to multiple lines (default true)
array_auto_collapse = false # Automatically collapse arrays if they fit in one line.(default true)
compact_arrays = true # Omit whitespace padding inside single-line arrays.(default true)
compact_inline_tables = false # Omit whitespace padding inside inline tables.(default false)
inline_table_expand = true # Expand values (e.g. arrays) inside inline tables.(default true)
compact_entries = false # Omit whitespace around =. (default false)
column_width = 80 # Target maximum column width after which arrays are expanded into new lines.(default 80)
indent_tables = false # Indent subtables if they come in order(default false)
indent_entries = false # Indent entries under tables.(default false)
indent_string = " " # Indentation to use, should be tabs or spaces but technically could be anything. 2 spaces (" ")
trailing_newline = true # Add trailing newline to the source. (default true)
reorder_keys = false # Alphabetically reorder keys that are not separated by blank lines. (default false)
reorder_arrays = false # Alphabetically reorder array values that are not separated by blank lines. (default false)
allowed_blank_lines = 1 # The maximum amount of consecutive blank lines allowed. (default 2)
crlf = false # Use CRLF line endings. (default false)
81 changes: 53 additions & 28 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,23 +1,34 @@
# Haskell Project Template

This is an opinionated template for creating Haskell projects. It uses
[Nix] [Flakes], [hpack] and [cabal].

> **TODO** Provide minimum viable documentation.
This is an opinionated template for creating Haskell projects. It uses [Nix]
[Flakes], [hpack] and [cabal].

## Features

- Nix flake-based dev/CI shells with a pinned toolchain (nixpkgs + flake-parts).
- hpack-driven Cabal setup (`package.yaml` -> `*.cabal`).
- `cabal-verify` for a full verify pass: format, lint, build, tests, docs.
- Static executable builds for Nix (`justStaticExecutables`) plus a Docker
image.
- `build-static.sh` for producing a musl-linked static binary via Stack.
- Preconfigured formatting and linting tools (fourmolu, hlint, weeder, stan,
nixfmt, statix, shfmt, shellcheck, taplo, prettier).
- Template bootstrap script (`run-template.sh`) to rename and configure the
project.

## Quickstart

Create your repository from this template, clone it on your computer
and enter its directory.
Create your repository from this template, clone it on your computer and enter
its directory.

Then, run following to configure your project:
Then run the following to configure your project:

```sh
bash ./run-template.sh
```

It will prompt some questions and configure your project according to
your answers.
It will prompt some questions and configure your project according to your
answers.

Once it is configured, provision `direnv`. You can copy the `.envrc.tmpl`:

Expand All @@ -39,8 +50,6 @@ development environment:
nix develop
```

And run the big, long build command as given in the next section.

Finally, you can remove the `run-template.sh` script:

```sh
Expand All @@ -49,42 +58,58 @@ rm run-template.sh

## Development

Big, long build command for the impatient:
To run checks, linters, tests and build the codebase in the development
environment, run:

```sh
hpack &&
direnv reload &&
fourmolu -i app/ src/ test/ &&
prettier --write . &&
find . -iname "*.nix" -not -path "*/nix/sources.nix" -print0 | xargs --null nixpkgs-fmt &&
hlint app/ src/ test/ &&
cabal build -O0 &&
cabal run -O0 haskell-template-hebele -- --version &&
cabal v1-test &&
cabal haddock -O0
cabal-verify
```

To run checks, tests and build the codebase in the development environment, run:
You can pass `-c` (or `--clean`) to clean the build artifacts first:

```sh
cabal-dev-test-build
cabal-verify -c
```

You can pass `-c` to clean the build artifacts first:
As of Cabal 3.12, you can now run the above as an external `cabal` command:

```sh
cabal-dev-test-build -c
cabal verify [-c|--clean]
```

As of Cabal 3.12, you can now run the above as an external `cabal` command:
`cabal-verify` is the "all checks" entrypoint. It runs, in order:

- `hpack` to regenerate the `.cabal` file.
- Format/lint for Nix, shell, TOML, Markdown/JSON, and Haskell.
- `cabal build`, a basic `cabal run` (with `--version`), and `cabal test`.
- `weeder` for dead code, `stan` for static analysis, and `cabal haddock`.

The script stops on the first failure and prints the captured output to keep CI
logs readable.

## Static compilation

For a portable, fully static binary (musl-linked), run:

```sh
cabal dev-test-build [-c]
./build-static.sh
```

This script uses [Docker], [Stack], and [ghc-musl], then compresses the binary
with `upx` and copies it to `/tmp/<exe>-static-<os>-<arch>`.

We keep a `stack.yaml` because Stack is the most reliable way to build a static
musl binary without Nix. The resolver should match the nixpkgs baseline Haskell
package set (and thus the [Stackage LTS] used by nixpkgs) to avoid GHC or
dependency mismatches between Nix and the static build pipeline.

<!-- REFERENCES -->

[Nix]: https://nixos.org
[Flakes]: https://wiki.nixos.org/wiki/Flakes
[hpack]: https://github.com/sol/hpack
[cabal]: https://www.haskell.org/cabal
[Docker]: https://www.docker.com
[Stack]: https://docs.haskellstack.org/en/stable/
[ghc-musl]: https://github.com/benz0li/ghc-musl
[Stackage LTS]: https://www.stackage.org/lts
75 changes: 25 additions & 50 deletions build-static.sh
Original file line number Diff line number Diff line change
@@ -1,83 +1,58 @@
#!/usr/bin/env bash

## NOTE: Things would be much easier if we could use Nix, but we can
## not (or I find it rather tedious). So, we have to use Docker.
##
## Also, `cabal install` does not work with
## `--enable-executable-static` flag. So, we have to use `cabal build`
## instead. Finally, `cabal build` does not work with
## `--enable-executable-stripping`, hence the `strip` command usage.
## not (or I find it rather tedious). So, we have to use Docker and
## Haskell Stack to build our static binary.

## Get extra parameters for docker run:
docker_run_opts=("$@")
## Executable name:
EXECUTABLE_NAME="$(yq ".executables | keys | .[0]" package.yaml)"

## Stackage resolver:
STACKAGE_RESOLVER="$(yq ".resolver" stack.yaml)"

## GHC version:
GHC_VERSION="9.8.4"
GHC_VERSION="$(curl -s "https://www.stackage.org/${STACKAGE_RESOLVER}" | grep -oP 'ghc-\K[0-9.]+' | head -n1)"

## Docker image:
DOCKER_IMAGE="quay.io/benz0li/ghc-musl:${GHC_VERSION}"

## Executable name:
EXECUTABLE_NAME="haskell-template-hebele"

## Get the kernel name:
FINAL_KERNEL_NAME="$(docker run "${docker_run_opts[@]}" --rm "${DOCKER_IMAGE}" uname --kernel-name)"

## Get the machine architecture:
FINAL_MACHINE_ARCH="$(docker run "${docker_run_opts[@]}" --rm "${DOCKER_IMAGE}" uname --machine)"

## Final executable name:
FINAL_EXECUTABLE_NAME="${EXECUTABLE_NAME}-static-${FINAL_KERNEL_NAME}-${FINAL_MACHINE_ARCH}"
FINAL_EXECUTABLE_NAME="${EXECUTABLE_NAME}-static-$(uname --kernel-name | tr '[:upper:]' '[:lower:]')-$(uname --machine)"

## Final executable path:
FINAL_EXECUTABLE_PATH="/tmp/${FINAL_EXECUTABLE_NAME}"

## Docker container name:
CONTAINER_NAME="static-builder-for-${EXECUTABLE_NAME}"

echo "Docker image: ${DOCKER_IMAGE}"
echo "Docker container name: ${CONTAINER_NAME}"
echo "Final executable name: ${FINAL_EXECUTABLE_NAME}"
echo "Final executable path: ${FINAL_EXECUTABLE_PATH}"
echo "Building static binary for ${FINAL_KERNEL_NAME} on ${FINAL_MACHINE_ARCH} using GHC ${GHC_VERSION}"

## Create/update .cabal file:
hpack

## Cleanup first:
cabal clean
cabal v1-clean

## First, pin all packages as per Nix:
cabal freeze

## Run the Docker container:
docker run "${docker_run_opts[@]}" -i --detach -v "$(pwd):/app" --name "${CONTAINER_NAME}" "${DOCKER_IMAGE}" /bin/bash
docker run -i --detach -v "$(pwd):/app" --name "${CONTAINER_NAME}" "${DOCKER_IMAGE}" /bin/bash

## Whitelist codebase directory for Git queries:
docker exec "${CONTAINER_NAME}" git config --global --add safe.directory /app

## Update cabal database:
docker exec "${CONTAINER_NAME}" cabal update
## Cleanup inside the container:
docker exec -w "/app" "${CONTAINER_NAME}" cabal clean
docker exec -w "/app" "${CONTAINER_NAME}" cabal v1-clean
docker exec -w "/app" "${CONTAINER_NAME}" stack clean --full

## Build the static binary:
docker exec -w "/app" "${CONTAINER_NAME}" cabal build --enable-executable-static
docker exec -w "/app" "${CONTAINER_NAME}" stack build

## Get the path to the executable:
BUILD_PATH="$(docker exec -w "/app" "${CONTAINER_NAME}" cabal list-bin "${EXECUTABLE_NAME}")"
## Install the static binary to our local-bin-path (/tmp):
docker exec -w "/app" "${CONTAINER_NAME}" stack install

## Strip debugging symbols:
docker exec "${CONTAINER_NAME}" strip "${BUILD_PATH}"

## Copy the binary to the host:
docker cp "${CONTAINER_NAME}:${BUILD_PATH}" "${FINAL_EXECUTABLE_PATH}"
## Install upx:
docker exec -w "/app" "${CONTAINER_NAME}" apk add upx

## Compress the executable:
upx "${FINAL_EXECUTABLE_PATH}"
docker exec -w "/app" "${CONTAINER_NAME}" upx "/tmp/${EXECUTABLE_NAME}"

## Copy the binary to the host:
docker cp "${CONTAINER_NAME}:/tmp/${EXECUTABLE_NAME}" "${FINAL_EXECUTABLE_PATH}"

## Cleanup:
docker exec -w "/app" "${CONTAINER_NAME}" cabal clean
docker exec -w "/app" "${CONTAINER_NAME}" cabal v1-clean
docker exec -w "/app" "${CONTAINER_NAME}" stack clean --full
docker rm -f "${CONTAINER_NAME}"
rm cabal.project.freeze
file "${FINAL_EXECUTABLE_PATH}"
find "${FINAL_EXECUTABLE_PATH}"
Loading