r/git • u/TachikawaKan5241 • 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
9
Upvotes
29
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.
10
u/gororuns 22h 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.
35
u/just_here_for_place 1d ago
Whenever you feel like it, but at least after every meaningful increment.
11
u/cringelord000222 1d ago •
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 1d ago
Smallest meaningful change the compiles. Think of commits like little checkpoints.
3
u/realmauer01 1d ago edited 1d 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 -iis 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 1d 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/mainandorigin/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 -nor 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 -idoes. 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 1d 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 --amendon 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 1d 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 1d ago
Often. One day you will be glad you committed that version 25 minutes ago.
2
u/CarryTheBoat 21h 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”
2
u/symbiatch 17h 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.
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 1d 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/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
1
u/felixnavid 1d ago
A commit has two roles:
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 1d 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 1d ago
An agreed upon frequency with your team
If it is just you, it doesn’t matter, like every hour? lol
1
u/destroyerpants 1d 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
u/mredding 1d 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 1d 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 1d 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 1d ago edited 1d 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 1d 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 1d ago
I commit every few minutes, as soon as I have a change I want a checkpoint for.
1
u/Frequent_Field_6894 1d 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 1d ago
More often than you reboot your computer
1
u/VoidLance 20h 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 19h 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 19h 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/Wisdom_Wizard_Waldo 10h ago edited 6h ago
Time is irrelevant.
The analogy i like to use is a RPG video game. There are autosaves and manual saves.
Autosaves represent saving changes to your files locally in your editor. Set it up so it just happens.
Manual saves are commits, specific points in time where you exercise your agency and take a snapshot / bookmark that particular point in the game. Why?
Maybe you want to try independent routes / strategies, or just see what works, without having to start a level or quest from the beginning (branch / stash).
Or maybe there's a particular part of the game you like and know you'll want to jump back to in future (tag commit / versioning).
As others have said it's best to only commit when your repo is in a working state e.g. typically wouldn't save your game as you are falling to your death.
Both because it becomes easier to checkout any commit later, but also because having commits be in a working state means you can use things like
git bisectwith the code bases test suite to find any regressions, without having to worry about if code itself works.However for any rules there are exceptions.
For example sometimes you need to commit/push in a broken state to share and get help. In those cases branch strategies become important i.e. the ability to refactor / squash commits independent of
main/master. And then you can choose to merge or rebase (note if you know the nuances, rebasing is better, fight me! 😎).Final note, you want to keep commits as "digestible" / easy to comprehend as possible. Imagine someone else or yourself 6 months from now reading the commit logs.
If you make changes to several hundred lines over multiple files for a single commit, it's considered rude. Because it increases the mental load on the future reader to trying to figure out what's happening assuming they need more detail then in the commit msg.
1
u/Loud-Bake-2740 6h ago
i commit all the time and push sparingly. best of both worlds
0
u/funcyChaos 1d 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 1d ago
when it's done