Esempio n. 1
0
def tmpconfig(tmpdir):
    conf_file = tmpdir.join('conf.ini')
    conf_file.write("\n".join([
        "[core]", "owner=testnick", "nick = TestBot", "enable = coretasks"
        ""
    ]))
    return config.Config(conf_file.strpath)
Esempio n. 2
0
 def gen(data):
     with open(filename, 'w') as fileo:
         fileo.write(data)
     cfg = conf.Config(filename)
     irc_bot = irc.Bot(cfg)
     irc_bot.config = cfg
     return irc_bot
Esempio n. 3
0
def fakeconfig(tmphomedir):
    conf_file = tmphomedir.join('conf.cfg')
    conf_file.write(FAKE_CONFIG.format(homedir=tmphomedir.strpath))

    test_settings = config.Config(conf_file.strpath)
    test_settings.define_section('fake', FakeConfigSection)
    return test_settings
Esempio n. 4
0
def plugins_wizard(filename):
    """Plugins Configuration Wizard.

    :param str filename: path to an existing Sopel configuration
    :return: the configuration object

    This wizard function helps to configure plugins for an existing Sopel
    config file.
    """
    if not os.path.isfile(filename):
        raise config.ConfigurationNotFound(filename)

    settings = config.Config(filename, validate=False)
    _plugins_wizard(settings)

    try:
        settings.save()
    except Exception:  # TODO: Be specific
        tools.stderr(
            "We've encountered an error while writing the configuration file."
            "This shouldn't happen. Check your permissions settings to make sure nothing is out of place."
        )
        raise

    return settings
Esempio n. 5
0
def test_save_modified_config(multi_fakeconfig):
    """Assert modified values are restored properly"""
    multi_fakeconfig.fake.choiceattr = 'spam'
    multi_fakeconfig.spam.eggs = [
        'one',
        'two',
    ]
    multi_fakeconfig.spam.cheeses = [
        'camembert, reblochon, and cheddar',
    ]

    multi_fakeconfig.save()

    with open(multi_fakeconfig.filename) as fd:
        print(fd.read())  # used for debug purpose if an assert fails

    saved_config = config.Config(multi_fakeconfig.filename)
    saved_config.define_section('fake', FakeConfigSection)
    saved_config.define_section('spam', SpamSection)

    assert saved_config.fake.choiceattr == 'spam'
    assert saved_config.spam.eggs == ['one', 'two']
    assert saved_config.spam.cheeses == [
        'camembert, reblochon, and cheddar',
    ], ('ListAttribute with one line only, with commas, must *not* be split '
        'differently from what was expected, i.e. into one (and only one) value'
        )
Esempio n. 6
0
def multi_fakeconfig(tmphomedir):
    conf_file = tmphomedir.join('conf.cfg')
    conf_file.write(MULTILINE_CONFIG.format(homedir=tmphomedir.strpath))

    test_settings = config.Config(conf_file.strpath)
    test_settings.define_section('fake', FakeConfigSection)
    test_settings.define_section('spam', SpamSection)
    return test_settings
Esempio n. 7
0
def tmpconfig(tmpdir):
    conf_file = tmpdir.join('conf.ini')
    conf_file.write("\n".join([
        "[core]",
        "owner = Exirel",
        "nick = Sopel",
        "user = sopel",
        "name = Sopel (https://sopel.chat)",
        "flood_burst_lines = 1000",  # we don't want flood protection here
    ]))
    return config.Config(conf_file.strpath)
Esempio n. 8
0
def reset_variable(bot, trigger):
    global irc_connection

    settings = config.Config(f"/{os.environ['HOME']}/.sopel/default.cfg",
                             validate=False)
    joined_channels = [str(channel).lower() for channel in bot.channels]
    settings_channels = [channel.lower() for channel in settings.core.channels]
    if sorted(joined_channels) == sorted(settings_channels):
        irc_connection = True
    else:
        irc_connection = False
Esempio n. 9
0
def wizard(filename):
    """Global Configuration Wizard.

    :param str filename: name of the new file to be created
    :return: the created configuration object

    This wizard function helps the creation of a Sopel configuration file,
    with its core section and its plugins' sections.
    """
    configdir, basename = os.path.split(filename)
    if not basename:
        raise config.ConfigurationError(
            'Sopel requires a filename for its configuration, not a directory')

    try:
        if not os.path.isdir(configdir):
            print('Creating config directory at {}'.format(configdir))
            os.makedirs(configdir)
            print('Config directory created')
    except Exception:
        tools.stderr('There was a problem creating {}'.format(configdir))
        raise

    name, ext = os.path.splitext(basename)
    if not ext:
        # Always add .cfg if filename does not have an extension
        filename = os.path.join(configdir, name + '.cfg')
    elif ext != '.cfg':
        # It is possible to use a non-cfg file for Sopel
        # but the wizard does not allow it at the moment
        raise config.ConfigurationError(
            'Sopel uses ".cfg" as configuration file extension, not "%s".' % ext)

    settings = config.Config(filename, validate=False)

    print("Please answer the following questions "
          "to create your configuration file (%s):\n" % filename)
    config.core_section.configure(settings)
    if settings.option(
        'Would you like to see if there are any plugins '
        'that need configuring'
    ):
        _plugins_wizard(settings)

    try:
        settings.save()
    except Exception:  # TODO: Be specific
        tools.stderr("Encountered an error while writing the config file. "
                     "This shouldn't happen. Check permissions.")
        raise

    print("Config file written successfully!")
    return settings
