forked from ci4s/pipeline-convert
94 lines
3.2 KiB
Python
94 lines
3.2 KiB
Python
import subprocess
|
|
import argparse
|
|
import os
|
|
import sys
|
|
import tempfile
|
|
|
|
def clone_repo(ssh_key_content, username, password, repo_url, branch, depth, output_dir):
|
|
# 确保输出目录存在
|
|
if not os.path.exists(output_dir):
|
|
os.makedirs(output_dir)
|
|
|
|
# 如果提供了 SSH 私钥内容,使用 SSH 方式克隆代码
|
|
if ssh_key_content:
|
|
print("Using SSH private key for cloning.")
|
|
with tempfile.NamedTemporaryFile(delete=False) as tmpfile:
|
|
ssh_key_path = tmpfile.name
|
|
tmpfile.write(ssh_key_content.encode())
|
|
print("SSH key path is:", ssh_key_path)
|
|
os.chmod(ssh_key_path, 0o600)
|
|
|
|
# 设置 SSH 私钥的环境变量
|
|
os.environ['GIT_SSH_COMMAND'] = f'ssh -i {ssh_key_path} -o StrictHostKeyChecking=no'
|
|
|
|
clone_cmd = [
|
|
'git', 'clone', '-b', branch,
|
|
'--depth', str(depth), repo_url, output_dir
|
|
]
|
|
|
|
# 如果提供了用户名和密码,使用 HTTP/HTTPS 方式克隆代码
|
|
elif username and password:
|
|
print("Using username and password for cloning.")
|
|
# 构造带有用户名和密码的 URL
|
|
protocol, url_without_protocol = repo_url.split("://")
|
|
auth_url = f"{protocol}://{username}:{password}@{url_without_protocol}"
|
|
|
|
clone_cmd = [
|
|
'git', 'clone', '-b', branch,
|
|
'--depth', str(depth), auth_url, output_dir
|
|
]
|
|
|
|
# 如果既没有 SSH 私钥也没有用户名和密码,使用常规方式克隆公共仓库
|
|
else:
|
|
print("Cloning public repository without authentication.")
|
|
clone_cmd = [
|
|
'git', 'clone', '-b', branch,
|
|
'--depth', str(depth), repo_url, output_dir
|
|
]
|
|
|
|
# 执行 git clone 命令
|
|
try:
|
|
subprocess.run(clone_cmd, check=True)
|
|
except subprocess.CalledProcessError as e:
|
|
print(f'Error cloning repository: {e}')
|
|
return False
|
|
finally:
|
|
if ssh_key_content:
|
|
# 清理临时 SSH 私钥文件
|
|
os.remove(ssh_key_path)
|
|
|
|
return True
|
|
def main():
|
|
# 解析命令行参数
|
|
parser = argparse.ArgumentParser(description='Clone a Git repository.')
|
|
parser.add_argument('--ssh_private_key', help='SSH private key content')
|
|
parser.add_argument('--code_path', required=True, help='Git repository URL')
|
|
parser.add_argument('--branch', default='master', help='Branch to clone')
|
|
parser.add_argument('--depth', type=int, default=1, help='Depth for shallow clone')
|
|
parser.add_argument('--username', type=str, default="", help='username for git clone')
|
|
parser.add_argument('--password', type=str, default="", help='password for git clone')
|
|
parser.add_argument('--code_output', required=True, help='Directory to clone the repository into')
|
|
|
|
args = parser.parse_args()
|
|
|
|
# 执行克隆操作
|
|
success = clone_repo(
|
|
args.ssh_private_key,
|
|
args.username,
|
|
args.password,
|
|
args.code_path,
|
|
args.branch,
|
|
args.depth,
|
|
args.code_output
|
|
)
|
|
|
|
if success:
|
|
print('Repository cloned successfully.')
|
|
sys.exit(0)
|
|
else:
|
|
print('Failed to clone repository.')
|
|
sys.exit(1)
|
|
|
|
if __name__ == '__main__':
|
|
main()
|