r/git • • 1d ago

How often should I commit my changes?

I am fairly new to programming and git and I was just wondering how often I should commit my changes both locally and to Github? I feel like I'm doing it to often

8 Upvotes

74 comments sorted by

30

u/jorgb 1d ago

Everytime your code compiles, runs and has tests to ensure it is in working condition. Never commit broken code, only exception is in a branch for safe keeps (you can also use git stash for that) but never on your main branch.

20

u/TachikawaKan5241 1d ago

Oh right so like whenever the code is in a functioning state where if I mess something up I can just roll back to the last commit and know it will work from there?

7

u/Soggy_Writing_3912 advanced 1d ago

yes, exactly!

2

u/themule71 1d ago

More than that. It enable git bisec. Which goes several commits back, and expects working ones.

-1

u/jorgb 1d ago

Yes, if you can't trust previous versions to be working, you might as well create a zip file periodically of your codebase. It will become more and more important when your repo gets bigger and complex, then you might need to go a few versions back to debug a change

3

u/CommandLionInterface 21h ago

Disagree about the zip file. Why on earth would you need that?

3

u/jorgb 21h ago

It was meant that if you don't use git properly, why use git versioning at all, you might just go back to zipping your files as a backup. It wasn't meant seriously

5

u/One-Payment434 17h ago

You're describing when to create a pull-request; standard procedure is to do development on a branch and when the code in this branch is working it is merged into main.

During development you can commit as often as you want, I haven't seen anyone yet committing too often on a development branch.

1

u/DanKegel 6h ago

I don't commit until tests are passing.

I don't create a pull requests until the branch has a clean set of commits that do something useful.

-1

u/jorgb 17h ago

That depends on how the organization has their branching setup and development flow, if pull requests are a thing, sure. OP asked when to commit, and I just mentioned "commit tested, and working code only". I used VCS and git for a long time without pull requests, and when I work solo I only bother with branches if the code is complex enough to warrant multiple commits to get to an end goal.

3

u/One-Payment434 17h ago

IME if you are only committing when you have something that is in working condition you are not committing often enough, or only doing trivial things.

1

u/AlleyOcelot 6h ago

Put "WIP" and a description of where you're at / what the holdup is to it working in the commit message. ex 'product filter WIP, missing UI classes'. Hard second to everyone saying don't go over 1/2 day without a commit. Do all this on a non merged branch.

-1

u/kpg_on_ao3 8h ago

What? You should commit only when you've completed a discrete, logical task. You shouldn't be polluting commit history with broken code.

2

u/symbiatch 7h ago

Why not?

Are you confusing commits with pushing to others? I can make commit after each character if I want. Yet what is pushed will be very different. And what is merged is again different.

These are entirely different concepts. Don’t confuse them.

2

u/symbiatch 7h ago

Committing still is separate from pushing. If you’re always working on main branch and also pushing every commit you make you’re in a wildly different world from most others.

6

u/themule71 1d ago

Correct. But also WIP commits can be later squashed with a rebase, but of course better have a feature/wip dedicated branch at that point.

0

u/kpg_on_ao3 8h ago

why would you commit a WIP? A commit is a save point. Why would you want to revert back to broken code?

You should pick a single task/unit of work and implement it. Then commit. My current project, here's the previous few commits:

- feat: freeze Foo for hashability
  • feat(works): add chapter_ct, total_chapters to Item. Fixes #317.
  • feat(works): use Work.chapter_ct to decide when to trigger behavior X. Fixes #301.
  • fix: update models to use Work.chapter_ct
  • chore: bump DB lib to 7.1.0
  • refactor: use upsert on DTRepository
  • feat(spider): refresh index if required by chapter_ct

Each commit compiles, passes all tests, lints, etc., and they all implement one small thing completely. The messages cross-reference tickets, identify if it's a feature or a bug fix or other (chore/refactor/etc.), and often they identify which piece of the code base this commit is about.

Anyone can see from the history what a commit does, and if you look, they usually only involve a couple files. It's easy for anyone to look at and understand quickly.

Keep your commit history clean!