Esempio n. 10
0
def load_settings(options):
    """Load Sopel's settings using the command line's ``options``.

    :param options: parsed arguments
    :return: sopel configuration
    :rtype: :class:`sopel.config.Config`
    :raise sopel.config.ConfigurationNotFound: raised when configuration file
                                               is not found
    :raise sopel.config.ConfigurationError: raised when configuration is
                                            invalid

    This function loads Sopel's settings from one of these sources:

    * value of ``options.config``, if given,
    * ``SOPEL_CONFIG`` environment variable, if no option is given,
    * otherwise the ``default`` configuration is loaded,

    then loads the settings and returns it as a :class:`~sopel.config.Config`
    object.

    If the configuration file can not be found, a
    :exc:`sopel.config.ConfigurationNotFound` error will be raised.

    .. note::

        This function expects that ``options`` exposes two attributes:
        ``config`` and ``configdir``.

        The :func:`sopel.cli.utils.add_common_arguments` function should be
        used to add these options to the argument parser.

    """
    # Default if no options.config or no env var or if they are empty
    name = 'default'
    if options.config:
        name = options.config
    elif 'SOPEL_CONFIG' in os.environ:
        name = os.environ['SOPEL_CONFIG'] or name  # use default if empty

    filename = find_config(options.configdir, name)

    if not os.path.isfile(filename):
        raise config.ConfigurationNotFound(filename=filename)

    return config.Config(filename)
Esempio n. 11
0
def load_settings(options):
    """Load Sopel's settings using the command line's ``options``.

    :param options: parsed arguments
    :return: sopel configuration
    :rtype: :class:`sopel.config.Config`
    :raise sopel.config.ConfigurationNotFound: raised when configuration file
                                               is not found
    :raise sopel.config.ConfigurationError: raised when configuration is
                                            invalid

    This function loads Sopel's settings from ``options.config``. This option's
    value should be from one of these sources:

    * given by the command line argument,
    * ``SOPEL_CONFIG`` environment variable, if the argument is not used,
    * otherwise it should default to ``default``,

    then it returns it as a :class:`~sopel.config.Config` object.

    If the configuration file can not be found, a
    :exc:`sopel.config.ConfigurationNotFound` error will be raised.

    .. note::

        This function expects that ``options`` exposes two attributes:
        ``config`` and ``configdir``.

        The :func:`sopel.cli.utils.add_common_arguments` function should be
        used to add these options to the argument parser. This function is also
        responsible for using the environment variable or the default value.

    """
    filename = find_config(options.configdir, options.config)

    if not os.path.isfile(filename):
        raise config.ConfigurationNotFound(filename=filename)

    return config.Config(filename)
Esempio n. 12
0
def test_save_unmodified_config(multi_fakeconfig):
    """Assert type attributes are kept as they should be"""
    multi_fakeconfig.save()
    saved_config = config.Config(multi_fakeconfig.filename)
    saved_config.define_section('fake', FakeConfigSection)
    saved_config.define_section('spam', SpamSection)

    # core
    assert saved_config.core.owner == 'dgw'

    # fake
    assert saved_config.fake.valattr is None
    assert saved_config.fake.listattr == []
    assert saved_config.fake.choiceattr is None
    assert saved_config.fake.af_fileattr is None
    assert saved_config.fake.ad_fileattr is None
    assert saved_config.fake.rf_fileattr is None
    assert saved_config.fake.rd_fileattr is None

    # spam
    assert saved_config.spam.eggs == [
        'one',
        'two',
        'three',
        'four',
        'and a half',  # no-newline + comma
    ], 'Comma separated line: "four" and "and a half" must be separated'
    assert saved_config.spam.bacons == [
        'grilled',
        'burn out',
        'greasy, fat, and tasty',
    ]
    assert saved_config.spam.cheeses == [
        'cheddar',
        'reblochon',
        'camembert',
    ]
    assert saved_config.spam.channels == TEST_CHANNELS
Esempio n. 13
0
File: utils.py Progetto: hekel/sopel
def load_settings(options):
    """Load Sopel's settings using the command line's ``options``.

    :param options: parsed arguments
    :return: sopel configuration
    :rtype: :class:`sopel.config.Config`
    :raise sopel.config.ConfigurationNotFound: raised when configuration file
                                               is not found
    :raise sopel.config.ConfigurationError: raised when configuration is
                                            invalid

    This function loads Sopel's settings from one of these sources:

    * value of ``options.config``, if given,
    * or the ``default`` configuration is loaded,

    then loads the settings and returns it as a :class:`~sopel.config.Config`
    object.

    If the configuration file can not be found, a
    :exc:`sopel.config.ConfigurationNotFound` error will be raised.

    .. note::

        To use this function effectively, the
        :func:`sopel.cli.utils.add_common_arguments` function should be used to
        add the proper option to the argument parser.

    """
    name = options.config or 'default'
    filename = find_config(config.DEFAULT_HOMEDIR, name)

    if not os.path.isfile(filename):
        raise config.ConfigurationNotFound(filename=filename)

    return config.Config(filename)
Esempio n. 14
0
 def __call__(self, name, data):
     tmpfile = self.tmpdir.join(name)
     tmpfile.write(data)
     return config.Config(tmpfile.strpath)
Esempio n. 15
0
 def read_config(self):
     configo = config.Config(self.filename)
     configo.define_section('fake', FakeConfigSection)
     return configo