def run(self): """ Removes, if exists, the current folder and clones the repository in that folder that you have passed by - argument with space like delimiter (ie: !git_clone https://github.com/bilardi/sceptre-git-clone-hook my-folder) - sceptre_user_data with properties GitRepository and RepositoryFolder Raise (Exception): when the system does not find the arguments repository and folder in argument or sceptre_user_data """ if self.argument and self.DELIMITER in self.argument: repository, folder = self.argument.split(self.DELIMITER, 1) self.logger.debug( "[{}] Parameters parsed from the argument".format(self.NAME)) elif self.stack.sceptre_user_data and 'GitRepository' in self.stack.sceptre_user_data and 'RepositoryFolder' in self.stack.sceptre_user_data: repository = self.stack.sceptre_user_data.get('GitRepository', {}) folder = self.stack.sceptre_user_data.get('RepositoryFolder', {}) self.logger.debug( "[{}] Parameters parsed from sceptre_user_data".format( self.NAME)) else: raise Exception( "Parameters GitRepository and RepositoryFolder could not be parsed from sceptre_user_data or argument" ) if os.path.exists(folder): shutil.rmtree(folder) self.logger.info( "[{}] Removed the local repository folder {}".format( self.NAME, folder)) Repo.clone_from(repository, folder) self.logger.info( "[{}] Downloaded the remote repository in the folder {}".format( self.NAME, folder))
def clone_repo(start=0, end=100000): """ Clones the GitHub repositories if the repositories has not been cloned initially. Parameters: start(int): This is an integer that specifies which URL cloning should start from in the CSV file of the GitHub repositories. Defaults to zero. end(int): This is an integer that specifies which URL cloning should end in the CSV file of the GitHub repositories. Defaults to 100000, which is the last URL. Returns: count(int): The number of repository cloned. """ repo_list = repo_url['URLs'] count = 0 for url in repo_list[start:end]: url = str(url) name = url.rsplit( '/', 2) #get the repo name (last 2 part) of the repository url last = name[-2] + '-' + name[-1] try: if not os.path.exists(last): os.mkdir(last) #Make folder for a repo if it does not exist repo = str(url) + '.git' folder = r'repos' Repo.clone_from(repo, last) count += 1 print('cloned ', repo) except: continue return count
def clone(where, what): from pathlib import Path dest_fn = Path(GLOBS['kk_code_dir'], what) if dest_fn.exists(): return (False, str(dest_fn)) """ans = None while ans not in "ynYN": ans = input("The destination folder, {dest_fn}, exists already. Should we overwrite it?") if ans in "nN":""" if not dest_fn.exists(): print("Module doesn't exist. Attempting to load it from GitHub...") if where[0] == '@': where = where[1:] url = "https://github.com/%s/%s" % (where, what) print(f"Cloning '{where}/{what}' into '{dest_fn}' ...") from git.repo.base import Repo fld = Path(GLOBS['kk_code_dir']) if not fld.exists(): fld.mkdir() Repo.clone_from(url, dest_fn) return (True, str(dest_fn))
def CloneGitRepo(link,dir): try: from git.repo.base import Repo except ImportError: print("Please install GitPython package first!") return None Repo.clone_from(link, dir, progress=Progress())
def install_playbook(self, **kwargs): """ Validates that self._playbook is a valid path or url. If it is a url git clone to /tmp. If it has a requires file install dependencies. """ logger.debug('Installing playbook...') if "url" in kwargs: # Should probably extract the playbook name from the playbook # URL Repo.clone_from( kwargs["url"], self.path ) elif "path" in kwargs: if os.path.exists(kwargs["path"]): path = None if os.path.isfile(kwargs["path"]): path = os.path.dirname(kwargs["path"]) else: path = kwargs["path"] os.symlink(os.path.realpath(path), self.path,) else: raise ValueError( 'The path value provided (%s) does not exists', kwargs['path'] ) assert os.path.exists(self.path)
def clone(): try: print(f'Using existing repo in {settings.REPOSITORY_DIR}') Repo(settings.REPOSITORY_DIR) except: print('Repo does not exist') Repo.clone_from(settings.GIT_REPOSITORY, settings.REPOSITORY_DIR)
def CheckFiles(): if os.path.isdir('scripts'): print ("File Does exist") checkall() else: print ("File not exist, Creating") Repo.clone_from("https://github.com/ChokunPlayZ/ChatSpammer-Data.git", "scripts")
def main(hub, archived, archived_only, forks, depth, prune, org): """ Clone an entire GitHub organization into the current directory. Each repo becomes a subdirectory. """ if archived_only: archived = True dir_names = set() for repo in hub.organization(org).repositories(): if repo.fork and not forks: continue if repo.archived and not archived: continue if not repo.archived and archived_only: continue dir_name = repo.name dir_name = dir_name.lstrip("-") # avoid dirname/option confusion dir_names.add(dir_name) if os.path.exists(dir_name): continue print("Cloning {}".format(repo.full_name)) clone_args = {} if depth: clone_args['depth'] = depth Repo.clone_from(repo.ssh_url, dir_name, **clone_args) if prune: for dir_name in os.listdir("."): if os.path.isdir(dir_name): if dir_name not in dir_names: print("Pruning {}".format(dir_name)) shutil.rmtree(dir_name)
def do_init(): for repository_name, repository_remote in settings.toclone.items(): git_dest = '' if repository_name in settings.inventorydirs: git_dest = settings.inventorydirs[repository_name] elif repository_name in settings.playbookdirs: git_dest = settings.playbookdirs[repository_name] elif repository_name in settings.localdirs: git_dest = settings.localdirs[repository_name] else: print( 'there is no corresponding directory defined in your config for {}' .format(repository)) if not git_dest: print('could not find git_dest') continue if os.path.isdir('{}/.git'.format(git_dest)): print('update repository {}'.format(git_dest)) git = Repo(git_dest).git git.pull() else: print('clone repository {}'.format(git_dest)) os.makedirs(git_dest, exist_ok=True) Repo.clone_from(repository_remote, git_dest)
def _resolve_git(url: str, destination: str) -> str: """ Clone a gh:// url to a local folder. Args: url: git url, the format is gh://organization/repo destination: the destination directory for the repo, must be empty Returns: The destination directory. Raises: ValueError: The github url is not valid. FileExistsError: The destination directory is not empty. """ url = url.lower() if not url.startswith('gh://'): raise ValueError(f'{url} is not a valid gh:// url.') if len(os.listdir(destination)): raise FileExistsError( f'The working directory {destination} is not empty!') parsed = urlparse(url) org, repo = parsed.netloc, parsed.path[1:] git_url = f'git://github.com/{org}/{repo}.git' try: Repo.clone_from(git_url, destination) except Exception as e: raise ValueError(f'The github url can not be cloned. Message: {e}') logger.info(f'Cloned {url} to {destination}') return destination
def rbenv_install(version: str = '2.4.2', force:bool = False): logger.debug('verifying that dependencies are installed') # Centos 7 Deps # git bzip2 gcc make openssl-devel readline-devel zlib-devel docker assert all([which(pkg) for pkg in ('git', 'bzip2', 'gcc', 'docker')]) # Get paths rbenv = path.join(local_path, '.rbenv') plugins = path.join(rbenv, 'plugins') ruby_build = path.join(plugins, 'ruby-build') rbenv_bin = path.join(rbenv, 'bin', 'rbenv') gem = path.join(rbenv, 'shims', 'gem') # Setup paths if not path.exists(rbenv): assert git git.clone_from('https://github.com/rbenv/rbenv.git', rbenv) if not path.exists(plugins): mkdir(plugins) if not path.exists: assert git git.clone_from('https://github.com/rbenv/ruby-build.git', ruby_build) # logger.debug('Installing ruby version {}'.format(version)) assert subprocess.Popen([rbenv_bin, 'install', version, '-f' if force else '-s']).wait() == 0 logger.debug('Setting ruby version {} as global'.format(version)) assert subprocess.Popen([rbenv_bin, 'global', version]).wait() == 0 logger.debug('installing bundle')
def parse(self, response, **kwargs): # inspect_response(response, self) links = response.xpath('/html/body/div/main/div/div/div/div/div[@class="org-repos repo-list"]/ul/li/div/div/h3[@class="wb-break-all"]/a[@data-hovercard-type="repository"]/@href').getall() for link in links: l = urljoin(self.start_urls[0], link) dir = Path.joinpath(self.output_dir, l.split('/')[-1]) os.makedirs(dir, exist_ok=True) Repo.clone_from(l, dir, branch='master')
def clone_git(self, github_repo, branch): tmpRoot = self.root + '/' + github_repo + '/' + branch git_url = self.github_base + github_repo + ".git" if not os.path.isdir(tmpRoot): os.makedirs(os.path.dirname(tmpRoot), exist_ok=True) branch_opt = '--branch ' + branch Repo.clone_from(git_url, tmpRoot, multi_options=[branch_opt])
def clone_repo(owner, repo, path_to_clone): try: if (not os.path.exists(path_to_clone)): git_url = "https://github.com/" + owner + "/" + repo Repo.clone_from(url=git_url, to_path=path_to_clone) else: print("Jumped repo because its folder already exists: " + repo['id']) except: print("Error for: Owner -- {0} Repo -- {1}".format(owner, repo)) print(sys.exc_info()[0])
def include_git(self, github_repo, file_path, branch, local_path): tmpRoot = self.root + '/' + github_repo + '/' + branch git_url = self.github_base + github_repo + ".git" if not os.path.isdir(tmpRoot): os.makedirs(os.path.dirname(tmpRoot), exist_ok=True) branch_opt = '--branch ' + branch Repo.clone_from(git_url, tmpRoot, multi_options=[branch_opt,'--depth 1']) self.include_file(tmpRoot + "/" + file_path, local_path)
def file_download(): Repo.clone_from("https://github.com/sakshamsahu007/DevOps.git", '../Test') file = pathlib.Path('../Test/requirements.txt') if file.exists(): print('File exists and installing...') pip.main( ['install', '-t', '../Test', '-r', '../Test/requirements.txt']) else: print("File does not exist.")
def index(): if((os.path.isdir(desktop))==False): #clones the repository if repository folder doesn't exist Repo.clone_from("https://github.com/Divyadarbe/Assignment1", desktop) #searches .md files recursively & appends them to md_files for file in glob.iglob(os.path.join(desktop,'**/*.md'),recursive=True): md_files.append(file) #displays all the href links return render_template('link.html', md_files = md_files) else: return render_template('link.html', md_files = md_files)
def git_update() -> NoReturn: uad_path = "/".join(cfg.debloater_list_path.split("/")[0:-1]) if not os.path.exists(uad_path): Repo.clone_from( "https://gitlab.com/W1nst0n/universal-android-debloater", uad_path) log_info(f"[GIT] cloned the repo 'universal android debloater'", logger="debuglog") else: repo = Repo(uad_path) repo.git.pull() log_info(f"[GIT] updated local repo of debloat-scripts", logger="debuglog")
def main(hub, forks, depth, org): for repo in hub.organization(org).iter_repos(): if repo.fork and not forks: continue dir_name = repo.name dir_name = dir_name.lstrip("-") # avoid dirname/option confusion if os.path.exists(dir_name): continue print(repo.full_name) clone_args = {} if depth: clone_args['depth'] = depth Repo.clone_from(repo.ssh_url, dir_name, **clone_args)
def main(hub, forks, depth, org): for repo in hub.organization(org).repositories(): if repo.fork and not forks: continue dir_name = repo.name dir_name = dir_name.lstrip("-") # avoid dirname/option confusion if os.path.exists(dir_name): continue print(repo.full_name) clone_args = {} if depth: clone_args['depth'] = depth Repo.clone_from(repo.ssh_url, dir_name, **clone_args)
def cloneRepoFromGithub(reponame): repopath = "https://github.com/andreaslbauer/" + reponame localrepopath = SERVICEBASE + '/' + reponame logging.debug("Clone repository %s to local path %s", repopath, localrepopath) try: Repo.clone_from(repopath, localrepopath) logging.info("Successfully cloned repository %s", repopath) except Exception as e: logging.exception("Exception occurred while trying to clone repo %s", reponame) logging.error("Unable to clone repository %s", reponame)
def clone_resource(content_to_index): content_type, user, repo, _, _, _ = content_to_index dest_folder = "./{}_{}_{}".format(user, repo, content_type) url = "" if content_type == 'wiki': url = GIT_WIKI_URL.format(user, repo) elif content_type == 'repo' or content_type == 'hugo': url = GIT_URL.format(user, repo) # clear the dest directory if it exists shutil.rmtree(dest_folder, ignore_errors=True) print('Cloning {} into folder {} ...'.format(url, dest_folder)) Repo.clone_from(url, dest_folder) print('Cloning successful!')
def checkGit(git): print(git) try: name = git.split("/")[-1].split(".")[0] repo = Repo.clone_from(git, name) check = check_if_localised(repo.working_dir) shutil.rmtree(repo.working_dir) except : return False return check
def __set_path(config: Config, attr: str): while True: if not hasattr(config, attr) or not getattr(config, attr): path = config.temp_root_path if not hasattr(config, "two_factor_authentication"): config.two_factor_authentication = prompt_yesno_question( "Are you using two-factor authentication on GitHub?") if config.two_factor_authentication: repository_url = "[email protected]:" + config.github_repo + ".git" else: repository_url = "https://github.com/" + config.github_repo + ".git" log_info("Cloning temporary repository from " + repository_url + " to " + str(path) + " for processing the release...") Repo.clone_from(repository_url, path, multi_options=["--config core.longpaths=true"]) else: path = getattr(config, attr) # set by script param if not __check_path(path): setattr(config, attr, "") continue if (attr == "root_path") & (os.path.realpath(__file__).startswith( os.path.abspath(path))): log_error( "Please copy and run the create release script in another place outside of the repository and execute again." ) sys.exit() try: Git(path) except InvalidGitRepositoryError: log_error("Path " + path + " is not a git repository.") setattr(config, attr, path) info = { "root_path": "Executing release in path '", } log_info(info[attr] + str(getattr(config, attr)) + "'") break
def setup_bkrepo(repo_url, repo_path): try: repo = Repo(repo_path) except NoSuchPathError: logging.info('git clone: {}'.format(repo_url)) repo = Repo.clone_from(repo_url, repo_path) else: logging.info('git pull: {}'.format(repo_url)) repo.remote().pull() return repo
def clone(self): logger.info('start to download repo from %s . ' % self.configs.repo_url) try: self.repo = Repo.clone_from(self.configs.repo_url, self.configs.repo_basedir, multi_options=['--depth 1'], progress=LogGitProgress()) except GitCommandError as e: logger.error(format_exc()) raise SvnDownloadException() logger.info('finish to download repo. ')
def setup_avlos() -> int: """ Installs the remote repository with dotfiles and copies them over to home directory """ ### install github repository ### home_directory = str(Path.home()) installation_directory = home_directory + '/.dotfiles' logger.info("Cloning git repository {} to {}".format( GITHUB_DOTFILES_REPOSITORY, installation_directory)) # check if folder exists, remove # if os.path.isdir(installation_directory): shutil.rmtree(installation_directory) Repo.clone_from(GITHUB_DOTFILES_REPOSITORY, installation_directory) ### copy dotfiles to home directory ### dotfiles = os.listdir(installation_directory) dotfiles = [ d for d in dotfiles if d.startswith('.') and d not in ['.git', '.gitignore'] ] # check for existing dotfiles # existing_dotfiles = list(set(os.listdir(home_directory)) & set(dotfiles)) if len(existing_dotfiles) > 0: logger.warning("The configuration files {} already exist.".format( ", ".join(existing_dotfiles))) answer = input("Overwrite? (Y/N): ") if not answer.lower().startswith('y'): dotfiles = list(set(dotfiles) - set(existing_dotfiles)) # copy to home directory for dotfile in dotfiles: shutil.copyfile(installation_directory + '/' + dotfile, home_directory + '/' + dotfile) logger.info("Pre-commit configuration installed.") return 0
def code_download(repo, workspace): print(repo) #os.chmod(code_directory, 0o777) for root, dirs, files in os.walk(code_directory): for d in dirs: os.chmod(os.path.join(root, d), 0o777) for f in files: os.chmod(os.path.join(root, f), 0o777) if (os.path.isdir(code_directory)): shutil.rmtree(code_directory) Repo.clone_from(repo, code_directory) #ToDo fetch and checkout based on Environment Varaiable for root, dirs, files in os.walk(code_directory + "/.git"): for d in dirs: os.chmod(os.path.join(root, d), 0o777) for f in files: os.chmod(os.path.join(root, f), 0o777) shutil.rmtree(code_directory + "/.git")
def clone(self) -> None: """Clones repo to cloning_path. If you break off the operation with a `KeyBoardInterrupt` before the cloning is completed, this method will delete whatever was partially downloaded from your system.""" self.cloning_path.mkdir(parents=True, exist_ok=False) try: logger.info(f"Cloning repo {GIT_REPO_URL} to {self.cloning_path}") self.repo = Repo.clone_from(GIT_REPO_URL, self.cloning_path, branch="main") except KeyboardInterrupt: self.delete() logger.error("Cancelled download of repository.. Rolled back.")
def download_git_repo(url: str, depth: int = 1) -> Path: """Download git repository to a temporary dir.""" stdout = sys.stdout appdir = user_cache_dir('pylex', 'Aleksei Panfilov') # clear temp dir from previous run try: if Path(appdir).exists(): shutil.rmtree(appdir, onerror=remove_readonly) os.makedirs(appdir) except PermissionError: raise PermissionError( 'Please, provide access to cache directory at {0}'.format(appdir)) with contextlib.suppress(FileNotFoundError): try: Repo.clone_from(url=url, to_path=appdir, depth=depth, progress=Progress(stdout=stdout)) except GitCommandError: logging.error('Couldn\'t download git repository {0}.'.format(url)) shutil.rmtree(appdir, onerror=remove_readonly) return Path(appdir)
def resolve(self, source): if not self.package_linker.package_folder: raise ValueError( '"package_folder" is required but not specified, see -w parameter.' ) repo_uri = source[len(self.scheme):] repo_uri, branch_or_tag, sub_path = _normalize_uri(repo_uri) # branch = branch_or_tag # tag = None # if branch_or_tag and ':' in branch_or_tag: # idx = branch_or_tag.index(':') # tag = branch_or_tag[idx + 1:] # branch = branch_or_tag[:idx] repo_id = repo_uri if branch_or_tag: repo_id = '%s.%s' % (repo_uri, branch_or_tag) repo_id = repo_id.replace('.', '_').replace(':', '_').replace('/', '_') repo_path = os.path.join(self.package_linker.package_folder, repo_id) utils.mkdir_p(self.package_linker.package_folder) # Check if the repo already exists repo = None if os.path.isdir(repo_path): try: repo = Repo(repo_path) if not hasattr( repo.remotes, 'origin') or not repo_uri == repo.remotes.origin.url: raise RuntimeError('Invalid existing repository %s' % repo_path) else: repo.remotes.origin.pull() except: utils.rmdir(repo_path) repo = None # the repository does not exist. if not repo: repo = Repo.clone_from(repo_uri, repo_path) self._swith_branch_or_tag(repo, branch_or_tag) return os.path.join(repo_path, sub_path)
def git_clone(repo_url, ref): # repo_url - URL of git repo to clone # ref - branch, commit or reference in the repo to clone if repo_url == '': print("No repo URL") try: # Entering remote git URL and folder to save repo = Repo.clone_from(repo_url, repodir) # Getting selected branch files repo.remotes.origin.fetch(ref) # Working dir of Git g = Git(repo.working_dir) # Getting latest fetch g.checkout('FETCH_HEAD') except Exception: print("Git clone failed.")
def run(self): config_file = "development.ini" if "BIOSHADOCK_CONFIG" in os.environ: config_file = os.environ["BIOSHADOCK_CONFIG"] config = ConfigParser.ConfigParser() config.readfp(open(config_file)) logging.config.fileConfig(config_file) while True: logging.info("New build run") if BioshadockDaemon.db_mongo is None: mongo = MongoClient(config.get('app:main','mongo_url')) BioshadockDaemon.db_mongo = mongo['mydockerhub'] if BioshadockDaemon.db_redis is None: BioshadockDaemon.db_redis = redis.StrictRedis(host=config.get('app:main','redis_host'), port=int(config.get('app:main','redis_port')), db=0) if BioshadockDaemon.cli is None: if config.get('app:main', 'docker_connect'): BioshadockDaemon.cli = Client(base_url=config.get('app:main', 'docker_connect')) else: BioshadockDaemon.cli = Client() BioshadockDaemon.cli.login(username=config.get('app:main','push_auth_user'), password=config.get('app:main','push_auth_password'), email=config.get('app:main','push_auth_email'),registry=config.get('app:main','service')) build = BioshadockDaemon.db_redis.lpop('bioshadock:builds') dockerfile = None if build is not None: dt = datetime.datetime.now() timestamp = time.mktime(dt.timetuple()) build = loads(build) logging.debug(str(build)) dockerfile = build['dockerfile'] gitrepo = build['git'] do_git = False git_repo_dir = None if gitrepo is not None and gitrepo and gitrepo != 'none': # TODO clone repo in a dir, chdir to repo and optionally write # dockerfile git_repo_dir = tempfile.mkdtemp(suffix='.git') git_info = gitrepo.split('#') gitrepo = git_info[0] selectedbranch = 'master' subdir = None if len(git_info) > 1: branch_path = git_info[1].split(':') if branch_path[0]: selectedbranch = branch_path[0] if len(branch_path) > 1 and branch_path[1]: subdir = branch_path[1] logging.info(str(gitrepo)) logging.info("Using branch "+selectedbranch) logging.info("Directory: "+str(subdir)) try: Repo.clone_from(gitrepo, git_repo_dir, branch=selectedbranch) if subdir is not None: git_repo_dir = os.path.join(git_repo_dir, subdir) logging.debug(str(git_repo_dir)) os.chdir(git_repo_dir) except Exception as e: logging.error(str(e)) continue #if dockerfile: if not os.path.exists("Dockerfile"): logging.debug("Overwrite Dockerfile") f = open('Dockerfile', 'w') f.write(dockerfile.encode('utf-8')) f.close() else: logging.debug("Use git Dockerfile") with open ("Dockerfile", "r") as gitDockerfile: dockerfile=gitDockerfile.read().encode('utf-8') f = BytesIO(dockerfile.encode('utf-8')) build_tag = '' if 'tag' in build and build['tag']: build_tag = ':'+build['tag'] logging.info('Build: '+str(build['id'])) response = [line for line in BioshadockDaemon.cli.build( fileobj=f, rm=True, tag=config.get('app:main', 'service')+"/"+build['id']+build_tag)] build['response'] = response if build['response']: last = build['response'][len(build['response'])-1] matches = re.search('Successfully built\s+(\w+)', last) if matches is None: build['status'] = False else: build['status'] = True build['image_id'] = matches.group(1) p= subprocess.Popen(["docker", "push", config.get('app:main', 'service')+"/"+build['id']]) else: build['status'] = False build['timestamp'] = timestamp BioshadockDaemon.db_mongo['repository'].update({'id': build['id']}, {'$push': {'builds': build}, '$set':{'meta.Dockerfile': dockerfile}}) if do_git: cur_dir = os.path.dirname(os.path.realpath(__file__)) os.chdir(cur_dir) shutil.rmtree(git_repo_dir) time.sleep(2)
def clone(self , url): self.repo = Repo.clone_from( url , self.work_dir )
def make_client( origin ): name = os.path.basename( origin.working_tree_dir ) client_path = os.path.join( tempfile.mkdtemp() , name ) origin_url = "file://%s" % origin.working_tree_dir return Repo.clone_from( origin_url , client_path )
def clone(uri, path): return Repo.clone_from(uri, path, progress=ProgressPrinter())
def git_repo(self, request, github_repo, branch=None, remote='origin', checkout_root=None): """ py.test fixture to clone a GitHub based repo onto the local disk. Arguments: github_repo (:class:`~github3.GitHub`): The repo to read from branch (str): The branch to check out Returns: A :class:`~git.repo.base.Repo` object, with the master branch checked out and up to date with the remote. """ if checkout_root is None: checkout_root = request.config.option.checkout_root if not os.path.exists(checkout_root): os.makedirs(checkout_root) repo_dir = os.path.join( os.path.join(checkout_root, github_repo.owner.name), github_repo.name ) if github_repo.private: repo_url = github_repo.ssh_url else: repo_url = github_repo.clone_url if not os.path.exists(repo_dir): repo = Repo.clone_from(repo_url, repo_dir) else: repo = Repo(repo_dir) if github_repo not in SYNCED: try: remote_obj = repo.remote(remote) except ValueError: repo.create_remote(remote, repo_url) remote_obj = repo.remote(remote) if remote_obj.fetch != repo_url: remote_obj.set_url(repo_url) remote_obj.fetch() SYNCED.add(github_repo) if branch is None: branch = github_repo.default_branch head = repo.head remote_branch = RemoteReference(repo, 'refs/remotes/{}/{}'.format(remote, branch)) local_branch = Head(repo, 'refs/heads/{}'.format(branch)) try: if head.commit != remote_branch.commit: local_branch.commit = remote_branch.commit local_branch.checkout() except ValueError: pytest.xfail("Branch {} is empty".format(branch)) return repo
backup_file_path = os.path.join(app_folder, repo_name + "-" + args.revert + ".zip") get(sftp, backup_file_path, os.path.join(PATH, backup_file_name)) fh = open(os.path.join(PATH, backup_file_name), "rb") z = zipfile.ZipFile(fh) for name in z.namelist(): outpath = os.path.join(PATH, repo_name) z.extract(name, outpath) fh.close() rm(sftp, os.path.join(app_folder, repo_name)) put_all(sftp, os.path.join(PATH, repo_name), app_folder) exit(0) try: Repo.clone_from(git_repo, os.path.join(PATH, repo_name)) except Exception, e: print "git error" print e sys.exit(2) if not remote_file_exists(sftp, app_folder + repo_name): # sftp.mkdir(app_folder+repo_name) put_all(sftp, os.path.join(PATH, repo_name), app_folder) shutil.rmtree(os.path.join(PATH, repo_name)) else: os.mkdir(os.path.join(PATH, "tmp")) get_all(sftp, app_folder + repo_name, os.path.join(PATH, "tmp")) zip_name = repo_name + "-" + time.strftime("%d-%m-%Y-%I:%M:%S") + ".zip"
from git.repo.base import Repo import sys, os url = sys.argv[1] path = "repos/{0}".format(url.split("/", 3)[-1]) if __name__ == '__main__': if not os.path.isdir(path): repo = Repo.clone_from(url, path)