99% of the Git commands you'll need at work, demonstrated in a single script
bitbucket.org
bitbucket.org
- Always pull w/ rebase for the current branch.
- Always merge other branches into your current branch, eg master -> feature.
- Always stage individual chunks of code one at a time to make sure I'm committing the right stuff.
- Always squash feature branches into a single commit when merging back.
- Stash changes if needed when switching branches.
- Cherry-pick one-off commits if needed.
- Append a previous commit that I haven't pushed yet if I happened to forget something.
- For complicated merge conflicts I switch to Visual Studio Code which also has a great GUI.
I think this covers 99% of the stuff I encounter in my day-to-day.
It seems to have next to zero functionality. What is the point of it? What you you use it for, other than commit, push?
I use Sublime Merge, but no Git GUI I've used comes close to tortoisehg for mercurial. Tortoisehg is actually superior to and a comprehensive replacement for the command line. I wish something like it existed for git, if not for me then for the newbie-ish people I need to instruct on project workflows.
git commit --fixup 6138D3A
git rebase --autosquash --interactive origin/master
to keep a clean history of cohesive commits. Rarely do I change _everything_ required for an objective in one go, I still like to commit as I work, I just like the finished product to _seem_ like I did it in one go, for future maintainers' sake.And I rebase to catch up with upstream, I can't stand having intermediate merge commits in my history and rebasing lets you resolve conflicts as they're introduced, instead of an all-at-once at the end.
[alias]
fix = "!_() { c=$(git rev-parse $1) && git commit --fixup $c && if grep -qv \"No local changes\" <<<$(git stash); then s=1; fi; git -c core.editor=cat rebase -i --autosquash $c~; if [[ -n "$s" ]]; then git stash pop; fi; }; _"
The workflow becomes: $ git add ... # stage the changes you want to apply to 6138d3a
$ git fix 6138d3aThank you!
Find a _simple_ git workflow, document it in a style guide, stick to it. Git doesn't have to be complicated.
This is really the only command I do by hand because I can't find the equivalent (yet, probably haven't looked hard enough) in Fork.
edit: oh I think I misread what you said. When working on a feature branch I don't care too much about the branch history since I know it's eventually being squashed back into a single commit.
Without using either flag rebase should update the commit date and preserve the author date.
If by rebase you meant GitHub's rebase merge option I think you're out of luck :-/
For the sake of your future sanity (and your coworkers'), please stop trying to rewrite history for the sake of aesthetics. The defaults are what they are for a reason.
Additionally, if I do the aforementioned git pull, I have no way of turning the commit message into an informative one because I have no information regarding the commits. Is there a way to actually know it beforehand to turn that message into a meaningful one? If so, how would you do it? If it is possible, should I just have a list of all the commits' message in that one merge commit? Regardless, I see lots of "Merge branch ... of ... into ..." commit messages and they are not useful to me at all. Why do you think people keep doing it?
> Additionally, if I do the aforementioned git pull, I have no way of turning the commit message into an informative one because I have no information regarding the commits. Is there a way to actually know it beforehand to turn that message into a meaningful one?
If there are any conflicts then it will force you to stop and resolve them, which seems like a decent point to document anything that needs to be. Otherwise, you can always amend in a more relevant message afterwards.
Rebasing does this too. Can't we compromise, and agree to never allow "git pull" to spontaneously and unthinkingly create a merge commit with two parents?
Instead, let's do merges of our rebased feature branches, into the trunks that they are based on, but with "no-ff" – this retains the information you wanted about what feature branches have merged into what trunks, and when. But the history of each branch maintains linearity and no commit ever has more than one parent.
I don't have to work with either of you, but this is how we resolved this debate on my team, and we haven't looked back. It's not even worth having this conversation unless you need branches to be long-lived. But if someone else ever has to rebase your branch with merges in it, they'll thank you if you have honored this, and curse you under their breath if you have left these thoughtless merge commits around.
Do merge, but please only merge deliberately. (I also recommend checking out Deliberate Git for a great talk on Git, with similar ideas! https://vimeo.com/72762735)
No. Shorter-lived branches naturally bring a smaller window to create nonsense history, but the risk is still there, and the benefits are as absent as ever.
> But if someone else ever has to rebase your branch with merges in it, they'll thank you if you have honored this, and curse you under their breath if you have left these thoughtless merge commits around.
So.. don't? That seems like a good thing, software should discourage you from shooting yourself in the foot.
What is the simple diff content of a merge commit which solves a conflict between two parents? There isn't one, change my mind.
We both agree that software should discourage shooting yourself in the foot. We disagree about which one of us is using the feature that encapsulates the moment where shooting ourself in the foot happens. It's not nonsense history if it reflects the order that branches were actually merged, which is far more interesting than the order in which commits were written concurrently across disparate branches IMHO.
If you are working with other people that can't read your thoughts, especially those who are too distant to reach you to return the favor when you have inflicted pain on them, they will appreciate it if you rebase your feature branch before submitting your PR and don't send forward an unmerged conflict unless we actually need to talk it over for some reason.
On the other hand I don't know anyone who will be mad that you did this. The rebase feature exists for a reason, and so does amend, reset, squash, etc. How many of these features do you think I shouldn't use? I am only discouraging the use of one feature, the automatic octopus merge that happens when you thoughtlessly run "git pull".
Why do thoughtless things? Don't you want to review the code you've pulled?
Rebasing also guarantees that the commit your CI has tested is identical to the commit that becomes head after the branches merge. How do you guarantee that your branches still function properly after merges? Carefully running the tests by hand between merge and push? My test suite is too large, and we are too busy for that, friend.
If you care about patches then the structure or order of the history doesn't really matter as long as the dependencies of each patch are satisfied (they produce the same final file when applied, and no conflicts). Take this philosophy to its extreme, and you end up with Darcs or Pijul.
If you care about tree snapshots then each commit is a promise that "I have made these changes, and afterwards the entire combined codebase still works and makes sense". If you alter the untouched code then this still breaks the promise, because "the entire combined codebase" is now different. Take this philosophy further and you end up closer to Mercurial.
Personally I lean hard towards the latter. Code tends to make a lot of assumptions about its surroundings that won't show up in a naive text-based diff (and thus won't generate conflicts), such as "class X exists and contains method Y".
The confusing thing about git is that it doesn't really make a clear choice. Some commands only make sense in a diff-based world (such as rebase and friends), while some only make sense if you think in snapshots (such as bisect, which tests whether your app satisfies some expectation at a given snapshot, not whether your diff does what it claims to).
And besides..
> Rebasing also guarantees that the commit your CI has tested is identical to the commit that becomes head after the branches merge. How do you guarantee that your branches still function properly after merges? Carefully running the tests by hand between merge and push? My test suite is too large, and we are too busy for that, friend.
If you care about bisecting then a rebase requires you to retest each commit in the branch, while a merge only creates one new commit to test. As a wise person once said:
> My test suite is too large, and we are too busy for that, friend.
This is an unreasonably high bar to reach for each commit. This is the right test to apply (among others) for whether a PR has the right stuff to get merged into a trunk, or not.
Treat it as a squash where the individual commits can be recovered. Git treats commits as left-biased, so the branch you're merging into will be the primary parent.
I'm coming at this from my angle as a team lead, or mediator between novice contributors who are both pointing the finger at each other. If the two parent branches both passed, but the merge fails, and both upstream committers are gone, I no longer can have only one throat to choke. I have to check out both branches and confer with both contributors in order to resolve the conflict again.
One contributor or the other has broke the build. It will require additional investigation to decide which. If one branch has merged first, and the other second after rebase, then I never have this problem, and my debugging process has only one throat to choke. Delegation becomes much easier.
Whoever won the race to get their PR approved and merged first is not the one at fault. (This is the greatest incentive to get your stuff tested and merged, also!) The branch that has been rebased on the other one, then, must be at fault, because his merge came later. It's not a value judgement on a person, I am just keeping it simple. My one and only motivation for operating this way is to have 100% certainty that contributors' PRs which (we) have decided to merge after reviewing the test outcomes, are the same, so that all the intensive testing we performed and spent our time reviewing before the merges will not have been a waste.
I generally don't want merges in my feature branches, and I don't think you will convince me to want otherwise. But I appreciate you having engaged me in this debate. Every time I get to talk about my strongly held beliefs, I get a better perspective on why someone else might disagree. :+1:
My teams have usually been very small, and I can't say for sure that my strategy can scale. But we have scaled it successfully past 2 and into 4 developers. It requires everyone's cooperation, but once we have it this delegation subjectively seems about a thousand percent more reliable.
I have used this in projects and it worked great for the whole team for a long time. You can of course do something else which can work for you and your team.
- needing to memorize branch names for easy use: there is tab completion for this;
- differences between staged and pushed commits: I'm not sure what you refer here. the closest concept to the "stage" term is "staged changes". this is by design; the idea is that while one applies changes within a single commit, some are definitive, some are evolving; for this workflow, it's very convenient. if one doesn't want, they can just add all and commit (preferrably, with a single alias ;-)).
The "most extensive" Git UX problem is possibly the excess of functionality given to the `checkout` command, which in fact is being split.
(I don't imply that Git UX is good, though)
It absolutely is. The whole "branch" paradigm evokes topology. The visual structure of the thing you're working with ought to be made clear to you, the user.
If a GUI has trouble when the workflow deviates from normalcy, it's just not powerful enough.
That being said, there will always be users who prefer the command line, and that's totally fine.
- visualise the project in its current state which may spread across several feature branches all coming in and out of master
- code preview (hugely valuable) across one or more files
- see your branches
- see your stashes
- remotes, etc
- all of the above across multiple, simultaneous, projects.
Large projects can be difficult to manage if you don't have context and oversight, which is harder to obtain from the CLI.
Of course we can get this information from the prompt but it is much more difficult to get the information in an easier-to-consume fashion.
I use Tig as well, but more often than not the git cli is sufficient.
I don't know why, but I've always felt uncomfortable using git in a GUI, but I know a lot of people who love it.
For some reason, anytime I try to use a GUI, I don't feel like I'm really doing git, if that makes any sense. Also, I've personally never felt the need to see the branches visually. And if I do get the itch to 'see' them, nothing a quick
git log --oneline --graph
cant fix!* I almost always just do a regular merge to master (rather than squash).
* I use GitKraken which (in the pro version) has a great merge tool.
A lot of people seem to want "clean history" so just I'd just like to put it out there that it's not really necessary (there's nothing wrong with it, of course), and regular merges work just fine. In my experience, the two main reasons I look at git history are:
(1) Checking when a feature was done and what releases it got into
(2) Finding out why a particular line of code exists (blame)
For (1), with software with numbered releases, you end up following the branches anyway. Having the individual commits from feature branches makes you scroll more, but it doesn't make it any harder to follow. If you really don't like seeing them, you can hide anything but merge commits.
Even simpler, if all you care about is whether a given feature branch is done (merged) or not, that's easy to see and the same as a squash-merge workflow.
With continuously-deployed ("cloud") services, things are even simpler - you start at the hash currently deployed and go backwards. It makes no difference if there's one branch or many feature branches (other than scrolling past more granularity).
For (2), the greater granularity from individual commits is generally useful (at least provided that each commit has a ticket number and useful description), and squashing erases this detail.
Also, a nice thing is if you end up merging the same branch to multiple places (master and a release branch, for example) it's obvious what happened by looking at the tree. Contrast to if you cherry pick a squash merge commit, the only way to see that is to read both commits and realize they're the same -- and this is much less obvious if there's other commits between them.
Basically, squash merging doesn't help with either of these, and in fact actively hinders (2).
My team has been doing this for a few years, and I'm not even sure if it was a conscious decision to merge this way (or not do squash merge) but we've had no reason to change. It does depend on every commit being well-formed, but this is pretty easy to ensure in a paid team that works on this every day (whereas with open source I'm not sure it'd work well).
Anyway, like many things in git, there's more than one way to do it, and there's no clear "right" or "wrong" way.
Anything works when both of those prerequisites are met. You're unlikely to do the bad things that force more advanced needs.
Everyone should do this. Think back to how much time you've lost due to git problems. It'd probably take less time to learn it correctly up-front, and never have to deal with them ever again.
I also don't bother appending (though my GUI lets me undo the last commit if I haven't pushed which is maybe the same thing.)
Most developers get way too fancy with Git and screw something up. I use GitHub Desktop and rarely touch the command line for Git. It has a great UI for being able to just pop over and see my current changes, and easily commit just a line or two from them to make commits other people can understand.
https://github.com/hlissner/doom-emacs
In magit in those Emacs distributions, the question mark brings up a list of available commands and if you type the first letter of a command with multiple letters, it'll show you the names of the actions that start with that key.
[0] https://github.com/tpope/vim-fugitiveI know without hesitation all commands I use daily. And then I keep a note with the few commands I use less often. An exception is when I want to display changes between version, or conflict resolution.
That being said, I'd like to rely just on my IDE (VSCode) for better consistency, and I tried a few times, but I always return to the command line which is a great tool. For the same reason, I prefer to `CMD-tab` to terminal and `make` rather than build from the IDE.
this is emacs we are talking about :) you are supposed to use the keyboard for everything.
In which cases you found it "opens" git for deeper inspection?
My experience is that it lets me operate at higher levels of abstraction than cli git. (e.g. Instant Fixup)
#!/usr/bin/env bash
emacsclient -c --eval "(progn (magit-status) (delete-other-windows))"
The learning curve is a bit long, but really worth it!Note: this require you to have setup emacs as a deamon somehow
I was happy with the git cli (and occasional tig) when I started using magit full time and initially never understood all the buzz. It did not seem that powerful over what I was using.
After 3-6 months of use, for some reason I had to go back to the cli and then I realized the ease and speed I had got accustomed to.
Magit is magical; use it for some time and try going back to your previous setup.
One of the things I appreciate about magit is that it gives you sane default behaviour. For instance, the -f option when pushing with magit is —force-with-lease, rather than —force, so that you don’t inadvertently overwrite someone else’s work. When stashing, it helpfully prompts by default you to enter a message for your stash to differentiate it from the 10 other stashes you might have on a branch. Sure, these are things you can get on the command line, but they’re not the defaults, and you have to remember how to get to them.
I only have emacs open for magit (:
git add/rm/commit/status/push
git branch/checkout/merge/rebase
git tag/push --tag
Anything else should be handled by policies. If you get bad PR, reject it instead of trying to fix it using some complex sequence of git commands.That's probably anathema to some users, though.
I _really_ love working with Git, but in my experience engineers unfortunately do need to tap into the long tail of “advanced” commands fairly often. At least often enough that they will quickly be frustrated by it.
(I’m currently helping move a bunch of our engineers from SVN to Git, and while I believe the better ecosystem will be worth it, it does break my heart every time someone has pointless trouble simply because of Git’s CLI.)
Reclone from master (or the active branch if something else) to another directory, merge in their final changes, manually if needed, properly test the result, and sent a new PR with the cleaned up version?
(caveat: I've not used git in anger, there may be more to it than that, but I can't imagine much more)
I suppose who is responsible for dealing with cleaning up updates before merging them into the main project depends upon who wants it merged most: the PR submitter because they want a fix/change/other in upstream so they don't have to maintain their own fork, or the project maintainer because the update is more generally useful to other users or more specifically useful to the maintainer.
If you submit a badly arranged PR or other patch you are creating extra work for the project maintainer(s). Depending on the project and maintainer(s) this may be acceptable or, equally rightly, it may not.
Of course for your own local history the same technique can work, you just keep the old branch as well as the newly cleaned one. Though that might be unnecessary clutter to many.
You also need `git log` with all sorts of arcane options if you actually want to use the history.
Stash can be useful, but it’s good to know that you can get by without it very easily, there’s nothing you can do with stash that you can’t do with commits & branches, and stash doesn’t have the same safety mechanisms that commits have. I think the biggest git accidents I’ve seen, where people have gotten confused in the middle of a merge and lost their work, are due to using stash.
Stash is something I try to avoid after multiple accidents.
For example build and test all commits but deploy only if it's on master branch AND has a version tag.
My own list contains:
ssh user@rsync.net "git clone git://github.com/LabAdvComp/UDR.git github/udr"
... which is how I make my own copy (in the cloud) of (what I consider to be) important packages that I want my own archive of. git guiI'd also be interested to hear what git commands others use frequently (that don't involve a GUI). I'm curious to know which workloads might require some of git's more advanced features on a regular basis.
https://www.git-scm.com/docs/git-log#Documentation/git-log.t...
git diff --color-moved
(seriously, read through the man page for git diff sometime)
git log -p --all -- <path/to/file>
(I use this with multiple remotes, so I can track changes in my fork and in upstream when looking for context around a file)
git cherry-pick -x
(for automatically adding a reference to the original commit)
A couple more, but I think they're really quite specific to my personal workflow and responsibilities
I like this one. I'll remember it. Thanks for sharing!
I agree about `git log -p`. A good trick with that is to use it as a quick way to search for a commit that includes a certain string (since the pager is less, one can search back in time with `/`).
Same trick for `git reflog -p`.
`git stash show -p` is another less-known diff command (look at a stash without applying it).
Have you read through the gittutorial, gittutorial-2, and especially the gitcore-tutorial manpages[1]? Reading those guides and actually following the steps and examining the results on disk was extremely helpful for me in understanding how Git actually works. Once you've got that understanding, the Git UI seems less arbitrary. You can start to see how it was put together over the years, which should help you use the tool more intuitively and effectively.
> I'm curious to know which workloads might require some of git's more advanced features on a regular basis.
I work on a very large and very old (mid-90s) project, so history-diving and diffing branches is very useful for me. I use all of git-blame, git-show, and git-diff to examine history to learn how the code came to be as it is. Even git-cat-file comes up occasionally when I just want to look at some old object I happen to have a hash for and don't want to look up properly through the porcelain.
We also maintain a bunch of branches and backport modern commits onto legacy branches. git-rebase can help for this, but more often I find myself doing it manually (well, with a bash script) with git-cherry-pick, as it's easier to work with commits without being in the middle of a rebase operation. Knowing git-log's many options to massage history into a useful form for my work comes in very handy here, too.
More details on the rebasing procedure I use: https://github.com/ValveSoftware/Proton/blob/proton_4.11/doc...
Here's some of the tooling I use often. For Git stuff, see pick_commits and gitconfig https://gitlab.com/mywinetools/mywinetools/
[1] I know, I know, no one likes studying and learning how to use a tool. But sometimes you gotta if you want to use the tool effectively.
I think the fact that you can use git locally to work within your perforce workspaces indicates some commonality among the two models, but git has way more features, edge cases, and jargon.
Wow, mid 90s! Git came out in 2005, so I assume they started out using some previous version control and then switched to git? That must lead to some serious knots. Is there a way to retroactively migrate source control history into git? Depends on the legacy source control tool, I guess.
I think git-blame and git-cat-file are probably the next commands I need to explore in depth. Will investigate those further.
Thanks for sharing your gitconfig as well. Always interesting to see how others are streamlining their workday.
[1] https://source.winehq.org/git/wine.git/shortlog/ec34a66612d0...
[2] https://source.winehq.org/git/wine.git/shortlog/ebfc0fee51aa...
Basically, you can do a working copy of the git environment without pulling the repo again, so you have only one .git folder.
A godsend if you, like me, work on gigantic repos that build unbearably slowly and want to be able to use multiple instances of the same repo at the same time.
After `make clean` and `git status --ignored` shows nothing worth preserving, you can delete the worktree (via `git worktree remove`) with impunity. No more paranoid checking that there is no valuable work stashed or hiding in other branches before typing `rm -rf`, as those are shared with the main worktree so won't be lost.
Also known as a porcelain, as opposed to the low-level commands known as the plumbing.
Committing, pushing, handling local branches, updating, merging, rebasing, cherry-picking, squashing and stashing is almost all that everyone uses, and several of those not even on a daily basis.
$ git reset --hard origin/master
over the suggested
$ git reset --hard HEAD
If you use git and don't know the difference, read this: https://stackoverflow.com/questions/8196544/what-are-the-git...
Love seeing high-quality software developed by just 2 people.
branch checkout add commit pull push
Reading and understanding the documentation for those six core commands isn't a big investment, and it will pay off if you're doing software or documentation development.
But I can’t bring myself to run a web browser to run git commands either. The git binary on my system comes out at 2.5Mb and the MacOS .app bundle for this is 346.5Mb.
Right now, Im partial to Sublime Merge[0] as it’s fast, has a clean UI for diffing, shares many similarities with Sublime, and also shows the use what git commands they’re running by hovering. It can be a very effective tool for learning git. It has the same evaluation structure as Sublime, so that’s a bonus as well.
Then I met sublime-merge. And fell in love. It is the only Gui I find more efficient and beautiful than my terminal. I highly reccomend it.
http://www.philandstuff.com/2014/02/09/git-pickaxe.html
Also I do allot of
git reset --soft HEAD;
(pick-hunks-with-GUI);
git stash -u -k;
run-test.sh;
git commit -m "blah"`
[alias]
# top 10
top = !sh -c 'git log --oneline|head -10'
It shows the top 10 commits. I use it several times every day, to orient myself while flipping between multiple repositories and branches. alias hist='git log --pretty=format:"%h %ad | %s%d [%an]" --graph --date=short'When the conflict occurs you can do git status and the highlighted files are those with a conflict -- at that point you can just navigate there in the code editor of your choice and look for the <<<< blocks. After you get those files into the state you would like then you run 'git commit' to resolve.
(i.e. that this is necessary speaks volumes)