예제 #1
0
def version(request):
    return {
        'version': get_version_string(),
        'package_version': get_package_version(),
        'is_release': is_release(),
        'version_raw': VERSION,
    }
def parse_options():
    """
    Parses the options and stores them in the global options variable.
    """
    parser = OptionParser(usage="%prog name [options]",
                          version="Review Board " + get_version_string())
    parser.add_option("--class-name",
                      dest="class_name", default=None,
                      help="class name of extension (capitalized no spaces)")
    parser.add_option("--package-name",
                      dest="package_name", default=None,
                      help="package name of extension (lower case with " \
                           "underscores)")
    parser.add_option("--description",
                      dest="description", default=None,
                      help="description of extension")
    parser.add_option("--author",
                      dest="author", default=None,
                      help="author of the extension")
    parser.add_option("--is-configurable",
                      dest="is_configurable", action="store_true",
                      default=False,
                      help="whether this extension is configurable")
    (globals()["options"], args) = parser.parse_args()

    if len(args) != 1:
        print("Error: incorrect number of arguments")
        parser.print_help()
        exit(-1)
    options.extension_name = args[0]

    autofill_unprovided_options()
예제 #3
0
def get_server_info(request=None):
    """Return server information for use in the API.

    This is used for the root resource and for the deprecated server
    info resource.

    Args:
        request (django.http.HttpRequest, optional):
            The HTTP request from the client.

    Returns:
        dict:
        A dictionary of information about the server and its capabilities.
    """
    return {
        'product': {
            'name': 'Review Board',
            'version': get_version_string(),
            'package_version': get_package_version(),
            'is_release': is_release(),
        },
        'site': {
            'url': get_server_url(request=request),
            'administrators': [
                {
                    'name': name,
                    'email': email,
                }
                for name, email in settings.ADMINS
            ],
            'time_zone': settings.TIME_ZONE,
        },
        'capabilities': get_capabilities(request=request),
    }
예제 #4
0
def get_server_info(request=None):
    """Returns server information for use in the API.

    This is used for the root resource and for the deprecated server
    info resource.
    """
    capabilities = _capabilities_defaults.copy()
    capabilities.update(_registered_capabilities)

    return {
        'product': {
            'name': 'Review Board',
            'version': get_version_string(),
            'package_version': get_package_version(),
            'is_release': is_release(),
        },
        'site': {
            'url': get_server_url(request=request),
            'administrators': [
                {
                    'name': name,
                    'email': email,
                }
                for name, email in settings.ADMINS
            ],
            'time_zone': settings.TIME_ZONE,
        },
        'capabilities': capabilities
    }
예제 #5
0
    def get(self, request, *args, **kwargs):
        """Returns the information on the Review Board server."""
        site = Site.objects.get_current()
        siteconfig = SiteConfiguration.objects.get_current()

        url = '%s://%s%s' % (siteconfig.get('site_domain_method'), site.domain,
                             local_site_reverse('root', request=request))

        return 200, {
            self.item_result_key: {
                'product': {
                    'name': 'Review Board',
                    'version': get_version_string(),
                    'package_version': get_package_version(),
                    'is_release': is_release(),
                },
                'site': {
                    'url': url,
                    'administrators': [{'name': name, 'email': email}
                                       for name, email in settings.ADMINS],
                    'time_zone': settings.TIME_ZONE,
                },
                'capabilities': {
                    'diffs': {
                        'base_commit_ids': True,
                        'moved_files': True,
                    },
                    'scmtools': {
                        'perforce': {
                            'moved_files': True,
                        },
                    },
                },
            },
        }
예제 #6
0
def js_product_info():
    """Return JSON-serialized information on the product.

    This will include the product name, version (human-readable and raw
    version information), release status, and the URL to the manual, in a
    form that can be directly embedded into a template's JavaScript section.

    Since the data won't change between calls without performing an upgrade
    and restart, result is cached in the process. Repeated calls will return
    the cached information.

    Returns:
        django.utils.safestring.SafeText:
        The JSON-serialized product information.
    """
    global _product_info_str

    # We're caching the results, since this isn't going to ever change
    # between requests while the process is still running.
    if _product_info_str is None:
        _product_info_str = json_dumps({
            'isRelease': is_release(),
            'manualURL': get_manual_url(),
            'name': settings.PRODUCT_NAME,
            'version': get_version_string(),
            'versionInfo': VERSION[:-1],
        })

    return _product_info_str
예제 #7
0
def admin_sidebar(context):
    """Render the admin sidebar.

    This includes the configuration links and setting indicators.
    """
    request = context.get('request')

    request_context = {
        'count_users':
        User.objects.count(),
        'count_review_groups':
        Group.objects.count(),
        'count_default_reviewers':
        DefaultReviewer.objects.count(),
        'count_oauth_applications':
        Application.objects.count(),
        'count_repository':
        Repository.objects.accessible(request.user,
                                      visible_only=False).count(),
        'count_webhooks':
        WebHookTarget.objects.count(),
        'count_hosting_accounts':
        HostingServiceAccount.objects.count(),
        'has_cache_stats':
        get_has_cache_stats(),
        'version':
        get_version_string(),
    }

    return RequestContext(request, request_context)
예제 #8
0
def init_siteconfig():
    """Initialize the site configuration.

    This will create a SiteConfiguration object if one does not exist, or
    update the existing one with the current version number.
    """
    siteconfig, is_new = SiteConfiguration.objects.get_or_create(
        site=Site.objects.get_current())

    new_version = get_version_string()

    if is_new:
        migrate_settings(siteconfig)

        siteconfig.version = new_version
        siteconfig.save()
    elif siteconfig.version != new_version:
        print(
            _('Upgraded %(product)s from %(old_version)s to '
              '%(new_version)s') % {
                  'product': settings.PRODUCT_NAME,
                  'old_version': siteconfig.version,
                  'new_version': new_version,
              })
        siteconfig.version = new_version
        siteconfig.save(update_fields=('version', ))
