Beispiel #1
0
def test_json():
    tmpdir = tempfile.mkdtemp()
    try:
        root_data = dict(a=1, x=2, nest={'a': 1, 'x': 2})
        with open(os.path.join(tmpdir, 'foo.json'), 'w') as f:
            json.dump(root_data, f)
        # also make a foo.d/ directory with multiple json files
        os.makedirs(os.path.join(tmpdir, 'foo.d'))
        with open(os.path.join(tmpdir, 'foo.d', 'a.json'), 'w') as f:
            json.dump(dict(a=2, b=1, nest={'a': 2, 'b': 1}), f)
        with open(os.path.join(tmpdir, 'foo.d', 'b.json'), 'w') as f:
            json.dump(
                dict(a=3,
                     b=2,
                     c=3,
                     nest={
                         'a': 3,
                         'b': 2,
                         'c': 3
                     },
                     only_in_b={'x': 1}), f)
        manager = BaseJSONConfigManager(config_dir=tmpdir,
                                        read_directory=False)
        data = manager.get('foo')
        assert 'a' in data
        assert 'x' in data
        assert 'b' not in data
        assert 'c' not in data
        assert data['a'] == 1
        assert 'x' in data['nest']
        # if we write it out, it also shouldn't pick up the subdirectoy
        manager.set('foo', data)
        data = manager.get('foo')
        assert data == root_data

        manager = BaseJSONConfigManager(config_dir=tmpdir, read_directory=True)
        data = manager.get('foo')
        assert 'a' in data
        assert 'b' in data
        assert 'c' in data
        # files should be read in order foo.d/a.json foo.d/b.json foo.json
        assert data['a'] == 1
        assert data['b'] == 2
        assert data['c'] == 3
        assert data['nest']['a'] == 1
        assert data['nest']['b'] == 2
        assert data['nest']['c'] == 3
        assert data['nest']['x'] == 2

        # when writing out, we don't want foo.d/*.json data to be included in the root foo.json
        manager.set('foo', data)
        manager = BaseJSONConfigManager(config_dir=tmpdir,
                                        read_directory=False)
        data = manager.get('foo')
        assert data == root_data

    finally:
        shutil.rmtree(tmpdir)
def test_json(tmp_path):
    tmpdir = str(tmp_path)

    root_data = dict(a=1, x=2, nest={"a": 1, "x": 2})
    with open(os.path.join(tmpdir, "foo.json"), "w") as f:
        json.dump(root_data, f)
    # also make a foo.d/ directory with multiple json files
    os.makedirs(os.path.join(tmpdir, "foo.d"))
    with open(os.path.join(tmpdir, "foo.d", "a.json"), "w") as f:
        json.dump(dict(a=2, b=1, nest={"a": 2, "b": 1}), f)
    with open(os.path.join(tmpdir, "foo.d", "b.json"), "w") as f:
        json.dump(
            dict(a=3,
                 b=2,
                 c=3,
                 nest={
                     "a": 3,
                     "b": 2,
                     "c": 3
                 },
                 only_in_b={"x": 1}), f)
    manager = BaseJSONConfigManager(config_dir=tmpdir, read_directory=False)
    data = manager.get("foo")
    assert "a" in data
    assert "x" in data
    assert "b" not in data
    assert "c" not in data
    assert data["a"] == 1
    assert "x" in data["nest"]
    # if we write it out, it also shouldn't pick up the subdirectoy
    manager.set("foo", data)
    data = manager.get("foo")
    assert data == root_data

    manager = BaseJSONConfigManager(config_dir=tmpdir, read_directory=True)
    data = manager.get("foo")
    assert "a" in data
    assert "b" in data
    assert "c" in data
    # files should be read in order foo.d/a.json foo.d/b.json foo.json
    assert data["a"] == 1
    assert data["b"] == 2
    assert data["c"] == 3
    assert data["nest"]["a"] == 1
    assert data["nest"]["b"] == 2
    assert data["nest"]["c"] == 3
    assert data["nest"]["x"] == 2

    # when writing out, we don't want foo.d/*.json data to be included in the root foo.json
    manager.set("foo", data)
    manager = BaseJSONConfigManager(config_dir=tmpdir, read_directory=False)
    data = manager.get("foo")
    assert data == root_data
