Skip to content

kbishopzz/java-checkstyle-autofix

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

3 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Java Checkstyle Auto-Fix Toolkit

🎯 Intelligent Java code quality automation with one-command fixing and formatting

License: MIT Platform Java PRs Welcome Code Style: Google

Stop fixing Java code style issues manually! This toolkit automatically checks, fixes, and formats your Java code in a single command using Checkstyle and Google Java Format integration.

Quick Start β€’ Features β€’ Installation β€’ Documentation β€’ Contributing


πŸ’‘ Why Use This?

  • ⚑ Save Hours: Automatically fixes 60%+ of common Checkstyle violations
  • 🎯 One Command: Replaces complex tool chains with single checkstyle command
  • πŸ”§ Zero Config: Works out-of-the-box with sensible defaults
  • πŸš€ Production Ready: Used by students and professionals for code quality assurance
  • πŸ“š Well Documented: Comprehensive guides, examples, and troubleshooting
  • 🎨 Google Style: Industry-standard formatting built-in

🎯 What This Does

Automatic Fixes

When you run checkstyle YourFile.java, it automatically fixes:

  • βœ… Uppercase 'L' suffix on long literals (123l β†’ 123L)
  • βœ… Array bracket positioning (String arr[] β†’ String[] arr)
  • βœ… Variable naming (my_var β†’ myVar, preserves CONSTANTS)
  • βœ… Unused star imports (removes unused import java.util.*;)
  • βœ… All whitespace/indentation/spacing (via google-java-format)

Manual Fixes Required

These violations are detected but require manual fixing:

  • ❌ Star imports that ARE being used
  • ❌ Multiple variable declarations (int a, b; β†’ separate lines)
  • ❌ Missing braces on if/for/while statements
  • ❌ Empty catch blocks
  • ❌ Magic numbers (hardcoded numeric values)
  • ❌ Missing Javadoc comments

οΏ½ Quick Demo

# Before: messy code with violations
$ cat MyClass.java
public class my_class{
private long num=123l;
private String arr[]=new String[5];
}

# After: one command fixes everything!
$ checkstyle MyClass.java
βœ“ Fixed: Variable naming (my_class β†’ myClass)
βœ“ Fixed: Long literal suffix (123l β†’ 123L)
βœ“ Fixed: Array bracket position (String arr[] β†’ String[])
βœ“ Formatted: Applied Google Java Style
All checks passed! βœ…

# Your code is now clean and compliant
$ cat MyClass.java
public class MyClass {
  private long num = 123L;
  private String[] arr = new String[5];
}

οΏ½πŸš€ Quick Start

Installation

cd scripts
chmod +x setup-checkstyle.sh
./setup-checkstyle.sh

Then restart your terminal:

source ~/.zshrc  # or source ~/.bashrc

Basic Usage

# Check and auto-fix a single file
checkstyle MyClass.java

# Check and auto-fix all Java files
checkstyle *.java

# Check with custom config
checkstyle -c checkstyle.xml MyClass.java

# Skip auto-formatting (still auto-fixes)
checkstyle --no-format MyClass.java

# Skip auto-fixing (still formats)
checkstyle --no-fix MyClass.java

# Check only (no fixes or formatting)
checkstyle --no-fix --no-format MyClass.java

πŸ“‹ Requirements

System Requirements

  • Java JDK: 8 or higher
  • Package Manager: Homebrew (macOS) or apt-get (Linux)
  • Optional: VS Code with Java extensions

Installed by Setup Script

  • Checkstyle: 10.12.7+ (code quality checker)
  • google-java-format: Latest (code formatter)
  • Python 3: For VS Code settings management (usually pre-installed)

πŸ“¦ What Gets Installed

The setup script installs and configures:

  1. Checkstyle via Homebrew/apt-get
  2. google-java-format for automatic code formatting
  3. Global configuration at ~/.config/checkstyle/checkstyle.xml
  4. Wrapper script at ~/.local/bin/checkstyle-wrapper
  5. VS Code integration (if VS Code is installed)
  6. Shell alias for seamless command-line usage

File Locations