예제 #9
0
def get_server_info(request=None):
    """Return server information for use in the API.

    This is used for the root resource and for the deprecated server
    info resource.

    Args:
        request (django.http.HttpRequest, optional):
            The HTTP request from the client.

    Returns:
        dict:
        A dictionary of information about the server and its capabilities.
    """
    return {
        'product': {
            'name': 'Review Board',
            'version': get_version_string(),
            'package_version': get_package_version(),
            'is_release': is_release(),
        },
        'site': {
            'url':
            get_server_url(request=request),
            'administrators': [{
                'name': name,
                'email': email,
            } for name, email in settings.ADMINS],
            'time_zone':
            settings.TIME_ZONE,
        },
        'capabilities': get_capabilities(request=request),
    }
예제 #10
0
def admin_actions(context):
    """Render the admin sidebar.

    This includes the configuration links and setting indicators.
    """
    request = context.get('request')

    if '_popup' not in request.REQUEST or 'pop' not in request.REQUEST:
        request_context = {
            'show_sidebar':
            True,
            'count_users':
            User.objects.count(),
            'count_review_groups':
            Group.objects.count(),
            'count_default_reviewers':
            DefaultReviewer.objects.count(),
            'count_repository':
            Repository.objects.accessible(request.user,
                                          visible_only=False).count(),
            'count_webhooks':
            WebHookTarget.objects.count(),
            'count_hosting_accounts':
            HostingServiceAccount.objects.count(),
            'has_cache_stats':
            get_has_cache_stats(),
            'version':
            get_version_string(),
        }
    else:
        request_context = {
            'show_sidebar': False,
        }

    return RequestContext(request, request_context)
예제 #11
0
def admin_actions(context):
    """Render the admin sidebar.

    This includes the configuration links and setting indicators.
    """
    request = context.get('request')

    if '_popup' not in request.REQUEST or 'pop' not in request.REQUEST:
        request_context = {
            'show_sidebar': True,
            'count_users': User.objects.count(),
            'count_review_groups': Group.objects.count(),
            'count_default_reviewers': DefaultReviewer.objects.count(),
            'count_repository': Repository.objects.accessible(
                request.user, visible_only=False).count(),
            'count_webhooks': WebHookTarget.objects.count(),
            'count_hosting_accounts': HostingServiceAccount.objects.count(),
            'has_cache_stats': get_has_cache_stats(),
            'version': get_version_string(),
        }
    else:
        request_context = {
            'show_sidebar': False,
        }

    return RequestContext(request, request_context)
예제 #12
0
def admin_actions(context):
    """Admin Sidebar with configuration links and setting indicators."""
    request = context.get('request')

    if '_popup' not in request.REQUEST or 'pop' not in request.REQUEST:
        request_context = {
            'show_sidebar':
            True,
            'count_users':
            User.objects.count(),
            'count_review_groups':
            Group.objects.count(),
            'count_default_reviewers':
            DefaultReviewer.objects.count(),
            'count_repository':
            Repository.objects.accessible(request.user,
                                          visible_only=False).count(),
            'has_cache_stats':
            get_has_cache_stats(),
            'version':
            get_version_string(),
        }
    else:
        request_context = {
            'show_sidebar': False,
        }

    return RequestContext(request, request_context)
예제 #13
0
def get_server_info(request=None):
    """Returns server information for use in the API.

    This is used for the root resource and for the deprecated server
    info resource.
    """
    capabilities = _capabilities_defaults.copy()
    capabilities.update(_registered_capabilities)

    return {
        'product': {
            'name': 'Review Board',
            'version': get_version_string(),
            'package_version': get_package_version(),
            'is_release': is_release(),
        },
        'site': {
            'url':
            get_server_url(request=request),
            'administrators': [{
                'name': name,
                'email': email,
            } for name, email in settings.ADMINS],
            'time_zone':
            settings.TIME_ZONE,
        },
        'capabilities': capabilities
    }
예제 #14
0
def parse_options(args):
    """Parse the given arguments into the global ``options`` dictionary."""
    global options

    hostname = None

    parser = OptionParser(usage='%prog [options] [user@]hostname [command]',
                          version='%prog ' + get_version_string())
    parser.disable_interspersed_args()
    parser.add_option('-l',
                      dest='username', metavar='USERNAME', default=None,
                      help='the user to log in as on the remote machine')
    parser.add_option('-p', '--port',
                      type='int', dest='port', metavar='PORT', default=None,
                      help='the port to connect to')
    parser.add_option('-q', '--quiet',
                      action='store_true', dest='quiet', default=False,
                      help='suppress any unnecessary output')
    parser.add_option('-s',
                      dest='subsystem', metavar='SUBSYSTEM', default=None,
                      nargs=2,
                      help='the subsystem to use (ssh or sftp)')
    parser.add_option('-V',
                      action='callback', callback=print_version,
                      help='display the version information and exit')
    parser.add_option('--rb-disallow-agent',
                      action='store_false', dest='allow_agent',
                      default=os.getenv('RBSSH_ALLOW_AGENT') != '0',
                      help='disable using the SSH agent for authentication')
    parser.add_option('--rb-local-site',
                      dest='local_site_name', metavar='NAME',
                      default=os.getenv('RB_LOCAL_SITE'),
                      help='the local site name containing the SSH keys to '
                           'use')

    (options, args) = parser.parse_args(args)

    if options.subsystem:
        if len(options.subsystem) != 2:
            parser.error('-s requires a hostname and a valid subsystem')
        elif options.subsystem[1] not in ('sftp', 'ssh'):
            parser.error('Invalid subsystem %s' % options.subsystem[1])

        hostname, options.subsystem = options.subsystem

    if len(args) == 0 and not hostname:
        parser.print_help()
        sys.exit(1)

    if not hostname:
        hostname = args[0]
        args = args[1:]

    if options.port:
        port = options.port
    else:
        port = SSH_PORT

    return hostname, port, args
