dockerfmt

repository·main·Indexed 20 days ago

https://github.com/reteps/dockerfmt

An opinionated Dockerfile formatter that normalizes whitespace, upgrades deprecated directives such as MAINTAINER to LABEL, and uses shfmt for consistent shell command formatting within RUN steps. It provides a CLI tool, Go installation, Docker container usage, and JavaScript bindings via WebAssembly (@reteps/dockerfmt). Features include EditorConfig support, a check mode for CI/CD pipelines, and the ability to ignore specific directives using # dockerfmt-ignore.

Tokens
2.4K
Snippets
15
Records
18
Agent score
70%

What's inside dockerfmt

  1. Ignore specific Dockerfile directives

    main

    If the formatter produces unwanted output for a specific command, you can skip formatting for that directive by placing a # dockerfmt-ignore comment on the line immediately preceding it. The ignore rule applies only to the single next directive.

    # dockerfmt-ignore
    RUN   echo   "this stays exactly as-is"
    RUN echo "this gets formatted normally"
  2. Install dockerfmt

    main

    You can install dockerfmt using several methods depending on your environment:

    Via Go

    If you have Go installed, use go install:

    go install github.com/reteps/dockerfmt@latest

    Via Docker

    Run the formatter as a containerized tool without local installation:

    docker run --rm -v $(pwd):/pwd ghcr.io/reteps/dockerfmt:latest /pwd/Dockerfile

    Via Binaries

    Download pre-built binaries directly from the releases page.

  3. Use @reteps/dockerfmt in JavaScript

    main

    The @reteps/dockerfmt package provides JavaScript bindings for the Golang dockerfmt tool via WebAssembly. You can format a Dockerfile by providing a file path, or format a raw string using formatDockerfileContents.

    To use the library, import formatDockerfile and pass the path to your Dockerfile along with an options object.

    import { formatDockerfile } from '@reteps/dockerfmt'
    
    // Formats a Dockerfile from a file path
    const result = await formatDockerfile('../tests/comment.dockerfile', { 
      indent: 4, 
      trailingNewline: true 
    })
    
    console.log(result)
  4. Use dockerfmt to format Dockerfiles

    main

    The dockerfmt CLI allows you to format Dockerfiles via file paths or stdin.

    Common Commands

    • Print to stdout: View the formatted version without modifying the file.
    • Write in-place: Apply formatting changes directly to the file using the -w flag.
    • Check mode: Verify if a file is already formatted. This is useful for CI/CD pipelines; it exits with a non-zero status if the file requires formatting.
    • Stdin: Pipe content into dockerfmt to format it on the fly.
    # format and print to stdout
    dockerfmt Dockerfile
    
    # format in place
    dockerfmt -w Dockerfile
    
    # read from stdin
    cat Dockerfile | dockerfmt
    
    # check if already formatted (exits non-zero if not)
    dockerfmt -c Dockerfile
  5. Integrate dockerfmt with pre-commit

    main

    To automatically format Dockerfiles before every commit, add the following configuration to your .pre-commit-config.yaml file:

    repos:
      - repo: https://github.com/reteps/dockerfmt
        rev: main  # run `pre-commit autoupdate` to pin a version
        hooks:
          - id: dockerfmt
            args:
              - --indent=4
              - --newline
              - --write
  6. Configure dockerfmt with EditorConfig

    main

    When formatting files by path, dockerfmt respects .editorconfig files to apply project-level defaults. Note that CLI flags always take precedence over EditorConfig settings. EditorConfig is not used when reading from stdin.

    [Dockerfile]
    indent_size = 2
    insert_final_newline = true
  7. Configure dockerfmt via EditorConfig

    main

    For file-specific formatting, dockerfmt supports .editorconfig files. When a file path is provided, dockerfmt looks for EditorConfig definitions to override default behavior.

    Precedence Rule: Explicitly set CLI flags always take precedence over EditorConfig settings.

    Supported EditorConfig keys:

    • indent_size: Sets the number of spaces for indentation.
    • insert_final_newline: Determines if a trailing newline is added.
    • space_redirects: A dockerfmt-specific property (not a standard EditorConfig key) that determines if redirect operators are followed by a space.
  8. Ignore specific blocks with # dockerfmt-ignore

    main

    You can prevent dockerfmt from formatting a specific block of code by inserting the following comment on its own line:

    # dockerfmt-ignore
    RUN some complex command that should not be touched

    When the engine detects this comment in a block, it emits the original multiline text verbatim instead of applying formatting rules.

  9. Use dockerfmt in CI with check mode

    main

    To ensure Dockerfiles remain formatted in a CI/CD pipeline, use the --check (or -c) flag. If any provided file is not correctly formatted, dockerfmt will print a message indicating which file failed and exit with status code 1.

    dockerfmt --check Dockerfile
  10. Understand dockerfmt limitations

    main

    While dockerfmt is a powerful tool, it has the following known limitations:

    • RUN Formatter: Does not support command grouping (e.g., { \) or unescaped semicolons; these lines will be returned unformatted.
    • Parser Directives: The # escape=X parser directive is not supported.
    • JSON: No line wrapping is applied to long JSON-form commands.
  11. Configure dockerfmt formatting options

    main

    The Config struct defines the formatting behavior for the dockerfmt engine. Use these fields to control indentation and line endings:

    • IndentSize (uint): The number of spaces used for indentation.
    • TrailingNewline (bool): If true, ensures the output ends with a newline character.
    • SpaceRedirects (bool): Controls how whitespace is handled during shell command formatting (passed to the underlying shfmt printer).
    config := &lib.Config{
        IndentSize:      4,
        TrailingNewline: true,
        SpaceRedirects:  true,
    }
  12. Reference dockerfmt CLI flags

    main

    The following flags are available for controlling the formatting behavior of dockerfmt.

    Flags:
      -c, --check             Check if the file(s) are formatted
      -h, --help              help for dockerfmt
      -i, --indent uint       Number of spaces to use for indentation (default 4)
      -n, --newline           End the file with a trailing newline
      -s, --space-redirects   Redirect operators will be followed by a space
      -w, --write             Write the formatted output back to the file(s)