rupeshj
rupeshj

Reputation: 139

Gitlab api to get commits in a merge request

From the GITLAB API documentation, I can get the merge request details, from which I can get the source project and the branch.

The api to get the list of commits in the branch, list all the commits in that branch.

Is there a way to get the list of commits specific to a merge request through API.?

The objective is to know only the new commits in the merge request.

Thank You.

Upvotes: 11

Views: 6138

Answers (2)

Alex Punnen
Alex Punnen

Reputation: 6254

You can use the gitlab python library

gl = gitlab.Gitlab('https://xxx.xxx.com', private_token='xxx',api_version=4,ssl_verify=True)
gl.auth()
project = gl.projects.get(1233,lazy=True)

plus ,something like below

def isValidfile(filepath):
  _, extension = os.path.splitext(filepath)
  if extension in ['.java','.go']: # lets do .ts later
    #print(filepath)
    return True
  return False
  
def get_commit_diff(project, commit_hash):
    commit = project.commits.get(commit_hash)
    diffs =[]
    for val in commit.diff(get_all=True):
      if isValidfile(val['new_path']):
         diffs.append(val)
         #print(val)
      #print(diffs)
    return diffs   

def getAllDiffs(project,mr_iid):
    mr = project.mergerequests.get(mr_iid)
    diffs = mr.diffs.list()
    vals = []
    for diff in diffs:
      commit =diff.attributes['head_commit_sha'] 
      vals.append(get_commit_diff(project,commit))
    return vals

def get_all_merge_requests(project):
    all_mrs = []
    page = 1
    while True:
        mrs = project.mergerequests.list(state='merged', target_branch="master", page=page, per_page=10)
        if not mrs:
            break
        all_mrs += mrs
        page += 1
        for mr in all_mrs:
          print("-------------------------------------------")
          print(mr.iid)
          print(mr.sha)
          print(mr.description)
          print(len(getAllDiffs(project,mr.iid)))
          print("-------------------------------------------")

        break
    return all_mrs 

More details https://python-gitlab.readthedocs.io/en/stable/gl_objects/merge_requests.html

Upvotes: 0

Frol
Frol

Reputation: 136

I think you are looking for this:

curl --header "PRIVATE-TOKEN: ****" "http://gitlab/api/v3/projects/:project_id:/merge_requests/:mr_id:/commits"

https://docs.gitlab.com/ce/api/merge_requests.html#get-single-mr-commits

Upvotes: 9

Related Questions