oe-git-archive 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. #!/usr/bin/python3
  2. #
  3. # Helper script for committing data to git and pushing upstream
  4. #
  5. # Copyright (c) 2017, Intel Corporation.
  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 argparse
  17. import glob
  18. import json
  19. import logging
  20. import math
  21. import os
  22. import re
  23. import sys
  24. from collections import namedtuple, OrderedDict
  25. from datetime import datetime, timedelta, tzinfo
  26. from operator import attrgetter
  27. # Import oe and bitbake libs
  28. scripts_path = os.path.dirname(os.path.realpath(__file__))
  29. sys.path.append(os.path.join(scripts_path, 'lib'))
  30. import scriptpath
  31. scriptpath.add_bitbake_lib_path()
  32. scriptpath.add_oe_lib_path()
  33. from oeqa.utils.git import GitRepo, GitError
  34. from oeqa.utils.metadata import metadata_from_bb
  35. # Setup logging
  36. logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
  37. log = logging.getLogger()
  38. class ArchiveError(Exception):
  39. """Internal error handling of this script"""
  40. def format_str(string, fields):
  41. """Format string using the given fields (dict)"""
  42. try:
  43. return string.format(**fields)
  44. except KeyError as err:
  45. raise ArchiveError("Unable to expand string '{}': unknown field {} "
  46. "(valid fields are: {})".format(
  47. string, err, ', '.join(sorted(fields.keys()))))
  48. def init_git_repo(path, no_create, bare):
  49. """Initialize local Git repository"""
  50. path = os.path.abspath(path)
  51. if os.path.isfile(path):
  52. raise ArchiveError("Invalid Git repo at {}: path exists but is not a "
  53. "directory".format(path))
  54. if not os.path.isdir(path) or not os.listdir(path):
  55. if no_create:
  56. raise ArchiveError("No git repo at {}, refusing to create "
  57. "one".format(path))
  58. if not os.path.isdir(path):
  59. try:
  60. os.mkdir(path)
  61. except (FileNotFoundError, PermissionError) as err:
  62. raise ArchiveError("Failed to mkdir {}: {}".format(path, err))
  63. if not os.listdir(path):
  64. log.info("Initializing a new Git repo at %s", path)
  65. repo = GitRepo.init(path, bare)
  66. try:
  67. repo = GitRepo(path, is_topdir=True)
  68. except GitError:
  69. raise ArchiveError("Non-empty directory that is not a Git repository "
  70. "at {}\nPlease specify an existing Git repository, "
  71. "an empty directory or a non-existing directory "
  72. "path.".format(path))
  73. return repo
  74. def git_commit_data(repo, data_dir, branch, message, exclude, notes):
  75. """Commit data into a Git repository"""
  76. log.info("Committing data into to branch %s", branch)
  77. tmp_index = os.path.join(repo.git_dir, 'index.oe-git-archive')
  78. try:
  79. # Create new tree object from the data
  80. env_update = {'GIT_INDEX_FILE': tmp_index,
  81. 'GIT_WORK_TREE': os.path.abspath(data_dir)}
  82. repo.run_cmd('add .', env_update)
  83. # Remove files that are excluded
  84. if exclude:
  85. repo.run_cmd(['rm', '--cached'] + [f for f in exclude], env_update)
  86. tree = repo.run_cmd('write-tree', env_update)
  87. # Create new commit object from the tree
  88. parent = repo.rev_parse(branch)
  89. git_cmd = ['commit-tree', tree, '-m', message]
  90. if parent:
  91. git_cmd += ['-p', parent]
  92. commit = repo.run_cmd(git_cmd, env_update)
  93. # Create git notes
  94. for ref, filename in notes:
  95. ref = ref.format(branch_name=branch)
  96. repo.run_cmd(['notes', '--ref', ref, 'add',
  97. '-F', os.path.abspath(filename), commit])
  98. # Update branch head
  99. git_cmd = ['update-ref', 'refs/heads/' + branch, commit]
  100. if parent:
  101. git_cmd.append(parent)
  102. repo.run_cmd(git_cmd)
  103. # Update current HEAD, if we're on branch 'branch'
  104. if not repo.bare and repo.get_current_branch() == branch:
  105. log.info("Updating %s HEAD to latest commit", repo.top_dir)
  106. repo.run_cmd('reset --hard')
  107. return commit
  108. finally:
  109. if os.path.exists(tmp_index):
  110. os.unlink(tmp_index)
  111. def expand_tag_strings(repo, name_pattern, msg_subj_pattern, msg_body_pattern,
  112. keywords):
  113. """Generate tag name and message, with support for running id number"""
  114. keyws = keywords.copy()
  115. # Tag number is handled specially: if not defined, we autoincrement it
  116. if 'tag_number' not in keyws:
  117. # Fill in all other fields than 'tag_number'
  118. keyws['tag_number'] = '{tag_number}'
  119. tag_re = format_str(name_pattern, keyws)
  120. # Replace parentheses for proper regex matching
  121. tag_re = tag_re.replace('(', '\(').replace(')', '\)') + '$'
  122. # Inject regex group pattern for 'tag_number'
  123. tag_re = tag_re.format(tag_number='(?P<tag_number>[0-9]{1,5})')
  124. keyws['tag_number'] = 0
  125. for existing_tag in repo.run_cmd('tag').splitlines():
  126. match = re.match(tag_re, existing_tag)
  127. if match and int(match.group('tag_number')) >= keyws['tag_number']:
  128. keyws['tag_number'] = int(match.group('tag_number')) + 1
  129. tag_name = format_str(name_pattern, keyws)
  130. msg_subj= format_str(msg_subj_pattern.strip(), keyws)
  131. msg_body = format_str(msg_body_pattern, keyws)
  132. return tag_name, msg_subj + '\n\n' + msg_body
  133. def parse_args(argv):
  134. """Parse command line arguments"""
  135. parser = argparse.ArgumentParser(
  136. description="Commit data to git and push upstream",
  137. formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  138. parser.add_argument('--debug', '-D', action='store_true',
  139. help="Verbose logging")
  140. parser.add_argument('--git-dir', '-g', required=True,
  141. help="Local git directory to use")
  142. parser.add_argument('--no-create', action='store_true',
  143. help="If GIT_DIR is not a valid Git repository, do not "
  144. "try to create one")
  145. parser.add_argument('--bare', action='store_true',
  146. help="Initialize a bare repository when creating a "
  147. "new one")
  148. parser.add_argument('--push', '-p', nargs='?', default=False, const=True,
  149. help="Push to remote")
  150. parser.add_argument('--branch-name', '-b',
  151. default='{hostname}/{branch}/{machine}',
  152. help="Git branch name (pattern) to use")
  153. parser.add_argument('--no-tag', action='store_true',
  154. help="Do not create Git tag")
  155. parser.add_argument('--tag-name', '-t',
  156. default='{hostname}/{branch}/{machine}/{commit_count}-g{commit}/{tag_number}',
  157. help="Tag name (pattern) to use")
  158. parser.add_argument('--commit-msg-subject',
  159. default='Results of {branch}:{commit} on {hostname}',
  160. help="Subject line (pattern) to use in the commit message")
  161. parser.add_argument('--commit-msg-body',
  162. default='branch: {branch}\ncommit: {commit}\nhostname: {hostname}',
  163. help="Commit message body (pattern)")
  164. parser.add_argument('--tag-msg-subject',
  165. default='Test run #{tag_number} of {branch}:{commit} on {hostname}',
  166. help="Subject line (pattern) of the tag message")
  167. parser.add_argument('--tag-msg-body',
  168. default='',
  169. help="Tag message body (pattern)")
  170. parser.add_argument('--exclude', action='append', default=[],
  171. help="Glob to exclude files from the commit. Relative "
  172. "to DATA_DIR. May be specified multiple times")
  173. parser.add_argument('--notes', nargs=2, action='append', default=[],
  174. metavar=('GIT_REF', 'FILE'),
  175. help="Add a file as a note under refs/notes/GIT_REF. "
  176. "{branch_name} in GIT_REF will be expanded to the "
  177. "actual target branch name (specified by "
  178. "--branch-name). This option may be specified "
  179. "multiple times.")
  180. parser.add_argument('data_dir', metavar='DATA_DIR',
  181. help="Data to commit")
  182. return parser.parse_args(argv)
  183. def main(argv=None):
  184. """Script entry point"""
  185. args = parse_args(argv)
  186. if args.debug:
  187. log.setLevel(logging.DEBUG)
  188. try:
  189. if not os.path.isdir(args.data_dir):
  190. raise ArchiveError("Not a directory: {}".format(args.data_dir))
  191. data_repo = init_git_repo(args.git_dir, args.no_create, args.bare)
  192. # Get keywords to be used in tag and branch names and messages
  193. metadata = metadata_from_bb()
  194. keywords = {'hostname': metadata['hostname'],
  195. 'branch': metadata['layers']['meta']['branch'],
  196. 'commit': metadata['layers']['meta']['commit'],
  197. 'commit_count': metadata['layers']['meta']['commit_count'],
  198. 'machine': metadata['config']['MACHINE']}
  199. # Expand strings early in order to avoid getting into inconsistent
  200. # state (e.g. no tag even if data was committed)
  201. commit_msg = format_str(args.commit_msg_subject.strip(), keywords)
  202. commit_msg += '\n\n' + format_str(args.commit_msg_body, keywords)
  203. branch_name = format_str(args.branch_name, keywords)
  204. tag_name = None
  205. if not args.no_tag and args.tag_name:
  206. tag_name, tag_msg = expand_tag_strings(data_repo, args.tag_name,
  207. args.tag_msg_subject,
  208. args.tag_msg_body, keywords)
  209. # Commit data
  210. commit = git_commit_data(data_repo, args.data_dir, branch_name,
  211. commit_msg, args.exclude, args.notes)
  212. # Create tag
  213. if tag_name:
  214. log.info("Creating tag %s", tag_name)
  215. data_repo.run_cmd(['tag', '-a', '-m', tag_msg, tag_name, commit])
  216. # Push data to remote
  217. if args.push:
  218. cmd = ['push', '--tags']
  219. # If no remote is given we push with the default settings from
  220. # gitconfig
  221. if args.push is not True:
  222. notes_refs = ['refs/notes/' + ref.format(branch_name=branch_name)
  223. for ref, _ in args.notes]
  224. cmd.extend([args.push, branch_name] + notes_refs)
  225. log.info("Pushing data to remote")
  226. data_repo.run_cmd(cmd)
  227. except ArchiveError as err:
  228. log.error(str(err))
  229. return 1
  230. return 0
  231. if __name__ == "__main__":
  232. sys.exit(main())