示例#1
0
    def config_write_py(self, filename=None, force=False, defaults=False):
        """Write the current configuration to a config.py file.

        Args:
            filename: The file to write to, or None for the default config.py.
            force: Force overwriting existing files.
            defaults: Write the defaults instead of values configured via :set.
        """
        if filename is None:
            filename = os.path.join(standarddir.config(), 'config.py')
        else:
            if not os.path.isabs(filename):
                filename = os.path.join(standarddir.config(), filename)
            filename = os.path.expanduser(filename)

        if os.path.exists(filename) and not force:
            raise cmdexc.CommandError("{} already exists - use --force to "
                                      "overwrite!".format(filename))

        if defaults:
            options = [(opt, opt.default)
                       for _name, opt in sorted(configdata.DATA.items())]
            bindings = dict(configdata.DATA['bindings.default'].default)
            commented = True
        else:
            options = list(self._config)
            bindings = dict(self._config.get_obj('bindings.commands'))
            commented = False

        writer = configfiles.ConfigPyWriter(options,
                                            bindings,
                                            commented=commented)
        writer.write(filename)
    def test_commented(self):
        opt = configdata.Option(name='opt',
                                typ=configtypes.Int(),
                                default='def',
                                backends=[usertypes.Backend.QtWebEngine],
                                raw_backends=None,
                                description='Hello World')
        options = [(None, opt, 'val')]
        bindings = {
            'normal': {
                ',x': 'message-info normal'
            },
            'caret': {
                ',y': 'message-info caret'
            }
        }

        writer = configfiles.ConfigPyWriter(options, bindings, commented=True)
        lines = list(writer._gen_lines())

        assert "## Autogenerated config.py" in lines
        assert "# config.load_autoconfig()" in lines
        assert "# c.opt = 'val'" in lines
        assert "## Bindings for normal mode" in lines
        assert "# config.bind(',x', 'message-info normal')" in lines
        caret_bind = ("# config.bind(',y', 'message-info caret', "
                      "mode='caret')")
        assert caret_bind in lines
示例#3
0
 def test_write(self, tmpdir):
     pyfile = tmpdir / 'config.py'
     writer = configfiles.ConfigPyWriter(options=[], bindings={},
                                         commented=False)
     writer.write(str(pyfile))
     lines = pyfile.read_text('utf-8').splitlines()
     assert '# Autogenerated config.py' in lines
示例#4
0
    def test_valid_values(self):
        opt1 = configdata.Option(
            name='opt1', typ=configtypes.BoolAsk(), default='ask',
            backends=[usertypes.Backend.QtWebEngine], raw_backends=None,
            description='Hello World')
        opt2 = configdata.Option(
            name='opt2', typ=configtypes.ColorSystem(), default='rgb',
            backends=[usertypes.Backend.QtWebEngine], raw_backends=None,
            description='All colors are beautiful!')

        options = [(opt1, 'ask'), (opt2, 'rgb')]

        writer = configfiles.ConfigPyWriter(options, bindings={},
                                            commented=False)
        text = '\n'.join(writer._gen_lines())

        expected = textwrap.dedent("""
            # Hello World
            # Type: BoolAsk
            # Valid values:
            #   - true
            #   - false
            #   - ask
            c.opt1 = 'ask'

            # All colors are beautiful!
            # Type: ColorSystem
            # Valid values:
            #   - rgb: Interpolate in the RGB color system.
            #   - hsv: Interpolate in the HSV color system.
            #   - hsl: Interpolate in the HSL color system.
            #   - none: Don't show a gradient.
            c.opt2 = 'rgb'
        """)
        assert expected in text
示例#5
0
 def test_empty(self):
     writer = configfiles.ConfigPyWriter(options=[], bindings={},
                                         commented=False)
     lines = list(writer._gen_lines())
     assert lines[0] == '# Autogenerated config.py'
     assert lines[-2] == 'config.load_autoconfig(False)'
     assert not lines[-1]
示例#6
0
 def test_binding_options_hidden(self):
     opt1 = configdata.DATA['bindings.default']
     opt2 = configdata.DATA['bindings.commands']
     options = [(opt1, {'normal': {'x': 'message-info x'}}),
                (opt2, {})]
     writer = configfiles.ConfigPyWriter(options, bindings={},
                                         commented=False)
     text = '\n'.join(writer._gen_lines())
     assert 'bindings.default' not in text
     assert 'bindings.commands' not in text