예제 #15
0
def parse_options(args):
    """Parse the given arguments into the global ``options`` dictionary."""
    global options

    hostname = None

    parser = OptionParser(usage='%prog [options] [user@]hostname [command]',
                          version='%prog ' + get_version_string())
    parser.disable_interspersed_args()
    parser.add_option('-l',
                      dest='username', metavar='USERNAME', default=None,
                      help='the user to log in as on the remote machine')
    parser.add_option('-p', '--port',
                      type='int', dest='port', metavar='PORT', default=None,
                      help='the port to connect to')
    parser.add_option('-q', '--quiet',
                      action='store_true', dest='quiet', default=False,
                      help='suppress any unnecessary output')
    parser.add_option('-s',
                      dest='subsystem', metavar='SUBSYSTEM', default=None,
                      nargs=2,
                      help='the subsystem to use (ssh or sftp)')
    parser.add_option('-V',
                      action='callback', callback=print_version,
                      help='display the version information and exit')
    parser.add_option('--rb-disallow-agent',
                      action='store_false', dest='allow_agent',
                      default=os.getenv('RBSSH_ALLOW_AGENT') != '0',
                      help='disable using the SSH agent for authentication')
    parser.add_option('--rb-local-site',
                      dest='local_site_name', metavar='NAME',
                      default=os.getenv('RB_LOCAL_SITE'),
                      help='the local site name containing the SSH keys to '
                           'use')

    (options, args) = parser.parse_args(args)

    if options.subsystem:
        if len(options.subsystem) != 2:
            parser.error('-s requires a hostname and a valid subsystem')
        elif options.subsystem[1] not in ('sftp', 'ssh'):
            parser.error('Invalid subsystem %s' % options.subsystem[1])

        hostname, options.subsystem = options.subsystem

    if len(args) == 0 and not hostname:
        parser.print_help()
        sys.exit(1)

    if not hostname:
        hostname = args[0]
        args = args[1:]

    if options.port:
        port = options.port
    else:
        port = SSH_PORT

    return hostname, port, args
예제 #16
0
def version(request):
    return {
        'version': get_version_string(),
        'package_version': get_package_version(),
        'is_release': is_release(),
        'version_raw': VERSION,
        'RB_MANUAL_URL': get_manual_url(),
    }
예제 #17
0
def get_server_info(request=None):
    """Returns server information for use in the API.

    This is used for the root resource and for the deprecated server
    info resource.
    """
    site = Site.objects.get_current()
    siteconfig = SiteConfiguration.objects.get_current()

    url = '%s://%s%s' % (siteconfig.get('site_domain_method'), site.domain,
                         local_site_reverse('root', request=request))

    return {
        'product': {
            'name': 'Review Board',
            'version': get_version_string(),
            'package_version': get_package_version(),
            'is_release': is_release(),
        },
        'site': {
            'url': url,
            'administrators': [
                {
                    'name': name,
                    'email': email,
                }
                for name, email in settings.ADMINS
            ],
            'time_zone': settings.TIME_ZONE,
        },
        'capabilities': {
            'diffs': {
                'base_commit_ids': True,
                'moved_files': True,
            },
            'review_requests': {
                'commit_ids': True,
            },
            'scmtools': {
                'git': {
                    'empty_files': True,
                },
                'mercurial': {
                    'empty_files': True,
                },
                'perforce': {
                    'moved_files': True,
                    'empty_files': True,
                },
                'svn': {
                    'empty_files': True,
                },
            },
            'text': {
                'markdown': True,
            },
        }
    }
예제 #18
0
def version(request):
    """Return a dictionary with version information."""
    return {
        'version': get_version_string(),
        'package_version': get_package_version(),
        'is_release': is_release(),
        'version_raw': VERSION,
        'RB_MANUAL_URL': get_manual_url(),
    }
예제 #19
0
def parse_options(args):
    global options

    hostname = None

    parser = OptionParser(usage='%prog [options] [user@]hostname [command]',
                          version='%prog ' + get_version_string())
    parser.disable_interspersed_args()
    parser.add_option('-l',
                      dest='username',
                      metavar='USERNAME',
                      default=None,
                      help='the user to log in as on the remote machine')
    parser.add_option('-p',
                      '--port',
                      type='int',
                      dest='port',
                      metavar='PORT',
                      default=None,
                      help='the port to connect to')
    parser.add_option('-q',
                      '--quiet',
                      action='store_true',
                      dest='quiet',
                      default=False,
                      help='suppress any unnecessary output')
    parser.add_option('-s',
                      dest='subsystem',
                      metavar='SUBSYSTEM',
                      default=None,
                      nargs=2,
                      help='the subsystem to use (ssh or sftp)')
    parser.add_option('-V',
                      action='callback',
                      callback=print_version,
                      help='display the version information and exit')

    (options, args) = parser.parse_args(args)

    if options.subsystem:
        if len(options.subsystem) != 2:
            parser.error('-s requires a hostname and a valid subsystem')
        elif options.subsystem[1] not in ('sftp', 'ssh'):
            parser.error('Invalid subsystem %s' % options.subsystem[1])

        hostname, options.subsystem = options.subsystem

    if len(args) == 0 and not hostname:
        parser.print_help()
        sys.exit(1)

    if not hostname:
        hostname = args[0]
        args = args[1:]

    return hostname, args
예제 #20
0
def get_server_info(request=None):
    """Returns server information for use in the API.

    This is used for the root resource and for the deprecated server
    info resource.
    """
    return {
        'product': {
            'name': 'Review Board',
            'version': get_version_string(),
            'package_version': get_package_version(),
            'is_release': is_release(),
        },
        'site': {
            'url': get_server_url(request=request),
            'administrators': [
                {
                    'name': name,
                    'email': email,
                }
                for name, email in settings.ADMINS
            ],
            'time_zone': settings.TIME_ZONE,
        },
        'capabilities': {
            'diffs': {
                'base_commit_ids': True,
                'moved_files': True,
            },
            'review_requests': {
                'commit_ids': True,
            },
            'scmtools': {
                'git': {
                    'empty_files': True,
                },
                'mercurial': {
                    'empty_files': True,
                },
                'perforce': {
                    'moved_files': True,
                    'empty_files': True,
                },
                'svn': {
                    'empty_files': True,
                },
            },
            'text': {
                'markdown': True,
                'per_field_text_types': True,
                'can_include_raw_values': True,
            },
        }
    }
예제 #21
0
def main(version_file, site_folder):
    running_version = reviewboard.get_version_string()

    try:
        with open(version_file) as f:
            previous_version = f.readline().strip()
    except IOError:
        previous_version = "0.0.0"

    if semver.compare(running_version, previous_version) == 1:
        print("ReviewBoard upgrade detected, performing rb-site upgrade")
        subprocess.check_call(["rb-site", "upgrade", site_folder])
        with open(version_file, 'w') as f:
            f.write(running_version)
