On Sunday, 6 January 2013 at 19:50:47 UTC, Andrei Alexandrescu wrote:
For example, I tried today to get the latest and greatest phobos into my repo, and got a bunch of conflicts. I searched a while on the net to figure what the command for "just get the latest remote into my local copy", which is entirely possible but not obvious and not easy to find.

#!/bin/bash

# Add untracked files to the index, so they're stashed and deleted. # This gives us a cleaner directory, and avoids possible collisions with files that are currently untracked, but are tracked in master.
git add --all .

# Saves any changes in the working tree or index, if any, as a stash.
git stash save "Automatic save before switching to latest master"

# Now that the working tree is clean, switch to whatever the "master" branch is currently.
git checkout master

# Reset the master branch to point to the remote's tracking branch. # This allows the merge implied by "git pull" to be a fast-forward.
git reset --hard origin/master

# Download new objects, update tracking branch, fast-forward current branch to tracking branch.
git pull

# End

This script assumes that the branch you want is "master", and that the remote is called "origin".

Do not invoke the script directly. Rather, create an alias in your .gitconfig which launches the script. This will allow it to work correctly even from a subdirectory in the project.

Instructions to recover data from accidental usage of this script:

To find what branch (or commit, with detached HEAD) you were on before the switch to master, check the output of `git reflog HEAD`. It should look something like this:

eb5121f HEAD@{0}: pull: Fast-forward
8e7ed2b HEAD@{1}: reset: moving to origin/master
d49acd5 HEAD@{2}: checkout: moving from foo to master
ecdc09c HEAD@{3}: ...
...

The commit you were on should be below the line the description of which starts with "checkout:".

Uncommitted data in your index or working tree will be in the git stash. Use `git stash apply` to apply the patch to the current working tree.

The script could be improved to be a little more efficient (e.g. avoid checking out the old master), or less noisy or reliant on the environment (e.g. detecting the name of the remote).

Reply via email to