~/.config/checkstyle/
β”œβ”€β”€ checkstyle.xml              # Global checkstyle configuration
└── checkstyle-10.12.7-all.jar  # Backup JAR file

~/.local/bin/
└── checkstyle-wrapper          # Intelligent wrapper script

~/.checkstyle-google.xml        # Google Style configuration

~/Library/Application Support/Code/User/settings.json  # VS Code settings (macOS)
~/.config/Code/User/settings.json                      # VS Code settings (Linux)

~/.zshrc or ~/.bashrc           # Shell alias added here

πŸ”§ Configuration

Using Project-Specific Configuration

Copy the included checkstyle.xml to your project root and customize:

cp checkstyle.xml /path/to/your/project/

Then use it:

checkstyle -c checkstyle.xml *.java

Customizing Rules

Edit checkstyle.xml to adjust strictness levels:

<!-- Example: Increase line length limit -->
<module name="LineLength">
    <property name="max" value="120"/>  <!-- Changed from 100 -->
</module>

<!-- Example: Disable a specific check -->
<module name="MagicNumber">
    <property name="severity" value="ignore"/>
</module>

<!-- Example: Allow more abbreviations in names -->
<module name="AbbreviationAsWordInName">
    <property name="allowedAbbreviationLength" value="2"/>  <!-- Changed from 0 -->
</module>

Indentation Settings

The default configuration uses 4-space indentation. To change:

<module name="Indentation">
    <property name="basicOffset" value="2"/>        <!-- Changed from 4 -->
    <property name="braceAdjustment" value="0"/>
    <property name="caseIndent" value="2"/>         <!-- Changed from 4 -->
</module>

πŸŽ“ How It Works

The Auto-Fix Process

  1. Pre-processing fixes (Perl regex)

    • Fixes uppercase L on long literals
    • Repositions array brackets
    • Converts snake_case to camelCase for variables
    • Removes obviously unused imports
  2. Auto-formatting (google-java-format)

    • Applies Google Java Style formatting
    • Fixes all whitespace and indentation
    • Handles line wrapping and spacing
  3. Style checking (Checkstyle)

    • Validates against remaining rules
    • Reports issues that need manual fixing
    • Exits with code 0 if all checks pass

Wrapper Script Intelligence

The checkstyle-wrapper script:

  • Detects available tools (checkstyle, google-java-format)
  • Applies fixes before checking
  • Supports custom configurations
  • Provides helpful options (--no-fix, --no-format)
  • Falls back gracefully if tools are missing

🏒 VS Code Integration

Features

After installation, VS Code automatically:

  • βœ… Runs Checkstyle on file save
  • βœ… Shows violations in Problems panel (Cmd/Ctrl+Shift+M)
  • βœ… Highlights issues inline with squiggly lines
  • βœ… Provides quick-fix suggestions where possible

Manual Checking

Right-click any Java file β†’ "Check Code with Checkstyle"

Disabling Auto-Check

Edit VS Code settings (settings.json):

{
  "java.checkstyle.autocheck": false
}

πŸ“– Examples

Example 1: Before and After

Before (BadStyle.java):

public class BadStyle {
    private String user_name;
    private long timestamp = 123l;
    private String items[] = {"one", "two"};

    public void printInfo(){
        if(user_name!=null)
            System.out.println(user_name);
    }
}

After running checkstyle BadStyle.java:

public class BadStyle {
  private String userName;  // Fixed: snake_case β†’ camelCase
  private long timestamp = 123L;  // Fixed: l β†’ L
  private String[] items = {"one", "two"};  // Fixed: array brackets

  public void printInfo() {  // Fixed: spacing
    if (userName != null) {  // Fixed: spacing, BUT still missing braces (manual)
      System.out.println(userName);
    }
  }
}

Remaining Issues (manual fix required):

[WARN] BadStyle.java:8: 'if' construct must use '{}'s. [NeedBraces]
[WARN] BadStyle.java:1: Missing a Javadoc comment. [MissingJavadocType]

Example 2: Common Violations