예제 #22
0
def admin_sidebar(context):
    """Render the admin sidebar.

    This includes the configuration links and setting indicators.
    """
    request = context.get('request')

    request_context = {
        'count_users': User.objects.count(),
        'count_review_groups': Group.objects.count(),
        'count_default_reviewers': DefaultReviewer.objects.count(),
        'count_oauth_applications': Application.objects.count(),
        'count_repository': Repository.objects.accessible(
            request.user, visible_only=False).count(),
        'count_webhooks': WebHookTarget.objects.count(),
        'count_hosting_accounts': HostingServiceAccount.objects.count(),
        'version': get_version_string(),
    }

    # We're precomputing URLs in here, rather than computing them in the
    # template, because we need to always ensure that reverse() will be
    # searching all available URL patterns and not just the ones bound to
    # request.current_app.
    #
    # current_app gets set by AdminSite views, and if we're in an extension's
    # AdminSite view, we'll fail to resolve these URLs from within the
    # template. We don't have that problem if calling reverse() ourselves.
    request_context.update({
        'url_%s' % url_name: reverse('admin:%s' % url_name)
        for url_name in ('auth_user_add',
                         'auth_user_changelist',
                         'hostingsvcs_hostingserviceaccount_add',
                         'hostingsvcs_hostingserviceaccount_changelist',
                         'notifications_webhooktarget_add',
                         'notifications_webhooktarget_changelist',
                         'oauth_application_add',
                         'oauth_application_changelist',
                         'reviews_defaultreviewer_add',
                         'reviews_defaultreviewer_changelist',
                         'reviews_group_add',
                         'reviews_group_changelist',
                         'scmtools_repository_add',
                         'scmtools_repository_changelist')
    })

    return RequestContext(request, request_context)
예제 #23
0
def init_siteconfig(app, created_models, verbosity, db=None, **kwargs):
    """Initialize the site configuration.

    This will create a SiteConfiguration object if one does not exist, or
    update the existing one with the current version number.
    """
    try:
        site = Site.objects.get_current()
    except Site.DoesNotExist:
        # This is an initial syncdb and we got called before Site's post_syncdb
        # handler did, so invoke it directly.
        from django.contrib.sites.management import create_default_site
        create_default_site(app, created_models, verbosity, db=db)
        site = Site.objects.get_current()

    siteconfig, is_new = SiteConfiguration.objects.get_or_create(site=site)

    new_version = get_version_string()

    if is_new:
        # Check the Site to see if this is a brand new installation. If so,
        # don't talk to the user about upgrades or other such nonsense.
        if Site not in created_models:
            print("*** Migrating settings from settings_local.py to the "
                  "database.")

        migrate_settings(siteconfig)

        if Site not in created_models:
            print("*** If you have previously configured Review Board "
                  "through a ")
            print("*** settings_local.py file, please ensure that the "
                  "migration ")
            print("*** was successful by verifying your settings at")
            print("*** %s://%s%sadmin/settings/" %
                  (siteconfig.get("site_domain_method"),
                   site.domain,
                   settings.SITE_ROOT))

        siteconfig.version = new_version
        siteconfig.save()
    elif siteconfig.version != new_version:
        print("Upgrading Review Board from %s to %s" % (siteconfig.version,
                                                        new_version))
        siteconfig.version = new_version
        siteconfig.save()
예제 #24
0
def init_siteconfig(app, created_models, verbosity, db=None, **kwargs):
    """
    Initializes the site configuration with the current version of the
    software.
    """
    try:
        site = Site.objects.get_current()
    except Site.DoesNotExist:
        # This is an initial syncdb and we got called before Site's post_syncdb
        # handler did, so invoke it directly.
        from django.contrib.sites.management import create_default_site
        create_default_site(app, created_models, verbosity, db=db)
        site = Site.objects.get_current()

    siteconfig, is_new = SiteConfiguration.objects.get_or_create(site=site)

    new_version = get_version_string()

    if is_new:
        # Check the Site to see if this is a brand new installation. If so,
        # don't talk to the user about upgrades or other such nonsense.
        if Site not in created_models:
            print "*** Migrating settings from settings_local.py to the " \
                  "database."

        migrate_settings(siteconfig)

        if Site not in created_models:
            print "*** If you have previously configured Review Board " \
                  "through a "
            print "*** settings_local.py file, please ensure that the " \
                  "migration "
            print "*** was successful by verifying your settings at"
            print "*** %s://%s%sadmin/settings/" % \
                (siteconfig.get("site_domain_method"),
                 site.domain,
                 settings.SITE_ROOT)

        siteconfig.version = new_version
        siteconfig.save()
    elif siteconfig.version != new_version:
        print "Upgrading Review Board from %s to %s" % (siteconfig.version,
                                                        new_version)
        siteconfig.version = new_version
        siteconfig.save()
예제 #25
0
def pytest_report_header(config):
    """Return information for the report header.

    This will log the version of Django.

    Args:
        config (object):
            The pytest configuration object.

    Returns:
        list of unicode:
        The report header entries to log.
    """
    return [
        'Review Board: %s' % reviewboard.get_version_string(),
        'Djblets: %s' % djblets.get_version_string(),
        'Django: %s' % django.get_version(),
    ]
예제 #26
0
def version(request):
    """Return a dictionary with version information.

    Args:
        request (django.http.HttpRequest):
            The current HTTP request.

    Returns:
        dict:
        State to add to the context.
    """
    return {
        'version': get_version_string(),
        'package_version': get_package_version(),
        'is_release': is_release(),
        'version_raw': VERSION,
        'RB_MANUAL_URL': get_manual_url(),
    }
예제 #27
0
def server_info(request):
    site = Site.objects.get_current()
    siteconfig = site.config.get()

    url = "%s://%s%s" % (siteconfig.get("site_domain_method"), site.domain, settings.SITE_ROOT)

    return WebAPIResponse(
        request,
        {
            "product": {
                "name": "Review Board",
                "version": get_version_string(),
                "package_version": get_package_version(),
                "is_release": is_release(),
            },
            "site": {"url": url, "administrators": [{"name": name, "email": email} for name, email in settings.ADMINS]},
        },
    )
