Skip to content

Instantly share code, notes, and snippets.

@matipan
Last active February 19, 2017 20:08
Show Gist options
  • Save matipan/1750719c5a46bd9196cfbcc5dc287800 to your computer and use it in GitHub Desktop.
Save matipan/1750719c5a46bd9196cfbcc5dc287800 to your computer and use it in GitHub Desktop.
package main
import (
"flag"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
)
var (
remote = flag.String("r", "", "remotes can be https or ssh")
username = flag.String("u", "", "specifies usernames to be changed, format is oldusername:newusername")
github = "[email protected]"
)
func main() {
flag.Parse()
if *remote == "" || *remote != "https" && *remote != "ssh" {
fmt.Println("invalid remote type")
return
}
s := strings.Split(*username, ":")
if *username == "" || len(s) != 2 {
fmt.Println("the format for usernames is oldusername:newusername")
return
}
oldu, newu := s[0], s[1]
filepath.Walk(os.Getenv("GOGITHUB"),
ChangeUsernames(oldu, newu, *remote))
}
// ChangeUsernames returns the func that runs inside the walk
func ChangeUsernames(oldu, newu, remote string) filepath.WalkFunc {
fmt.Printf("old username: %v\nnew username: %v\n", oldu, newu)
return func(path string, info os.FileInfo, err error) error {
if !info.IsDir() {
// just a file, ignore it
return nil
}
if _, err := os.Stat(filepath.Join(path, ".git")); os.IsNotExist(err) {
// this is not a repo
return nil
}
// this is a repo
cmd := exec.Command("git", "remote", "-v")
cmd.Dir = path
out, err := cmd.Output()
if err != nil {
fmt.Println(err)
panic("NOOOO")
}
res := string(out)
if res == "" {
return filepath.SkipDir
}
// rem = remote type, repo = the repo, rname = origin or something else
rem, rname, un, repo, err := fetchInfo(oldu, strings.Split(res, "\n")[0])
fmt.Printf("old: %v:%v/%v\n", rem, un, repo)
if err != nil {
return err
}
newrepo := fmt.Sprintf("%v:%v/%v", github, newu, repo)
fmt.Printf("new: %v\n", newrepo)
cmd = exec.Command("git", "remote", "set-url", rname, newrepo)
cmd.Dir = path
if err = cmd.Run(); err != nil {
fmt.Println(err)
panic("GAAAA")
}
return filepath.SkipDir
}
}
func fetchInfo(oldu, details string) (rem string, rname string, un string, repo string, err error) {
aux := strings.Split(strings.Trim(string(details), "(fetch)"), "\t")
rname = aux[0]
tmp := strings.Split(aux[1], ":")
rem, repo, un = tmp[0], strings.Split(tmp[1], "/")[1], strings.Split(tmp[1], "/")[0]
repo = strings.Trim(strings.Trim(repo, "\t"), " ")
if rem != github || un != oldu {
err = filepath.SkipDir
return
}
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment