ci_get_mr_info.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  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-2023 Espressif Systems (Shanghai) CO LTD
  7. # SPDX-License-Identifier: Apache-2.0
  8. #
  9. import argparse
  10. import os
  11. import subprocess
  12. import typing as t
  13. from pathlib import Path
  14. from gitlab_api import Gitlab
  15. if t.TYPE_CHECKING:
  16. from gitlab.v4.objects import ProjectCommit, ProjectMergeRequest
  17. def _get_mr_obj(source_branch: str) -> t.Optional['ProjectMergeRequest']:
  18. gl = Gitlab(os.getenv('CI_PROJECT_ID', 'espressif/esp-idf'))
  19. if not gl.project:
  20. return None
  21. mrs = gl.project.mergerequests.list(state='opened', source_branch=source_branch)
  22. if mrs:
  23. return mrs[0] # one source branch can only have one opened MR at one moment
  24. else:
  25. return None
  26. def get_mr_iid(source_branch: str) -> str:
  27. mr = _get_mr_obj(source_branch)
  28. if not mr:
  29. return ''
  30. else:
  31. return str(mr.iid)
  32. def get_mr_changed_files(source_branch: str) -> t.List[str]:
  33. mr = _get_mr_obj(source_branch)
  34. if not mr:
  35. return []
  36. git_output = subprocess.check_output(
  37. ['git', 'diff', '--name-only', '--diff-filter=d', f'origin/{mr.target_branch}...origin/{source_branch}']
  38. ).decode('utf8')
  39. return [line.strip() for line in git_output.splitlines() if line.strip()]
  40. def get_mr_commits(source_branch: str) -> t.List['ProjectCommit']:
  41. mr = _get_mr_obj(source_branch)
  42. if not mr:
  43. return []
  44. return list(mr.commits())
  45. def get_mr_components(
  46. source_branch: t.Optional[str] = None, modified_files: t.Optional[t.List[str]] = None
  47. ) -> t.List[str]:
  48. components: t.Set[str] = set()
  49. if modified_files is None:
  50. if not source_branch:
  51. raise RuntimeError('--src-branch is required if --modified-files is not provided')
  52. modified_files = get_mr_changed_files(source_branch)
  53. for f in modified_files:
  54. file = Path(f)
  55. if (
  56. file.parts[0] == 'components'
  57. and 'test_apps' not in file.parts
  58. and file.parts[-1] != '.build-test-rules.yml'
  59. ):
  60. components.add(file.parts[1])
  61. return list(components)
  62. def get_target_in_tags(tags: str) -> str:
  63. from idf_pytest.constants import TARGET_MARKERS
  64. for x in tags.split(','):
  65. if x in TARGET_MARKERS:
  66. return x
  67. raise RuntimeError(f'No target marker found in {tags}')
  68. def _print_list(_list: t.List[str], separator: str = '\n') -> None:
  69. print(separator.join(_list))
  70. if __name__ == '__main__':
  71. parser = argparse.ArgumentParser(description='Get the latest merge request info by pipeline')
  72. actions = parser.add_subparsers(dest='action', help='info type', required=True)
  73. common_args = argparse.ArgumentParser(add_help=False)
  74. common_args.add_argument('--src-branch', help='source branch')
  75. common_args.add_argument(
  76. '--modified-files',
  77. nargs='+',
  78. help='space-separated list specifies the modified files. will be detected by --src-branch if not provided',
  79. )
  80. actions.add_parser('id', parents=[common_args])
  81. actions.add_parser('commits', parents=[common_args])
  82. actions.add_parser('components', parents=[common_args])
  83. target = actions.add_parser('target_in_tags')
  84. target.add_argument('tags', help='comma separated tags, e.g., esp32,generic')
  85. args = parser.parse_args()
  86. if args.action == 'id':
  87. if not args.src_branch:
  88. raise RuntimeError('--src-branch is required')
  89. print(get_mr_iid(args.src_branch))
  90. elif args.action == 'commits':
  91. if not args.src_branch:
  92. raise RuntimeError('--src-branch is required')
  93. _print_list([commit.id for commit in get_mr_commits(args.src_branch)])
  94. elif args.action == 'components':
  95. _print_list(get_mr_components(args.src_branch, args.modified_files))
  96. elif args.action == 'target_in_tags':
  97. print(get_target_in_tags(args.tags))
  98. else:
  99. raise NotImplementedError('not possible to get here')