Last active
August 19, 2016 20:27
-
-
Save junhe/eabc9a6723c786b499868c2b142d5b2d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import argparse | |
import subprocess | |
import os | |
import sys | |
import shlex | |
import time | |
import shutil | |
class cd: | |
"""Context manager for changing the current working directory""" | |
def __init__(self, newPath): | |
self.newPath = newPath | |
def __enter__(self): | |
self.savedPath = os.getcwd() | |
os.chdir(self.newPath) | |
def __exit__(self, etype, value, traceback): | |
os.chdir(self.savedPath) | |
def shcmd(cmd, ignore_error=False): | |
print 'Doing:', cmd | |
ret = subprocess.call(cmd, shell=True) | |
print 'Returned', ret, cmd | |
if ignore_error == False and ret != 0: | |
raise RuntimeError("Failed to execute {}. Return code:{}".format( | |
cmd, ret)) | |
return ret | |
def prepare_dir(dirpath): | |
"create parent dirs for path if necessary" | |
if not os.path.exists(dirpath): | |
os.makedirs(dirpath) | |
def is_git_repos(dirpath): | |
return os.path.exists( os.path.join(dirpath, '.git') ) | |
def checkout_commit(target_dir, repo_name, commit): | |
""" | |
Clone the repository to the target directory if it is not there yet. | |
Checkout the specific commit | |
""" | |
prepare_dir(target_dir) | |
repos_path = os.path.join(target_dir, repo_name) | |
with cd(target_dir): | |
if is_git_repos(repos_path) is False: | |
if os.path.exists(repos_path): | |
shutil.rmtree(repos_path) | |
shcmd('git clone git@github.com:junhe/{}.git'.format(repo_name)) | |
with cd(repo_name): | |
shcmd('git pull', ignore_error=True) | |
shcmd('git checkout {}'.format(commit)) | |
def _main(): | |
parser = argparse.ArgumentParser( | |
description="" | |
) | |
parser.add_argument('--repo_name', action='store') | |
parser.add_argument('--target_dir', action='store') | |
parser.add_argument('--commit', action='store') | |
args = parser.parse_args() | |
argdic = vars(args) | |
if not all( v for _,v in argdic.items() ): | |
parser.print_help() | |
exit(1) | |
checkout_commit(target_dir=args.target_dir, | |
commit=args.commit, repo_name=args.repo_name) | |
if __name__ == '__main__': | |
_main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment