October 2nd, 2023

How do I manually update a remote tracking branch, say, to undo a fetch?

One of my colleagues who writes git tools wanted to know how to force a local repo’s remote tracking branch into a stale state. Doing so would allow testing of various edge cases.

$ git fetch origin
remote: Enumerating objects: 15, done.
remote: Counting objects: 100% (15/15), done.
remote: Total 15 (delta 0), reused 6 (delta 0), pack-reused 0
From http://contoso.com/sample
   844de02..01781ca  main       -> origin/main

How can we “unfetch” the origin/main branch so the local repo thinks that the remote is still on 844de02?

The magic command is git update-ref. This command lets you set the commit for any branch or tag.

$ git update-ref refs/remotes/origin/main 844de02

You can also use it to undo the creation of a branch via a fetch.

$ git fetch origin
remote: Enumerating objects: 22, done.
remote: Counting objects: 100% (22/22), done.
remote: Total 22 (delta 0), reused 9 (delta 0), pack-reused 0
From http://contoso.com/sample
 * [new branch]      dev        -> origin/dev

You can delete the remote tracking branch by saying

$ git update-ref -d refs/remotes/origin/dev
Topics
Other

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.