VSCode: trigger organizeImports when git staging

*爱你&永不变心* 提交于 2020-02-02 02:15:12

问题


I like the automated organize feature in VSCode, but having it doing it on every save has given me some trouble.

...
"editor.codeActionsOnSave": {
    "source.organizeImports": true
  },
...

Is it possible to set up some git hooks that organize the imports (either via vscode or some other script/lib) when I stage them?

Issues

If I hit save too early (do it to kick off prettier all the time) before I have used the imported methods - then it removes it and I have to write the import again.

If I break the code (.jsx) and something appears to not be used and I hit save (to trigger prettier), then it removes the imports. I then have to import them again.


回答1:


There is some form of hook that can be applied when running git add : filters defined in gitconfig and .gitattributes.

See this section of git book for detailed explanations.


Here are the sketches from the documentation (it illustrates how you can configure a filter to run on *.txt files) :

  • when running git add :

  • when running git checkout :

You can define in your gitconfig a filter, which consists of two commands to "clean" and "smudge" :

$ git config --global filter.jsximports.clean fiximports
$ git config --global filter.jsximports.smudge cat

and edit the .gitattributes file to apply this filter on jsx files

*.jsx    filter=jsximports

The script to apply may be tslint --fix, with the ordered-imports rule.

Actually : tslint's rule seem to have its own implementation, but it does something similar (see https://github.com/palantir/tslint/pull/4064)

In this answer : https://stackoverflow.com/a/57458656/86072
user thorn points to this npm package :
https://www.npmjs.com/package/organize-imports-cli
which calls organizeImports from cli



来源:https://stackoverflow.com/questions/56449677/vscode-trigger-organizeimports-when-git-staging

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