How to switch active IntelliJ Code Style for all existing local projects?

大兔子大兔子 提交于 2021-01-29 06:43:06

问题


I would like to standardize my java code style as per Google Java Style Guide. I downloaded intellij-java-google-style.xml, made a few custom tweaks and imported it in IntelliJ in the global IDE section:

Preferences... >> Editor >> Code Style >> gear icon >> Import Scheme >> IntelliJ code style xml

This applies the Code Style to the current project. However, existing IntelliJ projects keep their existing code style. I can see the new Google Style in the other projects' drop-down menus, but I have to manually reselect it for each project. My problem is I have hundreds of projects.

I would like to automatically select the new Google code style for all existing projects without having to go through the Preferences for each one. But how?

NOTE: I don't want to actually auto-format the code in my projects, that would be a git nightmare.


回答1:


If you had imported style xml file into Stored in IDE from the scheme dropdown menu, then it should be used as default for all your projects.

If you using either Apache Maven or Gradle, you can use Goggle Java Format to format all existing projects.

In my opinion, automatically applied code formatting to existing project would not be a good idea because it will affect the changelog for those projects. It make the code comparison much for meaningless.




回答2:


IntelliJ does not provide a way to automatically change code style on existing local repos. So we need to think outside the box.

Recursive Search-And-Replace

It turns out IntelliJ stores the active code style in .idea/codeStyles/codeStyleConfig.xml:

<component name="ProjectCodeStyleConfiguration">
  <state>
    <option name="PREFERRED_PROJECT_CODE_STYLE" value="OldCodeStyle" />
  </state>
</component>

We can do a recursive search-and-replace on all the code style config files in a folder and replace the value field in each. First, make sure you import the Google Style XML into IntelliJ as described in the question and call it GoogleStyle.

Here's the bash command. find recursively searches for all the paths to codeStyleConfig.xml. sed replaces the current code style with GoogleStyle.

find ~/projects -name codeStyleConfig.xml -type f -print0 | xargs -0 sed -i "" -E "s/(.+PREFERRED_PROJECT_CODE_STYLE\" value=\")(.+)(\" \/>)/\1GoogleStyle\3/"

This command has been tested on MacOS 11 and IntelliJ 2020.2. I have not tested on Linux. To understand how the command works, see here and here. For Windows, you can use Notepad++ to do a regex find-and-replace, install a bash library like Cygwin or find PowerShell equivalents (see here and here).



来源:https://stackoverflow.com/questions/65328523/how-to-switch-active-intellij-code-style-for-all-existing-local-projects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!