예제 #1
0
def get_static_page_config(app_settings_dir=None, logger=None):
    # Start with the deprecated `share/jupyter/lab/settings/page_config.json` data

    cm = ConfigManager(config_dir_name="labconfig")
    page_config = cm.get('page_config')

    # TODO: remove in JupyterLab 4.0
    if app_settings_dir:
        keyname = 'disabled_labextensions'
        old_page_config = pjoin(app_settings_dir, 'page_config.json')
        if osp.exists(old_page_config):
            if logger:
                logger.warn('** Upgrading deprecated page_config in %s' %
                            old_page_config)
                logger.warn(
                    '** This will no longer have an effect in JupyterLab 4.0')
                logger.warn('')
            with open(old_page_config) as fid:
                data = json.load(fid)
            os.remove(old_page_config)
            # Convert disabled_labextensions list to a dict
            oldKey = "disabledExtensions"
            if oldKey in data:
                data[keyname] = dict((key, True) for key in data[oldKey])
            del data[oldKey]

            recursive_update(page_config, data)
            cm.set('page_config', page_config)

    return page_config
예제 #2
0
def get_static_page_config(app_settings_dir=None, logger=None, level='all'):
    """Get the static page config for JupyterLab

    Params
    ------
    app_settings_dir: path, optional
        The path of the JupyterLab application settings directory
    logger: logger, optional
        An optional logging object
    level: string, optional ['all']
        The level at which to get config: can be 'all', 'user', 'sys_prefix', or 'system'
    """
    # Start with the deprecated `share/jupyter/lab/settings/page_config.json` data
    allowed = ['all', 'user', 'sys_prefix', 'system']
    if level not in allowed:
        raise ValueError(f'Page config level must be one of: {allowed}')

    if level == 'all':
        cm = ConfigManager(config_dir_name="labconfig")

    else:
        user = level == 'user'
        sys_prefix = level == 'sys_prefix'

        config_dir = _get_config_dir(level)

        cm = ConfigManager(config_dir_name="labconfig",
                           read_config_path=[config_dir],
                           write_config_dir=os.path.join(
                               config_dir, "labconfig"))

    page_config = cm.get('page_config')

    # TODO: remove in JupyterLab 4.0
    if app_settings_dir:
        keyname = 'disabled_labextensions'
        old_page_config = pjoin(app_settings_dir, 'page_config.json')
        if osp.exists(old_page_config):
            if logger:
                logger.warn('** Upgrading deprecated page_config in %s' %
                            old_page_config)
                logger.warn(
                    '** This will no longer have an effect in JupyterLab 4.0')
                logger.warn('')
            with open(old_page_config) as fid:
                data = json.load(fid)
            os.remove(old_page_config)
            # Convert disabled_labextensions list to a dict
            oldKey = "disabledExtensions"
            if oldKey in data:
                data[keyname] = dict((key, True) for key in data[oldKey])
            del data[oldKey]

            recursive_update(page_config, data)
            cm.set('page_config', page_config)

    return page_config
def _get_overrides(app_settings_dir):
    """Get overrides settings from `app_settings_dir`."""
    overrides, error = {}, ""
    overrides_path = os.path.join(app_settings_dir, 'overrides.json')
    if os.path.exists(overrides_path):
        with open(overrides_path, encoding='utf-8') as fid:
            try:
                overrides = json.load(fid)
            except Exception as e:
                error = e
    # Allow `default_settings_overrides.json` files in <jupyter_config>/labconfig dirs
    # to allow layering of defaults
    cm = ConfigManager(config_dir_name="labconfig")
    recursive_update(overrides, cm.get('default_setting_overrides'))

    return overrides, error