Beispiel #3
0
    def list_server_extensions(self):
        """List all enabled and disabled server extensions, by config path

        Enabled extensions are validated, potentially generating warnings.
        """
        config_dirs = jupyter_config_path()

        # Iterate over all locations where extensions might be named.
        for config_dir in config_dirs:
            cm = BaseJSONConfigManager(parent=self, config_dir=config_dir)
            data = cm.get("jupyter_server_config")
            server_extensions = (data.setdefault("ServerApp", {}).setdefault(
                "jpserver_extensions", {}))
            if server_extensions:
                self.log.info(u'config dir: {}'.format(config_dir))

            # Iterate over packages listed in jpserver_extensions.
            for pkg_name, enabled in server_extensions.items():
                # Attempt to get extension metadata
                _, __ = _get_server_extension_metadata(pkg_name)
                self.log.info(u'    {} {}'.format(
                    pkg_name, GREEN_ENABLED if enabled else RED_DISABLED))
                try:
                    self.log.info("    - Validating {}...".format(pkg_name))
                    version = validate_server_extension(pkg_name)
                    self.log.info("      {} {} {}".format(
                        pkg_name, version, GREEN_OK))

                except ExtensionValidationError as err:
                    self.log.warn("      {} {}".format(RED_X, err))
Beispiel #4
0
    def list_extensions(self):
        """List all the extensions"""
        config_dirs = [
            os.path.join(p, 'serverconfig') for p in jupyter_config_path()
        ]

        print("Known bundlerextensions:")

        for config_dir in config_dirs:
            head = u'  config dir: {}'.format(config_dir)
            head_shown = False

            cm = BaseJSONConfigManager(parent=self, config_dir=config_dir)
            data = cm.get('jupyter_server')
            if 'bundlerextensions' in data:
                if not head_shown:
                    # only show heading if there is an extension here
                    print(head)
                    head_shown = True

                for bundler_id, info in data['bundlerextensions'].items():
                    label = info.get('label')
                    module = info.get('module_name')
                    if label is None or module is None:
                        msg = u'    {} {}'.format(bundler_id, RED_DISABLED)
                    else:
                        msg = u'    "{}" from {} {}'.format(
                            label, module, GREEN_ENABLED)
                    print(msg)
Beispiel #5
0
 def get(self, section_name):
     """Get the config from all config sections."""
     config = {}
     # step through back to front, to ensure front of the list is top priority
     for p in self.read_config_path[::-1]:
         cm = BaseJSONConfigManager(config_dir=p)
         recursive_update(config, cm.get(section_name))
     return config
Beispiel #6
0
    def test_disable(self):
        """Should remove the bundler from the notebook configuration."""
        self.test_enable()
        disable_bundler_python('jupyter_server.bundler.zip_bundler')

        config_dir = os.path.join(_get_config_dir(user=True), 'serverconfig')
        cm = BaseJSONConfigManager(config_dir=config_dir)
        bundlers = cm.get('jupyter_server').get('bundlerextensions', {})
        self.assertEqual(len(bundlers), 0)
Beispiel #7
0
    def test_enable(self):
        """Should add the bundler to the notebook configuration."""
        enable_bundler_python('jupyter_server.bundler.zip_bundler')

        config_dir = os.path.join(_get_config_dir(user=True), 'serverconfig')
        cm = BaseJSONConfigManager(config_dir=config_dir)
        bundlers = cm.get('jupyter_server').get('bundlerextensions', {})
        self.assertEqual(len(bundlers), 1)
        self.assertIn('notebook_zip_download', bundlers)
