Removing unused code automatically

Every Monday, I approve and merge an auto-generated PR that removes all unused code in our 223k LOC front-end application.

If you use Elm, you can do this too! Here’s how:

📂 Install and init elm-review in your project

elm-review by Jeroen Engels is a static analysis tool.

It allows you to define rules to apply to your source code, and tells you which parts don’t follow them.

It can also fix problems automatically!

⚙️ Set up an elm-review config

In the new review folder, set up your ReviewConfig.elm file.

Here’s an example that removes all unused functions and types except for those in the DontScanMe directory:

module ReviewConfig exposing (config)

{-| Do not rename the ReviewConfig module or the config function, because
`elm-review` will look for these.
To add packages that contain rules, add them to this review project using
    `elm install author/packagename`
when inside the directory containing this file.
-}

import NoUnused.Variables
import Review.Rule


config : List Review.Rule.Rule
config =
    [ NoUnused.Variables.rule
    ]
        |> List.map
            (Review.Rule.ignoreErrorsForDirectories
                [ "src/elm/DontScanMe/"
                ]
            )

Run npx elm-review to make sure it works!

📄 Create a YAML configuration for a GitHub Action

Using GitHub Actions allows PRs to be created automatically on a schedule.

Here’s an example config:

# .github/workflows/cleanup.yml
# Runs the elm-review command on a regular basis and opens a PR removing unused code

name: Cleanup

# Controls when the action will run. Triggers the workflow on push or pull request
# events but only for the master branch
on:
   schedule:
     # Run at midnight UTC, every Sunday
     - cron: "0 0 * * 0"
    
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: install node
        uses: actions/setup-node@v1
        with:
          node-version: 14.x
      - run: npx install
      - run: yes | elm-review --fix-all
      - name: Create Pull Request
        uses: peter-evans/create-pull-request@v3
        with:
          commit-message: "Remove unused code"
          title: "Remove unused code using elm-review"
          body: |
            Auto-generated by the Cleanup 🧹 GitHub Action.
          branch: elm-review-cleanup

⬆️ Commit your changes and push to GitHub

That’s it! At the time you specified in the YAML file, you’ll see a PR that removes your project’s unused code.

Thanks to Jeroen Engels for elm-review, a great tool for maintaining your codebase! ❤️


This post was originally a Twitter thread as part of Ship 30 for 30.