import subprocess
import logging

from ghtools.ssh_key import SSHKey

log = logging.getLogger(__name__)

def migrate(src, dst, name):
	key = SSHKey()
	key.create()

	try:
		key.add_host(src.hostname)
		key.add_host(dst.hostname)

		src.add_public_key("ghtools migration tool", key.public_key)
		dst.add_public_key("ghtools migration tool", key.public_key)

		run("mkdir repos")
		run("git clone ghtools.{0}:{1} repos/{2}".format(dst.hostname, dst.full_name(name), name))
		run("cd repos/{0} && git remote add upstream ghtools.{1}:{2}".format(name, dst.hostname, src.full_name(name)))
		run("cd repos/{0} && git fetch --tags upstream".format(name))

		run("cd repos/{0} && git merge upstream/master".format(name))
		run("cd repos/{0} && git push origin".format(name))

	finally:
		if key.exists:
			src.remove_public_key(key.public_key)
			dst.remove_public_key(key.public_key)

			key.remove()


def run(command):
	log.debug(command)
	return subprocess.call(command, shell=True)


@@ -26,16 +26,59 @@
 logging%0A
+import os%0A%0Afrom ghtools.api import APIError
 %0Afrom gh
@@ -266,16 +266,24 @@
 tname)%0A%0A
+%09%09try:%0A%09
 %09%09src.ad
@@ -337,16 +337,17 @@
 ic_key)%0A
+%09
 %09%09dst.ad
@@ -396,24 +396,51 @@
 .public_key)
+%0A%09%09except APIError:%0A%09%09%09pass
 %0A%0A%09%09run(%22mkd
@@ -446,16 +446,19 @@
 dir 
+-p 
 repos%22)%0A
 %09%09ru
@@ -453,16 +453,71 @@
 repos%22)%0A
+%09%09if not os.path.exists(os.path.join(%22repos%22, name)):%0A%09
 %09%09run(%22g
@@ -525,16 +525,23 @@
 t clone 
+--bare 
 ghtools.
@@ -602,32 +602,33 @@
 name), name))%0A%09%09
+%09
 run(%22cd repos/%7B0
@@ -686,19 +686,19 @@
 t(name, 
-dst
+src
 .hostnam
@@ -722,16 +722,17 @@
 name)))%0A
+%0A
 %09%09run(%22c
@@ -760,15 +760,8 @@
 tch 
---tags 
 upst
@@ -780,17 +780,16 @@
 (name))%0A
-%0A
 %09%09run(%22c
@@ -811,52 +811,225 @@
 git 
-merge upstream/master%22.format(name))%0A
+push --mirror origin%22.format(name))%0A%0A%09%09branches = filter(None, map(str.strip, run('cd repos/%7B0%7D && git branch -r'.format(name), output=True).split(%22%5Cn%22)))%0A%09%09for branch in branches:%0A%09%09%09b = branch.split('/')%5B1%5D%0A%09
 %09%09run(
-%22
+'
 cd r
@@ -1049,38 +1049,131 @@
 it push 
-origin%22.format(name))%0A
+--force origin %7B1%7D:refs/heads/%7B2%7D'.format(name, branch, b))%0A%09except APIError as e:%0A%09%09print(e.response.text)%0A%09%09raise
 %0A%09finall
@@ -1308,16 +1308,30 @@
 (command
+, output=False
 ):%0A%09log.
@@ -1345,16 +1345,90 @@
 ommand)%0A
+%09if output:%0A%09%09return subprocess.check_output(command, shell=True)%0A%09else:%0A%09
 %09return 

Migrate all branches and tags