4

How can I configure visual studio code to commit to git on save? I saw it is possible to configure a task to compile on save. But I would like to commit when a file is saved. Is there a similar task for this?

Summary:

  • Write on a versioned file
  • Save
  • Trigger the task
  • The task commit the change with a generic message (a timestamp is fine)

Bonus before commit if possible:

  • Compile
  • Run tests

I added the agnostic tag because I would like to be able to do this in C#, F#, TS, Python or else if possible.

Inspired from visual studio code compile on save

aloisdg
  • 22,270
  • 6
  • 85
  • 105
  • 2
    Not straightly related to the technical side of the questions but.... Man, I don't think you want to commit _every time you save_. Per every time you commit something (like, a real revision you want to create), you will have saved things tenths of times... most of the times, anyway. – eftshift0 Sep 30 '18 at 09:07
  • 1
    I plan to use it for kata and TDD exercises. Also, I can squash them on push. – aloisdg Sep 30 '18 at 09:11
  • I think wanting to commit on save is a very valid use case. Git has powerful capabilities for history rewriting. Also, sometimes you may not care about the history, but more about the backup that you get. – MForster Jul 22 '22 at 04:35

2 Answers2

2

To the best of my knowledge, the ability to trigger a build is a special case; i.e. I don't believe VS has a general-purpose hook to do whatever you want "on save". That leaves open one very hacky solution: you can make a commit part of your build process. (As for how to do that: I think you'll find the relevant information here: https://msdn.microsoft.com/en-us/library/e85wte0k.aspx)

Now, in the commit action you add to your build step, you'll have to specify a commit message. I suggest choosing a message that will play nice with auto-squashing, because the creation of "junk commits" is the reason most of us are kind of cringing at this question.

Consider that best practices would say you should only commit code that passes unit tests. Want to run the unit tests? Well, you have to save (and, now, make a commit) first. So inevitably you will generate non-passing commits, and so to conform to best practice (and avoid rending tools like bisect useless) you'd have to squash them away later.

Mark Adelsberger
  • 42,148
  • 4
  • 35
  • 52
2

You could use the GitDoc extension.

This extension also allows to limit the number of commits by grouping changes over a configurable delay, and by only committing if there are no issues in the code.

It also has a few features to quickly restore/undo/squash versions.

MForster
  • 8,806
  • 5
  • 28
  • 32