Beispiel #8
0
def _set_bundler_state(name,
                       label,
                       module_name,
                       group,
                       state,
                       user=True,
                       sys_prefix=False,
                       logger=None):
    """Set whether a bundler is enabled or disabled.

    Returns True if the final state is the one requested.

    Parameters
    ----------
    name : string
        Unique name of the bundler
    label : string
        Human-readable label for the bundler menu item in the UI
    module_name : string
        Dotted module/package name containing the bundler
    group : string
        'download' or 'deploy' indicating the parent menu containing the label
    state : bool
        The state in which to leave the extension
    user : bool [default: True]
        Whether to update the user's .jupyter/serverconfig directory
    sys_prefix : bool [default: False]
        Whether to update the sys.prefix, i.e. environment. Will override
        `user`.
    logger : Jupyter logger [optional]
        Logger instance to use
    """
    user = False if sys_prefix else user
    config_dir = os.path.join(
        _get_config_dir(user=user, sys_prefix=sys_prefix), 'serverconfig')
    cm = BaseJSONConfigManager(config_dir=config_dir)

    if logger:
        logger.info("{} {} bundler {}...".format(
            "Enabling" if state else "Disabling", name, module_name))

    if state:
        cm.update(
            BUNDLER_SECTION, {
                BUNDLER_SUBSECTION: {
                    name: {
                        "label": label,
                        "module_name": module_name,
                        "group": group
                    }
                }
            })
    else:
        cm.update(BUNDLER_SECTION, {BUNDLER_SUBSECTION: {name: None}})

    return (cm.get(BUNDLER_SECTION).get(BUNDLER_SUBSECTION, {}).get(name)
            is not None) == state
def toggle_server_extension_python(import_name,
                                   enabled=None,
                                   parent=None,
                                   user=False,
                                   sys_prefix=True):
    """Toggle the boolean setting for a given server extension
    in a Jupyter config file.
    """
    sys_prefix = False if user else sys_prefix
    config_dir = _get_config_dir(user=user, sys_prefix=sys_prefix)
    cm = BaseJSONConfigManager(parent=parent, config_dir=config_dir)
    cfg = cm.get("jupyter_server_config")
    server_extensions = cfg.setdefault("ServerApp",
                                       {}).setdefault("jpserver_extensions",
                                                      {})
    old_enabled = server_extensions.get(import_name, None)
    new_enabled = enabled if enabled is not None else not old_enabled
    server_extensions[import_name] = new_enabled
    cm.update("jupyter_server_config", cfg)
Beispiel #10
0
def set_password(args):
    password = args.password
    while not password:
        password1 = getpass("" if args.quiet else "Provide password: "******"" if args.quiet else "Repeat password:  "******"Passwords do not match, try again")
        elif len(password1) < 4:
            print("Please provide at least 4 characters")
        else:
            password = password1

    password_hash = passwd(password)
    cfg = BaseJSONConfigManager(config_dir=jupyter_config_dir())
    cfg.update("jupyter_server_config",
               {"ServerApp": {
                   "password": password_hash,
               }})
    if not args.quiet:
        print("password stored in config dir: %s" % jupyter_config_dir())
    def list_server_extensions(self):
        """List all enabled and disabled server extensions, by config path

        Enabled extensions are validated, potentially generating warnings.
        """
        config_dirs = jupyter_config_path()
        for config_dir in config_dirs:
            cm = BaseJSONConfigManager(parent=self, config_dir=config_dir)
            data = cm.get("jupyter_server_config")
            server_extensions = data.setdefault("ServerApp", {}).setdefault(
                "jpserver_extensions", {})
            if server_extensions:
                self.log.info(u"config dir: {}".format(config_dir))
            for import_name, enabled in server_extensions.items():
                self.log.info(u"    {} {}".format(
                    import_name, GREEN_ENABLED if enabled else RED_DISABLED))
                try:
                    self.log.info("    - Validating {}...".format(import_name))
                    _, __, version = validate_server_extension(import_name)
                    self.log.info("      {} {} {}".format(
                        import_name, version, GREEN_OK))

                except ExtensionValidationError as err:
                    self.log.warn("      {} {}".format(RED_X, err))
Beispiel #12
0
 def _update_write_config_dir(self, change):
     self.write_config_manager = BaseJSONConfigManager(
         config_dir=self.write_config_dir)
Beispiel #13
0
 def _default_write_config_manager(self):
     return BaseJSONConfigManager(config_dir=self.write_config_dir)
def get_config(user=True):
    cm = BaseJSONConfigManager(config_dir=_get_config_dir(user))
    data = cm.get("jupyter_server_config")
    return data.get("ServerApp", {}).get("jpserver_extensions", {})