예제 #28
0
def parse_options(args):
    global options

    hostname = None

    parser = OptionParser(usage='%prog [options] [user@]hostname [command]',
                          version='%prog ' + get_version_string())
    parser.disable_interspersed_args()
    parser.add_option('-l',
                      dest='username', metavar='USERNAME', default=None,
                      help='the user to log in as on the remote machine')
    parser.add_option('-p', '--port',
                      type='int', dest='port', metavar='PORT', default=None,
                      help='the port to connect to')
    parser.add_option('-q', '--quiet',
                      action='store_true', dest='quiet', default=False,
                      help='suppress any unnecessary output')
    parser.add_option('-s',
                      dest='subsystem', metavar='SUBSYSTEM', default=None,
                      nargs=2,
                      help='the subsystem to use (ssh or sftp)')
    parser.add_option('-V',
                      action='callback', callback=print_version,
                      help='display the version information and exit')

    (options, args) = parser.parse_args(args)

    if options.subsystem:
        if len(options.subsystem) != 2:
            parser.error('-s requires a hostname and a valid subsystem')
        elif options.subsystem[1] not in ('sftp', 'ssh'):
            parser.error('Invalid subsystem %s' % options.subsystem[1])

        hostname, options.subsystem = options.subsystem

    if len(args) == 0 and not hostname:
        parser.print_help()
        sys.exit(1)

    if not hostname:
        hostname = args[0]
        args = args[1:]

    return hostname, args
예제 #29
0
def server_info(request):
    site = Site.objects.get_current()
    siteconfig = site.config.get()

    url = '%s://%s%s' % (siteconfig.get('site_domain_method'), site.domain,
                         settings.SITE_ROOT)

    return WebAPIResponse(request, {
        'product': {
            'name': 'Review Board',
            'version': get_version_string(),
            'package_version': get_package_version(),
            'is_release': is_release(),
        },
        'site': {
            'url': url,
            'administrators': [{'name': name, 'email': email}
                               for name, email in settings.ADMINS],
        },
    })
예제 #30
0
    def compare_item(self, item_rsp, obj):
        self.assertIn('product', item_rsp)
        self.assertIn('site', item_rsp)
        self.assertIn('capabilities', item_rsp)

        product_rsp = item_rsp['product']
        self.assertEqual(product_rsp['name'], 'Review Board')
        self.assertEqual(product_rsp['version'], get_version_string())
        self.assertEqual(product_rsp['package_version'], get_package_version())
        self.assertEqual(product_rsp['is_release'], is_release())

        site_rsp = item_rsp['site']
        self.assertTrue(site_rsp['url'].startswith(get_server_url()))
        self.assertEqual(site_rsp['administrators'], [{
            'name': name,
            'email': email,
        } for name, email in settings.ADMINS])
        self.assertEqual(site_rsp['time_zone'], settings.TIME_ZONE)

        self.assertEqual(item_rsp['capabilities'], get_capabilities())
예제 #31
0
def parse_options():
    """
    Parses the options and stores them in the global options variable.
    """
    parser = OptionParser(usage="%prog name [options]",
                          version="Review Board " + get_version_string())
    parser.add_option("--class-name",
                      dest="class_name",
                      default=None,
                      help="class name of extension (capitalized no spaces)")
    parser.add_option("--package-name",
                      dest="package_name", default=None,
                      help="package name of extension (lower case with " \
                           "underscores)")
    parser.add_option("--description",
                      dest="description",
                      default=None,
                      help="description of extension")
    parser.add_option("--author",
                      dest="author",
                      default=None,
                      help="author of the extension")
    parser.add_option("--dashboard-link",
                      dest="dashboard_link", default=None,
                      metavar="DASHBOARD_LINK_LABEL",
                      help="creates a dashboard link with this name in the " \
                           "review requests sidebar (optional)")
    parser.add_option("--is-configurable",
                      dest="is_configurable",
                      action="store_true",
                      default=False,
                      help="whether this extension is configurable")
    (globals()["options"], args) = parser.parse_args()

    if len(args) != 1:
        print("Error: incorrect number of arguments")
        parser.print_help()
        exit(-1)
    options.extension_name = args[0]

    autofill_unprovided_options()
예제 #32
0
def init_siteconfig():
    """Initialize the site configuration.

    This will create a SiteConfiguration object if one does not exist, or
    update the existing one with the current version number.
    """
    siteconfig, is_new = SiteConfiguration.objects.get_or_create(
        site=Site.objects.get_current())

    new_version = get_version_string()

    if is_new:
        migrate_settings(siteconfig)

        siteconfig.version = new_version
        siteconfig.save()
    elif siteconfig.version != new_version:
        print('Upgrading Review Board from %s to %s' %
              (siteconfig.version, new_version))
        siteconfig.version = new_version
        siteconfig.save(update_fields=('version', ))
예제 #33
0
def admin_actions(context):
    """Admin Sidebar with configuration links and setting indicators."""
    request = context.get('request')

    if '_popup' not in request.REQUEST or 'pop' not in request.REQUEST:
        request_context = {
            'show_sidebar': True,
            'count_users': User.objects.count(),
            'count_review_groups': Group.objects.count(),
            'count_default_reviewers': DefaultReviewer.objects.count(),
            'count_repository':
                Repository.objects.accessible(request.user).count(),
            'has_cache_stats': get_has_cache_stats(),
            'version': get_version_string(),
        }
    else:
        request_context = {
            'show_sidebar': False,
        }

    return RequestContext(request, request_context)
예제 #34
0
    def get(self, request, *args, **kwargs):
        """Returns the information on the Review Board server."""
        site = Site.objects.get_current()
        siteconfig = SiteConfiguration.objects.get_current()

        url = '%s://%s%s' % (siteconfig.get('site_domain_method'), site.domain,
                             local_site_reverse('root', request=request))

        return 200, {
            self.item_result_key: {
                'product': {
                    'name': 'Review Board',
                    'version': get_version_string(),
                    'package_version': get_package_version(),
                    'is_release': is_release(),
                },
                'site': {
                    'url':
                    url,
                    'administrators': [{
                        'name': name,
                        'email': email
                    } for name, email in settings.ADMINS],
                    'time_zone':
                    settings.TIME_ZONE,
                },
                'capabilities': {
                    'diffs': {
                        'base_commit_ids': True,
                        'moved_files': True,
                    },
                    'scmtools': {
                        'perforce': {
                            'moved_files': True,
                        },
                    },
                },
            },
        }
예제 #35
0
def parse_options(args):
    global options

    # There are two sets of arguments we may find. We want to handle
    # anything before the hostname, but nothing after it. So, split
    # up the argument list.

    rbssh_args = []
    command_args = []

    found_hostname = False

    for arg in args:
        if arg.startswith('-'):
            if found_hostname:
                command_args.append(arg)
            else:
                rbssh_args.append(arg)
        else:
            found_hostname = True
            rbssh_args.append(arg)

    parser = OptionParser(usage='%prog [options] [user@]hostname command',
                          version='%prog ' + get_version_string())
    parser.add_option('-p', '--port',
                      dest='port', metavar='PORT', default=None,
                      help='the port to connect to')
    parser.add_option('-q', '--quiet',
                      action='store_true', dest='quiet', default=False,
                      help='suppress any unnecessary output')

    (options, args) = parser.parse_args(rbssh_args)

    if len(rbssh_args) < 2:
        parser.print_help()
        sys.exit(1)

    return args[0], args[1:] + command_args
예제 #36
0
    def __call__(self, parser, *args, **kwargs):
        """Call the action.

        This will display the version information directly to the terminal
        and then exit.

        Args:
            parser (argparse.ArgumentParser):
                The argument parser that called this action.

            *args (tuple, unused):
                Unused positional arguments.

            **kwargs (dict, unused):
                Unused keyword arguments.
        """
        parser.exit(message=('\n'.join([
            'Review Board/%s %s' %
            (parser.prog, reviewboard.get_version_string()),
            'Python %s' % sys.version.splitlines()[0],
            'Installed to %s' % os.path.dirname(reviewboard.__file__),
            '',
        ])))
예제 #37
0
    def compare_item(self, item_rsp, obj):
        self.assertIn('product', item_rsp)
        self.assertIn('site', item_rsp)
        self.assertIn('capabilities', item_rsp)

        product_rsp = item_rsp['product']
        self.assertEqual(product_rsp['name'], 'Review Board')
        self.assertEqual(product_rsp['version'], get_version_string())
        self.assertEqual(product_rsp['package_version'], get_package_version())
        self.assertEqual(product_rsp['is_release'], is_release())

        site_rsp = item_rsp['site']
        self.assertTrue(site_rsp['url'].startswith(get_server_url()))
        self.assertEqual(site_rsp['administrators'], [
            {
                'name': name,
                'email': email,
            }
            for name, email in settings.ADMINS
        ])
        self.assertEqual(site_rsp['time_zone'], settings.TIME_ZONE)

        self.assertEqual(item_rsp['capabilities'], get_capabilities())
예제 #38
0
#!/usr/bin/env python

from __future__ import print_function, unicode_literals

import os
import sys

if __name__ == '__main__':
    os.chdir(os.path.join(os.path.dirname(__file__), '..'))
    sys.path.insert(0, os.getcwd())

    import django
    import djblets
    import reviewboard

    print('Review Board %s' % reviewboard.get_version_string())
    print('Djblets %s' % djblets.get_version_string())
    print('Django %s' % django.__version__)
    print('Python %s.%s.%s' % sys.version_info[:3])
    print()

    # We're just wrapping the manage script. Both that script and the test
    # runner are expecting sys.argv to be set. Fake it here so we don't have
    # to shell out to another process just to get a proper set of arguments.
    sys.argv = [sys.argv[0], 'test', '--'] + sys.argv[1:]

    os.environ[str('RB_RUNNING_TESTS')] = str('1')
    os.environ[str('RBSSH_STORAGE_BACKEND')] = \
        str('reviewboard.ssh.storage.FileSSHStorage')

    from reviewboard.manage import run as run_manage
예제 #39
0
def check_updates_required():
    """Checks if there are manual updates required.

    Sometimes, especially in developer installs, some things need to be tweaked
    by hand before Review Board can be used on this server.
    """
    global _install_fine

    updates_required = []

    if not _install_fine:
        site_dir = os.path.dirname(settings.HTDOCS_ROOT)
        devel_install = (os.path.exists(os.path.join(settings.LOCAL_ROOT,
                                                     'manage.py')))
        siteconfig = None

        # Check if we can access a SiteConfiguration. There should always
        # be one, unless the user has erased stuff by hand.
        #
        # This also checks for any sort of errors in talking to the database.
        # This could be due to the database being down, or corrupt, or
        # tables locked, or an empty database, or other cases. We want to
        # catch this before getting the point where plain 500 Internal Server
        # Errors appear.
        try:
            siteconfig = SiteConfiguration.objects.get_current()
        except (DatabaseError, SiteConfiguration.DoesNotExist), e:
            updates_required.append((
                'admin/manual-updates/database-error.html', {
                    'error': e,
                }
            ))

        # Check if the version running matches the last stored version.
        # Only do this for non-debug installs, as it's really annoying on
        # a developer install.:
        cur_version = get_version_string()

        if siteconfig and siteconfig.version != cur_version:
            updates_required.append((
                'admin/manual-updates/version-mismatch.html', {
                    'current_version': cur_version,
                    'stored_version': siteconfig.version,
                    'site_dir': site_dir,
                    'devel_install': devel_install,
                }
            ))

        # Check if the site has moved and the old media directory no longer
        # exists.
        if siteconfig and not os.path.exists(settings.STATIC_ROOT):
            new_media_root = os.path.join(settings.HTDOCS_ROOT, "static")

            if os.path.exists(new_media_root):
                siteconfig.set("site_media_root", new_media_root)
                settings.STATIC_ROOT = new_media_root


        # Check if there's a media/uploaded/images directory. If not, this is
        # either a new install or is using the old-style media setup and needs
        # to be manually upgraded.
        uploaded_dir = os.path.join(settings.MEDIA_ROOT, "uploaded")

        if not os.path.isdir(uploaded_dir) or \
           not os.path.isdir(os.path.join(uploaded_dir, "images")):
            updates_required.append((
                "admin/manual-updates/media-upload-dir.html", {
                    'MEDIA_ROOT': settings.MEDIA_ROOT
                }
            ))


        try:
            username = getpass.getuser()
        except ImportError:
            # This will happen if running on Windows (which doesn't have
            # the pwd module) and if %LOGNAME%, %USER%, %LNAME% and
            # %USERNAME% are all undefined.
            username = "******"

        # Check if the data directory (should be $HOME) is writable by us.
        data_dir = os.environ.get('HOME', '')

        if (not data_dir or
            not os.path.isdir(data_dir) or
            not os.access(data_dir, os.W_OK)):
            try:
                username = getpass.getuser()
            except ImportError:
                # This will happen if running on Windows (which doesn't have
                # the pwd module) and if %LOGNAME%, %USER%, %LNAME% and
                # %USERNAME% are all undefined.
                username = "******"

            updates_required.append((
                'admin/manual-updates/data-dir.html', {
                    'data_dir': data_dir,
                    'writable': os.access(data_dir, os.W_OK),
                    'server_user': username,
                    'expected_data_dir': os.path.join(site_dir, 'data'),
                }
            ))


        # Check if the htdocs/media/ext directory is writable by us.
        ext_dir = settings.EXTENSIONS_STATIC_ROOT

        if not os.path.isdir(ext_dir) or not os.access(ext_dir, os.W_OK):
            updates_required.append((
                'admin/manual-updates/ext-dir.html', {
                    'ext_dir': ext_dir,
                    'writable': os.access(ext_dir, os.W_OK),
                    'server_user': username,
                }
            ))

        if not is_exe_in_path('patch'):
            if sys.platform == 'win32':
                binaryname = 'patch.exe'
            else:
                binaryname = 'patch'

            updates_required.append((
                "admin/manual-updates/install-patch.html", {
                    'platform': sys.platform,
                    'binaryname': binaryname,
                    'search_path': os.getenv('PATH'),
                }
            ))


        #
        # NOTE: Add new checks above this.
        #


        _install_fine = not updates_required
