コード例 #1
0
ファイル: postreview.py プロジェクト: cupcicm/rbtools
def main():
    origcwd = os.path.abspath(os.getcwd())

    if 'APPDATA' in os.environ:
        homepath = os.environ['APPDATA']
    elif 'HOME' in os.environ:
        homepath = os.environ["HOME"]
    else:
        homepath = ''

    # If we end up creating a cookie file, make sure it's only readable by the
    # user.
    os.umask(0077)

    # Load the config and cookie files
    cookie_file = os.path.join(homepath, ".post-review-cookies.txt")
    user_config, globals()['configs'] = load_config_files(homepath)

    args = parse_options(sys.argv[1:])

    debug('RBTools %s' % get_version_string())
    debug('Python %s' % sys.version)
    debug('Running on %s' % (platform.platform()))
    debug('Home = %s' % homepath)
    debug('Current Directory = %s' % os.getcwd())

    debug(
        'Checking the repository type. Errors shown below are mostly harmless.'
    )
    repository_info, tool = scan_usable_client(options)
    debug('Finished checking the repository type.')

    tool.user_config = user_config
    tool.configs = configs

    # Verify that options specific to an SCM Client have not been mis-used.
    tool.check_options()

    if repository_info.supports_changesets:
        changenum = tool.get_changenum(args)
    else:
        changenum = None

    if options.revision_range:
        diff, parent_diff = tool.diff_between_revisions(
            options.revision_range, args, repository_info)
    elif options.svn_changelist:
        diff, parent_diff = tool.diff_changelist(options.svn_changelist)
    elif options.diff_filename:
        parent_diff = None

        if options.diff_filename == '-':
            diff = sys.stdin.read()
        else:
            try:
                fp = open(os.path.join(origcwd, options.diff_filename), 'r')
                diff = fp.read()
                fp.close()
            except IOError, e:
                die("Unable to open diff filename: %s" % e)
コード例 #2
0
ファイル: postreview.py プロジェクト: psusloparov/ReviewBoard
def main():
    origcwd = os.path.abspath(os.getcwd())

    if 'APPDATA' in os.environ:
        homepath = os.environ['APPDATA']
    elif 'HOME' in os.environ:
        #homepath = os.environ["HOME"]
        homepath = '/usr/local/bin/perforce'
    else:
        homepath = ''

    # If we end up creating a cookie file, make sure it's only readable by the
    # user.
    os.umask(0077)

    # Load the config and cookie files
    cookie_file = os.path.join(homepath, ".post-review-cookies.txt")
    user_config, globals()['configs'] = load_config_files(homepath)

    args = parse_options(sys.argv[1:])

    debug('RBTools %s' % get_version_string())
    debug('Python %s' % sys.version)
    debug('Running on %s' % (platform.platform()))
    debug('Home = %s' % homepath)
    debug('Current Directory = %s' % os.getcwd())

    debug('Checking the repository type. Errors shown below are mostly harmless.')
    repository_info, tool = scan_usable_client(options)
    debug('Finished checking the repository type.')

    tool.user_config = user_config
    tool.configs = configs

    # Verify that options specific to an SCM Client have not been mis-used.
    tool.check_options()

    if repository_info.supports_changesets:
        changenum = tool.get_changenum(args)
    else:
        changenum = None

    if options.revision_range:
        diff, parent_diff = tool.diff_between_revisions(options.revision_range, args,
                                                        repository_info)
    elif options.svn_changelist:
        diff, parent_diff = tool.diff_changelist(options.svn_changelist)
    elif options.diff_filename:
        parent_diff = None

        if options.diff_filename == '-':
            diff = sys.stdin.read()
        else:
            try:
                fp = open(os.path.join(origcwd, options.diff_filename), 'r')
                diff = fp.read()
                fp.close()
            except IOError, e:
                die("Unable to open diff filename: %s" % e)
コード例 #3
0
ファイル: main.py プロジェクト: wadells/rbtools
def main():
    """Execute a command."""
    def exit_on_int(sig, frame):
        sys.exit(128 + sig)
    signal.signal(signal.SIGINT, exit_on_int)

    parser = OptionParser(prog=RB_MAIN,
                          usage='%prog [--version] <command> [options]'
                                ' [<args>]',
                          option_list=GLOBAL_OPTIONS,
                          add_help_option=False,
                          version='RBTools %s' % get_version_string())
    parser.disable_interspersed_args()
    opt, args = parser.parse_args()

    if not args:
        help([], parser)

    command_name = args[0]

    if command_name == "help":
        help(args[1:], parser)
    elif opt.help or "--help" in args or '-h' in args:
        help(args, 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", args[0])

    if not ep:
        try:
            ep = pkg_resources.iter_entry_points('rbtools_commands',
                                                 args[0]).next()
        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, e:
            sys.stderr.write("Unexpected error loading command %s: %s\n" %
                             (ep.name, e))
            sys.exit(1)

        command.run_from_argv([RB_MAIN] + args)
コード例 #4
0
ファイル: main.py プロジェクト: mhahn/rbtools
def main():
    """Execute a command."""
    def exit_on_int(sig, frame):
        sys.exit(128 + sig)
    signal.signal(signal.SIGINT, exit_on_int)

    parser = OptionParser(prog=RB_MAIN,
                          usage='%prog [--version] <command> [options]'
                                ' [<args>]',
                          option_list=GLOBAL_OPTIONS,
                          add_help_option=False,
                          version='RBTools %s' % get_version_string())
    parser.disable_interspersed_args()
    opt, args = parser.parse_args()

    if not args:
        help([], parser)

    command_name = args[0]

    if command_name == "help":
        help(args[1:], parser)
    elif opt.help or "--help" in args or '-h' in args:
        help(args, 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", args[0])

    if not ep:
        try:
            ep = pkg_resources.iter_entry_points('rbtools_commands',
                                                 args[0]).next()
        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, e:
            sys.stderr.write("Unexpected error loading command %s: %s\n" %
                             (ep.name, e))
            sys.exit(1)

        command.run_from_argv([RB_MAIN] + args)
コード例 #5
0
    def _check_version_output(self, version_arg):
        """Check if RBTools reports the correct version information.

        Args:
            version_arg (unicode):
                The version flag to pass to ``rbt``.
        """
        output = self._run_rbt(version_arg)

        self.assertEqual(
            output, 'RBTools %s (Python %d.%d.%d)\n' %
            (get_version_string(), sys.version_info[:3][0],
             sys.version_info[:3][1], sys.version_info[:3][2]))
コード例 #6
0
ファイル: vimrb.py プロジェクト: turlutux/rb-vim
def main():
    origcwd = os.path.abspath(os.getcwd())

    if 'APPDATA' in os.environ:
        homepath = os.environ['APPDATA']
    elif 'HOME' in os.environ:
        homepath = os.environ["HOME"]
    else:
        homepath = ''

    # If we end up creating a cookie file, make sure it's only readable by the
    # user.
    os.umask(0077)

    # Load the config and cookie files
    cookie_file = os.path.join(homepath, ".post-review-cookies.txt")
    user_config, globals()['configs'] = load_config_files(homepath)

    args = parse_options(sys.argv[1:])

    debug('RBTools %s' % get_version_string())
    debug('Home = %s' % homepath)

    repository_info, tool = scan_usable_client(options)
    tool.user_config = user_config
    tool.configs = configs

    # Verify that options specific to an SCM Client have not been mis-used.
    tool.check_options()

    # Try to find a valid Review Board server to use.
    if options.server:
        server_url = options.server
    else:
        server_url = tool.scan_for_server(repository_info)

    if not server_url:
        print "Unable to find a Review Board server for this source code tree."
        sys.exit(1)

    server = ReviewBoardServer(server_url, repository_info, cookie_file)

    # Handle the case where /api/ requires authorization (RBCommons).
    if not server.check_api_version():
        die("Unable to log in with the supplied username and password.")

    # Let's begin.
    server.login()

    tempt_fate(server)
コード例 #7
0
ファイル: __init__.py プロジェクト: halvorlu/rbtools
    def init_logging(self):
        """Initializes logging for the command.

        This will set up different log handlers based on the formatting we want
        for the given levels.

        The INFO log handler will just show the text, like a print statement.

        WARNING and higher will show the level name as a prefix, in the form of
        "LEVEL: message".

        If debugging is enabled, a debug log handler will be set up showing
        debug messages in the form of ">>> message", making it easier to
        distinguish between debugging and other messages.
        """
        root = logging.getLogger()

        if self.options.debug:
            handler = logging.StreamHandler()
            handler.setFormatter(logging.Formatter('>>> %(message)s'))
            handler.setLevel(logging.DEBUG)
            handler.addFilter(LogLevelFilter(logging.DEBUG))
            root.addHandler(handler)

            root.setLevel(logging.DEBUG)
        else:
            root.setLevel(logging.INFO)

        # Handler for info messages. We'll treat these like prints.
        handler = logging.StreamHandler()
        handler.setFormatter(logging.Formatter('%(message)s'))
        handler.setLevel(logging.INFO)
        handler.addFilter(LogLevelFilter(logging.INFO))
        root.addHandler(handler)

        # Handler for warnings, errors, and criticals. They'll show the
        # level prefix and the message.
        handler = logging.StreamHandler()
        handler.setFormatter(logging.Formatter('%(levelname)s: %(message)s'))
        handler.setLevel(logging.WARNING)
        root.addHandler(handler)

        logging.debug('RBTools %s', get_version_string())
        logging.debug('Python %s', sys.version)
        logging.debug('Running on %s', platform.platform())
        logging.debug('Home = %s', get_home_path())
        logging.debug('Current directory = %s', os.getcwd())
コード例 #8
0
ファイル: __init__.py プロジェクト: mqj0712/rbtools
    def init_logging(self):
        """Initializes logging for the command.

        This will set up different log handlers based on the formatting we want
        for the given levels.

        The INFO log handler will just show the text, like a print statement.

        WARNING and higher will show the level name as a prefix, in the form of
        "LEVEL: message".

        If debugging is enabled, a debug log handler will be set up showing
        debug messages in the form of ">>> message", making it easier to
        distinguish between debugging and other messages.
        """
        root = logging.getLogger()

        if self.options.debug:
            handler = logging.StreamHandler()
            handler.setFormatter(logging.Formatter('>>> %(message)s'))
            handler.setLevel(logging.DEBUG)
            handler.addFilter(LogLevelFilter(logging.DEBUG))
            root.addHandler(handler)

            root.setLevel(logging.DEBUG)
        else:
            root.setLevel(logging.INFO)

        # Handler for info messages. We'll treat these like prints.
        handler = logging.StreamHandler()
        handler.setFormatter(logging.Formatter('%(message)s'))
        handler.setLevel(logging.INFO)
        handler.addFilter(LogLevelFilter(logging.INFO))
        root.addHandler(handler)

        # Handler for warnings, errors, and criticals. They'll show the
        # level prefix and the message.
        handler = logging.StreamHandler()
        handler.setFormatter(logging.Formatter('%(levelname)s: %(message)s'))
        handler.setLevel(logging.WARNING)
        root.addHandler(handler)

        logging.debug('RBTools %s', get_version_string())
        logging.debug('Python %s', sys.version)
        logging.debug('Running on %s', platform.platform())
        logging.debug('Home = %s', get_home_path())
        logging.debug('Current directory = %s', os.getcwd())
コード例 #9
0
ファイル: main.py プロジェクト: sparkiegeek/rbtools
def main():
    """Execute a command."""
    parser = OptionParser(prog=RB_MAIN,
                          usage='%prog [--version] <command> [options]'
                                ' [<args>]',
                          option_list=GLOBAL_OPTIONS,
                          add_help_option=False,
                          version='RBTools %s' % get_version_string())
    parser.disable_interspersed_args()
    opt, args = parser.parse_args()

    if not args:
        help([], parser)

    command_name = args[0]

    if command_name == "help":
        help(args[1:], parser)
    elif opt.help or "--help" in args or '-h' in args:
        help(args, parser)

    # Attempt to retrieve the command class from the entry points.
    ep = pkg_resources.get_entry_info("rbtools", "rbtools_commands", args[0])

    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, e:
            sys.stderr.write("Unexpected error loading command %s: %s\n" %
                             (ep.name, e))
            sys.exit(1)

        command.run_from_argv([RB_MAIN] + args)
コード例 #10
0
# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'RBTools Documentation'
copyright = u'2013, Beanbag, Inc.'

# The version info for the project you're documenting, acts as
# replacement for |version| and |release|, also used in various other
# places throughout the built documents.
#
# The short X.Y version.
version = '.'.join([str(i) for i in rbtools.VERSION[:-1][:2]])
# The full version, including alpha/beta/rc tags.
release = rbtools.get_version_string()

# The language for content autogenerated by Sphinx. Refer to
# documentation for a list of supported languages.
#language = None

# There are two options for replacing |today|: either, you set today
# to some non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'

# List of documents that shouldn't be included in the build.
#unused_docs = []

# List of directories, relative to source directory, that shouldn't be searched
コード例 #11
0
ファイル: conf.py プロジェクト: clach04/rbtools
# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'RBTools Documentation'
copyright = u'2013, Beanbag, Inc.'

# The version info for the project you're documenting, acts as
# replacement for |version| and |release|, also used in various other
# places throughout the built documents.
#
# The short X.Y version.
version = '.'.join([str(i) for i in rbtools.VERSION[:-1][:2]])
# The full version, including alpha/beta/rc tags.
release = rbtools.get_version_string()

# The language for content autogenerated by Sphinx. Refer to
# documentation for a list of supported languages.
#language = None

# There are two options for replacing |today|: either, you set today
# to some non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'

# List of documents that shouldn't be included in the build.
#unused_docs = []

# List of directories, relative to source directory, that shouldn't be searched
コード例 #12
0
ファイル: main.py プロジェクト: dacaiguoguo/rbtools
import os
import pkg_resources
import signal
import subprocess
import sys

from rbtools import get_version_string
from rbtools.commands import find_entry_point_for_command, Option, RB_MAIN
from rbtools.utils.aliases import run_alias
from rbtools.utils.filesystem import load_config


GLOBAL_OPTIONS = [
    Option('-v', '--version',
           action='version',
           version='RBTools %s' % get_version_string()),
    Option('-h', '--help',
           action='store_true',
           dest='help',
           default=False),
    Option('command',
           nargs=argparse.REMAINDER,
           help='The RBTools command to execute, and any arguments. '
                '(See below)'),
]


def build_help_text(command_class):
    """Generate help text from a command class."""
    command = command_class()
    parser = command.create_parser({})
コード例 #13
0
import os
import pkg_resources
import signal
import subprocess
import sys

from rbtools import get_version_string
from rbtools.commands import Option, RB_MAIN
from rbtools.utils.aliases import run_alias
from rbtools.utils.filesystem import load_config

GLOBAL_OPTIONS = [
    Option('-v',
           '--version',
           action='version',
           version='RBTools %s' % get_version_string()),
    Option('-h', '--help', action='store_true', dest='help', default=False),
    Option('command',
           nargs=argparse.REMAINDER,
           help='The RBTools command to execute, and any arguments. '
           '(See below)'),
]


def build_help_text(command_class):
    """Generate help text from a command class."""
    command = command_class()
    parser = command.create_parser({})

    return parser.format_help()
コード例 #14
0
ファイル: postreview.py プロジェクト: NurKaynar/hacklab
def parse_options(args):
    parser = OptionParser(usage="%prog [-pond] [-r review_id] [changenum]",
                          version="RBTools " + get_version_string())

    parser.add_option("-p", "--publish",
                      dest="publish", action="store_true",
                      default=get_config_value(configs, 'PUBLISH', False),
                      help="publish the review request immediately after "
                           "submitting")
    parser.add_option("-r", "--review-request-id",
                      dest="rid", metavar="ID", default=None,
                      help="existing review request ID to update")
    parser.add_option("-o", "--open",
                      dest="open_browser", action="store_true",
                      default=get_config_value(configs, 'OPEN_BROWSER', False),
                      help="open a web browser to the review request page")
    parser.add_option("-n", "--output-diff",
                      dest="output_diff_only", action="store_true",
                      default=False,
                      help="outputs a diff to the console and exits. "
                           "Does not post")
    parser.add_option("--server",
                      dest="server",
                      default=get_config_value(configs, 'REVIEWBOARD_URL'),
                      metavar="SERVER",
                      help="specify a different Review Board server to use")
    parser.add_option("--disable-proxy",
                      action='store_true',
                      dest='disable_proxy',
                      default=not get_config_value(configs, 'ENABLE_PROXY',
                                                   True),
                      help="prevents requests from going through a proxy "
                           "server")
    parser.add_option("--diff-only",
                      dest="diff_only", action="store_true", default=False,
                      help="uploads a new diff, but does not update "
                           "info from changelist")
    parser.add_option("--reopen",
                      dest="reopen", action="store_true", default=False,
                      help="reopen discarded review request "
                           "after update")
    parser.add_option("--target-groups",
                      dest="target_groups",
                      default=get_config_value(configs, 'TARGET_GROUPS'),
                      help="names of the groups who will perform "
                           "the review")
    parser.add_option("--target-people",
                      dest="target_people",
                      default=get_config_value(configs, 'TARGET_PEOPLE'),
                      help="names of the people who will perform "
                           "the review")
    parser.add_option("--summary",
                      dest="summary", default=None,
                      help="summary of the review ")
    parser.add_option("--description",
                      dest="description", default=None,
                      help="description of the review ")
    parser.add_option("--description-file",
                      dest="description_file", default=None,
                      help="text file containing a description of the review")
    parser.add_option('-g', '--guess-fields',
                      dest="guess_fields", action="store_true",
                      default=get_config_value(configs, 'GUESS_FIELDS',
                                               False),
                      help="equivalent to --guess-summary --guess-description")
    parser.add_option("--guess-summary",
                      dest="guess_summary", action="store_true",
                      default=get_config_value(configs, 'GUESS_SUMMARY',
                                               False),
                      help="guess summary from the latest commit (git/"
                           "hg/hgsubversion only)")
    parser.add_option("--guess-description",
                      dest="guess_description", action="store_true",
                      default=get_config_value(configs, 'GUESS_DESCRIPTION',
                                               False),
                      help="guess description based on commits on this branch "
                           "(git/hg/hgsubversion only)")
    parser.add_option("--testing-done",
                      dest="testing_done", default=None,
                      help="details of testing done ")
    parser.add_option("--testing-done-file",
                      dest="testing_file", default=None,
                      help="text file containing details of testing done ")
    parser.add_option("--branch",
                      dest="branch",
                      default=get_config_value(configs, 'BRANCH'),
                      help="affected branch ")
    parser.add_option("--bugs-closed",
                      dest="bugs_closed", default=None,
                      help="list of bugs closed ")
    parser.add_option("--change-description", default=None,
                      help="description of what changed in this revision of "
                      "the review request when updating an existing request")
    parser.add_option("--revision-range",
                      dest="revision_range", default=None,
                      help="generate the diff for review based on given "
                           "revision range")
    parser.add_option("--submit-as",
                      dest="submit_as",
                      default=get_config_value(configs, 'SUBMIT_AS'),
                      metavar="USERNAME",
                      help="user name to be recorded as the author of the "
                           "review request, instead of the logged in user")
    parser.add_option("--username",
                      dest="username",
                      default=get_config_value(configs, 'USERNAME'),
                      metavar="USERNAME",
                      help="user name to be supplied to the reviewboard "
                           "server")
    parser.add_option("--password",
                      dest="password",
                      default=get_config_value(configs, 'PASSWORD'),
                      metavar="PASSWORD",
                      help="password to be supplied to the reviewboard server")
    parser.add_option("--change-only",
                      dest="change_only", action="store_true",
                      default=False,
                      help="updates info from changelist, but does "
                           "not upload a new diff (only available if your "
                           "repository supports changesets)")
    parser.add_option("--parent",
                      dest="parent_branch",
                      default=get_config_value(configs, 'PARENT_BRANCH'),
                      metavar="PARENT_BRANCH",
                      help="the parent branch this diff should be against "
                           "(only available if your repository supports "
                           "parent diffs)")
    parser.add_option("--tracking-branch",
                      dest="tracking",
                      default=get_config_value(configs, 'TRACKING_BRANCH'),
                      metavar="TRACKING",
                      help="Tracking branch from which your branch is derived "
                           "(git only, defaults to origin/master)")
    parser.add_option("--p4-client",
                      dest="p4_client",
                      default=get_config_value(configs, 'P4_CLIENT'),
                      help="the Perforce client name that the review is in")
    parser.add_option("--p4-port",
                      dest="p4_port",
                      default=get_config_value(configs, 'P4_PORT'),
                      help="the Perforce servers IP address that the review "
                           "is on")
    parser.add_option("--p4-passwd",
                      dest="p4_passwd",
                      default=get_config_value(configs, 'P4_PASSWD'),
                      help="the Perforce password or ticket of the user "
                           "in the P4USER environment variable")
    parser.add_option('--svn-changelist', dest='svn_changelist', default=None,
                      help='generate the diff for review based on a local SVN '
                           'changelist')
    parser.add_option("--repository-url",
                      dest="repository_url",
                      default=get_config_value(configs, 'REPOSITORY'),
                      help="the url for a repository for creating a diff "
                           "outside of a working copy (currently only "
                           "supported by Subversion with --revision-range or "
                           "--diff-filename and ClearCase with relative "
                           "paths outside the view). For git, this specifies"
                           "the origin url of the current repository, "
                           "overriding the origin url supplied by the git "
                           "client.")
    parser.add_option("-d", "--debug",
                      action="store_true", dest="debug",
                      default=get_config_value(configs, 'DEBUG', False),
                      help="display debug output")
    parser.add_option("--diff-filename",
                      dest="diff_filename", default=None,
                      help='upload an existing diff file, instead of '
                           'generating a new diff')
    parser.add_option('--http-username',
                      dest='http_username',
                      default=get_config_value(configs, 'HTTP_USERNAME'),
                      metavar='USERNAME',
                      help='username for HTTP Basic authentication')
    parser.add_option('--http-password',
                      dest='http_password',
                      default=get_config_value(configs, 'HTTP_PASSWORD'),
                      metavar='PASSWORD',
                      help='password for HTTP Basic authentication')

    (globals()["options"], args) = parser.parse_args(args)

    if options.description and options.description_file:
        sys.stderr.write("The --description and --description-file options "
                         "are mutually exclusive.\n")
        sys.exit(1)

    if options.description_file:
        if os.path.exists(options.description_file):
            fp = open(options.description_file, "r")
            options.description = fp.read()
            fp.close()
        else:
            sys.stderr.write("The description file %s does not exist.\n" %
                             options.description_file)
            sys.exit(1)

    if options.guess_fields:
        options.guess_summary = True
        options.guess_description = True

    if options.testing_done and options.testing_file:
        sys.stderr.write("The --testing-done and --testing-done-file options "
                         "are mutually exclusive.\n")
        sys.exit(1)

    if options.testing_file:
        if os.path.exists(options.testing_file):
            fp = open(options.testing_file, "r")
            options.testing_done = fp.read()
            fp.close()
        else:
            sys.stderr.write("The testing file %s does not exist.\n" %
                             options.testing_file)
            sys.exit(1)

    if options.reopen and not options.rid:
        sys.stderr.write("The --reopen option requires "
                         "--review-request-id option.\n")
        sys.exit(1)

    if options.change_description and not options.rid:
        sys.stderr.write("--change-description may only be used "
                         "when updating an existing review-request\n")
        sys.exit(1)

    if not options.diff_filename:
      print "Provide your Git formatted patches using --diff-filename=<patch>"
      sys.exit(1)

    def uploadOriginalPatch(patch_content):
        # Post original file to paste.cloudstack.org (patch stays only for
        # 1 month)
        import httplib, urllib
        params = urllib.urlencode({'content': patch_content, 'lexer': 'python',
         'title': '', 'author': 'RBTOOL', 'expire_options': '2592000'})
        headers = {"Content-type": "application/x-www-form-urlencoded",
               "Accept": "text/plain"}#,
               #"Cookie": 'sessionid=64b9b91cb3febac75b4d87ce6f7edd20'}
        conn = httplib.HTTPConnection("patchbin.baagi.org")
        conn.request("POST", "/upload", params, headers)
        response = conn.getresponse()
        patch_url = response.read() #response.getheader('location')
        conn.close()
        return patch_url #+ 'raw/'

    fp = open(os.path.join(os.path.abspath(os.getcwd()), options.diff_filename), 'r')
    diff = fp.read()
    fp.close()
    if options.description:
      options.description += "\nDownload original patch: %s" % uploadOriginalPatch(diff)
    else:
      options.description = "\nDownload original patch: %s" % uploadOriginalPatch(diff)
    return args
コード例 #15
0
ファイル: __init__.py プロジェクト: reviewboard/rbtools
    def init_logging(self):
        """Initializes logging for the command.

        This will set up different log handlers based on the formatting we want
        for the given levels.

        The INFO log handler will just show the text, like a print statement.

        WARNING and higher will show the level name as a prefix, in the form of
        "LEVEL: message".

        If debugging is enabled, a debug log handler will be set up showing
        debug messages in the form of ">>> message", making it easier to
        distinguish between debugging and other messages.
        """
        if sys.stdout.isatty():
            # We only use colorized logging when writing to TTYs, so we don't
            # bother initializing it then.
            colorama.init()

        root = logging.getLogger()

        if self.options.debug:
            handler = logging.StreamHandler()
            handler.setFormatter(self._create_formatter(
                'DEBUG', '{color}>>>{reset} %(message)s'))
            handler.setLevel(logging.DEBUG)
            handler.addFilter(LogLevelFilter(logging.DEBUG))
            root.addHandler(handler)

            root.setLevel(logging.DEBUG)
        else:
            root.setLevel(logging.INFO)

        # Handler for info messages. We'll treat these like prints.
        handler = logging.StreamHandler()
        handler.setFormatter(self._create_formatter(
            'INFO', '{color}%(message)s{reset}'))

        handler.setLevel(logging.INFO)
        handler.addFilter(LogLevelFilter(logging.INFO))
        root.addHandler(handler)

        # Handlers for warnings, errors, and criticals. They'll show the
        # level prefix and the message.
        levels = (
            ('WARNING', logging.WARNING),
            ('ERROR', logging.ERROR),
            ('CRITICAL', logging.CRITICAL),
        )

        for level_name, level in levels:
            handler = logging.StreamHandler()
            handler.setFormatter(self._create_formatter(
                level_name, '{color}%(levelname)s:{reset} %(message)s'))
            handler.addFilter(LogLevelFilter(level))
            handler.setLevel(level)
            root.addHandler(handler)

        logging.debug('RBTools %s', get_version_string())
        logging.debug('Python %s', sys.version)
        logging.debug('Running on %s', platform.platform())
        logging.debug('Home = %s', get_home_path())
        logging.debug('Current directory = %s', os.getcwd())
コード例 #16
0
def main():
    origcwd = os.path.abspath(os.getcwd())

    if 'APPDATA' in os.environ:
        homepath = os.environ['APPDATA']
    elif 'HOME' in os.environ:
        homepath = os.environ["HOME"]
    else:
        homepath = ''

    # If we end up creating a cookie file, make sure it's only readable by the
    # user.
    os.umask(0077)

    # Load the config and cookie files
    cookie_file = os.path.join(homepath, ".post-review-cookies.txt")
    user_config, globals()['configs'] = load_config_files(homepath)

    args = parse_options(sys.argv[1:])

    debug('RBTools %s' % get_version_string())
    debug('Home = %s' % homepath)

    repository_info, tool = scan_usable_client(options)
    tool.user_config = user_config
    tool.configs = configs

    # Verify that options specific to an SCM Client have not been mis-used.
    tool.check_options()

    # Try to find a valid Review Board server to use.
    if options.server:
        server_url = options.server
    else:
        server_url = tool.scan_for_server(repository_info)

    if not server_url:
        print "Unable to find a Review Board server for this source code tree."
        sys.exit(1)

    server = ReviewBoardServer(server_url, repository_info, cookie_file)

    # Handle the case where /api/ requires authorization (RBCommons).
    if not server.check_api_version():
        die("Unable to log in with the supplied username and password.")

    if repository_info.supports_changesets:
        changenum = tool.get_changenum(args)
    else:
        changenum = None

    if options.revision_range:
        diff, parent_diff = tool.diff_between_revisions(options.revision_range, args,
                                                        repository_info)
    elif options.svn_changelist:
        diff, parent_diff = tool.diff_changelist(options.svn_changelist)
    elif options.diff_filename:
        parent_diff = None

        if options.diff_filename == '-':
            diff = sys.stdin.read()
        else:
            try:
                fp = open(os.path.join(origcwd, options.diff_filename), 'r')
                diff = fp.read()
                fp.close()
            except IOError, e:
                die("Unable to open diff filename: %s" % e)
コード例 #17
0
    def init_logging(self):
        """Initializes logging for the command.

        This will set up different log handlers based on the formatting we want
        for the given levels.

        The INFO log handler will just show the text, like a print statement.

        WARNING and higher will show the level name as a prefix, in the form of
        "LEVEL: message".

        If debugging is enabled, a debug log handler will be set up showing
        debug messages in the form of ">>> message", making it easier to
        distinguish between debugging and other messages.
        """
        root = logging.getLogger()

        if self.options.debug:
            handler = logging.StreamHandler()
            handler.setFormatter(logging.Formatter('>>> %(message)s'))
            handler.setLevel(logging.DEBUG)
            handler.addFilter(LogLevelFilter(logging.DEBUG))
            root.addHandler(handler)

            root.setLevel(logging.DEBUG)
        else:
            root.setLevel(logging.INFO)

        # Handler for info messages. We'll treat these like prints.
        handler = logging.StreamHandler()
        handler.setFormatter(logging.Formatter('%(message)s'))
        handler.setLevel(logging.INFO)
        handler.addFilter(LogLevelFilter(logging.INFO))
        root.addHandler(handler)

        # Handler for warnings, errors, and criticals. They'll show the
        # level prefix and the message.
        handler = logging.StreamHandler()

        if (self.options.color == 'always'
                or (self.options.color == 'auto' and sys.stderr.isatty())):
            handler.setFormatter(
                ColoredFormatter(
                    '%(log_color)s%(levelname)-8s%(reset)s'
                    '%(message_log_color)s%(message)s',
                    datefmt=None,
                    reset=True,
                    log_colors={
                        'WARNING': self.options.warn_color,
                        'ERROR': self.options.error_color,
                        'CRITICAL': self.options.critical_color,
                    },
                    secondary_log_colors={
                        'message': {
                            'WARNING': self.options.warn_color,
                            'ERROR': self.options.error_color,
                            'CRITICAL': self.options.critical_color,
                        }
                    },
                    style='%'))
        else:
            handler.setFormatter(
                logging.Formatter('%(levelname)s: %(message)s'))

        handler.setLevel(logging.WARNING)
        root.addHandler(handler)

        logging.debug('RBTools %s', get_version_string())
        logging.debug('Python %s', sys.version)
        logging.debug('Running on %s', platform.platform())
        logging.debug('Home = %s', get_home_path())
        logging.debug('Current directory = %s', os.getcwd())
コード例 #18
0
import pkg_resources
import signal
import subprocess
import sys

from rbtools import get_version_string
from rbtools.commands import find_entry_point_for_command, Option, RB_MAIN
from rbtools.utils.aliases import run_alias
from rbtools.utils.filesystem import load_config


GLOBAL_OPTIONS = [
    Option('-v', '--version',
           action='version',
           version='RBTools %s (Python %d.%d.%d)' % (
               get_version_string(),
               sys.version_info[:3][0],
               sys.version_info[:3][1],
               sys.version_info[:3][2])),
    Option('-h', '--help',
           action='store_true',
           dest='help',
           default=False),
    Option('command',
           nargs=argparse.REMAINDER,
           help='The RBTools command to execute, and any arguments. '
                '(See below)'),
]


def build_help_text(command_class):
コード例 #19
0
ファイル: __init__.py プロジェクト: totoroliu/rbtools
    def init_logging(self):
        """Initializes logging for the command.

        This will set up different log handlers based on the formatting we want
        for the given levels.

        The INFO log handler will just show the text, like a print statement.

        WARNING and higher will show the level name as a prefix, in the form of
        "LEVEL: message".

        If debugging is enabled, a debug log handler will be set up showing
        debug messages in the form of ">>> message", making it easier to
        distinguish between debugging and other messages.
        """
        if sys.stdout.isatty():
            # We only use colorized logging when writing to TTYs, so we don't
            # bother initializing it then.
            colorama.init()

        root = logging.getLogger()

        if self.options.debug:
            handler = logging.StreamHandler()
            handler.setFormatter(self._create_formatter(
                'DEBUG', '{color}>>>{reset} %(message)s'))
            handler.setLevel(logging.DEBUG)
            handler.addFilter(LogLevelFilter(logging.DEBUG))
            root.addHandler(handler)

            root.setLevel(logging.DEBUG)
        else:
            root.setLevel(logging.INFO)

        # Handler for info messages. We'll treat these like prints.
        handler = logging.StreamHandler()
        handler.setFormatter(self._create_formatter(
            'INFO', '{color}%(message)s{reset}'))

        handler.setLevel(logging.INFO)
        handler.addFilter(LogLevelFilter(logging.INFO))
        root.addHandler(handler)

        # Handlers for warnings, errors, and criticals. They'll show the
        # level prefix and the message.
        levels = (
            ('WARNING', logging.WARNING),
            ('ERROR', logging.ERROR),
            ('CRITICAL', logging.CRITICAL),
        )

        for level_name, level in levels:
            handler = logging.StreamHandler()
            handler.setFormatter(self._create_formatter(
                level_name, '{color}%(levelname)s:{reset} %(message)s'))
            handler.addFilter(LogLevelFilter(level))
            handler.setLevel(level)
            root.addHandler(handler)

        logging.debug('RBTools %s', get_version_string())
        logging.debug('Python %s', sys.version)
        logging.debug('Running on %s', platform.platform())
        logging.debug('Home = %s', get_home_path())
        logging.debug('Current directory = %s', os.getcwd())
コード例 #20
0
ファイル: __init__.py プロジェクト: benasher44/rbtools
    def init_logging(self):
        """Initializes logging for the command.

        This will set up different log handlers based on the formatting we want
        for the given levels.

        The INFO log handler will just show the text, like a print statement.

        WARNING and higher will show the level name as a prefix, in the form of
        "LEVEL: message".

        If debugging is enabled, a debug log handler will be set up showing
        debug messages in the form of ">>> message", making it easier to
        distinguish between debugging and other messages.
        """
        root = logging.getLogger()

        if self.options.debug:
            handler = logging.StreamHandler()
            handler.setFormatter(logging.Formatter('>>> %(message)s'))
            handler.setLevel(logging.DEBUG)
            handler.addFilter(LogLevelFilter(logging.DEBUG))
            root.addHandler(handler)

            root.setLevel(logging.DEBUG)
        else:
            root.setLevel(logging.INFO)

        # Handler for info messages. We'll treat these like prints.
        handler = logging.StreamHandler()
        handler.setFormatter(logging.Formatter('%(message)s'))
        handler.setLevel(logging.INFO)
        handler.addFilter(LogLevelFilter(logging.INFO))
        root.addHandler(handler)

        # Handler for warnings, errors, and criticals. They'll show the
        # level prefix and the message.
        handler = logging.StreamHandler()

        if (self.options.color == 'always' or
            (self.options.color == 'auto' and
             sys.stderr.isatty())):
            handler.setFormatter(ColoredFormatter(
                '%(log_color)s%(levelname)-8s%(reset)s'
                '%(message_log_color)s%(message)s',
                datefmt=None,
                reset=True,
                log_colors={
                    'WARNING': self.options.warn_color,
                    'ERROR': self.options.error_color,
                    'CRITICAL': self.options.critical_color,
                },
                secondary_log_colors={
                    'message': {
                        'WARNING': self.options.warn_color,
                        'ERROR': self.options.error_color,
                        'CRITICAL': self.options.critical_color,
                    }
                },
                style='%'
            ))
        else:
            handler.setFormatter(logging.Formatter('%(levelname)s: %(message)s'))

        handler.setLevel(logging.WARNING)
        root.addHandler(handler)

        logging.debug('RBTools %s', get_version_string())
        logging.debug('Python %s', sys.version)
        logging.debug('Running on %s', platform.platform())
        logging.debug('Home = %s', get_home_path())
        logging.debug('Current directory = %s', os.getcwd())
コード例 #21
0
def parse_options(args):
    parser = OptionParser(usage="%prog [-pond] [-r review_id] [changenum]",
                          version="RBTools " + get_version_string())

    parser.add_option("-p", "--publish",
                      dest="publish", action="store_true",
                      default=get_config_value(configs, 'PUBLISH', False),
                      help="publish the review request immediately after "
                           "submitting")
    parser.add_option("-r", "--review-request-id",
                      dest="rid", metavar="ID", default=None,
                      help="existing review request ID to update")
    parser.add_option("-o", "--open",
                      dest="open_browser", action="store_true",
                      default=get_config_value(configs, 'OPEN_BROWSER', False),
                      help="open a web browser to the review request page")
    parser.add_option("-n", "--output-diff",
                      dest="output_diff_only", action="store_true",
                      default=False,
                      help="outputs a diff to the console and exits. "
                           "Does not post")
    parser.add_option("--server",
                      dest="server",
                      default=get_config_value(configs, 'REVIEWBOARD_URL'),
                      metavar="SERVER",
                      help="specify a different Review Board server to use")
    parser.add_option("--disable-proxy",
                      action='store_true',
                      dest='disable_proxy',
                      default=not get_config_value(configs, 'ENABLE_PROXY',
                                                   True),
                      help="prevents requests from going through a proxy "
                           "server")
    parser.add_option("--diff-only",
                      dest="diff_only", action="store_true", default=False,
                      help="uploads a new diff, but does not update "
                           "info from changelist")
    parser.add_option("--reopen",
                      dest="reopen", action="store_true", default=False,
                      help="reopen discarded review request "
                           "after update")
    parser.add_option("--target-groups",
                      dest="target_groups",
                      default=get_config_value(configs, 'TARGET_GROUPS'),
                      help="names of the groups who will perform "
                           "the review")
    parser.add_option("--target-people",
                      dest="target_people",
                      default=get_config_value(configs, 'TARGET_PEOPLE'),
                      help="names of the people who will perform "
                           "the review")
    parser.add_option("--summary",
                      dest="summary", default=None,
                      help="summary of the review ")
    parser.add_option("--description",
                      dest="description", default=None,
                      help="description of the review ")
    parser.add_option("--description-file",
                      dest="description_file", default=None,
                      help="text file containing a description of the review")
    parser.add_option('-g', '--guess-fields',
                      dest="guess_fields", action="store_true",
                      default=get_config_value(configs, 'GUESS_FIELDS',
                                               False),
                      help="equivalent to --guess-summary --guess-description")
    parser.add_option("--guess-summary",
                      dest="guess_summary", action="store_true",
                      default=get_config_value(configs, 'GUESS_SUMMARY',
                                               False),
                      help="guess summary from the latest commit (git/"
                           "hg/hgsubversion only)")
    parser.add_option("--guess-description",
                      dest="guess_description", action="store_true",
                      default=get_config_value(configs, 'GUESS_DESCRIPTION',
                                               False),
                      help="guess description based on commits on this branch "
                           "(git/hg/hgsubversion only)")
    parser.add_option("--testing-done",
                      dest="testing_done", default=None,
                      help="details of testing done ")
    parser.add_option("--testing-done-file",
                      dest="testing_file", default=None,
                      help="text file containing details of testing done ")
    parser.add_option("--branch",
                      dest="branch",
                      default=get_config_value(configs, 'BRANCH'),
                      help="affected branch ")
    parser.add_option("--bugs-closed",
                      dest="bugs_closed", default=None,
                      help="list of bugs closed ")
    parser.add_option("--change-description", default=None,
                      help="description of what changed in this revision of "
                      "the review request when updating an existing request")
    parser.add_option("--revision-range",
                      dest="revision_range", default=None,
                      help="generate the diff for review based on given "
                           "revision range")
    parser.add_option("--submit-as",
                      dest="submit_as",
                      default=get_config_value(configs, 'SUBMIT_AS'),
                      metavar="USERNAME",
                      help="user name to be recorded as the author of the "
                           "review request, instead of the logged in user")
    parser.add_option("--username",
                      dest="username",
                      default=get_config_value(configs, 'USERNAME'),
                      metavar="USERNAME",
                      help="user name to be supplied to the reviewboard "
                           "server")
    parser.add_option("--password",
                      dest="password",
                      default=get_config_value(configs, 'PASSWORD'),
                      metavar="PASSWORD",
                      help="password to be supplied to the reviewboard server")
    parser.add_option("--change-only",
                      dest="change_only", action="store_true",
                      default=False,
                      help="updates info from changelist, but does "
                           "not upload a new diff (only available if your "
                           "repository supports changesets)")
    parser.add_option("--parent",
                      dest="parent_branch",
                      default=get_config_value(configs, 'PARENT_BRANCH'),
                      metavar="PARENT_BRANCH",
                      help="the parent branch this diff should be against "
                           "(only available if your repository supports "
                           "parent diffs)")
    parser.add_option("--tracking-branch",
                      dest="tracking",
                      default=get_config_value(configs, 'TRACKING_BRANCH'),
                      metavar="TRACKING",
                      help="Tracking branch from which your branch is derived "
                           "(git only, defaults to origin/master)")
    parser.add_option("--p4-client",
                      dest="p4_client",
                      default=get_config_value(configs, 'P4_CLIENT'),
                      help="the Perforce client name that the review is in")
    parser.add_option("--p4-port",
                      dest="p4_port",
                      default=get_config_value(configs, 'P4_PORT'),
                      help="the Perforce servers IP address that the review "
                           "is on")
    parser.add_option("--p4-passwd",
                      dest="p4_passwd",
                      default=get_config_value(configs, 'P4_PASSWD'),
                      help="the Perforce password or ticket of the user "
                           "in the P4USER environment variable")
    parser.add_option('--svn-changelist', dest='svn_changelist', default=None,
                      help='generate the diff for review based on a local SVN '
                           'changelist')
    parser.add_option("--repository-url",
                      dest="repository_url",
                      default=get_config_value(configs, 'REPOSITORY'),
                      help="the url for a repository for creating a diff "
                           "outside of a working copy (currently only "
                           "supported by Subversion with --revision-range or "
                           "--diff-filename and ClearCase with relative "
                           "paths outside the view). For git, this specifies"
                           "the origin url of the current repository, "
                           "overriding the origin url supplied by the git "
                           "client.")
    parser.add_option("-d", "--debug",
                      action="store_true", dest="debug",
                      default=get_config_value(configs, 'DEBUG', False),
                      help="display debug output")
    parser.add_option("--diff-filename",
                      dest="diff_filename", default=None,
                      help='upload an existing diff file, instead of '
                           'generating a new diff')
    parser.add_option('--http-username',
                      dest='http_username',
                      default=get_config_value(configs, 'HTTP_USERNAME'),
                      metavar='USERNAME',
                      help='username for HTTP Basic authentication')
    parser.add_option('--http-password',
                      dest='http_password',
                      default=get_config_value(configs, 'HTTP_PASSWORD'),
                      metavar='PASSWORD',
                      help='password for HTTP Basic authentication')

    (globals()["options"], args) = parser.parse_args(args)

    if options.debug:
        logging.getLogger().setLevel(logging.DEBUG)

    if options.description and options.description_file:
        sys.stderr.write("The --description and --description-file options "
                         "are mutually exclusive.\n")
        sys.exit(1)

    if options.description_file:
        if os.path.exists(options.description_file):
            fp = open(options.description_file, "r")
            options.description = fp.read()
            fp.close()
        else:
            sys.stderr.write("The description file %s does not exist.\n" %
                             options.description_file)
            sys.exit(1)

    if options.guess_fields:
        options.guess_summary = True
        options.guess_description = True

    if options.testing_done and options.testing_file:
        sys.stderr.write("The --testing-done and --testing-done-file options "
                         "are mutually exclusive.\n")
        sys.exit(1)

    if options.testing_file:
        if os.path.exists(options.testing_file):
            fp = open(options.testing_file, "r")
            options.testing_done = fp.read()
            fp.close()
        else:
            sys.stderr.write("The testing file %s does not exist.\n" %
                             options.testing_file)
            sys.exit(1)

    if options.reopen and not options.rid:
        sys.stderr.write("The --reopen option requires "
                         "--review-request-id option.\n")
        sys.exit(1)

    if options.change_description and not options.rid:
        sys.stderr.write("--change-description may only be used "
                         "when updating an existing review-request\n")
        sys.exit(1)

    return args
コード例 #22
0
import pkg_resources
import signal
import subprocess
import sys

from rbtools import get_version_string
from rbtools.commands import find_entry_point_for_command, Option, RB_MAIN
from rbtools.utils.aliases import run_alias
from rbtools.utils.filesystem import load_config

GLOBAL_OPTIONS = [
    Option('-v',
           '--version',
           action='version',
           version='RBTools %s (Python %d.%d.%d)' %
           (get_version_string(), sys.version_info[:3][0],
            sys.version_info[:3][1], sys.version_info[:3][2])),
    Option('-h', '--help', action='store_true', dest='help', default=False),
    Option('command',
           nargs=argparse.REMAINDER,
           help='The RBTools command to execute, and any arguments. '
           '(See below)'),
]


def build_help_text(command_class):
    """Generate help text from a command class."""
    command = command_class()
    parser = command.create_parser({})

    return parser.format_help()