1#!/usr/bin/env python 2# 3# internal use only for CI 4# get latest MR information by source branch 5# 6# Copyright 2020 Espressif Systems (Shanghai) PTE LTD 7# 8# Licensed under the Apache License, Version 2.0 (the "License"); 9# you may not use this file except in compliance with the License. 10# You may obtain a copy of the License at 11# 12# http://www.apache.org/licenses/LICENSE-2.0 13# 14# Unless required by applicable law or agreed to in writing, software 15# distributed under the License is distributed on an "AS IS" BASIS, 16# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17# See the License for the specific language governing permissions and 18# limitations under the License. 19# 20 21import argparse 22import os 23import subprocess 24 25from gitlab_api import Gitlab 26 27try: 28 from typing import Any, Union 29except ImportError: 30 # Only used for type annotations 31 pass 32 33 34def _get_mr_obj(source_branch): # type: (str) -> Union[Gitlab, None] 35 if not source_branch: 36 return None 37 gl = Gitlab(os.getenv('CI_PROJECT_ID', 'espressif/esp-idf')) 38 if not gl.project: 39 return None 40 mrs = gl.project.mergerequests.list(state='opened', source_branch=source_branch) 41 if mrs: 42 return mrs[0] # one source branch can only have one opened MR at one moment 43 else: 44 return None 45 46 47def get_mr_iid(source_branch): # type: (str) -> str 48 mr = _get_mr_obj(source_branch) 49 if not mr: 50 return '' 51 else: 52 return str(mr.iid) 53 54 55def get_mr_changed_files(source_branch): # type: (str) -> Any 56 mr = _get_mr_obj(source_branch) 57 if not mr: 58 return '' 59 60 return subprocess.check_output(['git', 'diff', '--name-only', 61 'origin/{}...origin/{}'.format(mr.target_branch, source_branch)]).decode('utf8') 62 63 64def get_mr_commits(source_branch): # type: (str) -> str 65 mr = _get_mr_obj(source_branch) 66 if not mr: 67 return '' 68 return '\n'.join([commit.id for commit in mr.commits()]) 69 70 71if __name__ == '__main__': 72 parser = argparse.ArgumentParser(description='Get the latest merge request info by pipeline') 73 actions = parser.add_subparsers(dest='action', help='info type') 74 75 common_args = argparse.ArgumentParser(add_help=False) 76 common_args.add_argument('src_branch', nargs='?', help='source branch') 77 78 actions.add_parser('id', parents=[common_args]) 79 actions.add_parser('files', parents=[common_args]) 80 actions.add_parser('commits', parents=[common_args]) 81 82 args = parser.parse_args() 83 84 if args.action == 'id': 85 print(get_mr_iid(args.src_branch)) 86 elif args.action == 'files': 87 print(get_mr_changed_files(args.src_branch)) 88 elif args.action == 'commits': 89 print(get_mr_commits(args.src_branch)) 90 else: 91 raise NotImplementedError('not possible to get here') 92