Beispiel #1
0
def install(enable=False, disable=False, prefix=None):
    """Install the nb_config_manager config piece.

    Parameters
    ----------
    enable: bool
        Enable the nb_config_manager on every notebook launch
    disable: bool
        Disable nb_config_manager on every notebook launch
    """
    from notebook.services.config import ConfigManager

    if enable:
        if prefix is not None:
            path = join(prefix, "etc", "jupyter")
            if not exists(path):
                print("Making directory", path)
                os.makedirs(path)
        else:
            path = jupyter_config_dir()

        cm = ConfigManager(config_dir=path)
        print("Enabling nb_config_manager in", cm.config_dir)
        cfg = cm.get("jupyter_notebook_config")
        print("Existing config...")
        pprint(cfg)

        notebook_app = cfg.setdefault("NotebookApp", {})
        if "config_manager_class" not in notebook_app:
            cfg["NotebookApp"]["config_manager_class"] = "nb_config_manager.EnvironmentConfigManager"

        cm.update("jupyter_notebook_config", cfg)
        print("New config...")
        pprint(cm.get("jupyter_notebook_config"))

    if disable:
        if prefix is not None:
            path = join(prefix, "etc", "jupyter")
        else:
            path = jupyter_config_dir()

        cm = ConfigManager(config_dir=path)
        print("Disabling nb_config_manager in", cm.config_dir)
        cfg = cm.get("jupyter_notebook_config")
        print("Existing config...")
        pprint(cfg)

        config_manager = cfg["NotebookApp"]["config_manager_class"]

        if "nb_config_manager.EnvironmentConfigManager" == config_manager:
            cfg["NotebookApp"].pop("config_manager_class")

        cm.set("jupyter_notebook_config", cfg)
        print("New config...")
        pprint(cm.get("jupyter_notebook_config"))
class NBSetup(object):
    extensions_map = {
        'notebook': 'main.js',
        'tree': 'tree.js',
        'edit': 'edit.js'
    }

    def __init__(self, name, **kwargs):
        self.name = name
        self.prefix = kwargs.get('prefix', None)
        self.kwargs = kwargs
        if self.prefix is None:
            self.path = jupyter_config_dir()
        else:
            self.path = join(self.prefix, "etc", "jupyter")
        self.cm = ConfigManager(config_dir=join(self.path, 'nbconfig'))
        self.cm_server = ConfigManager(config_dir=self.path)

    def install(self):
        """
        Install an extension (copy or symlinks)
        """
        try:
            install_nbextension(self.kwargs['static'],
                                **self._install_params())
            self._echo("Installing {}".format(self.name), 'ok')
        except Exception as e:
            self._echo(e, None)
            self._echo("Installing {}".format(self.name), 'fail')

    def enable(self):
        mkdir_p(self.cm.config_dir)
        self._enable_client_extensions()
        try:
            __import__(self.name)
            self._enable_server_extensions()
        except ImportError:
            pass
        self._echo('Enabling {}'.format(self.name), 'ok')

    def disable(self):
        # Client side
        self._disable_client_extension()
        self._disable_server_extension()

    def _disable_client_extension(self):
        for _type, filename in list(self.extensions_map.items()):
            cfg = self.cm.get(_type)
            try:
                nb_key = "{}/{}".format(self.name, filename[:-3])
                nb_extensions = list(cfg['load_extensions'].keys())
                if nb_key in nb_extensions:
                    cfg['load_extensions'].pop(nb_key)
                    self.cm.set(_type, cfg)
                    self._echo("Disabling {} as {}".format(self.name, _type),
                               'ok')
            except KeyError:
                self._echo("{} wasn't enabled as a {}. Nothing to do.".format(
                    self.name, _type))

    def _disable_server_extension(self):
        cfg = self.cm_server.get("jupyter_notebook_config")
        try:
            server_extensions = cfg["NotebookApp"]["server_extensions"]
            if "{}.nbextension".format(self.name) in server_extensions:
                server_extensions.remove("{}.nbextension".format(self.name))
            self.cm_server.update("jupyter_notebook_config", cfg)
            self._echo(
                "{} was disabled as a server extension".format(self.name),
                'ok')
        except KeyError:
            self._echo(
                "{} was't enabled as a server extension. Nothing to do.".
                format(self.name))

    def _install_params(self):
        params = copy.deepcopy(self.kwargs)
        params['destination'] = self.name
        if params.get('verbose', False):
            params['verbose'] = 2
        else:
            params['verbose'] = 0
        for key in ['enable', 'static', 'version', 'main', 'path']:
            try:
                del params[key]
            except KeyError:
                pass

        return params

    def _echo(self, msg, status=None):
        if status == 'ok':
            print(' '.join([msg, '\033[92m', 'OK' + '\033[0m']))
        elif status == 'fail':
            print(' '.join([msg, '\033[91m', 'FAIL' + '\033[0m']))
        else:
            print(msg)

    def _enable_client_extensions(self):
        directory = self.kwargs['static']
        for key, filename in list(self.extensions_map.items()):
            if filename in os.listdir(directory):
                self.cm.update(
                    key, {
                        "load_extensions": {
                            "{}/{}".format(self.name, filename[:-3]): True
                        }
                    })

    def _enable_server_extensions(self):
        cfg = self.cm_server.get("jupyter_notebook_config")
        server_extensions = (cfg.setdefault("NotebookApp", {}).setdefault(
            "server_extensions", []))
        if "{}.nbextension".format(self.name) not in server_extensions:
            cfg["NotebookApp"]["server_extensions"] += [
                "{}.nbextension".format(self.name)
            ]
        self.cm_server.update("jupyter_notebook_config", cfg)
