# This script will go through every directory in a directory, see if it is a git directory,
# and then will check to see if the old username is included in the remote URL of that git
# directory. If it is, then the script will change the remote URL to instead point to the
# new username's remote URL.

OLD_USERNAME = 'emmasax1'
NEW_USERNAME = 'emma-sax4'


current_dir = Dir.pwd
nested_dirs = Dir.entries(current_dir).select do |entry|
  entry_dir = File.join(current_dir, entry)
  File.directory?(entry_dir) && !(entry == '.' || entry == '..')
end

nested_dirs.each do |dir|
  Dir.chdir dir
  if File.exist?('.git')
    puts "Found git directory: #{dir}."
    resp = `git remote -v`
    if resp.include?(OLD_USERNAME)
      puts "  Git directory's remote is pointing to: '#{OLD_USERNAME}'.'"
      repo = resp.scan(/\/([\S]*).git/).first.first.sub(OLD_USERNAME, NEW_USERNAME)
      remote_name = resp.scan(/([a-zA-z]+)/).first.first
      puts "  Changing the remote URL #{remote_name} to be git@github.com:#{NEW_USERNAME}/#{repo}."
      begin
        `git remote set-url #{remote_name} git@github.com:#{NEW_USERNAME}/#{repo}`
        puts "  Done."
      rescue Exception => e
        puts "  Could not complete: #{e.message}"
      end
    else
      puts "  No need to update this directory's remote URL."
    end
  end
  Dir.chdir current_dir
end

Add file that will change all of the remote URLs in git dirs
Add file that will change all of the remote URLs in git dirs

Upon changing my GitHub username, I wanted a fast way to change all of the remote URLs in all of the git directories in a repository. So, I developed this quick ruby script that will do just that. It's hard-coded to check for my old/new usernames, but that's an easy change that could be made. It's also hard-coded to assume that there's only one remote URL, so the script may need to be modified if there are two (think `origin` and `upstream`).

Run the script like such: `ruby change_remote.rb`.
