How to clone github repo branch from existing branch by python script

Viewed 94

My organization is migrating from GitLab to GitHub and we were using some existing Python scripts to check commit difference and to create multiple release branches in one go by cloning the previous release branch. I know how we do this for GitLab but not able to find some solution to the same in GitHub. If someone can please help me with how can I do the same in GitHub too it will be really helpful. We are using below code in gitlab for now

def createBranch(projectName, existingBranch, newBranchName):
    projectId=projMap[projectName]
    gl = gitlab.Gitlab('github URL', private_token='git token', ssl_verify=False)
    project = gl.projects.get(projectId)
     
    try:
        project.branches.get(newBranchName)
        log.info("    %s %s already exist", projectName, newBranchName)
        return 0
    except:   
        log.info("createBranch %s from:%s to:%s", project.name, existingBranch, newBranchName)       
        try:        
            project.branches.create({"branch": newBranchName,
                                 "ref": existingBranch})
        except:
            raise Exception(project.name, " error creating " + newBranchName + " from " + existingBranch) 

projMap -> this is one text file which stores all project name and their projectIDs.

I tried multiple threads in Stackoverflow but none one seems to help me.

1 Answers

PyGithub has the functionality you're looking for.

  • Connecting to the GitHub API
gh = Github(params)
  • Getting a repo:
repo = gh.get_repo(id)
  • Getting a branch:
branch = repo.get_branch(branch)
  • Making a branch:
repo.create_git_ref(ref='refs/heads/' + 'new_branch_name', sha=branch.commit.sha)

All a copy paste from the PyGithub reference page.

Related