See the examples/ directory for sample files demonstrating:

  • CommonIssues.java - Various style violations and their fixes
  • BeforeAfter.java - Side-by-side comparisons
  • ManualFixes.java - Issues requiring manual intervention

πŸ› οΈ Troubleshooting

Issue: Command not found

# Verify installation
which checkstyle
# Should output: checkstyle: aliased to checkstyle-wrapper

# If not, reload shell config
source ~/.zshrc  # or ~/.bashrc

Issue: Permission denied

chmod +x ~/.local/bin/checkstyle-wrapper
chmod +x scripts/setup-checkstyle.sh

Issue: google-java-format not working

# Verify installation
which google-java-format

# Reinstall if needed (macOS)
brew install google-java-format

# Or use --no-format flag
checkstyle --no-format MyClass.java

Issue: VS Code not detecting configuration

  1. Open VS Code Settings (Cmd/Ctrl+,)
  2. Search for "checkstyle"
  3. Verify "Java > Checkstyle: Configuration" points to correct file
  4. Reload VS Code window

Issue: Too many violations

Start with relaxed rules, then gradually increase strictness:

# Use Google config (more lenient)
checkstyle -c ~/.checkstyle-google.xml MyClass.java

# Or customize checkstyle.xml to disable strict checks

🌟 Best Practices

For Students

  1. Run checkstyle *.java before every submission
  2. Fix auto-fixable issues first, then manual ones
  3. Use --no-fix --no-format to see what checkstyle will find on submission
  4. Keep a backup before first run: cp MyClass.java MyClass.java.backup

For Developers

  1. Integrate into your build process
  2. Use project-specific checkstyle.xml for team consistency
  3. Run checkstyle in CI/CD pipelines
  4. Configure IDE to match checkstyle rules

For Teams

  1. Commit checkstyle.xml to version control
  2. Enforce checks in pull request reviews
  3. Document project-specific customizations
  4. Run checkstyle in pre-commit hooks

πŸ”„ Uninstallation

# Remove installed tools (macOS)
brew uninstall checkstyle google-java-format

# Remove configuration files
rm -rf ~/.config/checkstyle
rm ~/.checkstyle-google.xml
rm ~/.local/bin/checkstyle-wrapper

# Remove shell alias (edit ~/.zshrc or ~/.bashrc)
# Delete lines containing: alias checkstyle='checkstyle-wrapper'

πŸ“š Additional Resources

Official Documentation

Learning Resources


🌟 Star History

If you find this project helpful, please consider giving it a star ⭐

🀝 Contributing

We welcome contributions! This project is continuously improved by the community.

Contributors

Thanks to all who have contributed to making this project better!


πŸ“Š Project Stats

  • Language: Shell Script, Perl, Java Configuration
  • License: MIT (free for personal and commercial use)
  • Platforms: macOS, Linux
  • Dependencies: Checkstyle, google-java-format, Java 8+
  • Status: Actively maintained βœ…

πŸ—ΊοΈ Roadmap

  • Windows support (WSL compatibility)
  • GitHub Actions integration examples
  • Maven/Gradle plugin versions
  • Pre-commit hook templates
  • Docker container version
  • IntelliJ IDEA plugin integration

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

MIT License - Copyright (c) 2026 Keith Bishop
Free to use, modify, and distribute with attribution.

πŸ™ Acknowledgments

Built with:

Special Thanks

  • Checkstyle community for extensive documentation
  • Google for open-source formatting tools
  • All contributors and users who provide feedback

πŸ“ž Contact & Support

Get Help

  1. πŸ“– Check the Troubleshooting section
  2. πŸ“‚ Review examples/ for sample code
  3. πŸ“š Consult Checkstyle documentation
  4. πŸ› Open an issue if you're stuck

Stay Updated

  • ⭐ Star this repo to follow updates
  • πŸ‘€ Watch for new releases
  • πŸ”” Enable notifications for important changes

Made with ❀️ for the Java community

Made with Love Maintained Ask Me Anything!

Happy Coding! ✨

⬆ Back to Top

About

A powerful Java code quality toolkit that automatically fixes Checkstyle violations with intelligent auto-fixing and Google Java Format integration

Topics

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages