Wednesday, November 21, 2018

Format code from command line

Command-line source code formatter is a special functionality within Intellij IDEA and Intellij-based products like PhpStorm, WebStorm and etc. which allows to format arbitrary files outside a project scope using an XML file with exported code style settings and a file specification which defines a file or a group of files to be formatted. Although subsequent sections refer to Intellij IDEA they are equally applicable to so-called small IDEs. For the file(s) to be formatted there should be corresponding plug-ins which support required file types. For example, PHP files will be formatted only if PHP plug-in is installed.

Formatter Launcher Script
The script is format.bat on Windows or on Linux/Mac in <Intellij dir>/bin directory, where <Intellij dir> is Intellij IDEA's root installation directory. The script launches Intellij IDEA or Intellij-based IDE which formats specified files and quits. If launched without any parameters or -h parameter, the script outputs a list of its options.


format [-h] [-r|-R] [-s|-settings settingsPath[-m|-mask masks] [path1 [path2]...]


-hShow a help message and exit.
-r|-RScan directories specified in path1,path2.. recursively.
A path to the file with code style settings. To create the settings file open Intellij IDEA, Settings|Editor|Code Style, choose a code style you'd like to use and make necessary adjustments. Click "Manage...", make sure the code style you want to use is selected and click "Export...". Choose "Code style XML file", select a directory and specfiy a file which should contain the settings. Later you can use it's path as settingsPath parameter.
Note: if the parameter is omitted, default code style settings are used.
-m|-mask masks
A comma-separated list of file masks which define the files to be processed, supports wildcard characters: '*' - any string, '?' - any single character.

pathNA path to a file or a directory to be processed.


format -r /Java/src
Format all files in C:\Data\src derectory including all subdirectories using default code style settings.
format -s C:\Data\settings.xml -m * .java,*.html C:\Data\src
Non-recursively format .java and .html files in C:\Data\src directory using code style settings from C:\Data\settings.xml