ci_get_mr_info.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #!/usr/bin/env python
  2. #
  3. # internal use only for CI
  4. # get latest MR information by source branch
  5. #
  6. # SPDX-FileCopyrightText: 2020-2022 Espressif Systems (Shanghai) CO LTD
  7. # SPDX-License-Identifier: Apache-2.0
  8. #
  9. import argparse
  10. import os
  11. import subprocess
  12. from gitlab_api import Gitlab
  13. try:
  14. from typing import Any, Union
  15. except ImportError:
  16. # Only used for type annotations
  17. pass
  18. def _get_mr_obj(source_branch): # type: (str) -> Union[Gitlab, None]
  19. if not source_branch:
  20. return None
  21. gl = Gitlab(os.getenv('CI_PROJECT_ID', 'espressif/esp-idf'))
  22. if not gl.project:
  23. return None
  24. mrs = gl.project.mergerequests.list(state='opened', source_branch=source_branch)
  25. if mrs:
  26. return mrs[0] # one source branch can only have one opened MR at one moment
  27. else:
  28. return None
  29. def get_mr_iid(source_branch): # type: (str) -> str
  30. mr = _get_mr_obj(source_branch)
  31. if not mr:
  32. return ''
  33. else:
  34. return str(mr.iid)
  35. def get_mr_changed_files(source_branch): # type: (str) -> Any
  36. mr = _get_mr_obj(source_branch)
  37. if not mr:
  38. return ''
  39. return subprocess.check_output(['git', 'diff', '--name-only',
  40. 'origin/{}...origin/{}'.format(mr.target_branch, source_branch)]).decode('utf8')
  41. def get_mr_commits(source_branch): # type: (str) -> str
  42. mr = _get_mr_obj(source_branch)
  43. if not mr:
  44. return ''
  45. return '\n'.join([commit.id for commit in mr.commits()])
  46. if __name__ == '__main__':
  47. parser = argparse.ArgumentParser(description='Get the latest merge request info by pipeline')
  48. actions = parser.add_subparsers(dest='action', help='info type')
  49. common_args = argparse.ArgumentParser(add_help=False)
  50. common_args.add_argument('src_branch', nargs='?', help='source branch')
  51. actions.add_parser('id', parents=[common_args])
  52. actions.add_parser('files', parents=[common_args])
  53. actions.add_parser('commits', parents=[common_args])
  54. args = parser.parse_args()
  55. if args.action == 'id':
  56. print(get_mr_iid(args.src_branch))
  57. elif args.action == 'files':
  58. print(get_mr_changed_files(args.src_branch))
  59. elif args.action == 'commits':
  60. print(get_mr_commits(args.src_branch))
  61. else:
  62. raise NotImplementedError('not possible to get here')