#!/usr/bin/python #-*- coding:utf-8 -*- import os import argparse from git.repo import Repo def clone(repo_url, token, abs_local_repo): repo_full_url = 'http://oauth2:%s@%s' % (token, repo_url) Repo.clone_from(repo_full_url, to_path=abs_local_repo, branc='master') def return_newest_tag(repo): all_tags = repo.tags return all_tags[-1].name def change_to_tag(repo, tag): repo.git.checkout(tag) def get_latest_commit(repo): # commit_log = repo.git.log('--pretty={"commit":"%h","author":"%an","summary":"%s","date":"%cd"}', max_count=50, date='format:%Y-%m-%d %H:%M') commit_log = repo.git.log('--pretty={"commit":"%h","author":"%an","summary":"%s","date":"%cd"}', max_count=50) log_list = commit_log.split(' ') return log_list[0] def main(): description = '从GitLab检出代码,并切换到最新的tag ' quick_usage = ''' python checkout_from_gitlab.py -local_repo local_dir -outdir local_repo_exists_dir ''' newParser = argparse.ArgumentParser(description=description, usage=quick_usage) newParser.add_argument('-repo_url', dest='repo_url', help='repo url') newParser.add_argument('-token', dest='token', help='gitlab access_tokens', default='_NuYiHQz-XuUXyj1exxx') newParser.add_argument('-local_repo', dest='local_repo', help='local repo dir name', default='local_dir') newParser.add_argument('-outdir', dest='outdir', help='default is current workdir', default=os.getcwd()) args = newParser.parse_args() argsDict = args.__dict__ repo_url = argsDict['repo_url'] token = argsDict['token'] local_repo = argsDict['local_repo'] outdir = argsDict['outdir'] abs_local_repo = os.path.join(outdir, local_repo) if os.path.exists(abs_local_repo): os.system('rm -rf %s' % abs_local_repo) clone(repo_url, token, abs_local_repo) repo = Repo(abs_local_repo) newest_tag = return_newest_tag(repo) print newest_tag change_to_tag(repo, newest_tag) latest_commit = get_latest_commit(repo)
如果是gitlab,可以通过如下方式生成token :