I want to format java code and organize the imports in the pre-commit hook using command line, When i searched how to do this i found this link
which explains how to format the code using eclipse from command line as the following:
eclipse -application org.eclipse.jdt.core.JavaCodeFormatter -config {setting}/org.eclipse.jdt.core.prefs {project.basedir}/src
But couldn't know the parameter name that is responsible for formatting the code, as i expect the command will be like this:
eclipse -application {Java_Import_Organizer_Parameter} -config {setting}/org.eclipse.jdt.ui.prefs {project.basedir}/src
any idea?
Automatically organise import statements whenever you save Here are the steps to organising imports whenever you save: Go to Window > Preferences > Java > Editor > Save Actions. Select Perform the selected actions on save (off by default). Ensure that Organize imports is selected (on by default).
In Eclipse, you press CTRL + SHIFT + O “Organize Imports” to import packages automatically. For IntelliJ IDEA, if you press CTRL + ALT + O “Optimize Imports”, it just removes some unused imports, never imports any package.
Instead of resolving each unresolved references, you can press CTRL+SHIFT+O that is a short cut for organize imports in Spring STS or any eclipse based tool. If you are working on Mac like me then the shortcut is COMMAND+SHIFT+O.
In VSCode, go to File -> Preferences -> Settings and click on the icon in the top right hand corner to open up the settings in JSON. Et voilà! Your imports will now be organized every time you save a file.
The Google Java Style Formatter provides an option to fix imports:
$ java -jar google-java-format-1.4-all-deps.jar
no files were provided
Usage: google-java-format [options] file(s)
Options:
-i, -r, -replace, --replace
Send formatted output back to files, not stdout.
-
Format stdin -> stdout
--aosp, -aosp, -a
Use AOSP style instead of Google Style (4-space indentation)
--fix-imports-only
Fix import order and remove any unused imports, but do no other formatting.
--skip-sorting-imports
Do not fix the import order. Unused imports will still be removed.
--skip-removing-unused-imports
Do not remove unused imports. Imports will still be sorted.
--length, -length
Character length to format.
--lines, -lines, --line, -line
Line range(s) to format, like 5:10 (1-based; default is all).
--offset, -offset
Character offset to format (0-based; default is all).
--help, -help, -h
Print this usage statement
--version, -version, -v
Print the version.
If -i is given with -, the result is sent to stdout.
The --lines, --offset, and --length flags may be given more than once.
The --offset and --length flags must be given an equal number of times.
If --lines, --offset, or --length are given, only one file (or -) may be given.
google-java-format: Version 1.0
https://github.com/google/google-java-format
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With