Skip to content

Instantly share code, notes, and snippets.

@dvinciguerra
Last active July 22, 2022 15:09
Show Gist options
  • Save dvinciguerra/d390ea3c87a65050a624f484b2ecc5f9 to your computer and use it in GitHub Desktop.
Save dvinciguerra/d390ea3c87a65050a624f484b2ecc5f9 to your computer and use it in GitHub Desktop.
Ruby script to update all git repositories recursively
#!/usr/bin/env ruby
# frozen_string_literal: true
require 'logger'
# globals
$stdout.sync = true
$logger = Logger.new($stdout)
# arguments
path = ARGV.first
current_dir = path || Dir.pwd
def repositories(current_dir)
Dir
.glob("#{current_dir}/**/.git")
.map { |path| path.sub('/.git', '') }
end
def change_working_dir(path)
Dir.chdir(path)
end
def head_branch
`git remote show origin | grep 'HEAD branch:'`
.chomp
.scan(/HEAD branch: (master|main)/)
.flatten
.first
end
repositories(current_dir).each do |repository_path|
$logger.info("Processing repo #{repository_path}")
# go to repository path
change_working_dir(repository_path)
# get head branch or skip
main_branch = head_branch
next unless main_branch
# update remote branches and make the head branch pull
`git fetch --all &&
git stash push &&
git checkout #{main_branch} &&
git pull origin #{main_branch} &&
git remote prune origin &&
git branch --merged #{main_branch} | grep -v #{main_branch} | xargs git branch -d &&
git checkout -`
end
@dvinciguerra
Copy link
Author

The git branch --merged master | grep -v master | xargs git branch -d && improvement by @lockland. Thanks! =)

@lockland
Copy link

The git branch --merged master | grep -v master | xargs git branch -d && improvement by @lockland. Thanks! =)

:)

I just think you need to replace the string master by that variable you've created main_branch otherwise it wont work for repos that use main branch instead of master one

@dvinciguerra
Copy link
Author

The git branch --merged master | grep -v master | xargs git branch -d && improvement by @lockland. Thanks! =)

:)

I just think you need to replace the string master by that variable you've created main_branch otherwise it wont work for repos that use main branch instead of master one

Cool! Thank's again! =D

Fixed!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment