gitarchive.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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 oeqa.utils.git import GitRepo, GitError
  20. class ArchiveError(Exception):
  21. """Internal error handling of this script"""
  22. def format_str(string, fields):
  23. """Format string using the given fields (dict)"""
  24. try:
  25. return string.format(**fields)
  26. except KeyError as err:
  27. raise ArchiveError("Unable to expand string '{}': unknown field {} "
  28. "(valid fields are: {})".format(
  29. string, err, ', '.join(sorted(fields.keys()))))
  30. def init_git_repo(path, no_create, bare, log):
  31. """Initialize local Git repository"""
  32. path = os.path.abspath(path)
  33. if os.path.isfile(path):
  34. raise ArchiveError("Invalid Git repo at {}: path exists but is not a "
  35. "directory".format(path))
  36. if not os.path.isdir(path) or not os.listdir(path):
  37. if no_create:
  38. raise ArchiveError("No git repo at {}, refusing to create "
  39. "one".format(path))
  40. if not os.path.isdir(path):
  41. try:
  42. os.mkdir(path)
  43. except (FileNotFoundError, PermissionError) as err:
  44. raise ArchiveError("Failed to mkdir {}: {}".format(path, err))
  45. if not os.listdir(path):
  46. log.info("Initializing a new Git repo at %s", path)
  47. repo = GitRepo.init(path, bare)
  48. try:
  49. repo = GitRepo(path, is_topdir=True)
  50. except GitError:
  51. raise ArchiveError("Non-empty directory that is not a Git repository "
  52. "at {}\nPlease specify an existing Git repository, "
  53. "an empty directory or a non-existing directory "
  54. "path.".format(path))
  55. return repo
  56. def git_commit_data(repo, data_dir, branch, message, exclude, notes, log):
  57. """Commit data into a Git repository"""
  58. log.info("Committing data into to branch %s", branch)
  59. tmp_index = os.path.join(repo.git_dir, 'index.oe-git-archive')
  60. try:
  61. # Create new tree object from the data
  62. env_update = {'GIT_INDEX_FILE': tmp_index,
  63. 'GIT_WORK_TREE': os.path.abspath(data_dir)}
  64. repo.run_cmd('add .', env_update)
  65. # Remove files that are excluded
  66. if exclude:
  67. repo.run_cmd(['rm', '--cached'] + [f for f in exclude], env_update)
  68. tree = repo.run_cmd('write-tree', env_update)
  69. # Create new commit object from the tree
  70. parent = repo.rev_parse(branch)
  71. git_cmd = ['commit-tree', tree, '-m', message]
  72. if parent:
  73. git_cmd += ['-p', parent]
  74. commit = repo.run_cmd(git_cmd, env_update)
  75. # Create git notes
  76. for ref, filename in notes:
  77. ref = ref.format(branch_name=branch)
  78. repo.run_cmd(['notes', '--ref', ref, 'add',
  79. '-F', os.path.abspath(filename), commit])
  80. # Update branch head
  81. git_cmd = ['update-ref', 'refs/heads/' + branch, commit]
  82. if parent:
  83. git_cmd.append(parent)
  84. repo.run_cmd(git_cmd)
  85. # Update current HEAD, if we're on branch 'branch'
  86. if not repo.bare and repo.get_current_branch() == branch:
  87. log.info("Updating %s HEAD to latest commit", repo.top_dir)
  88. repo.run_cmd('reset --hard')
  89. return commit
  90. finally:
  91. if os.path.exists(tmp_index):
  92. os.unlink(tmp_index)
  93. def expand_tag_strings(repo, name_pattern, msg_subj_pattern, msg_body_pattern,
  94. keywords):
  95. """Generate tag name and message, with support for running id number"""
  96. keyws = keywords.copy()
  97. # Tag number is handled specially: if not defined, we autoincrement it
  98. if 'tag_number' not in keyws:
  99. # Fill in all other fields than 'tag_number'
  100. keyws['tag_number'] = '{tag_number}'
  101. tag_re = format_str(name_pattern, keyws)
  102. # Replace parentheses for proper regex matching
  103. tag_re = tag_re.replace('(', '\(').replace(')', '\)') + '$'
  104. # Inject regex group pattern for 'tag_number'
  105. tag_re = tag_re.format(tag_number='(?P<tag_number>[0-9]{1,5})')
  106. keyws['tag_number'] = 0
  107. for existing_tag in repo.run_cmd('tag').splitlines():
  108. match = re.match(tag_re, existing_tag)
  109. if match and int(match.group('tag_number')) >= keyws['tag_number']:
  110. keyws['tag_number'] = int(match.group('tag_number')) + 1
  111. tag_name = format_str(name_pattern, keyws)
  112. msg_subj= format_str(msg_subj_pattern.strip(), keyws)
  113. msg_body = format_str(msg_body_pattern, keyws)
  114. return tag_name, msg_subj + '\n\n' + msg_body
  115. 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):
  116. if not os.path.isdir(data_dir):
  117. raise ArchiveError("Not a directory: {}".format(data_dir))
  118. data_repo = init_git_repo(git_dir, no_create, bare, log)
  119. # Expand strings early in order to avoid getting into inconsistent
  120. # state (e.g. no tag even if data was committed)
  121. commit_msg = format_str(commit_msg_subject.strip(), keywords)
  122. commit_msg += '\n\n' + format_str(commit_msg_body, keywords)
  123. branch_name = format_str(branch_name, keywords)
  124. tag_name = None
  125. if not no_tag and tagname:
  126. tag_name, tag_msg = expand_tag_strings(data_repo, tagname,
  127. tag_msg_subject,
  128. tag_msg_body, keywords)
  129. # Commit data
  130. commit = git_commit_data(data_repo, data_dir, branch_name,
  131. commit_msg, exclude, notes, log)
  132. # Create tag
  133. if tag_name:
  134. log.info("Creating tag %s", tag_name)
  135. data_repo.run_cmd(['tag', '-a', '-m', tag_msg, tag_name, commit])
  136. # Push data to remote
  137. if push:
  138. cmd = ['push', '--tags']
  139. # If no remote is given we push with the default settings from
  140. # gitconfig
  141. if push is not True:
  142. notes_refs = ['refs/notes/' + ref.format(branch_name=branch_name)
  143. for ref, _ in notes]
  144. cmd.extend([push, branch_name] + notes_refs)
  145. log.info("Pushing data to remote")
  146. data_repo.run_cmd(cmd)