➗0️⃣❓ Check Maybe Div By Zero for Gleam

Package <a href="https://github.com/inoas/check_maybe_div_by_zero/releases"><img src="https://img.shields.io/github/release/inoas/check_maybe_div_by_zero" alt="GitHub release"></a> Version Erlang-compatible JavaScript Compatible Hex Docs Discord

Gleam does not crash on division by zero.

In effect any literal division by zero in Gleam returns a 0. You may opt to use Gleam stdlib’s int.divide, int.modulo, int.remainder, float.divide and float.modulo to catch errors instead of assuming 0.

See following explanations why and what happens:

What does this utility do

This helper checks Gleam code for potential(!) literal division by zero.

  1. It may be 100% fine to run 1 / a if you know that a is never zero.
  2. It may also be fine to run 1 / a where a equals 0 depending on your logical requirements.
  3. This checker is for when this is not fine. It allows you to check a code repository for POTENTIAL literal division by zero in Gleam-land (it does NOT check Erlang or JS FFI).

Caveats

Installation

gleam add check_maybe_div_by_zero@1

Local usage

It is recommended to add this checker to your CI.

gleam run --module check_maybe_div_by_zero
# or explicitly define the src dir to check:
gleam run --module check_maybe_div_by_zero -- src

Further documentation can be found at https://hexdocs.pm/check_maybe_div_by_zero.

CI Integration

You may run gleam run --module check_maybe_div_by_zero which returns exit(0) if no potential division by zero is found, and exit(1) if a potential division by zero is found. It should thus stop the CI in case a division by zero is found.

jobs:
  test-and-no-div-zero:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: erlef/setup-beam@v1
        with:
          otp-version: "28.5"
          gleam-version: "1.16.0"
          rebar3-version: "3"
      - run: gleam deps download
      - run: gleam format --check src test
      - run: gleam test
      - run: gleam run --module check_maybe_div_by_zero -- src
      - run: gleam test --target javascript
      - run: gleam run --module check_maybe_div_by_zero --target javascript -- src

Targets

Development

gleam test # Run the tests on Erlang
gleam test --target javascript # Run the tests on JavaScript
Search Document