programing tip

git 저장소를 복제하는 Python 방법

itbloger 2020. 11. 10. 07:55
반응형

git 저장소를 복제하는 Python 방법


하위 프로세스를 사용하지 않고 git 저장소를 복제하지 않는 Python 방법이 있습니까? 나는 당신이 추천하는 모든 종류의 모듈을 사용하고 있습니다.


GitPython은 . 이전과 내부적으로 들어 보지 못했지만 어딘가에 git 실행 파일을 가지고 있어야합니다. 또한 많은 버그가있을 수 있습니다. 그러나 시도해 볼 가치가 있습니다.

복제 방법 :

import git
git.Git("/your/directory/to/clone").clone("git://gitorious.org/git-python/mainline.git")

(좋지 않고 지원되는 방법인지 모르겠지만 작동했습니다.)


GitPython사용하면 Git에 대한 좋은 파이썬 인터페이스를 얻을 수 있습니다.

예를 들어 설치 후 ( pip install gitpython) 새 저장소를 복제하려면 clone_from 함수를 사용할 수 있습니다 .

from git import Repo

Repo.clone_from(git_url, repo_dir)

Repo 객체 사용에 대한 예제 GitPython 자습서참조하십시오 .

참고 : GitPython은 시스템에 git이 설치되어 있어야하며 시스템의 PATH를 통해 액세스 할 수 있어야합니다.


내 솔루션은 매우 간단하고 간단합니다. 암호 / 암호를 수동으로 입력 할 필요조차 없습니다.

내 완전한 코드는 다음과 같습니다.

import sys
import os

path  = "/path/to/store/your/cloned/project" 
clone = "git clone gitolite@<server_ip>:/your/project/name.git" 

os.system("sshpass -p your_password ssh user_name@your_localhost")
os.chdir(path) # Specifying the path where the cloned project needs to be copied
os.system(clone) # Cloning

Github의 libgit2 바인딩 인 pygit2 는 원격 디렉토리를 한 줄로 복제하는 기능을 제공합니다.

clone_repository(url, path, 
    bare=False, repository=None, remote=None, checkout_branch=None, callbacks=None)

Python 3의 경우

첫 번째 설치 모듈 :

pip install gitpython

나중에 코딩하십시오 :)

import os
from git.repo.base import Repo
Repo.clone_from("https://github.com/*****", "folderToSave")

도움이 되었기를 바랍니다.


GitPython 으로 리포지토리 를 복제하는 동안 진행 상황을 인쇄하는 방법은 다음과 같습니다.

import time
import git
from git import RemoteProgress

class CustomProgress(RemoteProgress):
    def update(self, op_code, cur_count, max_count=None, message=''):
        if message:
            print(message)

print('Cloning into %s' % git_root)
git.Repo.clone_from('https://github.com/your-repo', '/your/repo/dir', 
        branch='master', progress=CloneProgress())

덜 리치 팁을 사용하면 다음을 수행 할 수 있습니다.

from dulwich.repo import Repo
Repo("/path/to/source").clone("/path/to/target")

이것은 여전히 ​​매우 기본적입니다. 객체와 참조를 통해 복사하지만 베어가 아닌 저장소를 생성하는 경우 작업 트리의 내용을 아직 생성하지 않습니다.


gitpython 모듈을 사용하는 gitpull 및 gitpush의 샘플 코드입니다.

import os.path
from git import *
import git, os, shutil
# create local Repo/Folder
UPLOAD_FOLDER = "LocalPath/Folder"
if not os.path.exists(UPLOAD_FOLDER):
  os.makedirs(UPLOAD_FOLDER)
  print(UPLOAD_FOLDER)
new_path = os.path.join(UPLOADFOLDER)
DIR_NAME = new_path
REMOTE_URL = "GitURL"  # if you already connected with server you dont need to give 
any credential
# REMOTE_URL looks "git@github.com:path of Repo"
# code for clone
class git_operation_clone():
  try:
    def __init__(self):
        self.DIR_NAME = DIR_NAME
        self.REMOTE_URL = REMOTE_URL

    def git_clone(self):

        if os.path.isdir(DIR_NAME):
            shutil.rmtree(DIR_NAME)
        os.mkdir(DIR_NAME)
        repo = git.Repo.init(DIR_NAME)
        origin = repo.create_remote('origin', REMOTE_URL)
        origin.fetch()
        origin.pull(origin.refs[0].remote_head)
  except Exception as e:
      print(str(e))
# code for push
class git_operation_push():
  def git_push_file(self):
    try:
        repo = Repo(DIR_NAME)
        commit_message = 'work in progress'
        # repo.index.add(u=True)
        repo.git.add('--all')
        repo.index.commit(commit_message)
        origin = repo.remote('origin')
        origin.push('master')
        repo.git.add(update=True)
        print("repo push succesfully")
    except Exception as e:
        print(str(e))
if __name__ == '__main__':
   a = git_operation_push()
   git_operation_push.git_push_file('')
   git_operation_clone()
   git_operation_clone.git_clone('')

Pretty simple method is to just pass the creds in the url, can be slightly suspect though - use with caution.

import os

def getRepo(repo_url, login_object):
  '''
  Clones the passed repo to my staging dir
  '''

  path_append = r"stage\repo" # Can set this as an arg 
  os.chdir(path_append)

  repo_moddedURL = 'https://' + login_object['username'] + ':' + login_object['password'] + '@github.com/UserName/RepoName.git'
  os.system('git clone '+ repo_moddedURL)

  print('Cloned!')


if __name__ == '__main__':
    getRepo('https://github.com/UserName/RepoYouWant.git', {'username': 'userName', 'password': 'passWord'})

참고URL : https://stackoverflow.com/questions/2472552/python-way-to-clone-a-git-repository

반응형