1

I have an old shell snippet that I use (or to its alias) often that updates all the repos in a folder.

find . -maxdepth 1 -type d -exec sh -c '(cd {} && git checkout master && git pull)' ';'

However, today many repos are converting to use main rather than master. In particular, GitHub now defaults to that. But there are still many repos that still use master.

I'm seeking a generic linux/macOS not-only-on-github replacement snippet (that I can alias) to checkout the correct branch (I'm willing to presume there is not both types) and pull.

That being said, if someone has a version of this that works with GitHub's gh tool, that would be useful. But I do need one that works outside of GitHub.

Another optional feature that I'd love is if the script can do the right thing if the max-depth 1 repo explicitly has submodules.

Related other Stack Overflow questions:

aynber
  • 22,380
  • 8
  • 50
  • 63
  • https://stackoverflow.com/q/28666357/7976758 Found in https://stackoverflow.com/search?q=%5Bgit%5D+get+default+branch – phd Feb 26 '22 at 22:16
  • As someone who advocates contributors rarely, if ever, checkout shared branches such as `master` or `main`, I find this question asking how to automate it, slightly amusing. ;) (Of course, I realize there are still plenty of use cases for checking out shared branches.) – TTT Feb 27 '22 at 01:21

1 Answers1

1

The gh version would involve getting the default branch through API.

gh api /repos/{owner}/{repo} --jq '.default_branch'

That way, your remote repository could use master or main or any other branch as default, you would switch to the right one locally

find . -maxdepth 1 -type d -exec sh -c \ 
  '(cd {} && \
    ownerRepo=$(git remote get-url origin) && \
    ownerRepo=${ownerRepo#https://github.com/} && \
    remoteBranch=$(gh api /repos/${ownerRepo} --jq '.default_branch') && \
    git switch ${remoteBranch} && git pull)' ';'

If you do not want to depend on a remote GitHub API, you can at least read the local repository default branch:

find . -maxdepth 1 -type d -exec sh -c \ 
  '(cd {} && \
    defaultBranch=$(git rev-parse --abbrev-ref origin/HEAD) && \
    defaultBranch=${defaultBranch#origin/} && \
    git switch ${defaultBranch} && git pull)' ';'
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250