def test_scan_for_server_reviewboardrc(self): """Testing MercurialClient.scan_for_server when in .reviewboardrc""" with self.reviewboardrc({'REVIEWBOARD_URL': self.TESTSERVER}): self.client.config = load_config() ri = self.client.get_repository_info() self.assertEqual(self.client.scan_for_server(ri), self.TESTSERVER)
def run_from_argv(self, argv): """Execute the command using the provided arguments. The options and commandline arguments will be parsed from ``argv`` and the commands ``main`` method will be called. """ self.config = load_config() parser = self.create_parser(self.config) options, args = parser.parse_args(argv[2:]) self.options = options # Check that the proper number of arguments have been provided. argspec = inspect.getargspec(self.main) minargs = len(argspec[0]) - 1 maxargs = minargs if argspec[1] is not None: maxargs = None if len(args) < minargs or (maxargs is not None and len(args) > maxargs): parser.error("Invalid number of arguments provided") sys.exit(1) self.main(*args)
def run_from_argv(self, argv): """Execute the command using the provided arguments. The options and commandline arguments will be parsed from ``argv`` and the commands ``main`` method will be called. """ self.config = load_config() parser = self.create_parser(self.config, argv) parser.add_argument('args', nargs=argparse.REMAINDER) self.options = parser.parse_args(argv[2:]) args = self.options.args # Check that the proper number of arguments have been provided. argspec = inspect.getargspec(self.main) minargs = len(argspec[0]) - 1 maxargs = minargs # Arguments that have a default value are considered optional. if argspec[3] is not None: minargs -= len(argspec[3]) if argspec[1] is not None: maxargs = None if len(args) < minargs or (maxargs is not None and len(args) > maxargs): parser.error('Invalid number of arguments provided') sys.exit(1) self.init_logging() logging.debug('Command line: %s', subprocess.list2cmdline(argv)) try: exit_code = self.main(*args) or 0 except CommandError as e: if isinstance(e, ParseError): parser.error(e) elif self.options.debug: raise logging.error(e) exit_code = 1 except CommandExit as e: exit_code = e.exit_code except Exception as e: # If debugging is on, we'll let python spit out the # stack trace and report the exception, otherwise # we'll suppress the trace and print the exception # manually. if self.options.debug: raise logging.critical(e) exit_code = 1 cleanup_tempfiles() sys.exit(exit_code)
def run_from_argv(self, argv): """Execute the command using the provided arguments. The options and commandline arguments will be parsed from ``argv`` and the commands ``main`` method will be called. """ self.config = load_config() parser = self.create_parser(self.config, argv) parser.add_argument('args', nargs=argparse.REMAINDER) self.options = parser.parse_args(argv[2:]) args = self.options.args # Check that the proper number of arguments have been provided. argspec = inspect.getargspec(self.main) minargs = len(argspec[0]) - 1 maxargs = minargs # Arguments that have a default value are considered optional. if argspec[3] is not None: minargs -= len(argspec[3]) if argspec[1] is not None: maxargs = None if len(args) < minargs or (maxargs is not None and len(args) > maxargs): parser.error('Invalid number of arguments provided') sys.exit(1) self.init_logging() try: exit_code = self.main(*args) or 0 except CommandError as e: if isinstance(e, ParseError): parser.error(e) elif self.options.debug: raise logging.error(e) exit_code = 1 except CommandExit as e: exit_code = e.exit_code except Exception as e: # If debugging is on, we'll let python spit out the # stack trace and report the exception, otherwise # we'll suppress the trace and print the exception # manually. if self.options.debug: raise logging.critical(e) exit_code = 1 cleanup_tempfiles() sys.exit(exit_code)
def test_scan_for_server_reviewboardrc(self): """Testing MercurialClient scan_for_server when in .reviewboardrc""" with self.reviewboardrc({'REVIEWBOARD_URL': self.TESTSERVER}): self.client.config = load_config() ri = self.client.get_repository_info() server = self.client.scan_for_server(ri) self.assertEqual(self.TESTSERVER, server)
def test_scan_for_server_reviewboardrc(self): """Testing MercurialClient scan_for_server when in .reviewboardrc""" rc = open(os.path.join(self.clone_dir, '.reviewboardrc'), 'w') rc.write('REVIEWBOARD_URL = "%s"' % self.TESTSERVER) rc.close() self.client.config = load_config() ri = self.client.get_repository_info() server = self.client.scan_for_server(ri) self.assertEqual(self.TESTSERVER, server)
def test_scan_for_server_with_reviewboardrc(self): """Testing MercurialClient.scan_for_server with SVN and configured .reviewboardrc """ with self.reviewboardrc({'REVIEWBOARD_URL': 'https://example.com/'}): self.client.config = load_config() ri = self.client.get_repository_info() self.assertEqual(self.client.scan_for_server(ri), 'https://example.com/')
def create_arg_parser(self, argv): """Create and return the argument parser. Args: argv (list of unicode): A list of command line arguments Returns: argparse.ArgumentParser: Argument parser for commandline arguments """ self.config = load_config() parser = self.create_parser(self.config, argv) parser.add_argument('args', nargs=argparse.REMAINDER) return parser
def main(self, pull_request_id): repository_info, tool = self.initialize_scm_tool() configs = [load_config()] if self.options.owner is None: self.options.owner = get_config_value(configs, "GITHUB_OWNER", None) if self.options.repo is None: self.options.repo = get_config_value(configs, "GITHUB_REPO", None) if self.options.owner is None or self.options.repo is None: raise CommandError("No GITHUB_REPO or GITHUB_OWNER has been configured.") diff = self.get_patch(pull_request_id) if self.options.patch_stdout: print diff else: try: if tool.has_pending_changes(): message = "Working directory is not clean." if not self.options.commit: print "Warning: %s" % message else: raise CommandError(message) except NotImplementedError: pass tmp_patch_file = make_tempfile(diff) self.apply_patch(repository_info, tool, pull_request_id, tmp_patch_file) if self.options.commit: message = self.generate_commit_message(pull_request_id) author = self.get_author_from_patch(tmp_patch_file) try: tool.create_commit(message, author) print ("Changes committed to current branch.") except NotImplementedError: raise CommandError("--commit is not supported with %s" % tool.name)
def run_from_argv(self, argv): """Execute the command using the provided arguments. The options and commandline arguments will be parsed from ``argv`` and the commands ``main`` method will be called. """ self.config = load_config() parser = self.create_parser(self.config) options, args = parser.parse_args(argv[2:]) self.options = options # Check that the proper number of arguments have been provided. argspec = inspect.getargspec(self.main) minargs = len(argspec[0]) - 1 maxargs = minargs if argspec[1] is not None: maxargs = None if len(args) < minargs or (maxargs is not None and len(args) > maxargs): parser.error("Invalid number of arguments provided") sys.exit(1) if self.options.debug: logging.getLogger().setLevel(logging.DEBUG) try: exit_code = self.main(*args) or 0 except Exception, e: # If debugging is on, we'll let python spit out the # stack trace and report the exception, otherwise # we'll suppress the trace and print the exception # manually. if self.options.debug: raise logging.critical(e) exit_code = 1
def run_from_argv(self, argv): """Execute the command using the provided arguments. The options and commandline arguments will be parsed from ``argv`` and the commands ``main`` method will be called. """ self.config = load_config() parser = self.create_parser(self.config, argv) parser.add_argument('args', nargs=argparse.REMAINDER) self.options = parser.parse_args(argv[2:]) args = self.options.args # Check that the proper number of arguments have been provided. argspec = inspect.getargspec(self.main) minargs = len(argspec[0]) - 1 maxargs = minargs if argspec[1] is not None: maxargs = None if len(args) < minargs or (maxargs is not None and len(args) > maxargs): parser.error("Invalid number of arguments provided") sys.exit(1) self.init_logging() try: exit_code = self.main(*args) or 0 except CommandError, e: if isinstance(e, ParseError): parser.error(e) elif self.options.debug: raise logging.error(e) exit_code = 1
def help(args, parser): if args: # TODO: First check for static help text file before # generating it at run time. ep = find_entry_point_for_command(args[0]) if ep: help_text = build_help_text(ep.load()) print(help_text) sys.exit(0) else: try: returncode = subprocess.call( ['%s-%s' % (RB_MAIN, args[0]), '--help'], stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr, env=os.environ.copy()) sys.exit(returncode) except OSError: # OSError is only raised in this scenario when subprocess.call # cannot find an executable with the name rbt-<command_name>. # If this command doesn't exist, we will check if an alias # exists with the name before printing an error message. pass aliases = load_config().get('ALIASES', {}) if args[0] in aliases: if aliases[args[0]].startswith('!'): print('"%s" is an alias for the shell command "%s"' % (args[0], aliases[args[0]][1:])) else: print('"%s" is an alias for the command "%s %s"' % (args[0], RB_MAIN, aliases[args[0]])) sys.exit(0) print('No help found for %s' % args[0]) sys.exit(0) parser.print_help() # We cast to a set to de-dupe the list, since third-parties may # try to override commands by using the same name, and then cast # back to a list for easy sorting. entrypoints = pkg_resources.iter_entry_points('rbtools_commands') commands = {entrypoint.name for entrypoint in entrypoints} for path_dir in os.environ.get('PATH').split(':'): path_prefix = '%s/%s-' % (path_dir, RB_MAIN) for cmd in glob.glob(path_prefix + '*'): commands.add(cmd.replace(path_prefix, '')) aliases = load_config().get('ALIASES', {}) commands |= set(aliases.keys()) common_commands = ['post', 'patch', 'close', 'diff'] other_commands = commands - set(common_commands) print('\nThe most commonly used commands are:') for command in common_commands: print(' %s' % command) print('\nOther commands:') for command in sorted(other_commands): print(' %s' % command) print('See "%s help <command>" for more information on a specific ' 'command.' % RB_MAIN) sys.exit(0)
def main(): """Execute a command.""" def exit_on_int(sig, frame): sys.exit(128 + sig) signal.signal(signal.SIGINT, exit_on_int) parser = argparse.ArgumentParser( prog=RB_MAIN, usage='%(prog)s [--version] <command> [options] [<args>]', add_help=False) for option in GLOBAL_OPTIONS: option.add_to(parser) opt = parser.parse_args() if not opt.command: help([], parser) command_name = opt.command[0] args = opt.command[1:] if command_name == 'help': help(args, parser) elif opt.help or '--help' in args[:2] or '-h' in args[:2]: help(opt.command, parser) ep = find_entry_point_for_command(command_name) if ep: try: command = ep.load()() except ImportError: # TODO: It might be useful to actual have the stack # trace here, due to an import somewhere down the import # chain failing. sys.stderr.write('Could not load command entry point %s\n' % ep.name) sys.exit(1) except Exception as e: sys.stderr.write('Unexpected error loading command %s: %s\n' % (ep.name, e)) sys.exit(1) command.run_from_argv([RB_MAIN, command_name] + args) else: # A command class could not be found, so try and execute # the "rb-<command>" on the system. try: sys.exit( subprocess.call(['%s-%s' % (RB_MAIN, command_name)] + args, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr, env=os.environ.copy())) except OSError: # OSError is only raised in this scenario when subprocess.call # cannot find an executable with the name rbt-<command_name>. If # this command doesn't exist, we will check if an alias exists # with the name before printing an error message. pass aliases = load_config().get('ALIASES', {}) if command_name in aliases: sys.exit(run_alias(aliases[command_name], args)) else: parser.error('"%s" is not a command' % command_name)
def main(): """Execute a command.""" def exit_on_int(sig, frame): sys.exit(128 + sig) signal.signal(signal.SIGINT, exit_on_int) parser = argparse.ArgumentParser( prog=RB_MAIN, usage='%(prog)s [--version] <command> [options] [<args>]', add_help=False) for option in GLOBAL_OPTIONS: option.add_to(parser) opt = parser.parse_args() if not opt.command: help([], parser) command_name = opt.command[0] args = opt.command[1:] if command_name == 'help': help(args, parser) elif opt.help or '--help' in args or '-h' in args: help(opt.command, parser) # Attempt to retrieve the command class from the entry points. We # first look in rbtools for the commands, and failing that, we look # for third-party commands. ep = pkg_resources.get_entry_info('rbtools', 'rbtools_commands', command_name) if not ep: try: ep = next( pkg_resources.iter_entry_points('rbtools_commands', command_name)) except StopIteration: # There aren't any custom entry points defined. pass if ep: try: command = ep.load()() except ImportError: # TODO: It might be useful to actual have the strack # trace here, due to an import somewhere down the import # chain failing. sys.stderr.write('Could not load command entry point %s\n' % ep.name) sys.exit(1) except Exception as e: sys.stderr.write('Unexpected error loading command %s: %s\n' % (ep.name, e)) sys.exit(1) command.run_from_argv([RB_MAIN, command_name] + args) else: # A command class could not be found, so try and execute # the "rb-<command>" on the system. try: sys.exit( subprocess.call(['%s-%s' % (RB_MAIN, command_name)] + args, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr, env=os.environ.copy())) except OSError: # OSError is only raised in this scenario when subprocess.call # cannot find an executable with the name rbt-<command_name>. If # this command doesn't exist, we will check if an alias exists # with the name before printing an error message. pass aliases = load_config().get('ALIASES', {}) if command_name in aliases: sys.exit(run_alias(aliases[command_name], args)) else: parser.error('"%s" is not a command' % command_name)