A problem with formatting code on a branch, is when you come to merge it back to the trunk, you end up having to work thorough lots of file changes which are really only formatting changes. The larger your project size, the more work this involves. I was faced with a similar task recently.
While editing file by file, I usually do the Ctrl-A Ctrl-Shift-F combo to ensure the file is formatted according to our corporate standards before saving any edits. Since much of the code I touched on the branch was formatted under a different standard, and I touched a lot of files while introducing log4j logging, the end result was heading for a hairy merge. What I really needed was a way to bulk format both the branch and the trunk versions of the code-base.
Luckily, I realised that that same formatter embedded in Eclipse can be used to bulk format Java source. Here’s how …
1. Create a configuration file for the formatter.
Create the configuration file, by selecting one of your Eclipse projects, and open the properties dialogue. Navigate to Properties->Java Code Style->Formatter->Enable project specific settings. Select the active profile, and modify it to your tastes, if necessary. Click OK when you’re done.
2. Get your hands on the configuration file.
Using your file manager, navigate to <workspace>/<project>/.settings, and copy org.eclipse.jdt.core.prefs to a new location. This file contains the configurations needed by the Eclipse code formatter, and we will use it later to specify how to format the code.
3. Invoke the code formatter on your project.
From the command line, issue the following command:
<path/to/eclipe>/eclipse.exe -vm <path/to/vm>/java.exe -application org.eclipse.jdt.core.JavaCodeFormatter -verbose -config <path/to/config-file>/org.eclipse.jdt.core.prefs <path/to/project/src>\
The Eclipse formatter will now proceed to format all java files contained in the specified source directory (and subdirectories). You can also limit this power by using file globbing (i.e. …<path/to/project/src>/*.java).
Sometimes the formatter may complain about your code. This is usually because it contains Java 5 constructs. This can be fixed by including the following configurations in your org.eclipse.jdt.core.prefs file:
org.eclipse.jdt.core.compiler.compliance=1.5 org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 org.eclipse.jdt.core.compiler.source=1.5
Now that both my branch and trunk code are formatted according to the same rules, merging could focus on the logic changes between code-bases, and the resulting merge was much easier to work through.