Beispiel #3
0
def _migrate_require_paths(logger=None):
    """Migrate require paths from old to new values."""
    if logger:
        logger.info('- Migrating require paths from old to new locations')

    mappings = {
        'notebook': [
            ('config/config_menu/main',
             'nbextensions_configurator/config_menu/main'),
        ] + [(req, req.split('/', 1)[1]) for req in [
            'codemirrormode/skill/skill',
            'publishing/gist_it/main',
            'publishing/printview/main',
            'styling/table_beautifier/main',
            'styling/zenmode/main',
            'usability/autosavetime/main',
            'usability/autoscroll/main',
            'usability/chrome-clipboard/main',
            'usability/code_font_size/code_font_size',
            'usability/codefolding/main',
            'usability/collapsible_headings/main',
            'usability/comment-uncomment/main',
            'usability/datestamper/main',
            'usability/dragdrop/main',
            'usability/equation-numbering/main',
            'usability/execute_time/ExecuteTime',
            'usability/exercise/main',
            'usability/exercise2/main',
            'usability/freeze/main',
            'usability/help_panel/help_panel',
            'usability/hide_input/main',
            'usability/hide_input_all/main',
            'usability/highlighter/highlighter',
            'usability/hinterland/hinterland',
            'usability/init_cell/main',
            'usability/keyboard_shortcut_editor/main',
            'usability/latex_envs/latex_envs',
            'usability/limit_output/main',
            'usability/move_selected_cells/main',
            'usability/navigation-hotkeys/main',
            'usability/notify/notify',
            'usability/python-markdown/main',
            'usability/qtconsole/qtconsole',
            'usability/rubberband/main',
            'usability/ruler/main',
            'usability/runtools/main',
            'usability/scratchpad/main',
            'usability/search-replace/main',
            'usability/skip-traceback/main',
            'usability/spellchecker/main',
            'usability/splitcell/splitcell',
            'usability/toc2/main',
            'usability/toggle_all_line_numbers/main',
        ]],
        'tree': [
            ('usability/tree-filter/index', 'tree-filter/index'),
        ]
    }

    fecm = FrontendConfigManager()
    for section in mappings:
        conf = fecm.get(section)
        load_extensions = conf.get('load_extensions', {})
        for old, new in mappings[section]:
            status = load_extensions.pop(old, None)
            if status is not None:
                if logger:
                    logger.debug('--  Migrating {!r} -> {!r}'.format(old, new))
                load_extensions[new] = status
        fecm.set(section, conf)
def _migrate_require_paths(logger=None):
    """Migrate require paths from old to new values."""
    if logger:
        logger.info('- Migrating require paths from old to new locations')

    mappings = {
        'notebook': [
            ('config/config_menu/main',
             'nbextensions_configurator/config_menu/main'),
        ] + [(req, req.split('/', 1)[1]) for req in [
            'codemirrormode/skill/skill',
            'publishing/gist_it/main',
            'publishing/printview/main',
            'styling/table_beautifier/main',
            'styling/zenmode/main',
            'usability/autosavetime/main',
            'usability/autoscroll/main',
            'usability/chrome-clipboard/main',
            'usability/code_font_size/code_font_size',
            'usability/codefolding/main',
            'usability/collapsible_headings/main',
            'usability/comment-uncomment/main',
            'usability/datestamper/main',
            'usability/dragdrop/main',
            'usability/equation-numbering/main',
            'usability/execute_time/ExecuteTime',
            'usability/exercise/main',
            'usability/exercise2/main',
            'usability/freeze/main',
            'usability/help_panel/help_panel',
            'usability/hide_input/main',
            'usability/hide_input_all/main',
            'usability/highlighter/highlighter',
            'usability/hinterland/hinterland',
            'usability/init_cell/main',
            'usability/keyboard_shortcut_editor/main',
            'usability/latex_envs/latex_envs',
            'usability/limit_output/main',
            'usability/move_selected_cells/main',
            'usability/navigation-hotkeys/main',
            'usability/notify/notify',
            'usability/python-markdown/main',
            'usability/qtconsole/qtconsole',
            'usability/rubberband/main',
            'usability/ruler/main',
            'usability/runtools/main',
            'usability/scratchpad/main',
            'usability/search-replace/main',
            'usability/skip-traceback/main',
            'usability/spellchecker/main',
            'usability/splitcell/splitcell',
            'usability/toc2/main',
            'usability/toggle_all_line_numbers/main',
        ]],
        'tree': [
            ('usability/tree-filter/index', 'tree-filter/index'),
        ]
    }

    fecm = FrontendConfigManager()
    for section in mappings:
        conf = fecm.get(section)
        load_extensions = conf.get('load_extensions', {})
        for old, new in mappings[section]:
            status = load_extensions.pop(old, None)
            if status is not None:
                if logger:
                    logger.debug('--  Migrating {!r} -> {!r}'.format(old, new))
                load_extensions[new] = status
        fecm.set(section, conf)