예제 #4
0
def _get_overrides(app_settings_dir):
    """Get overrides settings from `app_settings_dir`.

    The ordering of paths is:
    - {app_settings_dir}/overrides.d/*.{json,json5} (many, namespaced by package)
    - {app_settings_dir}/overrides.{json,json5} (singleton, owned by the user)
    """
    overrides, error = {}, ""

    overrides_d = os.path.join(app_settings_dir, 'overrides.d')

    # find (and sort) the conf.d overrides files
    all_override_paths = sorted([
        *(glob(os.path.join(overrides_d, '*.json'))),
        *(glob(os.path.join(overrides_d, '*.json5'))),
    ])

    all_override_paths += [
        os.path.join(app_settings_dir, 'overrides.json'),
        os.path.join(app_settings_dir, 'overrides.json5')
    ]

    for overrides_path in all_override_paths:
        if not os.path.exists(overrides_path):
            continue

        with open(overrides_path, encoding='utf-8') as fid:
            try:
                if overrides_path.endswith('.json5'):
                    path_overrides = json5.load(fid)
                else:
                    path_overrides = json.load(fid)
                for plugin_id, config in path_overrides.items():
                    recursive_update(overrides.setdefault(plugin_id, {}),
                                     config)
                print(overrides_path, overrides)
            except Exception as e:
                error = e

    # Allow `default_settings_overrides.json` files in <jupyter_config>/labconfig dirs
    # to allow layering of defaults
    cm = ConfigManager(config_dir_name="labconfig")

    for plugin_id, config in cm.get('default_setting_overrides').items():
        recursive_update(overrides.setdefault(plugin_id, {}), config)

    return overrides, error
예제 #5
0
def _override(schema_name, schema, overrides):
    """Override default values in the schema if necessary."""
    if schema_name in overrides:
        defaults = overrides[schema_name]
        for key in defaults:
            if key in schema["properties"]:
                new_defaults = schema["properties"][key]["default"]
                # If values for defaults are dicts do a recursive update
                if isinstance(new_defaults, dict):
                    recursive_update(new_defaults, defaults[key])
                else:
                    new_defaults = defaults[key]

                schema["properties"][key]["default"] = new_defaults
            else:
                schema["properties"][key] = dict(default=defaults[key])

    return schema
예제 #6
0
def get_page_config(labextensions_path, app_settings_dir=None, logger=None):
    """Get the page config for the application handler"""
    # Build up the full page config
    page_config = {}

    disabled_key = "disabledExtensions"

    # Start with the app_settings_dir as lowest priority
    if app_settings_dir:
        app_page_config = pjoin(app_settings_dir, "page_config.json")
        if osp.exists(app_page_config):
            with open(app_page_config, encoding="utf-8") as fid:
                data = json.load(fid)

            # Convert lists to dicts
            for key in [disabled_key, "deferredExtensions"]:
                if key in data:
                    data[key] = {key: True for key in data[key]}

            recursive_update(page_config, data)

    # Get the traitlets config
    static_page_config = get_static_page_config(logger=logger, level="all")
    recursive_update(page_config, static_page_config)

    # Handle federated extensions that disable other extensions
    disabled_by_extensions_all = {}
    extensions = page_config["federated_extensions"] = []

    federated_exts = get_federated_extensions(labextensions_path)

    # Ensure there is a disabled key
    page_config.setdefault(disabled_key, {})

    for (_, ext_data) in federated_exts.items():
        if "_build" not in ext_data["jupyterlab"]:
            logger.warning("%s is not a valid extension" % ext_data["name"])
            continue
        extbuild = ext_data["jupyterlab"]["_build"]
        extension = {"name": ext_data["name"], "load": extbuild["load"]}

        if "extension" in extbuild:
            extension["extension"] = extbuild["extension"]
        if "mimeExtension" in extbuild:
            extension["mimeExtension"] = extbuild["mimeExtension"]
        if "style" in extbuild:
            extension["style"] = extbuild["style"]
        extensions.append(extension)

        # If there is disabledExtensions metadata, consume it.
        name = ext_data["name"]

        if ext_data["jupyterlab"].get(disabled_key):
            disabled_by_extensions_all[
                ext_data["name"]] = ext_data["jupyterlab"][disabled_key]

    # Handle source extensions that disable other extensions
    # Check for `jupyterlab`:`extensionMetadata` in the built application directory's package.json
    if app_settings_dir:
        app_dir = osp.dirname(app_settings_dir)
        package_data_file = pjoin(app_dir, "static", "package.json")
        if osp.exists(package_data_file):
            with open(package_data_file, encoding="utf-8") as fid:
                app_data = json.load(fid)
            all_ext_data = app_data["jupyterlab"].get("extensionMetadata", {})
            for (ext, ext_data) in all_ext_data.items():
                if ext in disabled_by_extensions_all:
                    continue
                if ext_data.get(disabled_key):
                    disabled_by_extensions_all[ext] = ext_data[disabled_key]

    disabled_by_extensions = {}
    for name in sorted(disabled_by_extensions_all):
        # skip if the extension itself is disabled by other config
        if page_config[disabled_key].get(name) is True:
            continue

        disabled_list = disabled_by_extensions_all[name]
        for item in disabled_list:
            disabled_by_extensions[item] = True

    rollup_disabled = disabled_by_extensions
    rollup_disabled.update(page_config.get(disabled_key, []))
    page_config[disabled_key] = rollup_disabled

    # Convert dictionaries to lists to give to the front end
    for (key, value) in page_config.items():

        if isinstance(value, dict):
            page_config[key] = [subkey for subkey in value if value[subkey]]

    return page_config
