gitarchive.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. #
  2. # Helper functions for committing data to git and pushing upstream
  3. #
  4. # Copyright (c) 2017, Intel Corporation.
  5. # Copyright (c) 2019, Linux Foundation
  6. #
  7. # This program is free software; you can redistribute it and/or modify it
  8. # under the terms and conditions of the GNU General Public License,
  9. # version 2, as published by the Free Software Foundation.
  10. #
  11. # This program is distributed in the hope it will be useful, but WITHOUT
  12. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13. # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  14. # more details.
  15. #
  16. import os
  17. import re
  18. import sys
  19. from operator import attrgetter
  20. from collections import namedtuple
  21. from oeqa.utils.git import GitRepo, GitError
  22. class ArchiveError(Exception):
  23. """Internal error handling of this script"""
  24. def format_str(string, fields):
  25. """Format string using the given fields (dict)"""
  26. try:
  27. return string.format(**fields)
  28. except KeyError as err:
  29. raise ArchiveError("Unable to expand string '{}': unknown field {} "
  30. "(valid fields are: {})".format(
  31. string, err, ', '.join(sorted(fields.keys()))))
  32. def init_git_repo(path, no_create, bare, log):
  33. """Initialize local Git repository"""
  34. path = os.path.abspath(path)
  35. if os.path.isfile(path):
  36. raise ArchiveError("Invalid Git repo at {}: path exists but is not a "
  37. "directory".format(path))
  38. if not os.path.isdir(path) or not os.listdir(path):
  39. if no_create:
  40. raise ArchiveError("No git repo at {}, refusing to create "
  41. "one".format(path))
  42. if not os.path.isdir(path):
  43. try:
  44. os.mkdir(path)
  45. except (FileNotFoundError, PermissionError) as err:
  46. raise ArchiveError("Failed to mkdir {}: {}".format(path, err))
  47. if not os.listdir(path):
  48. log.info("Initializing a new Git repo at %s", path)
  49. repo = GitRepo.init(path, bare)
  50. try:
  51. repo = GitRepo(path, is_topdir=True)
  52. except GitError:
  53. raise ArchiveError("Non-empty directory that is not a Git repository "
  54. "at {}\nPlease specify an existing Git repository, "
  55. "an empty directory or a non-existing directory "
  56. "path.".format(path))
  57. return repo
  58. def git_commit_data(repo, data_dir, branch, message, exclude, notes, log):
  59. """Commit data into a Git repository"""
  60. log.info("Committing data into to branch %s", branch)
  61. tmp_index = os.path.join(repo.git_dir, 'index.oe-git-archive')
  62. try:
  63. # Create new tree object from the data
  64. env_update = {'GIT_INDEX_FILE': tmp_index,
  65. 'GIT_WORK_TREE': os.path.abspath(data_dir)}
  66. repo.run_cmd('add .', env_update)
  67. # Remove files that are excluded
  68. if exclude:
  69. repo.run_cmd(['rm', '--cached'] + [f for f in exclude], env_update)
  70. tree = repo.run_cmd('write-tree', env_update)
  71. # Create new commit object from the tree
  72. parent = repo.rev_parse(branch)
  73. git_cmd = ['commit-tree', tree, '-m', message]
  74. if parent:
  75. git_cmd += ['-p', parent]
  76. commit = repo.run_cmd(git_cmd, env_update)
  77. # Create git notes
  78. for ref, filename in notes:
  79. ref = ref.format(branch_name=branch)
  80. repo.run_cmd(['notes', '--ref', ref, 'add',
  81. '-F', os.path.abspath(filename), commit])
  82. # Update branch head
  83. git_cmd = ['update-ref', 'refs/heads/' + branch, commit]
  84. if parent:
  85. git_cmd.append(parent)
  86. repo.run_cmd(git_cmd)
  87. # Update current HEAD, if we're on branch 'branch'
  88. if not repo.bare and repo.get_current_branch() == branch:
  89. log.info("Updating %s HEAD to latest commit", repo.top_dir)
  90. repo.run_cmd('reset --hard')
  91. return commit
  92. finally:
  93. if os.path.exists(tmp_index):
  94. os.unlink(tmp_index)
  95. def expand_tag_strings(repo, name_pattern, msg_subj_pattern, msg_body_pattern,
  96. keywords):
  97. """Generate tag name and message, with support for running id number"""
  98. keyws = keywords.copy()
  99. # Tag number is handled specially: if not defined, we autoincrement it
  100. if 'tag_number' not in keyws:
  101. # Fill in all other fields than 'tag_number'
  102. keyws['tag_number'] = '{tag_number}'
  103. tag_re = format_str(name_pattern, keyws)
  104. # Replace parentheses for proper regex matching
  105. tag_re = tag_re.replace('(', '\(').replace(')', '\)') + '$'
  106. # Inject regex group pattern for 'tag_number'
  107. tag_re = tag_re.format(tag_number='(?P<tag_number>[0-9]{1,5})')
  108. keyws['tag_number'] = 0
  109. for existing_tag in repo.run_cmd('tag').splitlines():
  110. match = re.match(tag_re, existing_tag)
  111. if match and int(match.group('tag_number')) >= keyws['tag_number']:
  112. keyws['tag_number'] = int(match.group('tag_number')) + 1
  113. tag_name = format_str(name_pattern, keyws)
  114. msg_subj= format_str(msg_subj_pattern.strip(), keyws)
  115. msg_body = format_str(msg_body_pattern, keyws)
  116. return tag_name, msg_subj + '\n\n' + msg_body
  117. def gitarchive(data_dir, git_dir, no_create, bare, commit_msg_subject, commit_msg_body, branch_name, no_tag, tagname, tag_msg_subject, tag_msg_body, exclude, notes, push, keywords, log):
  118. if not os.path.isdir(data_dir):
  119. raise ArchiveError("Not a directory: {}".format(data_dir))
  120. data_repo = init_git_repo(git_dir, no_create, bare, log)
  121. # Expand strings early in order to avoid getting into inconsistent
  122. # state (e.g. no tag even if data was committed)
  123. commit_msg = format_str(commit_msg_subject.strip(), keywords)
  124. commit_msg += '\n\n' + format_str(commit_msg_body, keywords)
  125. branch_name = format_str(branch_name, keywords)
  126. tag_name = None
  127. if not no_tag and tagname:
  128. tag_name, tag_msg = expand_tag_strings(data_repo, tagname,
  129. tag_msg_subject,
  130. tag_msg_body, keywords)
  131. # Commit data
  132. commit = git_commit_data(data_repo, data_dir, branch_name,
  133. commit_msg, exclude, notes, log)
  134. # Create tag
  135. if tag_name:
  136. log.info("Creating tag %s", tag_name)
  137. data_repo.run_cmd(['tag', '-a', '-m', tag_msg, tag_name, commit])
  138. # Push data to remote
  139. if push:
  140. cmd = ['push', '--tags']
  141. # If no remote is given we push with the default settings from
  142. # gitconfig
  143. if push is not True:
  144. notes_refs = ['refs/notes/' + ref.format(branch_name=branch_name)
  145. for ref, _ in notes]
  146. cmd.extend([push, branch_name] + notes_refs)
  147. log.info("Pushing data to remote")
  148. data_repo.run_cmd(cmd)
  149. # Container class for tester revisions
  150. TestedRev = namedtuple('TestedRev', 'commit commit_number tags')
  151. def get_test_runs(log, repo, tag_name, **kwargs):
  152. """Get a sorted list of test runs, matching given pattern"""
  153. # First, get field names from the tag name pattern
  154. field_names = [m.group(1) for m in re.finditer(r'{(\w+)}', tag_name)]
  155. undef_fields = [f for f in field_names if f not in kwargs.keys()]
  156. # Fields for formatting tag name pattern
  157. str_fields = dict([(f, '*') for f in field_names])
  158. str_fields.update(kwargs)
  159. # Get a list of all matching tags
  160. tag_pattern = tag_name.format(**str_fields)
  161. tags = repo.run_cmd(['tag', '-l', tag_pattern]).splitlines()
  162. log.debug("Found %d tags matching pattern '%s'", len(tags), tag_pattern)
  163. # Parse undefined fields from tag names
  164. str_fields = dict([(f, r'(?P<{}>[\w\-.()]+)'.format(f)) for f in field_names])
  165. str_fields['branch'] = r'(?P<branch>[\w\-.()/]+)'
  166. str_fields['commit'] = '(?P<commit>[0-9a-f]{7,40})'
  167. str_fields['commit_number'] = '(?P<commit_number>[0-9]{1,7})'
  168. str_fields['tag_number'] = '(?P<tag_number>[0-9]{1,5})'
  169. # escape parenthesis in fields in order to not messa up the regexp
  170. fixed_fields = dict([(k, v.replace('(', r'\(').replace(')', r'\)')) for k, v in kwargs.items()])
  171. str_fields.update(fixed_fields)
  172. tag_re = re.compile(tag_name.format(**str_fields))
  173. # Parse fields from tags
  174. revs = []
  175. for tag in tags:
  176. m = tag_re.match(tag)
  177. groups = m.groupdict()
  178. revs.append([groups[f] for f in undef_fields] + [tag])
  179. # Return field names and a sorted list of revs
  180. return undef_fields, sorted(revs)
  181. def get_test_revs(log, repo, tag_name, **kwargs):
  182. """Get list of all tested revisions"""
  183. fields, runs = get_test_runs(log, repo, tag_name, **kwargs)
  184. revs = {}
  185. commit_i = fields.index('commit')
  186. commit_num_i = fields.index('commit_number')
  187. for run in runs:
  188. commit = run[commit_i]
  189. commit_num = run[commit_num_i]
  190. tag = run[-1]
  191. if not commit in revs:
  192. revs[commit] = TestedRev(commit, commit_num, [tag])
  193. else:
  194. assert commit_num == revs[commit].commit_number, "Commit numbers do not match"
  195. revs[commit].tags.append(tag)
  196. # Return in sorted table
  197. revs = sorted(revs.values(), key=attrgetter('commit_number'))
  198. log.debug("Found %d tested revisions:\n %s", len(revs),
  199. "\n ".join(['{} ({})'.format(rev.commit_number, rev.commit) for rev in revs]))
  200. return revs
  201. def rev_find(revs, attr, val):
  202. """Search from a list of TestedRev"""
  203. for i, rev in enumerate(revs):
  204. if getattr(rev, attr) == val:
  205. return i
  206. raise ValueError("Unable to find '{}' value '{}'".format(attr, val))