예제 #40
0
def check_updates_required():
    """Check if there are manual updates required.

    Sometimes, especially in developer installs, some things need to be tweaked
    by hand before Review Board can be used on this server.
    """
    global _install_fine

    updates_required = []

    if not _install_fine:
        site_dir = os.path.dirname(settings.HTDOCS_ROOT)
        devel_install = (os.path.exists(
            os.path.join(settings.LOCAL_ROOT, 'manage.py')))
        siteconfig = None

        # Check if we can access a SiteConfiguration. There should always
        # be one, unless the user has erased stuff by hand.
        #
        # This also checks for any sort of errors in talking to the database.
        # This could be due to the database being down, or corrupt, or
        # tables locked, or an empty database, or other cases. We want to
        # catch this before getting the point where plain 500 Internal Server
        # Errors appear.
        try:
            siteconfig = SiteConfiguration.objects.get_current()
        except (DatabaseError, SiteConfiguration.DoesNotExist) as e:
            updates_required.append(
                ('admin/manual-updates/database-error.html', {
                    'error': e,
                }))

        # Check if the version running matches the last stored version.
        # Only do this for non-debug installs, as it's really annoying on
        # a developer install.:
        cur_version = get_version_string()

        if siteconfig and siteconfig.version != cur_version:
            updates_required.append(
                ('admin/manual-updates/version-mismatch.html', {
                    'current_version': cur_version,
                    'stored_version': siteconfig.version,
                    'site_dir': site_dir,
                    'devel_install': devel_install,
                }))

        # Check if the site has moved and the old media directory no longer
        # exists.
        if siteconfig and not os.path.exists(settings.STATIC_ROOT):
            new_media_root = os.path.join(settings.HTDOCS_ROOT, "static")

            if os.path.exists(new_media_root):
                siteconfig.set("site_media_root", new_media_root)
                settings.STATIC_ROOT = new_media_root

        # Check if the user has any pending static media configuration
        # changes they need to make.
        if siteconfig and 'manual-updates' in siteconfig.settings:
            stored_updates = siteconfig.settings['manual-updates']

            if not stored_updates.get('static-media', False):
                updates_required.append(
                    ('admin/manual-updates/server-static-config.html', {
                        'STATIC_ROOT': settings.STATIC_ROOT,
                        'SITE_ROOT': settings.SITE_ROOT,
                        'SITE_DIR': settings.LOCAL_ROOT,
                    }))

        # Check if there's a media/uploaded/images directory. If not, this is
        # either a new install or is using the old-style media setup and needs
        # to be manually upgraded.
        uploaded_dir = os.path.join(settings.MEDIA_ROOT, "uploaded")

        if not os.path.isdir(uploaded_dir) or \
           not os.path.isdir(os.path.join(uploaded_dir, "images")):
            updates_required.append(
                ("admin/manual-updates/media-upload-dir.html", {
                    'MEDIA_ROOT': settings.MEDIA_ROOT
                }))

        try:
            username = getpass.getuser()
        except ImportError:
            # This will happen if running on Windows (which doesn't have
            # the pwd module) and if %LOGNAME%, %USER%, %LNAME% and
            # %USERNAME% are all undefined.
            username = "******"

        # Check if the data directory (should be $HOME) is writable by us.
        data_dir = os.environ.get('HOME', '')

        if (not data_dir or not os.path.isdir(data_dir)
                or not os.access(data_dir, os.W_OK)):
            try:
                username = getpass.getuser()
            except ImportError:
                # This will happen if running on Windows (which doesn't have
                # the pwd module) and if %LOGNAME%, %USER%, %LNAME% and
                # %USERNAME% are all undefined.
                username = "******"

            updates_required.append(('admin/manual-updates/data-dir.html', {
                'data_dir':
                data_dir,
                'writable':
                os.access(data_dir, os.W_OK),
                'server_user':
                username,
                'expected_data_dir':
                os.path.join(site_dir, 'data'),
            }))

        # Check if the the legacy htdocs and modern static extension
        # directories exist and are writable by us.
        ext_roots = [settings.MEDIA_ROOT]

        if not settings.DEBUG:
            ext_roots.append(settings.STATIC_ROOT)

        for root in ext_roots:
            ext_dir = os.path.join(root, 'ext')

            if not os.path.isdir(ext_dir) or not os.access(ext_dir, os.W_OK):
                updates_required.append(('admin/manual-updates/ext-dir.html', {
                    'ext_dir':
                    ext_dir,
                    'writable':
                    os.access(ext_dir, os.W_OK),
                    'server_user':
                    username,
                }))

        if not is_exe_in_path('patch'):
            if sys.platform == 'win32':
                binaryname = 'patch.exe'
            else:
                binaryname = 'patch'

            updates_required.append(
                ("admin/manual-updates/install-patch.html", {
                    'platform': sys.platform,
                    'binaryname': binaryname,
                    'search_path': os.getenv('PATH'),
                }))

        #
        # NOTE: Add new checks above this.
        #

        _install_fine = not updates_required

    return updates_required