예제 #7
0
def get_page_config(labextensions_path, app_settings_dir=None, logger=None):
    """Get the page config for the application handler"""
    # Build up the full page config
    page_config = {}

    disabled_key = "disabledExtensions"

    # Start with the app_settings_dir as lowest priority
    if app_settings_dir:
        app_page_config = pjoin(app_settings_dir, 'page_config.json')
        if osp.exists(app_page_config):
            with open(app_page_config, encoding='utf-8') as fid:
                data = json.load(fid)

            # Convert lists to dicts
            for key in [disabled_key, "deferredExtensions"]:
                if key in data:
                    data[key] = dict((key, True) for key in data[key])

            recursive_update(page_config, data)

    # Get the traitlets config
    static_page_config = get_static_page_config(logger=logger, level='all')
    recursive_update(page_config, static_page_config)

    # Handle federated extensions that disable other extensions
    disabled_by_extensions_all = dict()
    extensions = page_config['federated_extensions'] = []

    federated_exts = get_federated_extensions(labextensions_path)

    # Ensure there is a disabled key
    page_config.setdefault(disabled_key, {})

    for (ext, ext_data) in federated_exts.items():
        if not '_build' in ext_data['jupyterlab']:
            logger.warn('%s is not a valid extension' % ext_data['name'])
            continue
        extbuild = ext_data['jupyterlab']['_build']
        extension = {
            'name': ext_data['name'],
            'load': extbuild['load']
        }

        if 'extension' in extbuild:
            extension['extension'] = extbuild['extension']
        if 'mimeExtension' in extbuild:
            extension['mimeExtension'] = extbuild['mimeExtension']
        if 'style' in extbuild:
            extension['style'] = extbuild['style']
        extensions.append(extension)

        # If there is disabledExtensions metadata, consume it.
        name = ext_data['name']

        if ext_data['jupyterlab'].get(disabled_key):
            disabled_by_extensions_all[ext_data['name']] = ext_data['jupyterlab'][disabled_key]

    # Handle source extensions that disable other extensions
    # Check for `jupyterlab`:`extensionMetadata` in the built application directory's package.json
    if app_settings_dir:
        app_dir = osp.dirname(app_settings_dir)
        package_data_file = pjoin(app_dir, 'static', 'package.json')
        if osp.exists(package_data_file):
            with open(package_data_file, encoding='utf-8') as fid:
                app_data = json.load(fid)
            all_ext_data = app_data['jupyterlab'].get('extensionMetadata', {})
            for (ext, ext_data) in all_ext_data.items():
                if ext in disabled_by_extensions_all:
                    continue
                if ext_data.get(disabled_key):
                    disabled_by_extensions_all[ext] = ext_data[disabled_key]

    disabled_by_extensions = dict()
    for name in sorted(disabled_by_extensions_all):
        # skip if the extension itself is disabled by other config
        if page_config[disabled_key].get(name) == True:
            continue

        disabled_list = disabled_by_extensions_all[name]
        for item in disabled_list:
            disabled_by_extensions[item] = True

    rollup_disabled = disabled_by_extensions
    rollup_disabled.update(page_config.get(disabled_key, []))
    page_config[disabled_key] = rollup_disabled

    # Convert dictionaries to lists to give to the front end
    for (key, value) in page_config.items():

        if isinstance(value, dict):
            page_config[key] = [subkey for subkey in value if value[subkey]]

    return page_config