Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VSCode: trigger organizeImports when git staging

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.

like image 231
Norfeldt Avatar asked Jun 04 '19 18:06

Norfeldt


People also ask

How do I make untracked Files tracked in VS code?

The 'U' means the files are 'untracked', and the 'M' means the files have been 'modified'. You can use the commands: git add -A – To add all the files to the staging area. git commit -m 'message' – To create a 'snapshot' of the files on the staging area.

How do I commit changes in git using Visual Studio code?

You can type a commit message above the changes and press Ctrl+Enter (macOS: ⌘+Enter) to commit them. If there are any staged changes, only those changes will be committed. Otherwise, you'll get a prompt asking you to select what changes you'd like to commit and get the option to change your commit settings.

How do I revert changes in Visual Studio code?

To do the same in Visual Studio, right-click the commit you want to revert and then select Revert.


1 Answers

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 :

apply the "clean" filter when adding files

  • when running git checkout :

apply the "smudge" filter when adding files

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

like image 70
LeGEC Avatar answered Sep 27 '22 19:09

LeGEC