Wednesday, March 11, 2020

Read and Updated the content of a file of a GitLab with GitLab API using Python

 Below is the script to Read and Updated the content of the files in GitLab with GitLab API using Python

You need to install the  "gitlab" Python package using pip before run the script.

#### install gitlab python package with root user
### pip install gitlab

import gitlab
import base64

gl = gitlab.Gitlab('https://xxxxxxxxxxxxxxxxxxxx/', private_token='xxxxxxxxxxxxxxxx')
gl.auth()

project = gl.projects.get(PROJECT_ID)  ####You can get the project PROJECT_ID from GITLab repo

f = project.files.get(file_path='pom.xml', ref='master')
file_content = f.decode().decode('utf-8')

print("====================BEFORE UPDATE================")
print(file_content)

old_line = '<groupId>com.test3</groupId>'
new_line = '<groupId>com.test4</groupId>'
new_file = file_content.replace(old_line, new_line)

print("====================AFTER UPDATE================")
print(new_file)

### COMMIT the changes to GIT
data = {
'branch': 'master',
'commit_message': 'TEST GITLABAPI',
'actions': [
{
'action': 'update',
'file_path': 'pom.xml',
'content': new_file,
}
]
}
commit = project.commits.create(data)

No comments:

Post a Comment