python-gitlab拉取git项目(python3)

安装就不多说了,python-gitlab这个模块貌似只适用于gitlab9版本以上,我用8版本一直报404,升级到9版本就好了

脚本内容如下:

如果不出现什么意外的话,只要地址和token正确,应该没有问题

project.repository_tree(all=True,recursive=True,as_list=True)脚本中这条语句是递归列出项目目录和文件,

recursive这个参数默认是false不进行递归

由于百度上没找到此办法,所以找了一下python-gitlab模块文件,里面有明确标明

/usr/local/python/lib/python3.7/site-packages/gitlab/v4/objects.py这个文件

#!/usr/sbin/python3
import gitlab
import time
import os

git_url = 'http://192.168.12.84/'
git_token = 'XbEURKtB1m2AkgTyyH6K'
project_root = '/root/flow-web'

class get_gitlab:
   
   def __init__(self):
       self.url = git_url
       self.token = git_token
       self.root_path = project_root

   #登陆
   def login_gitlab(self):
       gl = gitlab.Gitlab(self.url,self.token)
       return gl

   #用项目id获取项目
   def get_project_id(self,id):
       gl = self.login_gitlab()
       project = gl.projects.get(id)
       return project

   #由于是递归方式下载的所以要先创建项目相应目录
   def create_dir(self,dir_name):
       if not os.path.isdir(dir_name):
          print("\033[0;32;40m开始创建目录: \033[0m{0}".format(dir_name))
          os.makedirs(dir_name)
          time.sleep(0.1)

   
   def start_get(self):
      project = self.get_project_id(6)
      info = project.repository_tree(all=True,recursive=True,as_list=True)
      file_list = []
      if not os.path.isdir(self.root_path):
          os.makedirs(self.root_path)
      os.chdir(self.root_path)
      #调用创建目录的函数并生成文件名列表
      for info_dir in range(len(info)):
         if info[info_dir]['type'] == 'tree':
            dir_name = info[info_dir]['path']
            self.create_dir(dir_name)
         else:
            file_name = info[info_dir]['path']
            file_list.append(file_name)
      for info_file in range(len(file_list)):
         #开始下载
         getf = project.files.get(file_path=file_list[info_file],ref='master')
         content = getf.decode()
         with open(file_list[info_file] , 'wb') as code:
            print("\033[0;32;40m开始下载文件: \033[0m{0}".format(file_list[info_file]))
            code.write(content)

st_init = get_gitlab()
st_init.start_get()

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值