1

u/symbiatch 7h ago

You literally answered your own question.

“A commit is a save point.”

That doesn’t mean it’s working correctly. It’s a point. “Here I made part 1 work, everything else isn’t working” is a save point. It’s broken since it doesn’t work fully, but it’s reasonable to save it.

Why would I want to revert to that? Because part 1 works. I broke rest more. Not working, let’s go back and do differently.

And then you even list how you commit “broken code.”

You also seem to confuse this with pushes and merges which are entirely different thing.

3

u/boomkablamo 23h ago

You should pretty much never be committing, or more importantly pushing, directly on main...

1

u/dmazzoni 16h ago

You can if it’s your own repo and you’re the only developer.

Even at work I keep lots of repos for my own tools and scripts. I push changes directly to main.

1

u/boomkablamo 16h ago

You can do whatever you want in your own repo. But seems like OP wants to know best practices.

9

u/gororuns 11h ago

If you are working by yourself, you can always use 'commit --amend' to overwrite the last commit, to keep your branch clean. Imo there's no such thing as committing too often, only not committing enough, and a rookie mistake is to lose work by not committing.

4

u/TachikawaKan5241 11h ago

I had no idea about that flag for commit thanks! that'll be very useful I used to make whole new commits because I noticed a typo in my readme or forgot to make a .gitignore

1

u/devignswag 2h ago

You can also squash commits afterwards. Even better if you make commits to a feature branch, then squash merge into main when the feature is done.

32

u/just_here_for_place 1d ago

Whenever you feel like it, but at least after every meaningful increment.

9

u/Soggy_Writing_3912 advanced 1d ago

that being said, i would still strongly suggest a commit at the outermost of 4 hrs of work. in other words, if you have been at it for 4 hrs, and still don't have some meaningful state (by developers' definition, not business definition), then something else is wrong.

1

u/shozzlez 13h ago

Even if you don’t push to a remote branch ?

3

u/Soggy_Writing_3912 advanced 12h ago

treat the remote as a safety net in case the laptop gets corrupted, fluid spillage, theft, etc. In that case, how often would you push to remote so that you at least have a backup copy?

2

u/TagadaPouetPouet 15h ago

This is the most important. You can still rebase to squash or rework the commits, but in the end what really matters is having a list of meaningful commits.
A reviewer should be able to understand your work by reading the successive commit messages.

11

u/cringelord000222 1d ago • Bravo

many commits per day, even when you are still working on it

8

u/ohaz 1d ago

Commits are easy and fast to make and don't "cost" a lot. So I just make a lot of them. I commit broken stuff, basically as soon as a stream of thoughts in my brain comes to a conclusion. Then, when I think that my branch is ready to be reviewed or merged I use the rebase command to squash, rewrite and reorder commits, make sure that all of them are building, running, etc. A branch with 30 commits called "WIP" might boil down to 5-10 commits.

8

u/Diocletian335 1d ago

Basically, this depends on scope. You fix a bug which requires changing 3 or 4 files and several lines of code? That's a commit. You fix a bug which is literally just a typo in a DTO (literally one letter), that's still a single commit.

If you're adding a whole new feature, IMO it's better to create a branch and commit the build steps (i.e. "Created new blah blah entity/model"). Then you can merge or rebase the branch later.

If you don't know much about branches though, just focus on getting used to the flow of adding, committing, and pushing for now.

5

u/Comprehensive_Mud803 1d ago

How often do you feel that you need to make backup or safeguard?

From experience, there’s no “too often”.

The perfect answer is “often enough to be safe from data loss”.

You can always squash commits together during an interactive rebase, or squash the whole PR branch on merge.

8

u/2fletch 1d ago

Assuming you are on a feature branch do as many as you want, just rebase and squash before you make your PR.

I always think "would I want to lose this?"

4

u/ElnuDev 17h ago

Smallest meaningful change the compiles. Think of commits like little checkpoints.

2

u/eliquy 16h ago

Doesn't even need to compile. I'd rather have a junior push a broken branch that can be cleaned up later than have them hold uncommitted files for a week only on their machine because they're too afraid to break something

