pax_global_header00006660000000000000000000000064136035732220014515gustar00rootroot0000000000000052 comment=a2382a0fb00a4264ea1321db5ba589a4cd470bd8 git-publish-1.6.0/000077500000000000000000000000001360357322200137505ustar00rootroot00000000000000git-publish-1.6.0/.gitignore000066400000000000000000000000061360357322200157340ustar00rootroot00000000000000*.pyc git-publish-1.6.0/LICENSE000066400000000000000000000020361360357322200147560ustar00rootroot00000000000000Copyright (c) 2011 IBM, Corp. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. git-publish-1.6.0/README.md000066400000000000000000000041421360357322200152300ustar00rootroot00000000000000*Tired of manually creating patch series emails?* git-publish prepares patches and stores them as git tags for future reference. It works with individual patches as well as patch series. Revision numbering is handled automatically. No constraints are placed on git workflow, both vanilla git commands and custom workflow scripts are compatible with git-publish. Email sending and pull requests are fully integrated so that publishing patches can be done in a single command. Hook scripts are invoked during patch preparation so that custom checks or test runs can be automated. ## How to install ### Packages Packages are available for: * [Fedora](https://koji.fedoraproject.org/koji/packageinfo?packageID=25588) - `dnf install git-publish` * [Debian](https://packages.debian.org/buster/git-publish) and [Ubuntu](https://packages.ubuntu.com/bionic/git-publish) - `apt install git-publish` * [RHEL and CentOS](https://koji.fedoraproject.org/koji/packageinfo?packageID=25588) via [EPEL](https://fedoraproject.org/wiki/EPEL) - `yum install git-publish` ### Manual install You can also run git-publish from the source tree (useful for development). Assuming `~/bin` is on `$PATH`: ``` $ git clone https://github.com/stefanha/git-publish $ ln -s $PWD/git-publish/git-publish ~/bin/ ``` ### `git publish` alias Run `git-publish --setup` to install the git alias so you can invoke `git publish` instead of `git-publish`. ## How it works Send the initial patch series email like this: ```$ git publish --to patches@example.org --cc maintainer@example.org``` You will be prompted for a cover letter on a multi-patch series and you will be presented with a chance to review the emails before they are sent. Sending successive revisions is easy, you don't need to repeat all the details since git-publish stores them for you: ```$ git publish # to send v2, v3, etc``` ## Documentation Read the man page [here](https://github.com/stefanha/git-publish/blob/master/git-publish.pod). ## Get in touch Please submit pull requests on GitHub (https://github.com/stefanha/git-publish) or email patches to Stefan Hajnoczi . git-publish-1.6.0/git-publish000077500000000000000000001025061360357322200161310ustar00rootroot00000000000000#!/usr/bin/env python3 # # git-publish - Prepare and store patch revisions as git tags # # Copyright 2011 IBM, Corp. # Copyright 2014-2019 Red Hat, Inc. # # Authors: # Stefan Hajnoczi # # This work is licensed under the MIT License. Please see the LICENSE file or # http://opensource.org/licenses/MIT. from __future__ import print_function, unicode_literals from io import open import os import glob import sys import optparse import re import tempfile import shutil import subprocess import locale from email import message_from_file, header VERSION = '1.6.0' tag_version_re = re.compile(r'^[a-zA-Z0-9_/\-\.]+-v(\d+)$') ENCODING = locale.getpreferredencoding() # As a git alias it is helpful to be a single file script with no external # dependencies, so these git command-line wrappers are used instead of # python-git. class GitSendEmailError(Exception): pass class GitError(Exception): pass class GitHookError(Exception): pass class InspectEmailsError(Exception): pass def to_text(data): if isinstance(data, bytes): return data.decode(ENCODING) return data def popen_lines(cmd, **kwargs): '''Communicate with a Popen object and return a list of lines for stdout and stderr''' stdout, stderr = cmd.communicate(**kwargs) stdout = stdout.decode(ENCODING).split(os.linesep)[:-1] stderr = stderr.decode(ENCODING).split(os.linesep)[:-1] return stdout, stderr def _git_check(*args): '''Run a git command and return a list of lines, may raise GitError''' cmdstr = 'git ' + ' '.join(('"%s"' % arg if ' ' in arg else arg) for arg in args) if VERBOSE: print(cmdstr) cmd = subprocess.Popen(['git'] + list(args), stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = popen_lines(cmd) if cmd.returncode != 0: raise GitError('ERROR: %s\n%s' % (cmdstr, '\n'.join(stderr))) return stdout def _git(*args): '''Run a git command and return a list of lines, ignore errors''' try: return _git_check(*args) except GitError: # ignore git command errors return [] def _git_with_stderr(*args): '''Run a git command and return a list of lines for stdout and stderr''' if VERBOSE: print('git ' + ' '.join(args)) cmd = subprocess.Popen(['git'] + list(args), stdout=subprocess.PIPE, stderr=subprocess.PIPE) return popen_lines(cmd) def bool_from_str(s): '''Parse a boolean string value like true/false, yes/no, or on/off''' return s.lower() in ('true', 'yes', 'on') def git_get_config(*components): '''Get a git-config(1) variable''' lines = _git('config', '.'.join(components)) if len(lines): return lines[0] return None def git_get_config_list(*components): '''Get a git-config(1) list variable''' return _git('config', '--get-all', '.'.join(components)) def git_unset_config(*components): _git('config', '--unset-all', '.'.join(components)) def git_set_config(*components): '''Set a git-config(1) variable''' if len(components) < 2: raise TypeError('git_set_config() takes at least 2 arguments (%d given)' % len(components)) val = components[-1] name = '.'.join(components[:-1]) if isinstance(val, (str, bytes)) or not hasattr(val, '__iter__'): _git('config', name, val) else: git_unset_config(name) for v in val: _git('config', '--add', name, v) def git_get_var(name): '''Get a git-var(1)''' lines = _git('var', name) if len(lines): return lines[0] return None def git_get_current_branch(): git_dir = git_get_git_dir() rebase_dir = os.path.join(git_dir, 'rebase-merge') if os.path.exists(rebase_dir): branch_path = os.path.join(rebase_dir, 'head-name') prefix = 'refs/heads/' branch = open(branch_path).read().strip() if branch.startswith(prefix): return branch[len(prefix):] return branch else: return _git_check('symbolic-ref', '--short', 'HEAD')[0] GIT_TOPLEVEL = None def git_get_toplevel_dir(): global GIT_TOPLEVEL if GIT_TOPLEVEL is None: GIT_TOPLEVEL = _git_check('rev-parse', '--show-toplevel')[0] return GIT_TOPLEVEL GIT_DIR = None def git_get_git_dir(): global GIT_DIR if GIT_DIR is None: GIT_DIR = _git('rev-parse', '--git-dir')[0] return GIT_DIR def git_delete_tag(name): # Hide stderr when tag does not exist _git_with_stderr('tag', '-d', name) def git_get_tags(pattern=None): if pattern: return _git('tag', '-l', pattern) else: return _git('tag') def git_get_tag_message(tag): r = _git('tag', '-l', '--format=%(contents)', tag) # --format=%(contents) will print an extra newline if the tag message # already ends with a newline, so drop the extra line at the end: if r and r[-1] == '': r.pop() return r def git_get_remote_url(remote): '''Return the URL for a given remote''' return _git_check('ls-remote', '--get-url', remote)[0] def git_request_pull(base, remote, signed_tag): return _git_check('request-pull', base, remote, signed_tag) def git_log(revlist): return _git('log', '--no-color', '--oneline', revlist) def git_tag(name, annotate=None, force=False, sign=False, keyid=None): args = ['tag', '--annotate'] if annotate: args += ['--file', annotate] else: args += ['--message', ''] if force: args += ['--force'] if sign: args += ['--sign'] if keyid: args += ['--local-user', keyid] args += [name] _git_check(*args) def git_format_patch(revlist, subject_prefix=None, output_directory=None, numbered=False, cover_letter=False, signoff=False, notes=False, binary=True, headers=[], extra_args=[]): args = ['format-patch'] if subject_prefix: args += ['--subject-prefix', subject_prefix] if output_directory: args += ['--output-directory', output_directory] if numbered: args += ['--numbered'] if cover_letter: args += ['--cover-letter'] else: args += ['--no-cover-letter'] if signoff: args += ['--signoff'] if notes: args += ['--notes'] if not binary: args += ['--no-binary'] for header in headers: args += ['--add-header', header] args += [revlist] args += extra_args _git_check(*args) def git_send_email(to_list, cc_list, patches, suppress_cc, in_reply_to, dry_run=False): args = ['git', 'send-email'] for address in to_list: args += ['--to', address] for address in cc_list: args += ['--cc', address] if suppress_cc: args += ['--suppress-cc', suppress_cc] if in_reply_to: args += ['--in-reply-to', in_reply_to] if dry_run: args += ['--dry-run', '--relogin-delay=0'] else: args += ['--quiet'] args += ['--confirm=never'] args += patches if dry_run: return _git_with_stderr(*args[1:])[0] else: if subprocess.call(args) != 0: raise GitSendEmailError GIT_HOOKDIR = None def git_get_hook_dir(): global GIT_HOOKDIR if GIT_HOOKDIR is None: common_dir = _git('rev-parse', '--git-common-dir')[0] if common_dir.startswith("--git-common-dir"): common_dir = git_get_git_dir() GIT_HOOKDIR = os.path.join(common_dir, 'hooks') return GIT_HOOKDIR def invoke_hook(name, *args): '''Run a githooks(5) script''' hooks_path = git_get_config("core", "hooksPath") or \ os.path.join(git_get_hook_dir()) hook_path = os.path.join(hooks_path, name) if not os.access(hook_path, os.X_OK): return if subprocess.call((hook_path,) + args, cwd=git_get_toplevel_dir()) != 0: raise GitHookError def git_push(remote, ref, force=False): args = ['push'] if force: args += ['-f'] args += [remote, ref] _git_check(*args) def git_config_with_profile(*args): '''Like git-config(1) except with .gitpublish added to the file lookup chain Note that only git-config(1) read operations are supported. Write operations are not allowed since we should not modify .gitpublish.''' cmd = subprocess.Popen(['git', 'config', '--includes', '--file', '/dev/stdin'] + list(args), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # git-config(1) --includes requires absolute paths gitpublish = os.path.abspath(os.path.join(git_get_toplevel_dir(), '.gitpublish')) if 'GIT_CONFIG' in os.environ: gitconfig = os.path.abspath(os.environ['GIT_CONFIG']) else: gitconfig = os.path.abspath(os.path.join(git_get_git_dir(), 'config')) git_config_file = ''' [include] path = ~/.gitconfig path = %s path = %s ''' % (gitpublish, gitconfig) stdout, _ = popen_lines(cmd, input=git_config_file.encode(ENCODING)) return stdout def git_cover_letter_info(base, topic, to, cc, in_reply_to, number): cl_info = ['Lines starting with \'#\' will be ignored.'] cl_info += [''] cl_info += ['Version number: ' + str(number)] cl_info += ['Branches:'] cl_info += [' base: ' + base, ' topic: ' + topic] cl_info += [''] if to: cl_info += ['To: ' + '\n# '.join(list(to))] if cc: cl_info += ['Cc: ' + '\n# '.join(list(cc))] if in_reply_to: cl_info += ['In-Reply-To: ' + in_reply_to] cl_info += [''] cl_info += _git('shortlog', base + '..' + topic) cl_info += _git('diff', '--stat', base + '..' + topic) return ["#" + (l if l == '' else ' ' + l) for l in cl_info] def check_profile_exists(profile_name): '''Return True if the profile exists, False otherwise''' lines = git_config_with_profile('--get-regexp', '^gitpublishprofile\\.%s\\.' % profile_name) return bool(lines) def has_profiles(): '''Return True if any profile exists, False otherwise''' lines = git_config_with_profile('--get-regexp', '^gitpublishprofile\\.*\\.') return bool(lines) def get_profile_var(profile_name, var_name): '''Get a profile variable''' option = '.'.join(['gitpublishprofile', profile_name, var_name]) lines = git_config_with_profile(option) if len(lines): return lines[0] return None def get_profile_var_list(profile_name, var_name): '''Get a profile list variable''' option = '.'.join(['gitpublishprofile', profile_name, var_name]) return git_config_with_profile('--get-all', option) def setup(): '''Add git alias in ~/.gitconfig''' path = os.path.abspath(sys.argv[0]) ret = subprocess.call(['git', 'config', '--global', 'alias.publish', '!' + path]) if ret == 0: print('You can now use \'git publish\' like a built-in git command.') def tag_name(topic, number): '''Build a tag name from a topic name and version number''' return '%s-v%d' % (topic, number) def tag_name_staging(topic): '''Build a staging tag name from a topic name''' return '%s-staging' % topic def tag_name_pull_request(topic): '''Build a pull request tag name from a topic name''' return '%s-pull-request' % topic def get_latest_tag_number(branch): '''Find the latest tag number or 0 if no tags exist''' number = 0 for tag in git_get_tags('%s-v[0-9]*' % branch): m = tag_version_re.match(tag) if not m: continue n = int(m.group(1)) if n > number: number = n return number def get_latest_tag_message(topic, default_lines): '''Find the latest tag message or return a template if no tags exist''' msg = git_get_tag_message(tag_name_staging(topic)) if msg: return msg number = get_latest_tag_number(topic) msg = git_get_tag_message(tag_name(topic, number)) if msg: return msg return default_lines def get_pull_request_message(base, remote, topic): # Add a subject line message = [topic.replace('_', ' ').replace('-', ' ').capitalize() + ' patches', ''] output = git_request_pull(base, remote, tag_name_pull_request(topic)) # Chop off diffstat because git-send-email(1) will generate it first_separator = True for line in output: message.append(line) if line == '----------------------------------------------------------------': if not first_separator: break first_separator = False return message def get_number_of_commits(base): return len(git_log('%s..' % base)) def edit(*filenames): cmd = git_get_var('GIT_EDITOR').split(" ") cmd.extend(filenames) subprocess.call(cmd) def tag(name, template, annotate=False, force=False, sign=False, keyid=None): '''Edit a tag message and create the tag''' fd, tmpfile = None, None try: if annotate: fd, tmpfile = tempfile.mkstemp(text=True) os.fdopen(fd, 'wb').write(os.linesep.join(template + ['']).encode(ENCODING)) edit(tmpfile) git_tag(name, annotate=tmpfile, force=force, sign=sign, keyid=keyid) finally: if tmpfile: os.unlink(tmpfile) def menu_select(menu): while True: for k, v in menu: print("[%s] %s" % (k, v)) a = sys.stdin.readline().strip() if a not in [k for (k, v) in menu]: print("Unknown command, please retry") continue return a def parse_header(hdr): r = '' for h, c in header.decode_header(hdr): if c is None: c = 'us-ascii' if sys.version_info > (3, 0) and type(h) is str: r += h else: r += h.decode(c) if '\n' in r: r = " ".join([x.strip() for x in r.splitlines()]) return r def edit_email_list(cc_list): tmpfile = tempfile.NamedTemporaryFile(mode='wb', suffix='.txt') tmpfile.write(os.linesep.join(cc_list).encode(ENCODING)) tmpfile.flush() edit(tmpfile.name) r = [] for line in open(tmpfile.name, "r").readlines(): r += [x.strip() for x in line.split(",")] return r def git_save_email_lists(topic, to, cc, override_cc): # Store --to and --cc for next revision git_set_config('branch', topic, 'gitpublishto', to) if not override_cc: git_set_config('branch', topic, 'gitpublishcc', cc) def inspect_menu(tmpdir, to_list, cc_list, patches, suppress_cc, in_reply_to, topic, override_cc): while True: print('Stopping so you can inspect the patch emails:') print(' cd %s' % tmpdir) print() output = git_send_email(to_list, cc_list, patches, suppress_cc, in_reply_to, dry_run=True) index = 0 for f in patches: m = message_from_file(open(f)) print(parse_header(m['subject'])) # Print relevant 'Adding cc' lines from the git-send-email --dry-run output while index < len(output) and len(output[index]): if output[index].find('Adding cc') != -1: print(' ' + output[index]) index += 1 index += 1 print() print("To:", "\n ".join(to_list)) if cc_list: print("Cc:", "\n ".join(cc_list)) if in_reply_to: print("In-Reply-To:", in_reply_to) print() a = menu_select([ ('c', 'Edit Cc list in editor (save after edit)'), ('t', 'Edit To list in editor (save after edit)'), ('e', 'Edit patches in editor'), ('s', 'Select patches to send (default: all)'), ('p', 'Print final email headers (dry run)'), ('a', 'Send all'), ('q', 'Cancel (quit)'), ]) if a == 'q': raise InspectEmailsError elif a == 'c': new_cc_list = edit_email_list(cc_list) cc_list.clear() cc_list.update(new_cc_list) git_save_email_lists(topic, to_list, cc_list, override_cc) elif a == 't': new_to_list = edit_email_list(to_list) to_list.clear() to_list.update(new_to_list) git_save_email_lists(topic, to_list, cc_list, override_cc) elif a == 'e': edit(*patches) elif a == 's': listfile = tempfile.NamedTemporaryFile() listfile.write("\n".join(patches).encode(ENCODING)) listfile.flush() edit(listfile.name) listfile.seek(0) patches = [x for x in listfile.read().splitlines() if len(x.strip())] elif a == 'p': print('\n'.join(output)) elif a == 'a': break return patches def parse_args(): parser = optparse.OptionParser(version='%%prog %s' % VERSION, usage='%prog [options] -- [common format-patch options]', description='Prepare and store patch revisions as git tags.', epilog='Please report bugs to Stefan Hajnoczi .') parser.add_option('--annotate', dest='annotate', action='store_true', default=False, help='review and edit each patch email') parser.add_option('-b', '--base', dest='base', default=None, help='branch which this is based off [defaults to master]') parser.add_option('--blurb-template', dest='blurb_template', default=None, help='Template for blurb [defaults to *** BLURB HERE ***]') parser.add_option('--cc', dest='cc', action='append', default=[], help='specify a Cc: email recipient') parser.add_option('--cc-cmd', help='specify a command whose output to add to the cc list') parser.add_option('--no-check-url', dest='check_url', action='store_false', help='skip publicly accessible pull request URL check') parser.add_option('--check-url', dest='check_url', action='store_true', help='check pull request URLs are publicly accessible') parser.add_option('--edit', dest='edit', action='store_true', default=False, help='edit message but do not tag a new version') parser.add_option('--no-inspect-emails', dest='inspect_emails', action='store_false', help='no confirmation before sending emails') parser.add_option('--inspect-emails', dest='inspect_emails', action='store_true', default=True, help='show confirmation before sending emails') parser.add_option('-n', '--number', type='int', dest='number', default=-1, help='version number [auto-generated by default]') parser.add_option('--no-message', '--no-cover-letter', dest='message', action='store_false', help='do not add a message') parser.add_option('-m', '--message', '--cover-letter', dest='message', action='store_true', help='add a message') parser.add_option('--no-cover-info', dest='cover_info', action='store_false', default=True, help='do not append comments information when editing the cover letter') parser.add_option('--no-binary', dest='binary', action='store_false', default=True, help='Do not output contents of changes in binary files, instead display a notice that those files changed') parser.add_option('--profile', '-p', dest='profile_name', default='default', help='select default settings profile') parser.add_option('--pull-request', dest='pull_request', action='store_true', default=False, help='tag and send as a pull request') parser.add_option('--sign-pull', dest='sign_pull', action='store_true', help='sign tag when sending pull request') parser.add_option('-k', '--keyid', dest='keyid', help='use the given GPG key when signing pull request tag') parser.add_option('--no-sign-pull', dest='sign_pull', action='store_false', help='do not sign tag when sending pull request') parser.add_option('--subject-prefix', dest='prefix', default=None, help='set the email Subject: header prefix') parser.add_option('--clear-subject-prefix', dest='clear_prefix', action='store_true', default=False, help='clear the per-branch subject prefix') parser.add_option('--setup', dest='setup', action='store_true', default=False, help='add git alias in ~/.gitconfig') parser.add_option('-t', '--topic', dest='topic', help='topic name [defaults to current branch name]') parser.add_option('--to', dest='to', action='append', default=[], help='specify a primary email recipient') parser.add_option('-s', '--signoff', dest='signoff', action='store_true', default=False, help='add Signed-off-by: to commits when emailing') parser.add_option('--notes', dest='notes', action='store_true', default=False, help='Append the notes (see git-notes(1)) for the commit after the three-dash line.') parser.add_option('--suppress-cc', dest='suppress_cc', help='override auto-cc when sending email (man git-send-email for details)') parser.add_option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='show executed git commands (useful for troubleshooting)') parser.add_option('--forget-cc', dest='forget_cc', action='store_true', default=False, help='Forget all previous CC emails') parser.add_option('--override-to', dest='override_to', action='store_true', default=False, help='Ignore any profile or saved TO emails') parser.add_option('--override-cc', dest='override_cc', action='store_true', default=False, help='Ignore any profile or saved CC emails') parser.add_option('--in-reply-to', "-R", help='specify the In-Reply-To: of the cover letter (or the single patch)') parser.add_option('--add-header', '-H', action='append', dest='headers', help='specify custom headers to git-send-email') return parser.parse_args() def main(): global VERBOSE options, args = parse_args() VERBOSE = options.verbose # The --edit option is for editing the cover letter without publishing a # new revision. Therefore it doesn't make sense to combine it with options # that create new revisions. if options.edit and any((options.annotate, options.number != -1, options.setup, options.to, options.pull_request)): print('The --edit option cannot be used together with other options') return 1 # Keep this before any operations that call out to git(1) so that setup # works when the current working directory is outside a git repo. if options.setup: setup() return 0 if not check_profile_exists(options.profile_name): if options.profile_name == 'default': if has_profiles(): print('Using defaults when a non-default profile exists. Forgot to pass --profile ?') else: print('Profile "%s" does not exist, please check .gitpublish or git-config(1) files' % options.profile_name) return 1 current_branch = git_get_current_branch() if options.topic: topic = options.topic else: topic = current_branch base = options.base if not base: base = git_get_config('branch', current_branch, 'gitpublishbase') if not base: base = get_profile_var(options.profile_name, 'base') if not base: base = git_get_config('git-publish', 'base') if not base: base = 'master' if topic == base: print('Please use a topic branch, cannot version the base branch (%s)' % base) return 1 if options.number >= 0: number = options.number elif options.pull_request: number = 1 else: number = get_latest_tag_number(topic) + 1 to = set([to_text(_) for _ in options.to]) if not options.edit and not options.override_to: to = to.union(git_get_config_list('branch', topic, 'gitpublishto')) to = to.union(get_profile_var_list(options.profile_name, 'to')) if options.forget_cc: git_set_config('branch', topic, 'gitpublishcc', []) cc = set([to_text(_) for _ in options.cc]) if not options.edit and not options.override_cc: cc = cc.union(git_get_config_list('branch', topic, 'gitpublishcc')) cc = cc.union(get_profile_var_list(options.profile_name, 'cc')) cc_cmd = options.cc_cmd if not cc_cmd: cc_cmd = git_get_config('branch', topic, 'gitpublishcccmd') or \ get_profile_var(options.profile_name, 'cccmd') blurb_template = options.blurb_template if not blurb_template: blurb_template = '\n'.join(get_profile_var_list(options.profile_name, 'blurb-template')) if not blurb_template: blurb_template = "*** BLURB HERE ***" headers = options.headers if not headers: headers = [] if options.pull_request: remote = git_get_config('branch', topic, 'pushRemote') if remote is None: remote = git_get_config('remote', 'pushDefault') if remote is None: remote = git_get_config('branch', topic, 'remote') if remote is None or remote == '.': remote = get_profile_var(options.profile_name, 'remote') if remote is None: print('''Unable to determine remote repo to push. Please set git config branch.%s.pushRemote, branch.%s.remote, remote.pushDefault, or gitpublishprofile.%s.remote''' % (topic, topic, options.profile_name)) return 1 check_url = options.check_url if check_url is None: check_url_var = get_profile_var(options.profile_name, 'checkUrl') if check_url_var is None: check_url_var = git_get_config('git-publish', 'checkUrl') if check_url_var is not None: check_url = bool_from_str(check_url_var) if check_url is None: check_url = True url = git_get_remote_url(remote) if check_url and not any(url.startswith(scheme) for scheme in ('git://', 'http://', 'https://')): print('''Possible private URL "%s", normally pull requests reference publicly accessible git://, http://, or https:// URLs. Are you sure branch.%s.pushRemote is set appropriately? (Override with --no-url-check)''' % (url, topic)) return 1 sign_pull = options.sign_pull if sign_pull is None: sign_pull_var = get_profile_var(options.profile_name, 'signPull') if sign_pull_var is None: sign_pull_var = git_get_config('git-publish', 'signPull') if sign_pull_var is not None: sign_pull = bool_from_str(sign_pull_var) if sign_pull is None: sign_pull = True profile_message_var = get_profile_var(options.profile_name, 'message') if options.message is not None: message = options.message elif git_get_tag_message(tag_name_staging(topic)): # If there is a staged tag message, we definitely want a cover letter message = True elif profile_message_var is not None: message = bool_from_str(profile_message_var) elif options.pull_request: # Pull requests always get a cover letter by default message = True else: config_cover_letter = git_get_config('format', 'coverLetter') if config_cover_letter is None or config_cover_letter.lower() == 'auto': # If there are several commits we probably want a cover letter message = get_number_of_commits(base) > 1 else: message = bool_from_str(config_cover_letter) keyid = options.keyid if keyid is None: keyid_var = get_profile_var(options.profile_name, 'signingkey') if keyid_var is None: keyid_var = git_get_config('git-publish', 'signingkey') invoke_hook('pre-publish-tag', base) cl_info = [''] if options.cover_info: cl_info += git_cover_letter_info(base, topic, to, cc, options.in_reply_to, number) # Tag the tree if options.pull_request: tag_message = get_latest_tag_message(topic, ['Pull request']) tag_message += cl_info tag(tag_name_pull_request(topic), tag_message, annotate=message, force=True, sign=sign_pull, keyid=keyid) git_push(remote, tag_name_pull_request(topic), force=True) else: tag_message = get_latest_tag_message(topic, [ '*** SUBJECT HERE ***', '', blurb_template]) tag_message += cl_info anno = options.edit or message tag(tag_name_staging(topic), tag_message, annotate=anno, force=True) if options.clear_prefix: git_unset_config('branch', topic, 'gitpublishprefix') prefix = options.prefix if prefix is not None: git_set_config('branch', topic, 'gitpublishprefix', prefix) else: prefix = git_get_config('branch', topic, 'gitpublishprefix') if prefix is None: prefix = get_profile_var(options.profile_name, 'prefix') if prefix is None: if options.pull_request: prefix = 'PULL' else: prefix = git_get_config('format', 'subjectprefix') or 'PATCH' if number > 1: prefix = '%s v%d' % (prefix, number) if to: if options.pull_request: message = get_pull_request_message(base, remote, topic) else: message = git_get_tag_message(tag_name_staging(topic)) suppress_cc = options.suppress_cc if suppress_cc is None: suppress_cc = get_profile_var(options.profile_name, 'suppresscc') if options.signoff: signoff = True else: signoff = get_profile_var(options.profile_name, 'signoff') if options.inspect_emails: inspect_emails = True else: inspect_emails = get_profile_var(options.profile_name, 'inspect-emails') if options.notes: notes = True else: notes = get_profile_var(options.profile_name, 'notes') try: tmpdir = tempfile.mkdtemp() numbered = get_number_of_commits(base) > 1 or message git_format_patch(base + '..', subject_prefix=prefix, output_directory=tmpdir, numbered=numbered, cover_letter=message, signoff=signoff, notes=notes, binary=options.binary, headers=headers, extra_args=args) if message: cover_letter_path = os.path.join(tmpdir, '0000-cover-letter.patch') lines = open(cover_letter_path).readlines() lines = [s.replace('*** SUBJECT HERE ***', message[0]) for s in lines] blurb = os.linesep.join(message[2:]) lines = [s.replace('*** BLURB HERE ***', blurb) for s in lines] open(cover_letter_path, 'w').writelines(lines) patches = sorted(glob.glob(os.path.join(tmpdir, '*'))) if options.annotate: edit(*patches) if cc_cmd: for x in patches: output = subprocess.check_output(cc_cmd + " " + x, shell=True, cwd=git_get_toplevel_dir()).decode(ENCODING) cc = cc.union(output.splitlines()) cc.difference_update(to) if inspect_emails: selected_patches = inspect_menu(tmpdir, to, cc, patches, suppress_cc, options.in_reply_to, topic, options.override_cc) else: selected_patches = patches invoke_hook('pre-publish-send-email', tmpdir) final_patches = sorted(glob.glob(os.path.join(tmpdir, '*'))) if final_patches != patches: added = set(final_patches).difference(set(patches)) deleted = set(patches).difference(set(final_patches)) print("The list of files in %s changed and I don't know what to do" % tmpdir) if added: print('Added files: %s' % ' '.join(added)) if deleted: print('Deleted files: %s' % ' '.join(deleted)) return 1 git_send_email(to, cc, selected_patches, suppress_cc, options.in_reply_to) except (GitSendEmailError, GitHookError, InspectEmailsError): return 1 except GitError as e: print(e) return 1 finally: if tmpdir: shutil.rmtree(tmpdir) git_save_email_lists(topic, to, cc, options.override_cc) if not options.pull_request: # Publishing is done, stablize the tag now _git_check('tag', '-f', tag_name(topic, number), tag_name_staging(topic)) git_delete_tag(tag_name_staging(topic)) return 0 if __name__ == '__main__': sys.exit(main()) git-publish-1.6.0/git-publish.pod000066400000000000000000000405531360357322200167120ustar00rootroot00000000000000=encoding utf8 =head1 NAME git-publish - Prepare and store patch revisions as git tags =head1 SYNOPSIS git-publish [options] -- [common format-patch options] =head1 DESCRIPTION git-publish prepares patches and stores them as git tags for future reference. It works with individual patches as well as patch series. Revision numbering is handled automatically. No constraints are placed on git workflow, both vanilla git commands and custom workflow scripts are compatible with git-publish. Email sending and pull requests are fully integrated so that publishing patches can be done in a single command. Hook scripts are invoked during patch preparation so that custom checks or test runs can be automated. =head1 OPTIONS =over 4 =item B<--version> Show program's version number and exit. =item B<-h> =item B<--help> Show help message and exit. =item B<--annotate> Review and edit each patch email. =item B<-b BASE> =item B<--base=BASE> Branch which this is based off (defaults to master). =item B<--cc=CC> Specify a Cc: email recipient. =item B<--cc-cmd=CC_CMD> Specify a command add whose output to add the Cc: email recipient list. See L for details. =item B<--no-check-url> Do not check whether the pull request URL is publicly accessible. =item B<--check-url> Check whether the pull request URL is publicly accessible. This is the default. =item B<--edit> Edit message but do not tag a new version. Use this to draft the cover letter before actually tagging a new version. =item B<--no-inspect-emails> Do not prompt for confirmation before sending emails. =item B<--inspect-emails> Show confirmation before sending emails. =item B<-n NUMBER> =item B<--number=NUMBER> Explicitly specify the version number (auto-generated by default). =item B<--no-message> =item B<--no-cover-letter> Do not add a message. =item B<-m> =item B<--message> =item B<--cover-letter> Add a message. =item B<--no-binary> Do not output contents of changes in binary files, instead display a notice that those files changed. Patches generated using this option cannot be applied properly, but they are still useful for code review. =item B<-p PROFILE_NAME> =item B<--profile=PROFILE_NAME> Select default settings from the given profile. =item B<--pull-request> Tag and send as a pull request. =item B<--sign-pull> Sign tag when sending pull request. =item B<--no-sign-pull> Do not sign tag when sending pull request. =item B<-k KEYID> =item B<--keyid=KEYID> Use the given GPG key to sign tag when sending pull request =item B<--blurb-template> Use a pre-defined blurb message for the series HEAD. =item B<--subject-prefix=PREFIX> Set the email Subject: header prefix. =item B<--clear-subject-prefix> Clear the per-branch subject prefix. The subject prefix persists between versions by default. Use this option to reset it. =item B<--setup> Add git alias in ~/.gitconfig so that the "git publish" git sub-command works. =item B<-t TOPIC> =item B<--topic=TOPIC> Set the topic name (defaults to current branch name). =item B<--to=TO> Specify a primary email recipient. =item B<-s> =item B<--signoff> Add Signed-off-by: to commits when emailing. =item B<--notes> Append the notes for the commit after the three-dash line. See L for details. =item B<--suppress-cc=SUPPRESS_CC> Override auto-cc when sending email. See L for details. =item B<-v> =item B<--verbose> Show executed git commands (useful for troubleshooting). =item B<--forget-cc> Forget all previous Cc: email addresses. =item B<--override-to> Ignore any profile or saved To: email addresses. =item B<--override-cc> Ignore any profile or saved Cc: email addresses. =item B<-R IN_REPLY_TO> =item B<--in-reply-to=IN_REPLY_TO> Specify the In-Reply-To: of the cover letter (or the single patch). =back =head1 DISCUSSION =head2 Setup Run git-publish in setup mode to configure the git alias: $ git-publish --setup You can now use 'git publish' like a built-in git command. =head2 Quickstart Create a "topic branch" on which to do your work (implement a new feature or fix a bug): $ git checkout -b add-funny-jokes ... $ git commit ... $ git commit Send a patch series via email: $ git publish --to patches@example.org --cc maintainer@example.org Address code review comments and send a new revision: $ git rebase -i master ... $ git publish --to patches@example.org --cc maintainer@example.org Refer back to older revisions: $ git show add-funny-jokes-v1 This concludes the basic workflow for sending patch series. =head2 Storing patch revisions To store the first revision of a patch series: $ git checkout my-feature $ git publish This creates the my-feature-v1 git tag. Running git-publish again at a later point will create tags with incrementing version numbers: my-feature-v1 my-feature-v2 my-feature-v3 ... To refer back to a previous version, simply check out that git tag. This way a record is kept of each patch revision that has been published. =head3 Overriding the version number The version number can be set manually. This is handy when starting out with git-publish on branches that were previously manually versioned: $ git checkout my-existing-feature $ git publish --number 7 This creates the my-existing-feature-v7 tag. =head3 Overriding the branch name By default git-publish refuses to create a revision for the 'master' branch. Usually one works with so-called topic branches, one branch for each feature under development. Using the 'master' branch may indicate that one has forgotten to switch onto the intended topic branch. It is possible to override the topic name and even publish on 'master': $ git checkout branch-a $ git publish --topic branch-b This creates branch-b-v1 instead of branch-a-v1 and can be used to skip the check for 'master'. =head2 Tag messages Tag messages have a summary (or subject line) and a description (or blurb). When send email integration is used the summary is put into the cover letter Subject: line while the description is put into the body. When prompting for tag messages on v2, v3, or other incremental revisions, the previous revision's tag message is used as the starting point. This is handy for updating the existing description and keeping a changelog of the difference between revisions. The L format.coverLetter value is honored. The default 'auto' value adds a cover letter if there is more than 1 patch. The cover letter can also be forced with 'true' or 'false'. To insist on creating a tag message: $ git publish --message To refrain from creating a tag message: $ git publish --no-message For convenience these options are also available as --cover-letter and --no-cover-letter just like in L. =head3 Editing tag messages without publishing Sometimes it is useful to edit the tag message before publishing. This can be used to note down changelog entries as you prepare the next version of a patch series. To edit the tag message without publishing: $ git publish --edit This does not tag a new version. Instead a -staging tag will be created and the tag message will be picked up when you publish next time. For example, if you on branch my-feature and have already published v1 and v2, editing the tag message will create the tag my-feature-staging. When you publish next time the my-feature-v3 tag will be created and use the tag message you staged earlier. =head2 Setting the base branch git-publish detects whether the branch contains a single commit or multiple commits by comparing against a base branch ('master' by default). You can specify the base branch like this: $ git publish --base my-parent Most of the time 'master' works fine. It is also possible to persist which base branch to use. This is useful if you find yourself often specifying a base branch manually. It can be done globally for all branches in a reposity or just for a specific branch: $ git config git-publish.base origin/master # for all branches $ git config branch.foo.gitpublishbase origin/master # for one branch =head2 Send email integration git-publish can call L after creating a git tag. If there is a tag message it will be used as the cover letter. Email can be sent like this: $ git publish --to patches@example.org \ --cc alex@example.org --cc bob@example.org After the git tag has been created as usual, commits on top of the base branch are sent as the patch series. The base branch defaults to 'master' and can be set manually with --base. The L aliasesfile feature works since the email addresses are passed through without interpretation by git-publish. Patch emails can be manually edited before being sent, these changes only affect outgoing emails and are not stored permanently: $ git publish --to patches@example.org --annotate git-publish can background itself so patch emails can be inspected from the shell: $ git publish --to patches@example.org --inspect-emails Signed-off-by: lines can be applied to patch emails, only outgoing emails are affected and not the local git commits: $ git publish --to patches@example.org --signoff Sending [RFC] series instead of regular [PATCH] series can be done by customizing the Subject: line: $ git publish --to patches@example.org --subject-prefix RFC Using this way, specified "--subject-prefix" will be stored as per-branch subject prefix, and will be used for the next git-publish as well. One can override the stored per-branch subject prefix by providing the --subject-prefix parameter again, or to clear it permanently, we can use: $ git publish --clear-subject-prefix git-publish remembers the list of addresses CC'd on previous revisions of a patchset by default. To clear that internal list: $ git publish --to patches@example.org --forget-cc --cc new@example.org In the above example, new@example.org will be saved to the internal list for next time. CC addresses accumulate and cascade. Following the previous example, if we want to send a new version to both new@example.org and old@example.org: $ git-publish --cc old@example.org To temporarily ignore any CCs in the profile or saved list, and send only to the addresses specified on the CLI: $ git-publish --override-cc --cc onetime@example.org --to patches@example.org CCs specified alongside --override-cc are not remembered for future revisions. $ git publish --to patches@example.org --notes To include git-notes into a patch. One can attach notes to a commit with `git notes add `. For having the notes "following" a commit on rebase operation, you can use `git config notes.rewriteRef refs/notes/commits`. For more information, give a look at L. =head2 Creating profiles for frequently used projects Instead of providing command-line options each time a patch series is published, the options can be stored in L files: $ cat >>.git/config [gitpublishprofile "example"] prefix = PATCH for-example to = patches@example.org cc = maintainer1@example.org cc = maintainer2@example.org ^D $ git checkout first-feature $ git publish --profile example $ git checkout second-feature $ git publish --profile example The "example" profile is equivalent to the following command-line: $ git publish --subject-prefix 'PATCH for-example' --to patches@example.org --cc maintainer1@example.org --cc maintainer2@example.org If command-line options are given together with a profile, then the command-line options take precedence. The following profile options are available: [gitpublishprofile "example"] base = v2.1.0 # same as --base remote = origin # used if branch..remote not set prefix = PATCH # same as --patch to = patches@example.org # same as --to cc = maintainer@example.org # same as --cc suppresscc = all # same as --suppress-cc message = true # same as --message signoff = true # same as --signoff inspect-emails = true # same as --inspect-emails notes = true # same as --notes blurb-template = A blurb template # same as --blurb-template The special "default" profile name is active when no --profile command-line option was given. The default profile does not set any options but can be extended in L files: $ cat >>.git/config [gitpublishprofile "default"] suppresscc = all # do not auto-cc people If a file named .gitpublish exists in the repository top-level directory, it is automatically searched in addition to the L .git/config and ~/.gitconfig files. Since the .gitpublish file can be committed into git, this can be used to provide a default profile for branches that you expect to repeatedly use as a base for new work. =head2 Sending pull requests git-publish can send signed pull requests. Signed tags are pushed to a remote git repository that must be readable by the person who will merge the pull request. Ensure that the branch has a default remote repository saved: $ git config branch.foo.remote my-public-repo The remote must be accessible to the person receiving the pull request. Normally the remote URI should be git:// or https://. If the remote is configured for ssh:// then L can be supplemented with a public url and private pushurl. This ensures that pull requests always use the public URI: [remote ""] url = https://myhost.com/repo.git pushurl = me@myhost.com:repo.git Send a pull request: $ git publish --pull-request --to patches@example.org --annotate =head1 CONFIGURATION There are three possible levels of configuration with the following order of precedence: =over 4 =item 1. Per-branch options only apply to a specific branch. =item 2. Per-profile options apply when the profile is enabled with B<--profile>. =item 3. Global options apply in all cases. =back The following configuration options are available: =over 4 =item B =item B =item B Same as the B<--base> option. =item B =item B Same as the B<--to> option. =item B =item B Same as the B<--cc> option. =item B =item B Same as the B<--cc-cmd> option. =item B The remote where the pull request tag will be pushed. =item B Same as the B<--message> option. =item B =item B Same as the B<--subject-prefix> option. =item B Same as the B<--suppress-cc> option. =item B Same as the B<--signoff> option. =item B Same as the B<--inspect-emails> option. =item B Same as the B<--notes> option. =item B =item B Same as the B<--no-check-url> and B<--check-url> options. =item B =item B Same as the B<--no-sign-pull> and B<--sign-pull> options. =item B Same as the B<--keyid> option. =back =head1 HOOKS git-publish supports the L mechanism for running user scripts at important points during the workflow. The script can influence the outcome of the operation, for example, by rejecting a patch series that is about to be sent out. Available hooks include: =over 4 =item B Invoked before L. Takes the path to the patches directory as an argument. If the exit code is non-zero, the series will not be sent. =item B Invoked before creating the -staging tag on current branch. Takes one argument which refers to the base commit or branch. If the exit code is non-zero, git-publish will abort. =back =head1 SEE ALSO L, L, L, L, L =head1 AUTHOR Stefan Hajnoczi L =head1 COPYRIGHT Copyright (C) 2011-2018 Stefan Hajnoczi git-publish-1.6.0/hooks/000077500000000000000000000000001360357322200150735ustar00rootroot00000000000000git-publish-1.6.0/hooks/pre-publish-send-email.example000077500000000000000000000014311360357322200227200ustar00rootroot00000000000000#!/bin/bash # Check RHEL downstream patch format # # Copyright (c) 2014 Red Hat, Inc. # # This work is licensed under the MIT License. Please see the LICENSE file or # http://opensource.org/licenses/MIT. set -e [ ! -d redhat/ ] && exit 0 patch_dir=$1 fail() { echo "Error: $@" exit 1 } check() { regexp=$1 errmsg=$2 if ! grep -q "$regexp" $(ls "$patch_dir"/*.patch | head -n1); then fail "$errmsg" fi } check '^Subject: \[.*RH.*\]' 'missing RHEL/RHEV/RHV tag in Subject: line' check '^Subject: \[.*qemu-kvm.*\]' 'missing qemu-kvm/qemu-kvm-rhev tag in Subject: line' check '^\(Bugzilla\|BZ\): ' 'missing Bugzilla: header in cover letter' check '^\(Brew\|BREW\): ' 'missing Brew: header in cover letter' check '^\(Upstream\|UPSTREAM\): ' 'missing Upstream: header in cover letter' git-publish-1.6.0/testing/000077500000000000000000000000001360357322200154255ustar00rootroot00000000000000git-publish-1.6.0/testing/0000-fake_git-sanity-check.sh000077500000000000000000000020301360357322200224650ustar00rootroot00000000000000#!/bin/bash # fake_git sanity checks # # Copyright 2019 Red Hat, Inc. # # Authors: # Eduardo Habkost # # This work is licensed under the MIT License. Please see the LICENSE file or # http://opensource.org/licenses/MIT. source "$TESTS_DIR/functions.sh" # ensure fake_git is refusing to run git-send-email without --dry-run: if git send-email --quiet --to somebody@example.com HEAD^..HEAD;then abort "fake_git send-email without '--dry-run' was supposed to fail" fi grep -q 'send-email --quiet --to somebody@example.com' "$FAKE_GIT_COMMAND_LOG" || \ abort "fake_git didn't log send-email command" # --dry-run must succeed, though: if ! git send-email --dry-run --to somebody@example.com HEAD^..HEAD > /dev/null;then abort "git send-email --dry-run failed" fi # ensure simple git-publish usage is actually using fake_git: rm -f "$FAKE_GIT_COMMAND_LOG" echo q | git-publish -b HEAD^ --to somebody@example.com --inspect-emails || : [ -s "$FAKE_GIT_COMMAND_LOG" ] || \ abort "git-publish didn't run fake_git" git-publish-1.6.0/testing/0000-gitconfig-home000077500000000000000000000014071360357322200206310ustar00rootroot00000000000000#!/bin/bash # ensure git-config $HOME override is working as expected # # Copyright 2019 Red Hat, Inc. # # Authors: # Eduardo Habkost # # This work is licensed under the MIT License. Please see the LICENSE file or # http://opensource.org/licenses/MIT. source "$TESTS_DIR/functions.sh" assert [ "$HOME" = "$RESULTS_DIR/home" ] cat >> "$HOME/.gitconfig" < # # This work is licensed under the MIT License. Please see the LICENSE file or # http://opensource.org/licenses/MIT. from test_utils import * # note that 'git config' is not in the passthrough list of fake_git, # so this is safe to run: git_publish('--setup') assert last_git_command() == ['config', '--global', 'alias.publish', '!' + git_publish_path()] git-publish-1.6.0/testing/0002-no-cover-letter000077500000000000000000000012721360357322200207610ustar00rootroot00000000000000#!/usr/bin/env python3 # # Ensure --no-cover-letter won't generate a cover letter # # Copyright 2019 Red Hat, Inc. # # Authors: # Eduardo Habkost # # This work is licensed under the MIT License. Please see the LICENSE file or # http://opensource.org/licenses/MIT. from test_utils import * git_publish('-b HEAD^ --no-cover-letter --no-inspect-emails ' \ '--to somebody@example.com') last = last_git_command() assert last[:5] == ['send-email', '--to', 'somebody@example.com', '--quiet', '--confirm=never'], \ "Unexpected command run by git-publish" assert len(last[5:]) == 1, \ "Only one file should be passed to git-send-email" git-publish-1.6.0/testing/0003-config-ordering000077500000000000000000000033051360357322200210100ustar00rootroot00000000000000#!/bin/bash # Ensure configuration file precedence is correct # # Copyright 2019 Red Hat, Inc. # # Authors: # Eduardo Habkost # # This work is licensed under the MIT License. Please see the LICENSE file or # http://opensource.org/licenses/MIT. source "$TESTS_DIR/functions.sh" out="$TEST_DIR/git-publish.stdout" git config --global gitpublishprofile.global1.prefix GLOBAL1 git config --global gitpublishprofile.global2.prefix GLOBAL2 git config --global gitpublishprofile.default.prefix GLOBALDEFAULT rm -f "$FAKE_GIT_COMMAND_LOG" git-publish --no-inspect-emails --to somebody@example.com -b HEAD^ \ 2>> "$TEST_DIR/stderr.log" || : grep -q -- '--subject-prefix GLOBALDEFAULT' "$FAKE_GIT_COMMAND_LOG" || \ abort "Global default profile prefix was ignored" git config --file .gitpublish gitpublishprofile.project1.prefix PROJECT1 git config --file .gitpublish gitpublishprofile.project2.prefix PROJECT2 git config --file .gitpublish gitpublishprofile.default.prefix PROJECTDEFAULT rm -f "$FAKE_GIT_COMMAND_LOG" git-publish --no-inspect-emails --to somebody@example.com -b HEAD^ \ 2>> "$TEST_DIR/stderr.log" || : grep -q -- '--subject-prefix PROJECTDEFAULT' "$FAKE_GIT_COMMAND_LOG" || \ abort "Project-defined default profile prefix was ignored" git config --local gitpublishprofile.local1.prefix LOCAL1 git config --local gitpublishprofile.local2.prefix LOCAL2 git config --local gitpublishprofile.default.prefix LOCALDEFAULT rm -f "$FAKE_GIT_COMMAND_LOG" git-publish --no-inspect-emails --to somebody@example.com -b HEAD^ \ 2>> "$TEST_DIR/stderr.log" || : grep -q -- '--subject-prefix LOCALDEFAULT' "$FAKE_GIT_COMMAND_LOG" || \ abort "Local default profile prefix was ignored" git-publish-1.6.0/testing/0004-edit-tag000077500000000000000000000020311360357322200174260ustar00rootroot00000000000000#!/bin/bash source "$TESTS_DIR/functions.sh" msgfile="$TEST_DIR/message" cat >"$msgfile" <"$msgfile" <"$msgfile" < # # This work is licensed under the MIT License. Please see the LICENSE file or # http://opensource.org/licenses/MIT. """ fake_git - fake git command that should be used by git-publish when running test cases The following environment variables must be set: - $REAL_GIT - path to real git binary - $FAKE_GIT_LOG - path to human-readable debugging log - $FAKE_GIT_COMMAND_LOG - path to machine-readable command log """ import sys import os import logging import shlex logger = logging.getLogger('fakegit') dbg = logger.debug def escape_command(command): return ' '.join(shlex.quote(a) for a in command) def run_real_git(args): global REAL_GIT dbg("Running real git: %r", args) os.execl(REAL_GIT, 'git', *args) def run_send_email(args): if '--dry-run' not in args: logger.error("git send-email not run using --dry-run") sys.exit(1) run_real_git(args) # harmless commands that can be always run: # NOTE: git-config is only safe because the test runner overrides $HOME, so # we will never touch the real ~/.gitconfig. See the 0000-gitconfig-home # test case PASSTHROUGH_COMMANDS = ['tag', 'rev-parse', 'symbolic-ref', 'format-patch', 'config', 'checkout', 'var'] # special commands that require some validation: SPECIAL_COMMANDS = { 'send-email': run_send_email, } if len(sys.argv) < 2: sys.exit(1) REAL_GIT = os.getenv("REAL_GIT") if not REAL_GIT: print("$REAL_GIT not set", file=sys.stderr) sys.exit(1) if not os.access(REAL_GIT, os.X_OK): print("$REAL_GIT not executable", file=sys.stderr) sys.exit(1) # debugging log: log_file = os.getenv("FAKE_GIT_LOG") if not log_file: print("$FAKE_GIT_LOG not set", file=sys.stderr) sys.exit(1) logging.basicConfig(filename=log_file, level=logging.DEBUG) # warning and errors also go to stderr: err_handler = logging.StreamHandler() err_handler.setLevel(logging.WARN) logging.getLogger('').addHandler(err_handler) # command log: command_log = os.getenv("FAKE_GIT_COMMAND_LOG") if not command_log: print("$FAKE_GIT_COMMAND_LOG not set", file=sys.stderr) sys.exit(1) args = sys.argv[1:] logger.info("Command: %r", args) with open(command_log, 'a') as f: f.write('%s\n' % (escape_command(args))) if args[0] in PASSTHROUGH_COMMANDS: run_real_git(args) elif args[0] in SPECIAL_COMMANDS: SPECIAL_COMMANDS[args[0]](args) else: logger.error("command not allowed: %r", args) sys.exit(1) git-publish-1.6.0/testing/functions.sh000066400000000000000000000012051360357322200177670ustar00rootroot00000000000000# Utility functions for test case shell scripts # # Copyright 2019 Red Hat, Inc. # # Authors: # Eduardo Habkost # # This work is licensed under the MIT License. Please see the LICENSE file or # http://opensource.org/licenses/MIT. tail_fake_git_log() { if [ -r "$FAKE_GIT_LOG" ];then echo "---- last 5 lines of fake_git log: ----" >&2 tail -n 5 "$FAKE_GIT_LOG" >&2 echo "---- end of fake_git log ----" >&2 fi } abort() { echo "TEST FAILURE: $@" >&2 exit 1 } assert() { "$@" || abort "Assertion failed: $@" } assert_false() { ! "$@" || abort "Assertion failed: ! $@" } git-publish-1.6.0/testing/run_tests.sh000077500000000000000000000053251360357322200200170ustar00rootroot00000000000000#!/bin/bash # Automated test cases for git-publish # # Copyright 2019 Red Hat, Inc. # # Authors: # Eduardo Habkost # # This work is licensed under the MIT License. Please see the LICENSE file or # http://opensource.org/licenses/MIT. set -e export TESTS_DIR="$(realpath "$(dirname "$0")")" export RESULTS_DIR="$(mktemp -d)" GIT_PUBLISH="$1" if [ -z "$GIT_PUBLISH" ];then GIT_PUBLISH="$TESTS_DIR/../git-publish" fi export GIT_PUBLISH="$(realpath "$GIT_PUBLISH")" source "$TESTS_DIR/functions.sh" setup_path() { export REAL_GIT="$(which git)" export PATH="$RESULTS_DIR/bin:$PATH" export PYTHONPATH="$TESTS_DIR:$PYTHONPATH" # Place fake git on $PATH to ensure we will never run real git commands by accident: mkdir -p "$RESULTS_DIR/bin" fake_git="$RESULTS_DIR/bin/git" cp "$TESTS_DIR/fake_git" "$RESULTS_DIR/bin/git" # Make sure our fake git command will appear first assert [ "$(which git)" = "$fake_git" ] ln -s "$GIT_PUBLISH" "$RESULTS_DIR/bin/git-publish" # make sure `git-publish` command will run our copy: assert [ "$(which git-publish)" = "$RESULTS_DIR/bin/git-publish" ] } # Create fake git repository for testing create_git_repo() { git init -q cat > A < B <> B git add B git commit -q -m 'Second commit' } run_test_case() { local test_case="$1" local test_name="$(basename "$test_case")" export TEST_DIR="$RESULTS_DIR/$test_name" mkdir -p "$TEST_DIR" export FAKE_GIT_LOG="$TEST_DIR/fake_git.log" export FAKE_GIT_COMMAND_LOG="$TEST_DIR/fake_git_commands.log" echo -n "Running test case $test_name: " if ! "$test_case" > "$TEST_DIR/test_output.log" 2>&1;then echo FAILED echo "--- Last 10 lines of test output: ---" tail -n 10 "$TEST_DIR/test_output.log" echo "-------------------------------------" echo "Other log files are available at $TEST_DIR" >&2 exit 1 fi echo OK } # override $HOME so that git-config will never read/write ~/.gitconfig mkdir "$RESULTS_DIR/home" export HOME="$RESULTS_DIR/home" SOURCE_DIR="$RESULTS_DIR/source" mkdir "$SOURCE_DIR" cd "$SOURCE_DIR" # set fake user name and email to make git happy if system values are not set cat >> "$RESULTS_DIR/home/.gitconfig" < # # This work is licensed under the MIT License. Please see the LICENSE file or # http://opensource.org/licenses/MIT. import os import shlex import subprocess from subprocess import DEVNULL, PIPE, STDOUT def open_test_log(name='test.log', mode='a'): """Open test log file. Defaults to append mode""" return open(os.path.join(os.getenv('TEST_DIR'), name), mode) def git_command_log(): with open(os.getenv('FAKE_GIT_COMMAND_LOG'), 'r') as f: return [shlex.split(l) for l in f.readlines()] def last_git_command(): return git_command_log()[-1] def git_publish_path(): return os.getenv('GIT_PUBLISH') def git_publish(args, **kwargs): """Helper to run git-publish using subprocess.run()""" if isinstance(args, str): args = shlex.split(args) return subprocess.run([git_publish_path()] + args, **kwargs)