Skip to content

Instantly share code, notes, and snippets.

@MichalMazurek
Last active February 6, 2019 15:44
Show Gist options
  • Save MichalMazurek/29ed7e8b10a718863a19405d67a850f4 to your computer and use it in GitHub Desktop.
Save MichalMazurek/29ed7e8b10a718863a19405d67a850f4 to your computer and use it in GitHub Desktop.
import click
from subprocess import run
import os
@click.command()
@click.argument("source_repo", type=str)
@click.argument("source_branch", default="master", type=str)
@click.argument("target_repo", type=str)
@click.argument("target_directory", type=str)
@click.argument("target_branch", type=str, default="master")
def main(
source_repo: str,
source_branch: str,
target_repo: str,
target_directory: str,
target_branch: str,
):
"""Extract directory from repo and push it new repo with full history.
Args:
source_repo (str): url to source repo
source_branch (str): source repo branch
target_repo (str): url to target repo
target_directory (str): directory to be extracted
target_branch (str): branch for the target
"""
run(["git", "clone", source_repo, target_directory])
os.chdir(target_directory)
if source_branch != "master":
run(["git", "checkout", f"origin/{source_branch}"])
run(["git", "checkout", "-b", source_branch])
run(
[
"git",
"filter-branch",
"--prune-empty",
"--subdirectory-filter",
target_directory,
source_branch,
]
)
for line in run(
["git", "remote", "-v"], capture_output=True, text=True
).stdout.splitlines():
if source_repo not in line:
click.echo(
f"Source repo origins are not matching given source repo, bailing... {source_repo} not in {line}",
err=True,
)
return
run(["git", "remote", "set-url", "origin", target_repo])
for line in run(
["git", "remote", "-v"], capture_output=True, text=True
).stdout.splitlines():
if target_repo not in line:
click.echo(
f"Target repo origins are not matching given target repo, bailing... {source_repo} not in {line}",
err=True,
)
return
if source_branch != target_branch:
run(["git", "branch", "-m", target_branch, f"{target_branch}-old"])
run(["git", "branch", "-m", source_branch, target_branch])
run(["git", "push", "-u", "origin", target_branch])
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment