def test_gather_configuration(self):
        args = (lambda *args: True, self.log_printer)

        # Using incomplete settings (e.g. an invalid coafile) will error
        with self.assertRaises(SystemExit):
            gather_configuration(*args,
                                 arg_list=['-c abcdefghi/invalid/.coafile'])

        # Using a bad filename explicitly exits coala.
        with self.assertRaises(SystemExit):
            gather_configuration(
                *args, arg_list=['-S', 'test=5', '-c', 'some_bad_filename'])

        with make_temp() as temporary:
            sections, local_bears, global_bears, targets = (
                gather_configuration(
                    *args,
                    arg_list=['-S', 'test=5', '-c', temporary, '-s'] +
                    self.min_args))

        self.assertEqual(
            str(sections['cli']), "cli {bears : 'JavaTestBear', config : " +
            repr(PathArg(temporary)) +
            ", files : '*.java', save : 'True', test : '5'}")

        with make_temp() as temporary:
            sections, local_bears, global_bears, targets = (
                gather_configuration(*args,
                                     arg_list=[
                                         '-S test=5', '-f *.java',
                                         '-c ' + (temporary),
                                         '-b LineCountBear -s'
                                     ]))

        self.assertEqual(len(local_bears['cli']), 0)
Ejemplo n.º 2
0
 def test_normal_running(self):
     with tempfile.TemporaryDirectory() as directory:
         temporary = tempfile.mkstemp(suffix='.orig', dir=directory)
         os.close(temporary[0])
         section = Section('')
         section.append(Setting('project_dir', PathArg(directory)))
         retval = coala_delete_orig.main(section=section)
         self.assertEqual(retval, 0)
         self.assertFalse(os.path.isfile(temporary[1]))
Ejemplo n.º 3
0
    def test_path(self):
        self.uut = Setting('key',
                           ' 22\n',
                           '.' + os.path.sep,
                           strip_whitespaces=True)
        self.assertEqual(path(self.uut),
                         os.path.abspath(os.path.join('.', '22')))

        abspath = PathArg(os.path.abspath('.'))
        self.uut = Setting('key', abspath)
        self.assertEqual(path(self.uut), abspath)

        self.uut = Setting('key', ' 22', '')
        self.assertRaises(ValueError, path, self.uut)
        self.assertEqual(path(self.uut, origin='test' + os.path.sep),
                         os.path.abspath(os.path.join('test', '22')))
Ejemplo n.º 4
0
def load_configuration(arg_list,
                       log_printer=None,
                       arg_parser=None,
                       args=None,
                       silent=False):
    """
    Parses the CLI args and loads the config file accordingly, taking
    default_coafile and the users .coarc into account.

    :param arg_list:    The list of CLI arguments.
    :param log_printer: The LogPrinter object for logging.
    :param arg_parser:  An ``argparse.ArgumentParser`` instance used for
                        parsing the CLI arguments.
    :param args:        Alternative pre-parsed CLI arguments.
    :param silent:      Whether or not to display warnings, ignored if ``save``
                        is enabled.
    :return:            A tuple holding (log_printer: LogPrinter, sections:
                        dict(str, Section), targets: list(str)). (Types
                        indicated after colon.)
    """
    cli_sections = parse_cli(arg_list=arg_list, arg_parser=arg_parser,
                             args=args)
    check_conflicts(cli_sections)

    if (
            bool(cli_sections['cli'].get('find_config', 'False')) and
            str(cli_sections['cli'].get('config')) == ''):
        cli_sections['cli'].add_or_create_setting(
            Setting('config', PathArg(find_user_config(os.getcwd()))))

    # We don't want to store targets argument back to file, thus remove it
    targets = [item.lower() for item in list(
        cli_sections['cli'].contents.pop('targets', ''))]

    if bool(cli_sections['cli'].get('no_config', 'False')):
        sections = cli_sections
    else:
        base_sections = load_config_file(Constants.system_coafile,
                                         silent=silent)
        user_sections = load_config_file(
            Constants.user_coafile, silent=True)

        default_config = str(base_sections['default'].get('config', '.coafile'))
        user_config = str(user_sections['default'].get(
            'config', default_config))
        config = os.path.abspath(
            str(cli_sections['cli'].get('config', user_config)))

        try:
            save = bool(cli_sections['cli'].get('save', 'False'))
        except ValueError:
            # A file is deposited for the save parameter, means we want to save
            # but to a specific file.
            save = True

        coafile_sections = load_config_file(config,
                                            silent=save or silent)

        sections = merge_section_dicts(base_sections, user_sections)

        sections = merge_section_dicts(sections, coafile_sections)

        if 'cli' in sections:
            logging.warning('\'cli\' is an internally reserved section name. '
                            'It may have been generated into your coafile '
                            'while running coala with `--save`. The settings '
                            'in that section will inherit implicitly to all '
                            'sections as defaults just like CLI args do. '
                            'Please change the name of that section in your '
                            'coafile to avoid any unexpected behavior.')

        sections = merge_section_dicts(sections, cli_sections)

    for name, section in list(sections.items()):
        section.set_default_section(sections)
        if name == 'default':
            if section.contents:
                logging.warning('Implicit \'Default\' section inheritance is '
                                'deprecated. It will be removed soon. To '
                                'silence this warning remove settings in the '
                                '\'Default\' section from your coafile. You '
                                'can use dots to specify inheritance: the '
                                'section \'all.python\' will inherit all '
                                'settings from \'all\'.')
                sections['default'].update(sections['cli'])
                sections['default'].name = 'cli'
                sections['cli'] = sections['default']
            del sections['default']

    str_log_level = str(sections['cli'].get('log_level', '')).upper()
    logging.getLogger().setLevel(LOG_LEVEL.str_dict.get(str_log_level,
                                                        LOG_LEVEL.INFO))

    return sections, targets