ci_get_mr_info.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. import argparse
  21. import os
  22. import subprocess
  23. from gitlab_api import Gitlab
  24. def _get_mr_obj(source_branch):
  25. if not source_branch:
  26. return None
  27. gl = Gitlab(os.getenv('CI_PROJECT_ID', 'espressif/esp-idf'))
  28. if not gl.project:
  29. return None
  30. mrs = gl.project.mergerequests.list(state='opened', source_branch=source_branch)
  31. if mrs:
  32. return mrs[0] # one source branch can only have one opened MR at one moment
  33. else:
  34. return None
  35. def get_mr_iid(source_branch): # type: (str) -> str
  36. mr = _get_mr_obj(source_branch)
  37. if not mr:
  38. return ''
  39. else:
  40. return str(mr.iid)
  41. def get_mr_changed_files(source_branch):
  42. mr = _get_mr_obj(source_branch)
  43. if not mr:
  44. return ''
  45. return subprocess.check_output(['git', 'diff', '--name-only',
  46. 'origin/{}...origin/{}'.format(mr.target_branch, source_branch)]).decode('utf8')
  47. def get_mr_commits(source_branch):
  48. mr = _get_mr_obj(source_branch)
  49. if not mr:
  50. return ''
  51. return '\n'.join([commit.id for commit in mr.commits()])
  52. if __name__ == '__main__':
  53. parser = argparse.ArgumentParser(description='Get the latest merge request info by pipeline')
  54. actions = parser.add_subparsers(dest='action', help='info type')
  55. common_args = argparse.ArgumentParser(add_help=False)
  56. common_args.add_argument('src_branch', nargs='?', help='source branch')
  57. actions.add_parser('id', parents=[common_args])
  58. actions.add_parser('files', parents=[common_args])
  59. actions.add_parser('commits', parents=[common_args])
  60. args = parser.parse_args()
  61. if args.action == 'id':
  62. print(get_mr_iid(args.src_branch))
  63. elif args.action == 'files':
  64. print(get_mr_changed_files(args.src_branch))
  65. elif args.action == 'commits':
  66. print(get_mr_commits(args.src_branch))
  67. else:
  68. raise NotImplementedError('not possible to get here')