23 ms·
Some bad Git situations and how I got myself out of them
- random567 10y agoThe screwed up and committed to master should end with: git reset --hard origin/master (assuming that the remote is called "origin") With the example in the text, you have to know the number of commits you've made to master.
- NickHolt 10y agoIt was also a bit pointless to checkout a new branch just to switch back. The whole thing should be git branch some-new-branch-name git reset --hard origin/master git checkout some-new-branch-name
- NickHolt 10y agoThe "committed to wrong branch" case is also a little overly complex. I'd just do: git checkout correct-branch git cherry-pick wrong-branch git checkout wrong-branch git reset --hard HEAD~
- Dru89 10y agoThis is less safe than the branching alternatives. Instead of "moving" the original commit, this copies the original commit to a new one and leaves the original one dangling and waiting to be garbage collected. Also, if you have more than one commit before you noticed you were on the wrong branch, this only grabs the one commit.
- swang 10y agothe website's example is for when you only want to undo just the last commit you made.
- ekimekim 10y agotip: you can use @{u} to refer to "the upstream of my current branch", ie. what you said but will work no matter what the remote is called.
- cyphar 10y agoThe last rmdir example should be rm -rf.
- guessmyname 10y agoMaybe he has an alias named "rmdir" that executes "rm -rf"
- cyberferret 10y agoLOL. Bookmarking along with my other Git reference sites...
- m_mueller 10y agoOne of my SO questions could almost fit in there, somewhere before "Fuck this noise...": http://stackoverflow.com/questions/28759887/git-gc-no-space-left-on-device-even-though-3gb-available-and-tmp-pack-only-16m http://stackoverflow.com/questions/28759887/git-gc-no-space-...
- mcbain 10y ago'sudo rmdir'? I don't think that does what they think it does.
- deleted 10y ago[deleted]
- keyanp 10y agoFor posterity, `rmdir` will only remove empty directories. The author presumably should have used `rm -rf`.
- hacksonx 10y agoI think the command we're looking for is 'rm -R name_of_directory'
- BestViewedInNC 10y agoAt least in GNU rm, -R and -r are synonymous. -f suppresses all prompts ("remove write-protected file ...?"), so the parent is also correct :)
- corney91 10y agoNeed to use `-f` when dealing with git repositories unfortunately.
- inopinatus 10y agoHonestly, the proper command is not rm at all, because you can then have an "oh shit I forgot something" moment. I have learned (the hard way) to retain even an horribly broken repo, but shove it out of the way. Because disk is cheap, repeating work is expensive. So that example should have been: cd .. mv fucking-git-repo-dir fucking-git-repo-dir.archived.$(date +%s) git clone https://some.github.url/fucking-git-repo-dir.git
- falsedan 10y agogit fetch origin master && git reset --hard origin/master imo
- Illniyar 10y agoActually the easiest thing is simply not to care about how your log looks. If you don't then there are ry only two things you need to know how to do: If you didn't push to origin do an ammend. If you did, revert soft and commit the previous code to revert it (you can also put a stash or patch to apply it back). Which frankly is what the article does, basically.
- K0nserv 10y agoHaving a messy and complex git log is not only about the visuals though. It can make it a lot harder to track down when/where/why bugs and problematic code was introduced. It makes both git bisect and git blame less useful.
- eosrei 10y agoExactly. The canonical reference to how a git log should look is the Linux kernel, since git was written for it: https://github.com/torvalds/linux/commits/master https://github.com/torvalds/linux/commits/master Bisect and blame are amazing in that repo.
- shandor 10y ago> Actually the easiest thing is simply not to care about how your log looks. Yes, that sounds as easy as anything that accepts the idea of "let's do this the shitty-but-quick way now, and pay the technical debt later". So yes, it is "easier" to work with in the beginning. On the other hand, if I had to inherit your repository that was developed by "not caring about history", I would probably have to hunt you down and kill you. So there's that.
- Annatar 10y agoOn the other hand, if I had to inherit your repository that was developed by "not caring about history", I would probably have to hunt you down and kill you. So there's that. Yep. Some people just want to keep taking technical debt on (read: hack-it-'till-it-works), which makes them likely candidates for a good thrashing in some dark blind street in the middle of the night. And some don't even get it after that. Actually, now that you made me think about it, most people in this industry aren't really computer people material, that's the problem.
- deleted 10y ago[deleted]
- glandium 10y ago> Oh shit, I accidentally committed to the wrong branch! Other ways to do it (that don't require to retype the commit message): - rebase onto the correct branch: git branch foo git reset --hard HEAD~ git rebase --onto name-of-the-correct-branch HEAD foo git checkout name-of-the-correct-branch git merge foo git branch -D foo - cherry-pick git reset --hard HEAD~ git checkout name-of-the-correct-branch git cherry-pick name-of-the-branch-you-mistakenly-committed-to@{1} (or git cherry-pick HEAD@{2}) > Oh shit, I tried to run a diff but nothing happened?! You probably want to know `git diff HEAD` too. Edit: formatting.
- felixschl 10y agoI managed to "rm -rf .git" at one point. Took me about a minute to realize and -surprisingly after <c-c>-ing i lost nothing (as far as i was aware). Git is freaking hard to break. Also always remember git-reflog, it safes lives.
- noufalibrahim 10y agoI don't know if this post was intended as humour or a way to vent out some frustration but in my experience, this path of treating git as "spell X solves problem Y" will always break down. Version control systems are an important part of the programmers toolkit and it's worth investing a little time to get the fundamentals right. Sure git is not the friendliest of beasts but what it lacks in interface, it more than makes up in internal consistency and trying to learn it "inside out" is a better long term investment than having a list of ways to solve "git problems".
- rtpg 10y agoI think there's a bit of that in git in particular. The irony is that if you think of git in terms of deltas, with branches just being tags to commits, and "git commit" actually being "git commit + move branch", then a lot of stuff is easier to reason about. Like, if you get the notion of working tree, staging area, commits, and branches on a deep-ish level, things get easier. Things can still be hard, but there's a lot less "does running this cause everything to disappear???" I think it would be possible to make this awesome page even more awesome with a little "annotated version" that gives the details of what you're actually doing.
- dfsegoat 10y ago> and "git commit" actually being "git commit + move branch" Can you elaborate on that a little more? I liked where it was going -- because being able to explain how git works to someone coming from SVN has been an ongoing problem for me.
- _ikke_ 10y agoIn git, branches are pointers to commits (branches are a specific kind of refs or references). When you commit, git creates a new commit object, links it to the last commit on that branch, and then points that branch to the new commit. This way, you get a chain of commits, each pointing to the previous commit, and and branch references pointing to the last commit of each branch.
- 10y ago
- psyklic 10y agoAlso great for getting out of Git messes: http://justinhileman.info/article/git-pretty/ http://justinhileman.info/article/git-pretty/
- wfunction 10y agoSurprised there was nothing on messed-up merges or rebases. They're some of the worst to get out of when you're not totally comfortable with git yet.
- noufalibrahim 10y agoAnd reflog. It sort of like revision control of your branches and commands. Very useful to extricate oneself from various situations.
- web007 10y ago+100 for reflog. Even for the stupidest cross-merges I've broken reflog has been my savior. https://git-scm.com/docs/git-reflog https://git-scm.com/docs/git-reflog
- zubspace 10y agoAny points on how to continue from there? Been in a few "I give up" conditions during rebases that I completely stopped trusting git it any way. The thing is, some repositories on github require you to commit only after proper rebasing. But I can never in my life remember how and need to google it...
- wfunction 10y ago> Been in a few "I give up" conditions during rebases that I completely stopped trusting git it any way. Been there too, with the same result. > Any points on how to continue from there? Honestly? Not always from the command-line, unfortunately. Basically, I just don't know the right commands to type on the command-line for everything I do with git, and it's not necessarily easy to find them either. I use the TortoiseGit GUI, and over there, it's a LOT more easy to see what is going on and to abort or continue rebases/merges as necessary, or to do fancier stuff. But the thing is, because I understand git and I know what should logically happen at every step, I can cherry-pick commits, revert them, abort/continue merges, rebase commits, or do whatever else the heck I want without getting into trouble anymore... even though I don't know how to do many of them on the command line. Of course, it took a lot of suffering to get here. Starting with the GUI would of course be the wrong approach. But once you've understood what's going on, then I would recommend you entirely ditch the command line and switch to something like TortoiseGit (I hope you're either on Windows or your platform has something as good as that). The GUI actually shows you what your options are at every step, so you don't have to know all the valid commands at every possible state. You just need to know what effect you need to cause.
- mathieuh 10y agoI absolutely love git now. I'm still at uni (at a highly ranked but actually crap university where we don't learn git properly) and this year was my 'year in industry' as we call it in the UK, and my first proper experience with git, aside from `git init` at the end of my project and pushing it to a repo. I've become so much more confident with git. Seriously, with one caveat (i.e., you haven't pushed your changes to a branch which other developers are working on), it is almost impossible to break irrevocably. Even if you do accidentally break master/develop/whatever, it only causes a bit of hassle and grumbling. Highly recommend that everyone take a bit of time to learn about "undoing" git commands, whether that's through soft resets, hard resets to origin, or the reflog. Reflog is also useful for figuring out how someone else broke something and explaining what they did wrong, since you can see what branch they were on at what commit and what commands they ran. I think git's main problem is the somewhat arcane language it uses, and lack of understanding of what's actually happening behind those words like "rebase", "commit", "patch", "reset" etc.
- Annatar 10y agoit is almost impossible to break irrevocably. This tells me you still don't get the point about using a revision control system: the whole point is NOT that you can hack the revision control system's database every which way, but that you can never, as in ever, break something in a repository, because you can always revert the previous commit and do a new commit of that revert. Keeping it simple since January 1st, 1970. It's called the "unceremonious revert", popularized by Jeff Bonwick, the father of ZFS and former Solaris gatekeeper, in the "Quality death spiral": Bonwick was granted authority to "rip it out if itʼs broken" — an early BDFL model, and a template for later generations of engineering leadership. https://web.archive.org/web/20091028095830/http://hub.opensolaris.org/bin/view/Community+Group+on/qual_death_spiral https://web.archive.org/web/20091028095830/http://hub.openso... https://wiki.smartos.org/display/DOC/Community+History https://wiki.smartos.org/display/DOC/Community+History SEE ALSO http://dtrace.org/blogs/bmc/2015/09/03/software-immaculate-fetid-and-grimy/ http://dtrace.org/blogs/bmc/2015/09/03/software-immaculate-f... ...and do youserlf a favor, try out Bitkeeper (it's open source!) before you get completely absorbed into git. You might never be able to get out of that tar pit afterwards, or it might be decades before you realize it. Who will compensate you for all that lost time, and how would you be compensated?
- alistproducer2 10y agoOne of my favorite teachers in school was a dude-bro programmer who pretty sure as younger than me. He'd spent a summer at Google and made us use git and gerrit. I'm honestly a much better programmer thanks to him. I'm still using the git cli to this day. I also still say "new up" an object thanks to him. I'm not so proud of that one.
- vacri 10y agoNot quite in the spirit of this article, but "I just want this /one/ file without the rest of the changes from branch foo" is something I use all the time git checkout otherbranch git checkout firstbranch -- fileIwant maybe1more git commit -m "brought over files"
- partycoder 10y agoWell, there are many more situations you can get into. Like cherry picking, force pushing, merge --no-commit, rebasing... almost any operation can end up going wrong. Just pay attention.
- Kesty 10y agoBut he has the final solution to any git problem: cd .. sudo rm -r fucking-git-repo-dir git clone https://some.github.url/fucking-git-repo-dir.git
- partycoder 10y agoHe needs to create a hook that deletes the repo the next time they do anything with the repo.
- eyelidlessness 10y agoI can't believe no one has responded yet with "use a GUI". After gaining a basic understanding of how branches and merges work, and I do mean basic, I've never been able to screw up a local repo with a GUI client enough that I haven't been able to recover with the same GUI tools. I understand that people need to know how to use their tools, but for git most people can get away with the very basic usage that GUIs provide. If you've made some unrecoverable mistake with an important set of changes, you can always review the history in the same GUI and reimplement the important changes in a new branch.
- pauljaworski 10y agoI like to use a GUI for things like viewing staged/unstaged files, their riffs, and picking which files to stage for a commit, but for every other situation, the command line is just so much faster and easier to understand what's actually happening.
- mmusc 10y agoAgreed, a GUI have most of the functionality and a clear visual representation of the state of your repo. When it's not enough the terminal is once click away
- K0nserv 10y agoI have to disagree, I've seen people paint themselves into really hard to get out of corners by using GUI tools and not understanding the underlying tool. git GUIs are leaky abstractions that sometimes even change the meaning of core git concepts. I always recommend people start by using git at the command line until the have a solid understanding of how the tool works before switching to a GUI.
- noufalibrahim 10y agoYes. I teach git professionally and when I do, my approach is to stick to describing the nuts and bolts. Once people use it from the command line and get things done, they (usually) understand what's going on pretty well but are annoyed by the nitty gritties of the command line. Then they're ready to move on to a tool of their choice but can always map the actions there back to the data structures inside git so they've never lost. Also, they can always drop back down to the command line for any low level surgery that the client doesn't provide. I use magit myself for most things.
- hacksonx 10y agoI moved to git at the begining of this year and I must say that I miss SVN. But everyone keeps telling me that git is better so I'm sticking to it.
- Zelmor 10y agoIs the documentation really that bad? Would it benefit from a technical writer going over it? Is the project open for discussion on changes to the documentation?
- ubernostrum 10y agoGit is like Perl. And not in any of the good ways. Perl 5 -- I don't know enough about 6 to know whether this is still the case -- involved a couple of design decisions which worked well for one subset of people and did whatever the complete polar opposite of "works" is for a different subset of people. One of those design decisions is the famous "there's more than one way to do it". Ask five Perl programmers to solve a simple problem in the language and you'll get fourteen solutions, and no way of knowing which, if any, is to be preferred in real-world use. Git similarly tends to have multiple ways of achieving a given goal, and endless words have been devoted to documenting them; nobody has yet settled which of them is or should be generally recommended, or if there even can be such things as generally-recommended ways to use git. Perl also involves an incredible amount of memorization. The large collection of "magic" variables which can be read or set to determine language and local-scope behavior are daunting and can't be mastered through any process other than rote memorization. And the differing behavior of basic operations depending on context produces a combinatorial explosion of possibilities which, again, are not amenable to any technique short of rote memorization. The same is true in git: though there are underlying abstractions, the interface provided to them is inconsistent, varies depending on sometimes-invisible contextual factors, and ends up requiring rote memorization of commands and options and how they behave in any given situation. Unfortunately, no amount of documentation or review by technical writers can fix this. A bad API can't be made good through better documentation, it can only be made good through being replaced with a better API.
- atemerev 10y agoI am a long-time Perl user and also a long-time Git user. Git is worse than Perl. Perl is just opinionated: despite what you are saying about it is true, you can write working programs and have fun at all levels of Perl mastery. There's a lot to memorize, but you can start coding immediately and do something useful. Also, Perl community is incredibly friendly and helpful. Not so with Git. If you start without thorough understanding how Git internals work, you will get burned really soon. And more often than not, the only response you'll get is the arrogant RTFM or the link to Pro Git book.
- deleted 10y ago[deleted]
- OJFord 10y ago# create a new branch from the current state of master git checkout -b some-new-branch-name # remove the commit from the master branch git checkout master Or just `git branch some-new-branch-name`... cd .. sudo rmdir nsfw-git-repo-dir That will only remove it if it's empty? Which it never will be, because there's at least `.git/*`... Still, amusing :)
- Annatar 10y agoYep, git sucks but it's all the rage now. Mercurial is 100x nicer to use and logical, but since it's written in Python it's slow as molasses, especially with large binary files. Next on the list: Larry McVoy's Bitkeeper promises to be everything git and Mercurial aren't. (git is "inspired" (read: copycat) by Bitkeeper). It's funny how Sun Microsystems influenced the industry in so many ways, isn't it?
- bhrgunatha 10y agoFor anyone who wasn't aware, it's also open source these days - http://www.bitkeeper.org/ http://www.bitkeeper.org/
- bwghughes 10y agoFucking love it. alias gitshit="open http://ohshitgit.com/" http://ohshitgit.com/"
- wyclif 10y agoIf you're concerned about not knowing how to do certain things with git, and understanding at a deeper level how git works, I highly recommend reading Scott Chacon's "Pro Git" book: https://progit.org/ https://progit.org/
- pawadu 10y agoI second your recommendation, this book has saved my bacon multiple times. But does anyone know why this project has two homes? https://git-scm.com/book/en/v2 https://git-scm.com/book/en/v2
- wyclif 10y agoMy understanding is that the dedicated site above highlights the book itself, while git-scm.com recommends/promotes the book.
- deleted 10y ago[deleted]
- coldpie 10y agoThat book is great, and so is the built-in gittutorial(7). If you really want to get down and dirty with Git, I'd also strongly recommend going one step further and reading gitcore-tutorial(7). It shows you the man behind the memorized commands curtain.
- busterarm 10y agoSeconded. Also, I think everyone should go through Neo's Git Immersion at some point early in their experience with git. It is the best crash course by far.
- Gonzih 10y agowhy do you run git add . before git stash?
- bwghughes 10y agoFucking love it. alias gitshit="open http://ohshitgit.com/" http://ohshitgit.com/"
- abarrak 10y agoIt's probably a good time to check if you have some safety against `rm -fr `. Two days ago, I wanted to delete .git only, but accidentally as my fingers were accustomed with -fr , the command was `rm -fr * .git`. Rails server was running and some hope arose at the moment to just `lsof | grep` .. unfortunately that didn't work with me ! Ironically, all dot files have stuck as obvious :)
- 0xmohit 10y ago> Ironically, all dot files have stuck as obvious :) Those wouldn't have if you had set the following: shopt -s dotglob
- 0xmohit 10y agoNobody likes to read manuals or books, due to which one can see FAQs being posted on Q&A sites. http://gitready.com/ http://gitready.com/ contains a number of small articles categorized by beginner, intermediate and advanced that might be helpful. Another resource for commonly used git tips and tricks: https://github.com/git-tips/tips https://github.com/git-tips/tips
- lordnacho 10y agoSurprised he finds git to be complicated. It probably is deep down, but for day-to-day use, compare it to SVN. Until I switched, there was always a panic when branching or merging. With git, I can branch like a nutter and things seem to still work out in the end. Not sure why, perhaps someone else has a perspective on it.
- nicky0 10y agoIn my experience it's all fine and dandy until you hit a rebase or merge that needs manual attention.
- apk17 10y agoIn mine, not quite. All forms of merges are simple: resolve, add, commit. Inside a rebase I find it harder to memorize whether I need to to the add and/or commit or rebase --continue does it for me. And conflicts from 'stash pop' are somewhat counterintuitive to handle.
- niuzeta 10y agoThe last addendum reminds me of this inexorably relevant xkcd entry: https://xkcd.com/1597/ https://xkcd.com/1597/
- froh42 10y agoWith all these recipies - one thing I do whenever I attempt some stunt in git: I assign temporary tags to every changeset that's important. git tag tmp git perform-stunt This eases undoing the stunt without needing to find the "before" state from reflog. And if you use a graphical log viewer (I like SourceTree on Mac) you'll see the tagged state in the history view - which makes things a lot clearer. And to be aware what happens, there one single explanation of git that helps a lot: http://eagain.net/articles/git-for-computer-scientists/ http://eagain.net/articles/git-for-computer-scientists/ As soon as you start viewing git as a graph of nodes with branches/tags just being "marked" nodes a lot of things make sense, and whatever "git perform-stunt" you attempt it's easy to explain within that mental model.
- ramses0 10y agohttp://www.robertames.com/blog.cgi/entries/git-in-two-ten-minutes.html http://www.robertames.com/blog.cgi/entries/git-in-two-ten-mi... ... feedback welcome, but I feel like I go into a bit more depth using similar metaphors.
- jmiserez 10y agoThis doesn't even cover half of the bad situations I've gotten myself in over the last few years :D Long term, it's best to thouroughly read the man pages, e.g. nicely formatted here: https://git-scm.com/docs https://git-scm.com/docs
- shklnrj 10y agoIt is not the fault of Git if to use it you have to know it! However would appreciate a quick and dirty handbook.
- kuahyeow 10y agoMost of the time, stay calm. Do not `git push` hastily, and check `git status` if you can :)
- lambdacomplete 10y agoGetting to "Fuck this noise, I give up." is a very clear indication that you aren't competent enough and you should take a GOOD course about git as soon as humanly possible. Shameless plug: http://engineering.hipolabs.com/how-to-work-in-a-team-version-control-and-git/ http://engineering.hipolabs.com/how-to-work-in-a-team-versio...
- fmsf 10y agoMost of the problems can be solved easily if this is understood - Quote from that article - "Absorb that, internalise it, make it your mantra for the rest of your life or career: a git repository is a tree. "
- Doctor_Fegg 10y agoIf we had to take a GOOD course in every tool that can be used when writing software then we'd have no time to, you know, write software. Not all people who write software are full-time developers. Not all people who use git are developers at all, come to mention it. Not all people who use git for one thing use it for everything. Not everyone can justify the time required for a course for something that might be a tiny part of their work.
- dahart 10y ago> Getting to "Fuck this noise, I give up." is a very clear indication that you aren't competent enough I think that's a tad judgemental for two reasons: 1- because git is legitimately hard to learn. Personally I suspect git is unnecessarily hard to learn, that command names and the concepts and workflows I need are possible to learn and use with less effort. For many years people around me have been asking for git help because I know how to recover from lost stashes and use the reflog, etc., and yet I still have to google the magic incantations for commands I use regularly because they're impossible to remember. 2- There is actually a lot of value in being able to spin up a new repo instantly, in knowing that you can, and in practicing it often. Not unlike the move to VMs for development environments. Plus, there are definitely bad situations where a fresh git clone is the simpler way to go -- just not in this article. ;) Anyway, I also agree with you because this blog post doesn't describe any truly bad situations, and because for years I've seen people blowing away their repos and starting over, and always thought to myself it was funny. It's a drastic action that takes more work than a rebase or reflog or whatever the problem was, and doesn't work well if you've made changes.
- edem 10y agoI really like this article but there is a problem with it: what happens if I use one of your techniques and I screw up? These steps you describe are a black box to someone who is no git savvy yet. While these definitely help but they propagate the "git is scary, cross your fingers" mentality. What I mean by this is that the reader won't be any wiser after reading > git reset HEAD~ --hard What is ~ after HEAD? What is --hard? Is there a --deep option as well? So I think that you could upgrade this with some annotations over the cryptic parts with a little explanation. What do you think?
- ivanhoe 10y agoOn the other hand all of these options are well documented in the git book and manual, so it's quite easy to check the details you're not sure about (and learn something new in the process).
- Erwin 10y agoAfter all this time the HEAD~ syntax has suddenly started making sense to me -- this is the syntax for backup files in vim, so HEAD~ is the "backup" i.e. previous version of HEAD.
- oneloop 10y agoGit is complex and nuanced, and short term purple think it's faster to memorize some commands instead of understanding the fundamentals. I kept having problems with git, so I read a fucking book on it https://git-scm.com/book/en/v2 https://git-scm.com/book/en/v2 I'm not saying I never get into situations I can't get myself out of, but the examples in the oh shit website now look like obviously trivialities.
- crdoconnor 10y agoIt's easier to figure out the various workflows you need (most teams need very few - work on feature, sync code, commit/push/issue PR, release) and then scripting them. I noticed that git errors on my team were almost eliminated when we started doing that - especially once I started adding sanity checks to the git workflows. It also allowed members of the team who previously struggled with git to contribute much more effectively - they'd be rebasing without even necessarily knowing what rebasing was, for instance. It also meant that the git workflow, if it was version controlled, could also be amended. This worked out much better than the git course people were sent on.
- oneloop 10y ago> It's easier to figure out the various workflows you need Fine, that might be cheaper than properly training your employees. Of course, if your employees aren't training themselves out of genuine interest that's really the only option. But then once something goes wrong you'll have to resort to "oh shit" websites and hope that you can the exact issue that you're having, since you really don't understand what's going on anyway. > This worked out much better than the git course people were sent on. I submit this must be because people came out of the course without really understanding the tool. Why they didn't understand I won't speculate, but I submit that they didn't. EDIT: I think that which one is more appropriate depends on where it's used. I a big structured company I can believe that yours is better, or even crucial. But on a scenario where I'm starting a company with two other guys on a garage, I wouldn't want the guys to be the type of people who can only use a workflow that someone designed for them and never had the interest to dig under.
- swah 10y agoI fear Git so much that I make zip packages of the repo before potentially destroying operations.
- EdiX 10y agoAll of those things and more are way easier to do with gitk and git gui.
- Hello71 10y agolots of these are unnecessarily complicated: > Oh shit, I accidentally committed something to master that should have been on a brand new branch! # disappear the last commit and all changes from it git reset --hard HEAD^ # make a new branch using the last commit git checkout -b new-branch HEAD@{1} > Oh shit, I accidentally committed to the wrong branch! first, you don't need to git-add before and after stash, stash will save the working directory and the index (as documented in the DESCRIPTION of git-stash(1)). but for a more logical way: # disappear the last commit and all changes from it git reset --hard HEAD^ # get onto the new branch git checkout new-branch # grab the stuff from what was on the old branch git cherry-pick old-branch@{1} > Oh shit, I tried to run a diff but nothing happened?! git diff --cached recommended reading for intermediate git users: the DESCRIPTIONs of all of these commands (git-reset(1), git-checkout(1), git-cherry-pick(1), git-diff(1)), and the entirety of gitrevisions(7).
- throw2016 10y agogit to me is a work of art. There is a lot of complexity underneath but the end user sees something that is simple, fast and easy to use. It scales depending on user needs and It's easy to reason about. This is a feat of engineering, to take something complex and make it easy for anyone to undestand and use. It shows real expertise and deep understanding of the area. In many ways it's a shining example against the 'culture of complexity' that we increasingly find ourselves in. Here rather than simplying the objective is to be to make thing as complex as possible, usually in pursuit of extremely niche use cases or because either the expertise or the interest to simplify is not there. If git was designed in this culture it would be fragile, full of buzz words, poorly documented and prone to failure, and something only a few self appointed experts could reason about and use properly.
- jimktrains2 10y agoIf the owner is here: with javascript disabled the code is unreadable.
- Waterluvian 10y agoI'm curious, what would you say the % of sites you visit is where they're still useful without JS?
- majewsky 10y agoThat question is not very useful the way it's written down. Some sites legimitately require JS (everything in the "web apps" territory; just try to imagine Grafana without JS), so I would ignore these (which I hope is in line with your intentions). Of the sites that are mostly static content, I would estimate around 60%. There's a small chunk of sites that are just blank with JS disabled, and there's a larger chunk that will load images only when JS is enabled.
- Waterluvian 10y agoYeah that was a poorly worded question, sorry. I'm interested in how far one can get without JavaScript on today's Internet. But it sounds like you don't disable it fully, just only on untrusted sites? 60% is better than I'd expect for sites you expect to work without JS. =)
- majewsky 10y agoI use uMatrix and enable first-party JS by default. That allows me to get by on most sites. Sometimes I have to enable additional domains, mostly: - ajax.googleapis.com and the like - somethingsomething.cloudfront.com - variations of the same domain (for example, hn.algolia.com queries algolia.net and algolianet.com) By the way, it's a very valid question whether my model is actually more secure than just uBlock, but I like it on an emotional level because I feel in control.
- mkj 10y agoAnother option is to use Mercurial with hg-git to GitHub for network effects. I've been doing that for a while for dropbear ssh, it does hit occasional problems but is overall more pleasant than straight git.
- Siecje 10y agoI've had problems with tags. What else have caused you problems?
- mkj 10y agoMainly when I've merged a pull request on github, didn't pull to mercurial, then did some branching in mercurial. Eventually have always managed to sort it out, but sometimes requires a bit of push/pull fiddling. Now you mention it my git tags are out of date...
- coldpie 10y agoTo each his own, of course. As a Git aficionado, I find Mercurial utterly baffling. Branches are permanent and global? You have to clone the repo to make a new thing I would call a branch? "hg log" shows you things that are not in the history of your current source tree? Mind boggling. :)
- nicky0 10y agoThe last one is my usual tactic.
- oskob 10y agoOh shit, I commited a binary file larger than 100 mb and now i can't push to github.com. Solution: https://rtyley.github.io/bfg-repo-cleaner/ https://rtyley.github.io/bfg-repo-cleaner/
- amelius 10y agoIs there some tool that runs a full internal consistency check on a git repo? Because otherwise, how can I be sure that some tool didn't mess up my repo, and one day I'll be getting error messages when checking out files, etcetera?
- chungy 10y agogit fsck
- majewsky 10y agoThis. Also, hold on to the commit before you started refactoring (preferably by placing a temporary branch there, in order to avoid premature garbage collection). Then after your refactoring is done, `git fsck` and `git diff --stat $old_branch..HEAD` to verify that you did not lose any important content during the refactoring.
- jerf 10y agoThat is true in general. However, in the context of bfg-repo-cleaner, that doesn't help, because the purpose of the bfg-repo-cleaner is to completely remove commits that match the criteria you give it. I say this not to "correct" you per se, because you are correct, but to ensure that people using bfg-repo-cleaner do not believe that this will help them. The "correct" course of action prior to using the bfg-repo-cleaner is to make a complete copy of the target .git directory. I've used it many times and it seems quite reliable, but if nothing else, that's a good defense against terminating it halfway through accidentally or something. (Of course even without that, you shouldn't be operating on the only copy of your .git repo anyhow since it is almost certainly somewhere else, too, or you wouldn't be having the problem bfg-repo-cleaner is designed to solve in the first place. But losing your own local branches and work is still a pain.)
- chriswarbo 10y agoBased on the article, and many of the comments here, I didn't realise how comfortable I have become using git! For example, the last "bad situation" I had to get myself out of involved unreadable .git contents caused by filesystem corruption. If you can "rm -rf fucking-git-repo-dir" then it's not too bad; when that fails with an IO error is when things get interesting!
- uhtred 10y agoI prefer stackoverflow for things like this as I can see from comments and up votes whether the command does what the poster claims, or whether it is going to make things worse for me.
- coldpie 10y agoSpend a few hours and really learn how Git works! Then you'll understand what those commands actually do and be able to judge for yourself. Great resources are the ProGit book, gittutorial(7) and eventually gitcore-tutorial(7) when you want to go deeper.
- mhw 10y agoOne of the nice workflows that's already built in to the git command line tools is this one. When you're working on a branch and realise that a commit you made a few commits back has a mistake in it: # Make correcting change git commit --all --fixup=<ref of commit with mistake> # Continue working on branch, then at some point git rebase --interactive --autosquash The --fixup option creates commits with subjects formatted like 'fixup! previous commit subject'. --autosquash uses these subjects when building the interactive rebase list. Handy enough that I set rebase.autoSquash to true in my ~/.gitconfig so 'git rebase -i' always works like this.
- bennofs 10y agoEven better in combination with the `:/grep` syntax that allows you to specify the commit by grepping the commit messages, prefering more recent commits: `git commit --all --fixup ':/implement some feat'`.
- mhw 10y agoMmm - nice. Glad I posted it now, as I didn't know that variation!
- dahart 10y agoYeah, super useful, I can second setting auto squash in the config. I was almost thinking of saying the same thing, but I realized this post is probably deliberately avoiding rebase. This workflow is advanced relative to the problems described, and you'd agree those command lines are going to look pretty intimidating to a novice, right? They were to me the first time, there's a lot to understand before they're comfortable.
- mhw 10y ago> This workflow is advanced relative to the problems described Yeah, true. I posted it mostly because one of the bigger threads of comments was advocating using a GUI instead of the CLI. I'm not going to argue that the git CLI is simple, but it does have some nice features to support specific common workflows.
- mabbo 10y agoOne thing not covered very well was what to do if you push to origin. My favourite way to fix this: use git revert to create an exact opposite commit to your bad commit. git revert <bad commit> git push It leaves a history of the mistake, for better or worse, but it does undo the mistake on origin.
- yobaby1234 10y agoWhy not git commit to a different branch? You revert and push it anyway, right! I guess, for better or worse, it worth your while to keep a mistake, not two of them.
- jryan49 10y agoNever do this on a merge commit however. Unless you are prepared: https://git-scm.com/blog/2010/03/02/undoing-merges.html https://git-scm.com/blog/2010/03/02/undoing-merges.html
- shandor 10y agoThis is why rebase is so, so much better than merge. And it's infinitely better for bisecting, too. Simple, completely linear history for origin/master is just so powerful in many that aspects that I'm constantly baffled why merging seems to be the flow mostly being talked about. Now someone usually comes and says that merges are superior for long running branches. Which may be true in some aspects, but when you have more than one "running" branch and you got to try and find which commits have the code changes that only together seem to break and this is after 2 non-trivial merge commits, you really start to wish you'd gone with rebase.
- ThatGeoGuy 10y agoFor those of us who are uneducated / haven't seen this before: how do you use rebase to merge a separate branch? Are you suggesting you just `git rebase my-branch` from master / develop? How do you coordinate this with multiple team members. Merges appear to work better when you have multiple team members with separate feature branches that may have some overlap (conflicts may occur, but those can be handled as they arise).
- yobaby1234 10y agoWhy is no one saying "use a gui"
- dahart 10y agoGreat idea! We need more basic git workflows described in plain English. I was expecting some actual "bad" situations based on the title, and to be fair these were bad to me once and are bad for people new to git, but I'd love to see the level 2,3,etc. version of this article.
- falsedan 10y agoHere's my standard recommendations: * Learn Git Branching (gentle introduction to git's UI, with a visualization of the DAG) [0] * Git for ages 4 and up (beginner-oriented, teaches you how to model git's internal concepts, 90m video) [1] * Git from the bottom-up (high-level overview of git's internal data structures) [2] * My Git Habits (sophisticated, you will have to study the man pages used to completely internalize the workflow) [3] [0]: http://pcottle.github.io/learnGitBranching/ http://pcottle.github.io/learnGitBranching/ [1]: https://youtu.be/1ffBJ4sVUb4 https://youtu.be/1ffBJ4sVUb4 [2]: http://ftp.newartisans.com/pub/git.from.bottom.up.pdf http://ftp.newartisans.com/pub/git.from.bottom.up.pdf [3]: http://blog.plover.com/prog/git-habits.html http://blog.plover.com/prog/git-habits.html
- pc86 10y ago> This usually happens to me if I merge to master, then run tests/linters... and FML, I didn't put a space after the equals sign. Am I the only one that runs my tests before committing, let alone merging to master?
- SteveNuts 10y agoYeah, pushing untested code to master is not such a great way to work. Push to a remote branch other than master, test it there, then merge it into master. That's pretty much git 101
- njharman 10y agoThat's pretty much software development 101. Been happening for decades before git.
- pc86 10y agoOr test locally? I work in government contracting so everything is .Net and TFS, but even in this environment it's trivial to make sure your code isn't objectively broken: 1. Click "Run all tests" On your local machine even thousands of tests only takes a few seconds including the build process. We've got automated testing in the dev and test environments as well but if you're failing those there's a failure in workflow somewhere. There's very little reason to fail a test or to have a broken build in source control.
- iatanasov 10y agoThe post is missing the most important command : git --help
- samoa4 10y agomaybe also useful https://gitlab.com/esr/reposurgeon https://gitlab.com/esr/reposurgeon
- jakelazaroff 10y ago> Oh shit, I committed and immediately realized I need to make one small change! If you don't want to change the commit message, in addition to --amend: git commit --amend --no-edit
- dep_b 10y agoSomebody proposed to use a GUI. That doesn't solve the usability issues of Git. There's this triangle of what the user tries to do, what the commands and options are called and what they actually do. None of them really align, though with some careful use you can actually make Git do what you want - eventually. I would like to understand what's the yearly damage of such an important tool being so difficult to use. People committing the wrong stuff, unmergeable messes, people not being able to correct their mistakes, there must be thousands of Git rookies fucking up their Git repo or throwing away their work just as I am writing this. What would be the cost? Millions of Dollars? Perhaps even billions? It's about as bad as 0 being a legit value for a regular pointer.
- overgard 10y agoGod, it's probably billions. I love git but its user interface is borderline criminal. The sad thing is mercurial has like 95% of git's power and is waaay easier to understand, but it never took off in a big way.
- exDM69 10y ago> The sad thing is mercurial has like 95% of git's power and is waaay easier to understand Mercurial has a clean and simple UI, especially if you come from a SVN background. But Git's internals are simpler and the concept is much easier to understand, especially if you start looking at a handful of the most popular Mercurial extensions, some of which will be "must have" sooner or later. This is no excuse for an inconsistent UI in Git, but the damage is already done. There's no point in making major changes now (some renaming for consistency might be alright, though), it would be breaking existing workflows and scripts. I find the best explanation of how Git works is... the first commit of Git[0] itself. [0] https://github.com/git/git/commit/e83c5163316f89bfbde7d9ab23ca2e25604af290#diff-c47c7c7383225ab55ff591cb59c41e6bR1 https://github.com/git/git/commit/e83c5163316f89bfbde7d9ab23...
- marcinkuzminski 10y agoI think Mercurial is also great, and we also can provide some feedback as the platform that supports Mercurial as Source Code Management (RhodeCode). There are A LOT of mercurial users which are big companies, they just aren't so vocal on the internal like people using GIT. Mercurial has an established community, great plugability system, an awesome feature like phases. We see more and more people adopting Mercurial together with our product. I wish to see more advocates of Mercurial, it's a shame it doesn't get more public attention nowadays.
- atsaloli 10y agoThere is no substitute for understanding what's going on, especially using a power tool like Git. It's a cute website, and useful, I really like it. This sentence, Bizarrely, git won't do a dif of files that have been add-ed to your staging area without this flag. File under ¯\_(ツ)_/¯" just screams to me (a professional Git trainer), "I don't understand the Git staging area! I don't know my Git fundamentals! Train me!"
- Kratisto 10y agoAny resources you recommend for learning git in more detail?
- atsaloli 10y ago1. Our "Git Fundamentals: Basic Concepts and Definitions" webinar, http://www.verticalsysadmin.com/git/ http://www.verticalsysadmin.com/git/ (you have to register) lays the groundwork you need to start studying Git. If you have a team that needs Git training, email me and we can deliver a instance of this webinar (complete with Q&A session) free of charge (as an introductory service). 2. For someone just starting out, I also recommend "Learn Enough Git to be Dangerous", https://www.learnenough.com/git-tutorial https://www.learnenough.com/git-tutorial (HTML version available for free), from @mhartl, author of the popular RailsTutorial.org 3. The "Pro Git" book is great. https://git-scm.com/book/en/v2 https://git-scm.com/book/en/v2 A comprehensive resource.
- runeb 10y agoFor people wondering about this: Add --cached or --staged (synonyms) to scope to the staging area.
- init0 10y agofor the rest of it there is http://git.io/git-tips http://git.io/git-tips
- pmoriarty 10y agoI've heard advice from #git on freenode not to use "git commit --amend", especially on shared repos. I wish I still had a log of the conversation or remembered the exact problem that led up to it, but it involved a simple amend totally screwing up my repo, and I've avoided it since.
- nchelluri 10y agoI upvoted and am hopefully awaiting a response from someone who can chime in and explain why this is a problem. Amend after push, I could see. You commit, push, amend, push, but after your first push someone else pushes... then you have two heads. I could see that, but I'm guessing you'd mention that if it were the case. If one were to attempt avoiding amend you could always make all changes in a feature branch and rebase this branch onto your target afterwards, squashing commits.
- maw 10y agoIt's much like rebasing, with a similar set of benefits and drawbacks. Once other people can be expected to have done work based on your amended or rebased work, you can expect some annoyances (or worse). If you haven't pushed yet (or if you're really, really sure nobody's basing further work on something you've recently pushed), I say go crazy and amend and rebase to your heart's content.
- eosrei 10y agoThe problem occurs when you amend a commit that someone else is already using. That is rewriting the shared history. A merge commit is required to get the branches in sync again. Amending your commit in your own feature branch or fork isn't a problem. I often amend commits to make a cleaner git history to ease PR/code review. git checkout master git checkout -b 10-new-feature # Make changes git add example.code git commit git push origin 10-new-feature # Oops... left a debug message, fix it. git add example.code git commit --amend git push -f # Rewrites the remote history with your local modified version Consider --amend as the "Just the last commit" form of rebasing.
- chriscool 10y agoI just uploaded a presentation I gave last February called "Git back on your feet": http://www.slideshare.net/ChristianCouder/git-back-onyourfeet-65866467 http://www.slideshare.net/ChristianCouder/git-back-onyourfee...
- fizzbatter 10y agoI've been debating starting a section of my personal site for stuff like this. Unfortunately it's a bit embarrassing, but i figure anything i have to google to learn, it would be beneficial to help others learn it as well. Everything from programming languages (lots of Rust errors are foreign to me, for example), to git issues. I've often had the thought that if everyone did this it could have potential to be quite the open-sourced collection of material - a distributed self-answered Stack Overflow perhaps. Is there any sanity in this? Or would posting everything as self-answers to Stackoverflow be more welcome to the average Googler? (higher ranking, better meta, more likely for the user to see it and community features such as commenting/voting/editing)
- steveklabnik 10y agoPlease file bugs for bad errors in Rust. We have an entire tag dedicated to them, and have been doing a lot of work to make them better. A non-understandable error is a bug.
- MattyRad 10y ago> Bizarrely, git won't do a dif of files that have been add-ed to your staging area without this flag Not sure what's bizarre about that. Doing so helps keep your commits clean and helps git tools (diff, git-gutter, etc) by ignoring things you've already stated are complete. For example, I quickly fix a bug. The code is ugly and I don't want to commit it yet. So I add the bugfix files. Then I clean up the code (before commiting). Now I can do another diff between the staged and unstaged files, checking that it looks better than before, and still works. This way there is 1 clean commit "bugix" and not 2 commits "bugfix" and "bugfix code cleanup"
- MattyRad 10y ago> Bizarrely, git won't do a dif of files that have been add-ed to your staging area without this flag Not sure what's bizarre about that. Doing so helps keep your commits clean and helps git tools (diff, git-gutter, etc) by ignoring things you've already stated are complete. For example, I quickly fix a bug. The code is ugly and I don't want to commit it yet. So I add the bugfix files. Then I clean up the code (before commiting). Now I can do another diff between the staged and unstaged files, checking that it looks better than before, and still works. This way there is 1 clean commit "bugix" and not 2 commits "bugfix" and "bugfix code cleanup"
- fizzbatter 10y agoI constantly wonder if there's a "better CLI UI" that can be made for git, even if simply a wrapper around git. Ie, if the implementation of Git is right, but only the cli commands/etc are wrong.. what would the right UX be? What would a friendly UX look like? Seems like something a lot of people could love - even if blasphemy to Git purists.
- ThrustVectoring 10y agoA somewhat lesser known git trick that's pretty much a strict improvement - use `--force-with-lease` for force pushing instead of `--force`. What this does is check what's on the remote branch and compare it with what you think is on the remote branch, and only do the force if they're the same thing. So if someone pushes a commit, the force push errors out instead of silently overwriting it. Basically every single time you want to force push, you probably should be doing a `--force-with-lease` instead. I can't think of a situation where you'd want to silently lose commits you don't know about rather than get an error.
- bdhess 10y agoI also can't think of a situation where you'd want to force push to a branch that others might be committing to.
- ThrustVectoring 10y agoIf they're not committing to it, --force-with-lease is the same thing as --force, so it doesn't cost you anything.
- bdhess 10y agoCosts ten keystrokes by my count. But it's not the keystrokes that trouble me, it's the idea that one of my co-collaborators might use this feature to "safely" rewrite history in a branch I'm also using. "Safely" being relative, since the rest of the collaborators will have to force pull that branch later, and rebase their pending changes. By my reckoning, rewriting history just isn't a reasonable decision in shared branches.
- srigi 10y agoDoing mumbo-jumbo between branches with `git stash` is way to hell. Don't do it, you lose data. This fucker will unstash changes until first conflict, then it stop and present you with <<<<<<<ID and >>>>>>>ID which nobody understand. Well I understand it, but never know which is which (theirs/ours label don't help here). You try to undo everything, but then you're fucked - all unstashed changes are removed from stash while conflicts are still there. You must be very careful now not to lose changes. You won't succeed! That is I believe `git stash` should be removed from git as evil data loosing feature, not needed. Instead just make an alias `git save <TEMP_BRANCH_NAME>` which saves your temporary work to the branch: `save = !sh -c 'export PREV=$(git symbolic-ref HEAD|cut -d/ -f3-) && git checkout -b "$1" && git commit -am "$1" && git checkout "$PREV"' -`
- joshuahutt 10y agoYou can use `git stash apply` to apply the stashed changes without removing them from the stash.
- deleted 10y ago[deleted]
- Pinckney 10y agoFrom man git-stash: "Applying the state can fail with conflicts; in this case, it is not removed from the stash list. You need to resolve the conflicts by hand and call git stash drop manually afterwards." Or do I misunderstand you?
- adamkochanowicz 10y agoGreat article. A couple notes Just git reset <ref> should do. The --soft flag is implicit. Amending and rebasing is something you should be careful with. If you've already pushed, you'll now need to force push. If another person has put new commits upstream, they will be wiped out irreparably. Not saying don't do it, just that it's very risky. Instead of deleting and recloning the repo at the end, if you're really at that point, just doing git reset --hard origin/master should be equally as effective with fewer steps and less time. Pulling down the repo a second time, however, can be more useful for just having a snapshot of the code in a second location that is totally independent of git traffic (don't pull to it very often). Say someone force pushes something that removes code. Your snapshot or someone else's non-pulled repo is your only hope of getting it back.
- evanelias 10y agoJust a tiny correction: git reset <ref> defaults to --mixed, not --soft. The only difference is whether or not files are staged. Since the OP used --soft, I believe the subsequent `git add .` is unnecessary since the files should already be staged when --soft is used. Regarding the case of an erroneous force push removing code, usually things can be recovered by looking through the reflog and doing some surgery via the lower-level plumbing commands... it's not exactly a fun process though :)
- Anthony-G 10y agoFrom the section on using `git commit --amend`: > This usually happens to me if I merge to master, then run tests/linters. If this happens on more than one occasion, I’d strongly consider creating a pre-commit hook to run tests and/or lint the changed files, e.g., I run `checkbashisms` and `shellcheck` as a pre-commit hook when working on shell scripts.
- hobarrera 10y agogit add . Ugh, no, never do this, never recommend to users to BLINDLY ADD ALL THE CHANGES FROM THE WORKING COPY. I honestly can't think of any worse git usage than this. Add the single change you missed, or even better, `git add -p`, to add chunks manually.
- csbubbles 10y agoYou know, a few years back I had exactly the same attitude towards Git. I hated it, tried to approach multiple times and still hated it. But after working with Git on multiple projects, and having developed some deeper understanding of how things work there, I honestly think now that Git is one of the best tools that have been invented over last 20 years for improving the development processes and engineering excellence. I don't really want to defend it, the learning curve is apparently pretty steep (at least it was for me), but I would just recommend to not give up and keep trying. There are some good tutorials how to handle it and why it's helpful (Atlassian's Git book, for instance).
- sytelus 10y agoIt would be nice to add these two: Oh shit, someone checked-in huge file that shouldn't be in repo. Oh shit, this folder I had been working on should have been in its own repo.
- baddjobcent 10y agoHere lonely girl looking for fun with the guys http://u.to/i_g3Dw http://u.to/i_g3Dw