class NBSetup(object):
    extensions_map = {
        'notebook': 'main.js',
        'tree': 'tree.js',
        'edit': 'edit.js'
    }

    def __init__(self, name, **kwargs):
        self.name = name
        self.prefix = kwargs.get('prefix', None)
        self.kwargs = kwargs
        if self.prefix is None:
            self.path = jupyter_config_dir()
        else:
            self.path = join(self.prefix, "etc", "jupyter")
        self.cm = ConfigManager(config_dir=join(self.path, 'nbconfig'))
        self.cm_server = ConfigManager(config_dir=self.path)

    def install(self):
        """
        Install an extension (copy or symlinks)
        """
        try:
            install_nbextension(self.kwargs['static'], **self._install_params())
            self._echo("Installing {}".format(self.name), 'ok')
        except Exception as e:
            self._echo(e, None)
            self._echo("Installing {}".format(self.name), 'fail')

    def enable(self):
        mkdir_p(self.cm.config_dir)
        self._enable_client_extensions()
        try:
            __import__(self.name)
            self._enable_server_extensions()
        except ImportError:
            pass
        self._echo('Enabling {}'.format(self.name), 'ok')

    def disable(self):
        # Client side
        self._disable_client_extension()
        self._disable_server_extension()

    def _disable_client_extension(self):
        for _type, filename in list(self.extensions_map.items()):
            cfg = self.cm.get(_type)
            try:
                nb_key = "{}/{}".format(self.name, filename[:-3])
                nb_extensions = list(cfg['load_extensions'].keys())
                if nb_key in nb_extensions:
                    cfg['load_extensions'].pop(nb_key)
                    self.cm.set(_type, cfg)
                    self._echo("Disabling {} as {}".format(self.name, _type), 'ok')
            except KeyError:
                self._echo("{} wasn't enabled as a {}. Nothing to do.".format(self.name, _type))

    def _disable_server_extension(self):
        cfg = self.cm_server.get("jupyter_notebook_config")
        try:
            server_extensions = cfg["NotebookApp"]["server_extensions"]
            if "{}.nbextension".format(self.name) in server_extensions:
                server_extensions.remove("{}.nbextension".format(self.name))
            self.cm_server.update("jupyter_notebook_config", cfg)
            self._echo("{} was disabled as a server extension".format(self.name), 'ok')
        except KeyError:
            self._echo("{} was't enabled as a server extension. Nothing to do.".format(self.name))

    def _install_params(self):
        params = copy.deepcopy(self.kwargs)
        params['destination'] = self.name
        if params.get('verbose', False):
            params['verbose'] = 2
        else:
            params['verbose'] = 0
        for key in ['enable', 'static', 'version', 'main', 'path']:
            try:
                del params[key]
            except KeyError:
                pass

        return params

    def _echo(self, msg, status=None):
        if status == 'ok':
            print(' '.join([msg, '\033[92m', 'OK' + '\033[0m']))
        elif status == 'fail':
            print(' '.join([msg, '\033[91m', 'FAIL' + '\033[0m']))
        else:
            print(msg)

    def _enable_client_extensions(self):
        directory = self.kwargs['static']
        for key, filename in list(self.extensions_map.items()):
            if filename in os.listdir(directory):
                self.cm.update(
                    key, {
                        "load_extensions": {
                            "{}/{}".format(self.name, filename[:-3]): True
                        }
                    }
                )

    def _enable_server_extensions(self):
        cfg = self.cm_server.get("jupyter_notebook_config")
        server_extensions = (
            cfg.setdefault("NotebookApp", {})
            .setdefault("server_extensions", [])
        )
        if "{}.nbextension".format(self.name) not in server_extensions:
            cfg["NotebookApp"]["server_extensions"] += ["{}.nbextension".format(self.name)]
        self.cm_server.update("jupyter_notebook_config", cfg)