示例#7
0
    def test_unbind(self):
        bindings = {'normal': {',x': None},
                    'caret': {',y': 'message-info caret', ',z': None}}

        writer = configfiles.ConfigPyWriter([], bindings, commented=False)
        lines = list(writer._gen_lines())

        assert "config.unbind(',x')" in lines
        assert "config.unbind(',z', mode='caret')" in lines
        caret_bind = ("config.bind(',y', 'message-info caret', "
                      "mode='caret')")
        assert caret_bind in lines
    def test_output(self):
        desc = ("This is an option description.\n\n"
                "Nullam eu ante vel est convallis dignissim. Fusce suscipit, "
                "wisi nec facilisis facilisis, est dui fermentum leo, quis "
                "tempor ligula erat quis odio.")
        opt = configdata.Option(name='opt',
                                typ=configtypes.Int(),
                                default='def',
                                backends=[usertypes.Backend.QtWebEngine],
                                raw_backends=None,
                                description=desc)
        options = [(None, opt, 'val')]
        bindings = {
            'normal': {
                ',x': 'message-info normal'
            },
            'caret': {
                ',y': 'message-info caret'
            }
        }

        writer = configfiles.ConfigPyWriter(options, bindings, commented=False)
        text = '\n'.join(writer._gen_lines())

        assert text == textwrap.dedent("""
            # Autogenerated config.py
            #
            # NOTE: config.py is intended for advanced users who are comfortable
            # with manually migrating the config file on qutebrowser upgrades. If
            # you prefer, you can also configure qutebrowser using the
            # :set/:bind/:config-* commands without having to write a config.py
            # file.
            #
            # Documentation:
            #   qute://help/configuring.html
            #   qute://help/settings.html

            # Uncomment this to still load settings configured via autoconfig.yml
            # config.load_autoconfig()

            # This is an option description.  Nullam eu ante vel est convallis
            # dignissim. Fusce suscipit, wisi nec facilisis facilisis, est dui
            # fermentum leo, quis tempor ligula erat quis odio.
            # Type: Int
            c.opt = 'val'

            # Bindings for normal mode
            config.bind(',x', 'message-info normal')

            # Bindings for caret mode
            config.bind(',y', 'message-info caret', mode='caret')
        """).lstrip()
示例#9
0
 def test_pattern(self):
     opt = configdata.Option(
         name='opt', typ=configtypes.BoolAsk(), default='ask',
         backends=[usertypes.Backend.QtWebEngine], raw_backends=None,
         description='Hello World')
     options = [
         (urlmatch.UrlPattern('https://www.example.com/'), opt, 'ask'),
     ]
     writer = configfiles.ConfigPyWriter(options=options, bindings={},
                                         commented=False)
     text = '\n'.join(writer._gen_lines())
     expected = "config.set('opt', 'ask', 'https://www.example.com/')"
     assert expected in text
    def test_defaults_work(self, confpy):
        """Get a config.py with default values and run it."""
        options = [(None, opt, opt.default)
                   for _name, opt in sorted(configdata.DATA.items())]
        bindings = dict(configdata.DATA['bindings.default'].default)
        writer = configfiles.ConfigPyWriter(options, bindings, commented=False)
        writer.write(confpy.filename)

        try:
            configfiles.read_config_py(confpy.filename)
        except configexc.ConfigFileErrors as exc:
            # Make sure no other errors happened
            for error in exc.errors:
                assert isinstance(error.exception, configexc.BackendError)
示例#11
0
    def test_empty(self):
        writer = configfiles.ConfigPyWriter(options=[], bindings={},
                                            commented=False)
        text = '\n'.join(writer._gen_lines())
        expected = textwrap.dedent("""
            # Autogenerated config.py
            # Documentation:
            #   qute://help/configuring.html
            #   qute://help/settings.html

            # Uncomment this to still load settings configured via autoconfig.yml
            # config.load_autoconfig()
        """).lstrip()
        assert text == expected
示例#12
0
    def config_write_py(self,
                        filename: str = None,
                        force: bool = False,
                        defaults: bool = False) -> None:
        """Write the current configuration to a config.py file.

        Args:
            filename: The file to write to, or None for the default config.py.
            force: Force overwriting existing files.
            defaults: Write the defaults instead of values configured via :set.
        """
        if filename is None:
            filename = standarddir.config_py()
        else:
            filename = os.path.expanduser(filename)
            if not os.path.isabs(filename):
                filename = os.path.join(standarddir.config(), filename)

        if os.path.exists(filename) and not force:
            raise cmdutils.CommandError("{} already exists - use --force to "
                                        "overwrite!".format(filename))

        options: List[Tuple[Optional[urlmatch.UrlPattern], configdata.Option,
                            Any]] = []
        if defaults:
            options = [(None, opt, opt.default)
                       for _name, opt in sorted(configdata.DATA.items())]
            bindings = dict(configdata.DATA['bindings.default'].default)
            commented = True
        else:
            for values in self._config:
                for scoped in values:
                    options.append((scoped.pattern, values.opt, scoped.value))
            bindings = dict(self._config.get_mutable_obj('bindings.commands'))
            commented = False

        writer = configfiles.ConfigPyWriter(options,
                                            bindings,
                                            commented=commented)
        try:
            writer.write(filename)
        except OSError as e:
            raise cmdutils.CommandError(str(e))