Luís Soares
Luís Soares

Reputation: 6203

How to auto-format Java code

Note: Before voting to close this question, please be aware I'm not asking any opinion about coding guidelines; I just want help automating a task.


I have a new colleague who likes to have exotic code guidelines like spaces everywhere:

obj.method( a, b );

or

@JoinColumn( name = "LANGUAGE_ID", referencedColumnName = "ID" )
@ManyToOne( optional = false, fetch = EAGER )

spaces.. spaces everywhere!

When you have chained code, this becomes very hard to read.

adapters.stream().filter( adapter -> isValidCRM( adapter.getId(), crmIds ) )
            .forEach( crmAdapter -> futures.add( CompletableFuture
                    .supplyAsync( () -> crmAdapter.getPerson( id ), ec ).exceptionally( throwable -> {
                        LOGGER.error( throwable.getMessage() );
                        return Response.builder().error( throwable ).build();
                    } ) ) );

I'm tired arguing with him and I don't want to code like that, so I did some Google searches on pre-commit git hooks and Jalopy.. but couldn't find anything useful. Jalopy seems very old (Java 1.5).

Basically, I need to auto-format code on push according to his exotic guidelines (he had configured tt_checkstyle.xml). On pull, I don't mind manually reformatting the code according to Java coding guidelines.

We're on Java 1.8 and I use NetBeans. We use git.

Any help (or any alternative to deal with this)? thanks

Upvotes: 4

Views: 4738

Answers (1)

CodeWizard
CodeWizard

Reputation: 141946

You can use a git hook both on server and local or set up local filters (smudge/clean)

Git hooks

Read the official docs for a full reference.


Smudge / clean

Read all about it and to set it up here:
https://git-scm.com/book/en/v2/Customizing-Git-Git-Attributes

It turns out that you can write your own filters for doing substitutions in files on commit/checkout.

These are called clean and smudge filters.

In the .gitattributes file, you can set a filter for particular paths and then set up scripts that will process files just before they’re checked out (“smudge”, see Figure 8-2) and just before they’re staged (“clean”, see Figure 8-3).

These filters can be set to do all sorts of fun things.

enter image description here

Upvotes: 2

Related Questions