Thanks to visit codestin.com
Credit goes to github.com

Skip to content

jbangdev/jbang-fmt

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

38 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

JBang Java Formatter (jbang-fmt)

jbang fmt

Note

⚠️ Experimental:
This formatter is experimental and under active development.
Please report issues or suggestions on GitHub.

This project provides a command-line tool for formatting Java source files, with special support for JBang scripts and common Eclipse formatter styles.

Why does this exist?

Most Java code formatters (including Eclipse, Google Java Format, etc.) do not handle JBang script files well. JBang scripts often start with special comment-based directives (like //DEPS, //JAVA, etc.) that are standard Java syntax, but standard formatters may reformat, move, or even delete these directives, breaking the script or making it unreadable.

This tool was created to solve that problem: it formats Java code while leaving JBang directives untouched. It is especially useful for developers who want to keep their JBang scripts clean and consistently formatted, without risking the loss or corruption of important script metadata.

Features

  • Works 100% with Java while having JBang-friendly formatting: By default, the tool detects and protects JBang directives, only formatting the actual true Java code and comments.

  • Check mode for CI/commit hooks: Use --check to check if files would be formatted. Exit with 1 if any files would change.

  • Stdout output: Use --stdout to print formatted content to stdout instead of modifying files.

  • Detailed statistics: Shows processing time and file counts (processed, changed, clean, skipped).

  • Eclipse formatter support: Uses the Eclipse Java code formatter under the hood, with the ability to load custom Eclipse .xml or .prefs style settings.

  • Easy override: Override specific formatter settings, line length, Java version, indentation type, and indentation size.

  • Easy to use: Simple CLI interface, works with files and directories, and can be run via JBang.

  • Customizable: Supports toggling JBang-friendly mode and specifying custom formatter settings.

Usage

You can try out the tool without installing using JBang:

jbang jbang-fmt@jbangdev <parameters>

You can install (and run) the tool using JBang:

jbang app install jbang-fmt@jbangdev

Basic Examples

Format a single Java file:

jbang-fmt MyFile.java

Format all Java files in a directory:

jbang-fmt src/

Format multiple files and directories:

jbang-fmt MyFile.java src/ tests/

Using argument files (@ files):

You can use @ files to specify arguments from a file, which is useful for complex configurations or when you have many files to format:

jbang-fmt @args.txt

Where args.txt contains:

--style google
--line-length 120
--java 17
src/main/java
src/test/java

This is particularly useful for:

  • Complex formatting configurations

  • CI/CD pipelines where you want to version control the formatting arguments

  • Avoiding long command lines

  • Sharing formatting configurations across team members

Check Mode and CI Integration

Check if files would be formatted (perfect for CI):

jbang-fmt --check MyFile.java

Check multiple files and directories:

jbang-fmt --check src/ tests/

The --check flag will:

  • Show which files would be changed

  • Display timing and file statistics

  • Exit with code 1 if any files would change

  • Exit with code 0 if no changes are needed

Output to Stdout

Print formatted content to stdout instead of modifying files:

jbang-fmt --stdout MyFile.java

This is useful for:

  • Piping formatted content to other tools

  • Previewing changes before applying them

  • Integration with other build tools

Verbose and Quiet Output

The formatter provides two output control options to help you get the right amount of information for your use case:

Verbose mode (--verbose):

jbang-fmt --verbose MyFile.java

Use verbose mode when you need to:

  • Debug formatting issues - See exactly which formatter settings are being overridden and what values they’re being set to

  • Understand formatter behavior - Get detailed information about which formatter configuration is being used

  • Troubleshoot CI/CD failures - When format checks fail, verbose output helps identify what’s causing the formatting differences

  • Learn about formatter settings - See how your command-line overrides (like --line-length, --java, etc.) translate to actual Eclipse formatter properties

Quiet mode (--quiet or -q):

jbang-fmt --quiet MyFile.java
# or
jbang-fmt -q MyFile.java

Use quiet mode when you want to:

  • Clean up CI/CD output - Reduce noise in build logs by only showing errors

  • Script integration - When using the formatter in scripts where you only care about success/failure, not the process details

  • Batch processing - When formatting many files and you don’t need to see each file being processed

  • Focus on errors only - Suppress normal output and only see error messages when something goes wrong

Default behavior: Without either option, the formatter shows a balanced amount of information - it will display which files are being processed, the final statistics, and any errors, but won’t show the detailed setting overrides that verbose mode provides.

Using Different Formatter Styles

Use Google Java Format style:

jbang-fmt --style google MyFile.java

The following predefined styles are available:

  • jbang — JBang’s project style (default)

  • eclipse — Eclipse default Java formatter (Eclipse IDE style)

  • google — Google Java Style Guide

  • java — Java community style (OpenJDK-inspired)

  • quarkus — Quarkus project style

  • spring — Spring Framework style

Use custom Eclipse settings file:

If you want to be sure to have a specfifc style you should use the --style option with your version controlled Eclipse settings file.

jbang-fmt --style /path/to/my-formatter.xml MyFile.java

You can also use JBang magic URL fetching for arguments.

jbang jbang-fmt --style %{https://raw.githubusercontent.com/jbangdev/jbang-
fmt/refs/heads/main/src/quarkus.xml} --check .

Easy override

It is highly recommended to use the --style option to specify the formatter style you want to use for reproducible formatting.

But for those cases you might just want to do some one-off formatting without having to commit a new style file.

Below are options to tweak the formatter using property keys + some short hands for common settings (line length, java version, etc.).

Override specific formatter settings:

jbang-fmt --setttings "brace_style=next_line,indentation_size=4" MyFile.java

or if you prefer to use compact key/value pairs. Below compact_else_if is as if it was set to true because no value was specified.

jbang-fmt -Stext_block_indentation=next_line -Scompact_else_if MyFile.java

The keys are the property keys from the Eclipse formatter settings file, you can find the full list in the eclipse.xml file.

For ease of use you can leave out the org.eclipse.jdt.core.formatter. prefix.

Override line length:

jbang-fmt --line-length 120 MyFile.java

Override Java version for formatting:

jbang-fmt --java 17 MyFile.java

Override indentation type (spaces or tabs):

jbang-fmt --indent-with space MyFile.java
jbang-fmt --indent-with tab MyFile.java

Override indentation size:

jbang-fmt --indent-size 4 MyFile.java

Combine multiple options:

jbang-fmt --style google --line-length 100 --java 21 --indent-with space --indent-size 2 MyFile.java

Touch Directives

If you want to have JBang directives formatted as all other java code then run with --touch-jbang. With this option jbang-fmt should work exactly as any other Eclipse formatter.

Below example shows how to use --touch-jbang with the google style which by default formats Java header comments which will break the JBang directives. The main reason why jbang-fmt exists is to avoid this.

jbang-fmt --touch-directives --style google MyFile.java

Output Format

The tool provides detailed feedback about the formatting process:

Normal mode output:

Formatting with default[0 properties, jbang-friendly=false]...
MyFile.java
Formatted 3 files (1 changed, 2 clean, 0 skipped) in 0.2s

Check mode output:

Formatting with default[0 properties, touchJBang=false]...
MyFile.java
Would reformat 1 files (out of 3) in 0.2s. Run without --check to apply.

The statistics show:

  • Total files processed: All Java files that were examined

  • Changed: Files that were modified by the formatter

  • Clean: Files that were already properly formatted

  • Skipped: Non-Java files that were ignored

  • Processing time: How long the formatting took

Usecases

Git Integration

Format only changed Java files in a git commit hook:

Create a pre-commit hook (.git/hooks/pre-commit):

#!/bin/bash

# Get list of staged Java files
STAGED_JAVA_FILES=$(git diff --cached --name-only --diff-filter=ACMR | grep '\.java$')

if [ -n "$STAGED_JAVA_FILES" ]; then
    echo "Formatting staged Java files..."

    # Format the staged files
    jbang-fmt --style jbang $STAGED_JAVA_FILES

    # Re-stage the formatted files
    git add $STAGED_JAVA_FILES

    echo "Java files formatted and re-staged."
fi

Check-only hook to prevent commits with unformatted code:

Create a pre-commit hook (.git/hooks/pre-commit):

#!/bin/bash

# Get list of staged Java files
STAGED_JAVA_FILES=$(git diff --cached --name-only --diff-filter=ACMR | grep '\.java$')

if [ -n "$STAGED_JAVA_FILES" ]; then
    echo "Checking Java file formatting..."

    # Check if files need formatting
    if ! jbang-fmt --style jbang --check $STAGED_JAVA_FILES; then
        echo "❌ Some Java files are not properly formatted!"
        echo "Run 'jbang-fmt $STAGED_JAVA_FILES' to fix them."
        exit 1
    fi

    echo "✅ All Java files are properly formatted."
fi

Make the hook executable:

chmod +x .git/hooks/pre-commit

Maven Integration

Use the jbang-maven-plugin to format Java files in your Maven project:

Add the plugin to your pom.xml:

<plugin>
    <groupId>dev.jbang</groupId>
    <artifactId>jbang-maven-plugin</artifactId>
    <version>0.4.0</version>
    <executions>
        <execution>
            <id>format</id>
            <goals>
                <goal>run</goal>
            </goals>
            <configuration>
                <script>jbang-fmt@jbangdev/jbang-fmt</script>
                <args>
                    <arg>--style</arg>
                    <arg>jbang</arg>
                    <arg>src/main/java</arg>
                    <arg>src/test/java</arg>
                </args>
            </configuration>
        </execution>
    </executions>
</plugin>

Run formatting:

mvn jbang:run@format

Check formatting (for CI):

<plugin>
    <groupId>dev.jbang</groupId>
    <artifactId>jbang-maven-plugin</artifactId>
    <version>0.4.0</version>
    <executions>
        <execution>
            <id>check-format</id>
            <goals>
                <goal>run</goal>
            </goals>
            <configuration>
                <script>jbang-fmt@jbangdev/jbang-fmt</script>
                <args>
                    <arg>--style</arg>
                    <arg>jbang</arg>
                    <arg>--check</arg>
                    <arg>src/main/java</arg>
                    <arg>src/test/java</arg>
                </args>
            </configuration>
        </execution>
    </executions>
</plugin>

Run format check:

mvn jbang:run@check-format

Integration with Maven build lifecycle (format before compile):

<plugin>
    <groupId>dev.jbang</groupId>
    <artifactId>jbang-maven-plugin</artifactId>
    <version>0.4.0</version>
    <executions>
        <execution>
            <id>format-before-compile</id>
            <phase>generate-sources</phase>
            <goals>
                <goal>run</goal>
            </goals>
            <configuration>
                <script>jbang-fmt@jbangdev/jbang-fmt</script>
                <args>
                    <arg>--style</arg>
                    <arg>jbang</arg>
                    <arg>src/main/java</arg>
                    <arg>src/test/java</arg>
                </args>
            </configuration>
        </execution>
    </executions>
</plugin>

This will automatically format your Java files during the generate-sources phase, which runs before compilation. The formatting happens automatically when you run:

mvn compile

Alternative: Format check before compile (fail build if unformatted):

<plugin>
    <groupId>dev.jbang</groupId>
    <artifactId>jbang-maven-plugin</artifactId>
    <version>0.4.0</version>
    <executions>
        <execution>
            <id>check-format-before-compile</id>
            <phase>generate-sources</phase>
            <goals>
                <goal>run</goal>
            </goals>
            <configuration>
                <script>jbang-fmt@jbangdev/jbang-fmt</script>
                <args>
                    <arg>--style</arg>
                    <arg>jbang</arg>
                    <arg>--check</arg>
                    <arg>src/main/java</arg>
                    <arg>src/test/java</arg>
                </args>
            </configuration>
        </execution>
    </executions>
</plugin>

This will check formatting during the generate-sources phase and fail the build if any files need formatting.

Gradle Integration

Use the jbang-gradle-plugin to format Java files in your Gradle project:

Add the plugin to your build.gradle:

plugins {
    id 'dev.jbang.gradle' version '0.4.0'
}

jbang {
    script 'jbang-fmt@jbangdev/jbang-fmt'
    args '--style', 'jbang', 'src/main/java', 'src/test/java'
}

Run formatting:

./gradlew jbang

For format checking, create a separate task:

plugins {
    id 'dev.jbang.gradle' version '0.4.0'
}

task checkFormat(type: dev.jbang.gradle.JbangTask) {
    script 'jbang-fmt@jbangdev/jbang-fmt'
    args '--style', 'jbang', '--check', 'src/main/java', 'src/test/java'
}

task format(type: dev.jbang.gradle.JbangTask) {
    script 'jbang-fmt@jbangdev/jbang-fmt'
    args '--style', 'jbang', 'src/main/java', 'src/test/java'
}

Run tasks:

./gradlew format        # Format files
./gradlew checkFormat   # Check formatting

Integration with build lifecycle:

plugins {
    id 'dev.jbang.gradle' version '0.4.0'
}

task checkFormat(type: dev.jbang.gradle.JbangTask) {
    script 'jbang-fmt@jbangdev/jbang-fmt'
    args '--style', 'jbang', '--check', 'src/main/java', 'src/test/java'
}

// Run format check before compilation
compileJava.dependsOn checkFormat

TODO

Probably should make this a published jar on maven central and/or github release, jrelease etc…​.but for now just use it via JBang :)

About

Formatter for Java code that is JBang friendly

Resources

Stars

Watchers

Forks

Releases

No releases published

Sponsor this project

  •  

Packages

No packages published

Contributors 2

  •  
  •  

Languages