python-3.xpython-gitlab

Python Git and Git-Lab create project and push code/commit


We are building an automation process using python in which we clone a base source code repository and add necessary changes to it and add the new code to a new git repository and push it to our private gitlab server.

So far I'm using git library to clone, and initial a new repository and make an initial commit. however I'm not able to figure out "how to create and push the new repository to our private gitlab server.

import gitlab
import git
import json
import shutil
"""GitLab API"""
gl = gitlab.Gitlab('gitlab url of company', private_token='the token', api_version=4)
gl.auth()

"""Cloning the Base Code"""
git.Repo.clone_from("url","path to save")


"""Getting data"""
data_json = getData()

""" Copy Base Code to New Folder with Doctor Name"""
repo_name = "new_repo"

shutil.copytree("./base_code/public", "{}/public".format(repo_name))
shutil.copytree("./base_code/src", "{}/src".format(repo_name),dirs_exist_ok=True)
shutil.copy("./base_code/.gitignore", "{}/".format(repo_name))
shutil.copy("./base_code/package-lock.json", "{}/".format(repo_name))
shutil.copy("./base_code/package.json", "{}/".format(repo_name))
shutil.copy("./base_code/README.md", "{}/".format(repo_name))

"""Generate JSON File and save it new folder"""

with open("./{}/src/data.json".format(repo_name), 'w') as fout:
    json_dumps_str = json.dumps(data_json, indent=4)
    print(json_dumps_str, file=fout)

"""Create new git repo in the new folder"""
new_repo = git.Repo.init('{}'.format(repo_name))

"""Adding all the files to Staged Scenario"""    
new_repo.index.add(['.'])

"""Commit the changes"""
new_repo.index.commit('Initial commit.')

"""Create Project of the new Repository"""

How to create project and push the code to the new project?


Solution

  • This is how I created a new project in gitlab in python using python-gitlab libary.

    gl = gitlab.Gitlab('gitlab website url', private_token='token', api_version=4)
    gl.auth()
    gl.projects.list()
    
    """Create Project of the new Repository"""
    response = gl.projects.create({"name":"project name","namespace_id":"group-id if required"})
    

    The documentation of python-gitlab doesnt have any direct sample code for this use-case.