1

u/burlingk 12h ago

Yeah. If they are nervous, that's what branches are for. :)

1

u/kpg_on_ao3 8h ago

Impossible for them to break anything if they're not allowed to push to main!

It should be a PR, and then someone higher up the food chain inspects PRs. Have very few people with permissions to merge a PR into main.

You should have workflows enabled that run tests on every PR, and merge/rebase+FF only if all tests pass.

Basic stuff.

3

u/realmauer01 16h ago edited 15h ago

Its hard to commit too often. Its easy to not commit often enough. But the details depend on the context, if you have a team and go with a merge strategy it changes a bit. Also if you create new branches you can always rebase squash / fixup your commits.

If you are in a state that doesnt compile you just need to name your commit accordingly.

2

u/glglgl-de 1d ago

A good approach is to commit as often as possible and then regroup and squash commits in order to group them logically. git rebase -i is a very powerful command.

2

u/bigkahuna1uk 1d ago

This is not a git question really but a problem definition issue. If you’ve decomposed the solution you’re working on into many small discrete units of work, then the time for git commits naturally emerges when each unit is completed. If this doesn’t happen, the time for a commit becomes more subjective rather than objective. As a general rule I would commit at least after each milestone in a feature is complete whether that’s the whole feature or just a facet that allows one to determine what’s been completed and what is left to develop. You usually develop a good cadence and end up committing several times during the day.

2

u/Broad-Promise6954 ancient 20h ago

First, remember the fundamentals: each Git repository is independent of all other Git repositories and at some point you connect one Git repository to another and transfer commits (from the sender, to the receiver). You don't "commit to GitHub", you just commit. Later, you git push, making your Git repository the sender and some separate and different Git repository (on GitHub perhaps) the receiver, and only then do you send some of your existing commits to them.

This is, or at least can be, important because you pick which commits to send at the time you send them. This means you don't have to send the original commits you made. You can take some time to make new and improved commits, if and when that's appropriate.

What all this means is that you can commit whenever you want! It doesn't have to be working code or ready to go. Commit whenever you want to have a save point to which you can restore, like saving your progress in a game.

Obviously, achievements make good save points, so if you got something working the way you want (or think maybe you did) that's probably a good time to commit. But even failed attempts might be worth saving, if you want to try a different approach instead but reserve the option of going back to your earlier attempt again.

This is where you should consider the fundamentals again. Each commit remembers the ID of its parent commit(s), which means commits build on their parents as you go. To make a new commit that builds only on the commits that already exist in a different Git repository (say, on GitHub), keep a memory of which commits are the ones that are shared. Your own Git does this for you, automatically, via names like origin/main and origin/feature-X. You can create a new local-to-your-own-personal-Git branch starting from one of these commits, and make your own private, never-shared commits on this personal branch. As long as you don't push these commits to GitHub or wherever, no one else will ever know about them.

You're therefore free to replace those commits with new and improved versions, by starting a new private branch again and picking and choosing and even changing the contents of those commits as you make the new and improved ones. That's using git cherry-pick -n or similar for instance.

Once you have this practice down, it's a simple and easy step to realize that this "make new and improved commits" process is exactly what git rebase -i does. It just manages it without using two separate branch names. (Let's not get into the gory details of a "detached HEAD" here, which is how rebase manages the trick.)

When you want to save commits you've made locally to some external storage (in case your laptop is stolen or explodes mysteriously or whatever) you can push those commits to GitHub or wherever. Until then they're only in your own personal repository.

2

u/Narrow-Low-3137 18h ago

There really is no hard and fast rule. I commit very frequently on my feature branch. Especially when I want to try something out/not sure if it will work. 

I often make use of git commit --amend on my feature branch too.