예제 #41
0
# Yes, it's a hack. We can remove it when djblets is removed from the source
# directory.
log = __import__("djblets.log", {}, {}, ["log"])

from reviewboard import get_version_string
from reviewboard import signals
from reviewboard.reviews.feeds import RssReviewsFeed, AtomReviewsFeed, \
                                      RssSubmitterReviewsFeed, \
                                      AtomSubmitterReviewsFeed, \
                                      RssGroupReviewsFeed, \
                                      AtomGroupReviewsFeed


# Set up logging.
log.init_logging()
logging.info("Log file for Review Board v%s" % get_version_string())


# Generate cache serials
generate_cache_serials()


# Load in all the models for the admin UI.
if not admin.site._registry:
    admin.autodiscover()


# URLs global to all modes
urlpatterns = patterns('',
    (r'^admin/', include('reviewboard.admin.urls')),
)
예제 #42
0
# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'Review Board Codebase'
copyright = u'2009-2010, Christian Hammond'

# 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 reviewboard.__version_info__[:2]])
# The full version, including alpha/beta/rc tags.
release = reviewboard.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
예제 #43
0
def check_updates_required():
    """Checks if there are manual updates required.

    Sometimes, especially in developer installs, some things need to be tweaked
    by hand before Review Board can be used on this server.
    """
    global _install_fine

    updates_required = []

    if not _install_fine:
        site_dir = os.path.dirname(settings.HTDOCS_ROOT)
        devel_install = os.path.exists(os.path.join(settings.LOCAL_ROOT, "manage.py"))
        siteconfig = None

        # Check if we can access a SiteConfiguration. There should always
        # be one, unless the user has erased stuff by hand.
        #
        # This also checks for any sort of errors in talking to the database.
        # This could be due to the database being down, or corrupt, or
        # tables locked, or an empty database, or other cases. We want to
        # catch this before getting the point where plain 500 Internal Server
        # Errors appear.
        try:
            siteconfig = SiteConfiguration.objects.get_current()
        except (DatabaseError, SiteConfiguration.DoesNotExist) as e:
            updates_required.append(("admin/manual-updates/database-error.html", {"error": e}))

        # Check if the version running matches the last stored version.
        # Only do this for non-debug installs, as it's really annoying on
        # a developer install.:
        cur_version = get_version_string()

        if siteconfig and siteconfig.version != cur_version:
            updates_required.append(
                (
                    "admin/manual-updates/version-mismatch.html",
                    {
                        "current_version": cur_version,
                        "stored_version": siteconfig.version,
                        "site_dir": site_dir,
                        "devel_install": devel_install,
                    },
                )
            )

        # Check if the site has moved and the old media directory no longer
        # exists.
        if siteconfig and not os.path.exists(settings.STATIC_ROOT):
            new_media_root = os.path.join(settings.HTDOCS_ROOT, "static")

            if os.path.exists(new_media_root):
                siteconfig.set("site_media_root", new_media_root)
                settings.STATIC_ROOT = new_media_root

        # Check if the user has any pending static media configuration
        # changes they need to make.
        if siteconfig and "manual-updates" in siteconfig.settings:
            stored_updates = siteconfig.settings["manual-updates"]

            if not stored_updates.get("static-media", False):
                updates_required.append(
                    (
                        "admin/manual-updates/server-static-config.html",
                        {
                            "STATIC_ROOT": settings.STATIC_ROOT,
                            "SITE_ROOT": settings.SITE_ROOT,
                            "SITE_DIR": settings.LOCAL_ROOT,
                        },
                    )
                )

        # Check if there's a media/uploaded/images directory. If not, this is
        # either a new install or is using the old-style media setup and needs
        # to be manually upgraded.
        uploaded_dir = os.path.join(settings.MEDIA_ROOT, "uploaded")

        if not os.path.isdir(uploaded_dir) or not os.path.isdir(os.path.join(uploaded_dir, "images")):
            updates_required.append(("admin/manual-updates/media-upload-dir.html", {"MEDIA_ROOT": settings.MEDIA_ROOT}))

        try:
            username = getpass.getuser()
        except ImportError:
            # This will happen if running on Windows (which doesn't have
            # the pwd module) and if %LOGNAME%, %USER%, %LNAME% and
            # %USERNAME% are all undefined.
            username = "******"

        # Check if the data directory (should be $HOME) is writable by us.
        data_dir = os.environ.get("HOME", "")

        if not data_dir or not os.path.isdir(data_dir) or not os.access(data_dir, os.W_OK):
            try:
                username = getpass.getuser()
            except ImportError:
                # This will happen if running on Windows (which doesn't have
                # the pwd module) and if %LOGNAME%, %USER%, %LNAME% and
                # %USERNAME% are all undefined.
                username = "******"

            updates_required.append(
                (
                    "admin/manual-updates/data-dir.html",
                    {
                        "data_dir": data_dir,
                        "writable": os.access(data_dir, os.W_OK),
                        "server_user": username,
                        "expected_data_dir": os.path.join(site_dir, "data"),
                    },
                )
            )

        # Check if the the legacy htdocs and modern static extension
        # directories exist and are writable by us.
        ext_roots = [settings.MEDIA_ROOT]

        if not settings.DEBUG:
            ext_roots.append(settings.STATIC_ROOT)

        for root in ext_roots:
            ext_dir = os.path.join(root, "ext")

            if not os.path.isdir(ext_dir) or not os.access(ext_dir, os.W_OK):
                updates_required.append(
                    (
                        "admin/manual-updates/ext-dir.html",
                        {"ext_dir": ext_dir, "writable": os.access(ext_dir, os.W_OK), "server_user": username},
                    )
                )

        if not is_exe_in_path("patch"):
            if sys.platform == "win32":
                binaryname = "patch.exe"
            else:
                binaryname = "patch"

            updates_required.append(
                (
                    "admin/manual-updates/install-patch.html",
                    {"platform": sys.platform, "binaryname": binaryname, "search_path": os.getenv("PATH")},
                )
            )

        #
        # NOTE: Add new checks above this.
        #

        _install_fine = not updates_required

    return updates_required