Usually before I open a PR, I will squash my feature branch commits if they will just add a bunch of noise to branch history (think "wip", "testing", "in progress" commits that you really don't want crufting up your main branch history)

2

u/gydu2202 16h ago

It's a style question. I have about 20 per day. Those are checkpoints. And later I rebase, reorder, split, and squash them into meaningful commits. None of my colleagues do the same. Some are afraid of git, others like bigger commits.

2

u/BlimpIntolerant 14h ago

Often. One day you will be glad you committed that version 25 minutes ago.

2

u/CarryTheBoat 10h ago

You can commit a shitload, I’d just do it on a branch so you can easily squash merge it to something clean once everything is sorted out.

But sometimes cheap tiny commits are faster when your debugging or prototyping an idea if you find yourself getting down a rabbit hole that isn’t going anywhere and just blow away the changes and start on a new angle.

Just make sure your first commit message is “initial commit” and then all the rest are “committing files before <insert some event>” or “made some changes”

3

u/Motor-Concentrate788 1d ago

Everytime you make a change thats describable in a commit message and it can compile and passes all tests.

3

u/Both-Fondant-4801 1d ago

as often as you need as to not lose your changes... but as much as possible, don't commit broken codes.

2

u/Janky-Code 15h ago

If by yourself or with partners on a project you are enthusiatic about, commit frequently, push regularly, and keep pull requests small for easy review.

If with people you don't like on work you couldn't care any less about, once a week at most. Add commit messages like "fix: fix minor changes." Squash all commits into "fix fix." Save up pull requests so they are so large that whoever has to review and test them hates you. If they reject your pr, close it and open a new one. Add terse comments or better yet incorrect comments.

1

u/AlleyOcelot 6h ago

they're being sarcastic if thats not obvs ha. but this is a perfect negative example that does actually take place in the real world. ymmv

1

u/LuisBoyokan 1d ago

At the end of the day in case of fire or burglary during the night. I use the WIP on my branch

4

u/jorgb 1d ago

You better have a remote set and tell OP to push, otherwise commits don't add much if your repo is local 😉

1

u/Stock_Test2326 1d ago

haha true, my MacBook died suddenly and last few commits weren't pushed some are very critical things. gotta rebuild it again

1

u/felixnavid 1d ago

A commit has two roles:

  • for others, group changes logically
  • for you, save your work

Before AI, I have tried to split PRs into smaller commits so that my reviewer can follow my train of thoughts (role 2). Each commit can be built. Maybe tests are separate in the next commit. And during merge, you either squash all commits into one ( GitLab's preffered flow) or just merge all commits as is.

Locally, commit every day ( others said 4 hours), and add some notes for yourself so that tommorrow you can continue. (role 1) You can amend these commits later or squash them so that others can see browse the code logically ( role 2).

1

u/jack-dawed 1d ago

locally i commit as often as i need to but i tend to clean up my commits by squeaking and rebasing before pushing so that the commit history has some sort of logical progression.

1

u/boomkablamo 23h ago

Early and often. However, you should clean them up to be coherent, traceable, and as revertable as possible when submitting a PR.

1

u/Even_Gap_2253 23h ago

An agreed upon frequency with your team

If it is just you, it doesn’t matter, like every hour? lol

1

u/destroyerpants 22h ago

Like if you do green red green TDD, I would commit when you complete a reasonable unit of work.  Say you are building a util. 

  1. Create the stub method
  2. Create the first half of the happy path 2.5. second half? I guess
  3. Take care of the edge cases
  4. Commit. 

1

u/mredding 22h ago

You could use a TCR script - Test ? Commit: Rollback. You write code, compile and test. If test coverage drops, the code is reverted. If a test fails, the code is reverted. Only if the test passes is the change immediately committed. The idea is if it fails, you didn't understand what you were doing, so you try again smaller/simpler/better this time. The feedback loop helps train you to write better code.

1

u/bombay-boyz 21h ago

Think of commits as restore points. Every state where the whole project was working src and tests fully is a restore point. Using branches for experimentation is also a good practice especially for large chunks.

1

u/pptqvfer 21h ago

 https://www.aleksandrhovhannisyan.com/blog/atomic-git-commits/

Make atomic commits. The principles and reasons why are laid out nicely in the blog post.

1

u/Lion2471 19h ago edited 19h ago

Here's what I did during my software development career.

In the long term, I wanted one commit per bug or feature. By "feature", I generally mean the smallest piece of new functionality that can be coded and tested before being used as a base for the next change. For instance, in software that presents a panel to the user, one feature might simply add a text box with a label to the panel. The next feature might add the logic that processes whatever the user types in that text box when the panel is submitted.

While working on a bug or feature, I made very frequent work-in-progress commits on my own branch, usually multiple times per hour, to avoid any chance of losing my work. Once the bug or feature was done, then I squashed those WIP commits into the one long-term commit that I wanted. To be clear, unlike with the long-term commits, there's no rule that WIP commits need to compile cleanly, as they didn't affect anyone else.

1

u/scritchz 15h ago

Locally? Use as many commits and branches as you like. It's better to commit more than less because you can always reset, squash, edit and rebase them.

On upstream (like GitHub)? I prefer to keep it clean and organized, that means commits should be complete and functional where possible. If you check out any of the upstream commits, they should work.

1

u/CommercialFair405 15h ago

I commit every few minutes, as soon as I have a change I want a checkpoint for.

1

u/Frequent_Field_6894 15h ago

Working units of code changes.

i commit too much but worked at a company they did Days of worth with 1 commit.

1

u/BootyMcStuffins 13h ago

More often than you reboot your computer

1

u/VoidLance 9h ago

I do it wrong - I'm currently trying to train myself to use branches so I can deal with pull requests - but I use commits and push like I would saving a document and do it whenever there's a lull in work on the project

1

u/severoon 8h ago

Use a local branch to do checkpoint commits. A checkpoint commit is: I just did some work I want to be able to come back to, same idea as checkpointing in a video game. When you have code that builds, passes tests, and has all associated docs updated, stage that as a commit to push to whatever remote branch you're working on. Smallest commit possible that is a coherent chunk of work. Always include tests and doc updates that make sense for the bit of work you're committing — if it's in flight, then put TODO comments where the work is going to go and tests that test what's there (even if it's just an API that throws no implementation exceptions).

Small commits are better than large commits, and never do more two or more unrelated things in a single commit. This is because if you need to roll back a change, it rolls back at the level of your commit, so a clean rollback of the offending CL is sufficient. Otherwise, you have to fix-forward (whether it involves surgery on the too-large rollback or an actual fix).

Always do rollback-safe deployments of functionality. This means you should put all new functionality behind feature flags that preserve the original code behind the flag. You deploy the code with the new functionality hidden and just let it sit for several deployments before you enable it. This way, if someone else breaks prod that triggers a rollback, the rollback includes your deployment with both paths! If your new path depended on the thing that got rolled back, you just disable the flag and things keep working. If the new path doesn't depend on that, then you leave it enabled and your feature doesn't rollback because some unrelated thing broke and triggered one.

1

u/kpg_on_ao3 8h ago

You should have an atomic task you're working on. Do that. Commit. Repeat.

I find "how often should I commit" is often a question from someone who is just "writing the program" instead of writing a discrete part of the program.

1

u/symbiatch 7h ago

People here seem to be confused of three very different things: commits, pushes, merges.

Commit as often as you like. Got one part done? Commit. Got a part half done and want to make changes but think this part would be fine? Commit and you can do whatever and come back to this if it doesn’t work out. Commit commit commit. It doesn’t need to work or even compile. It’s a local commit.

When pushing out, for a pull request for example: squash the code with rebase. Here you can simplify the commits. If it’s in the end a smaller thing maybe squash it all. Others don’t need to see how you tried three different ways and in the end used one. These commits should be helpful for review: this part was just cleanup, this part added that thing, this part added another.

And merging might be yet another squash where the whole thing is put into a single commit.

If someone is talking about “polluting the commit history” then they don’t understand these separate things or how to work. Local commits aren’t often what goes out.

0

u/funcyChaos 20h ago

Some made up commits (look at a repo that sounds cool)

Initial commit

Had a hard time figuring out hit points but it's working

Added enemy hit points

New weapon modifier for bonus weapons

Fix wall glitch. Walls work now

0

u/divestblank 14h ago

when it's done