def filter_bears(language): """ Filter bears by language. :param language: The language to filter with. :return: A list of bears. """ return list(apply_filters([['language', language]], None)[0]['cli'])
def test_apply_filters(self): section_one = Section('apply') section_one.append(Setting('tags', 'save')) section_two = Section('filters') section_two.append(Setting('tags', 'change')) filtered = apply_filters({'section_tags': ('save',)}, sections=[section_one, section_two, ]) self.assertEqual(len(filtered), 1) self.assertEqual(filtered[0].name, 'apply')
def test_apply_filters(self): section_one = Section('apply') section_one.append(Setting('tags', 'save')) section_two = Section('filters') section_two.append(Setting('tags', 'change')) filtered = apply_filters([('section_tags', 'save')], sections=[ section_one, section_two, ]) self.assertEqual(len(filtered), 1) self.assertEqual(filtered[0].name, 'apply')
def main(debug=False): configure_logging() args = None # to have args variable in except block when parse_args fails try: # Note: We parse the args here once to check whether to show bears or # not. args = default_arg_parser().parse_args() if args.debug: req_ipdb = PipRequirement('ipdb') if not req_ipdb.is_installed(): logging.error( '--debug flag requires ipdb. ' 'You can install it with:\n%s', ' '.join(req_ipdb.install_command())) sys.exit(13) if debug or args.debug: args.log_level = 'DEBUG' # Defer imports so if e.g. --help is called they won't be run from coalib.coala_modes import (mode_format, mode_json, mode_non_interactive, mode_normal) from coalib.output.ConsoleInteraction import ( show_bears, show_language_bears_capabilities) console_printer = ConsolePrinter(print_colored=not args.no_color) configure_logging(not args.no_color) if args.show_bears: from coalib.settings.ConfigurationGathering import get_all_bears kwargs = {} if args.bears: kwargs['bear_globs'] = args.bears filtered_bears = get_all_bears(**kwargs) if args.filter_by_language: logging.warning("'--filter-by-language ...' is deprecated. " "Use '--filter-by language ...' instead.") if args.filter_by is None: args.filter_by = [] args.filter_by.append(['language'] + args.filter_by_language) if args.filter_by: # Each iteration of the following loop applies # filters one by one provided as arguments try: filtered_bears = apply_filters(args.filter_by, filtered_bears) except (InvalidFilterException, NotImplementedError) as ex: # If filter is not available or is unusable console_printer.print(ex) return 2 local_bears, global_bears = filtered_bears show_bears(local_bears, global_bears, args.show_description or args.show_details, args.show_details, console_printer, args) return 0 elif args.show_capabilities: from coalib.collecting.Collectors import ( filter_capabilities_by_languages) local_bears, _ = apply_filter('language', args.show_capabilities) capabilities = filter_capabilities_by_languages( local_bears, args.show_capabilities) show_language_bears_capabilities(capabilities, console_printer) return 0 if args.json: return mode_json(args, debug=debug) except BaseException as exception: # pylint: disable=broad-except if not isinstance(exception, SystemExit): if args and args.debug: import ipdb with ipdb.launch_ipdb_on_exception(): raise if debug: raise return get_exitcode(exception) if args.format: return mode_format(args, debug=debug) if args.non_interactive: return mode_non_interactive(console_printer, args, debug=debug) return mode_normal(console_printer, None, args, debug=debug)
def test_apply_filters(self): apply_filters_result = apply_filters({'language': ('C', 'Python'), 'can_fix': ('syntax',)}) self.assertIsNotNone(apply_filters_result)
def main(debug=False): configure_logging() args = None # to have args variable in except block when parse_args fails try: # Note: We parse the args here once to check whether to show bears or # not. args = default_arg_parser().parse_args() if args.debug: req_ipdb = PipRequirement('ipdb') if not req_ipdb.is_installed(): logging.error('--debug flag requires ipdb. ' 'You can install it with:\n%s', ' '.join(req_ipdb.install_command())) sys.exit(13) if debug or args.debug: args.log_level = 'DEBUG' # Defer imports so if e.g. --help is called they won't be run from coalib.coala_modes import ( mode_format, mode_json, mode_non_interactive, mode_normal) from coalib.output.ConsoleInteraction import ( show_bears, show_language_bears_capabilities) console_printer = ConsolePrinter(print_colored=not args.no_color) configure_logging(not args.no_color) if args.show_bears: from coalib.settings.ConfigurationGathering import get_all_bears kwargs = {} if args.bears: kwargs['bear_globs'] = args.bears filtered_bears = get_all_bears(**kwargs) if args.filter_by_language: logging.warning( "'--filter-by-language ...' is deprecated. " "Use '--filter-by language ...' instead.") if args.filter_by is None: args.filter_by = [] args.filter_by.append(['language'] + args.filter_by_language) if args.filter_by: # Each iteration of the following loop applies # filters one by one provided as arguments try: args.filter_by = filter_vector_to_dict(args.filter_by) filtered_bears = apply_filters( args.filter_by, filtered_bears) except (InvalidFilterException, NotImplementedError) as ex: # If filter is not available or is unusable console_printer.print(ex) return 2 local_bears, global_bears = filtered_bears show_bears(local_bears, global_bears, args.show_description or args.show_details, args.show_details, console_printer, args) return 0 elif args.show_capabilities: from coalib.collecting.Collectors import ( filter_capabilities_by_languages) local_bears, _ = apply_filter('language', args.show_capabilities) capabilities = filter_capabilities_by_languages( local_bears, args.show_capabilities) show_language_bears_capabilities(capabilities, console_printer) return 0 if args.json: return mode_json(args, debug=debug) except BaseException as exception: # pylint: disable=broad-except if not isinstance(exception, SystemExit): if args and args.debug: import ipdb with ipdb.launch_ipdb_on_exception(): raise if debug: raise return get_exitcode(exception) if args.format: return mode_format(args, debug=debug) if args.non_interactive: return mode_non_interactive(console_printer, args, debug=debug) return mode_normal(console_printer, None, args, debug=debug)
def run_coala(console_printer=None, log_printer=None, print_results=do_nothing, acquire_settings=fail_acquire_settings, print_section_beginning=do_nothing, nothing_done=do_nothing, autoapply=True, force_show_patch=False, arg_parser=None, arg_list=None, args=None, debug=False, cache=None): """ This is a main method that should be usable for almost all purposes and reduces executing coala to one function call. :param console_printer: Object to print messages on the console. :param log_printer: A LogPrinter object to use for logging. :param print_results: A callback that takes a LogPrinter, a section, a list of results to be printed, the file dict and the mutable file diff dict. :param acquire_settings: The method to use for requesting settings. It will get a parameter which is a dictionary with the settings name as key and a list containing a description in [0] and the names of the bears who need this setting in all following indexes. :param print_section_beginning: A callback that will be called with a section name string whenever analysis of a new section is started. :param nothing_done: A callback that will be called with only a log printer that shall indicate that nothing was done. :param autoapply: Set this to false to not autoapply any actions. If you set this to `False`, `force_show_patch` will be ignored. :param force_show_patch: If set to True, a patch will be always shown. (Using ApplyPatchAction.) :param arg_parser: Instance of ArgParser that is used to parse non-setting arguments. :param arg_list: The CLI argument list. :param args: Alternative pre-parsed CLI arguments. :param debug: Run in debug mode, bypassing multiprocessing, and not catching any exceptions. :param cache: Instance of a FileCache instance. :return: A dictionary containing a list of results for all analyzed sections as key. """ all_actions_possible = provide_all_actions() apply_single = None if getattr(args, 'single_action', None) is not None: while True: for i, action in enumerate(all_actions_possible, 1): console_printer.print(format_lines('{}'.format( action), symbol='[')) line = format_lines(STR_ENTER_LETTER, symbol='[') choice = input(line) if choice.isalpha(): choice = choice.upper() choice = '(' + choice + ')' if choice == '(N)': apply_single = 'Do (N)othing' break for i, action in enumerate(all_actions_possible, 1): if choice in action: apply_single = action break if apply_single: break console_printer.print(format_lines( 'Please enter a valid letter.', symbol='[')) args.apply_patch = False exitcode = 0 sections = {} results = {} file_dicts = {} try: yielded_results = yielded_unfixed_results = False did_nothing = True sections, local_bears, global_bears, targets = gather_configuration( acquire_settings, arg_parser=arg_parser, arg_list=arg_list, args=args) logging.debug('Platform {} -- Python {}, coalib {}' .format(platform.system(), platform.python_version(), VERSION)) settings_hash = get_settings_hash(sections, targets) flush_cache = bool(sections['cli'].get('flush_cache', False) or settings_changed(None, settings_hash)) if cache is None and not sections['cli'].get('disable_caching', False): cache = FileDictFileCache(None, os.getcwd(), flush_cache) if targets: sections = OrderedDict( (section_name, sections[section_name]) for section_name in targets) # Collect all the filters and try to filter sections filters = collect_filters(args, arg_list, arg_parser) if len(filters) > 0: all_sections = list(sections.values()) try: filtered = apply_filters(filters, sections=all_sections) sections = OrderedDict( (sect.name.lower(), sect) for sect in filtered) except (InvalidFilterException, NotImplementedError) as ex: console_printer.print(ex) for section_name, section in sections.items(): if not section.is_enabled(targets): continue if not autoapply: section['default_actions'] = '' elif force_show_patch: section['default_actions'] = '*: ShowPatchAction' section['show_result_on_top'] = 'yeah' print_section_beginning(section) section_result = execute_section( section=section, global_bear_list=global_bears[section_name], local_bear_list=local_bears[section_name], print_results=print_results, cache=cache, log_printer=None, console_printer=console_printer, debug=debug or args and args.debug, apply_single=(apply_single if apply_single is not None else False)) yielded, yielded_unfixed, results[section_name] = ( simplify_section_result(section_result)) yielded_results = yielded_results or yielded yielded_unfixed_results = ( yielded_unfixed_results or yielded_unfixed) did_nothing = False file_dicts[section_name] = section_result[3] update_settings_db(None, settings_hash) if cache: cache.write() if CounterHandler.get_num_calls_for_level('ERROR') > 0: exitcode = 1 elif did_nothing: nothing_done(None) exitcode = 2 elif yielded_unfixed_results: exitcode = 1 elif yielded_results: exitcode = 5 except BaseException as exception: # pylint: disable=broad-except if not isinstance(exception, SystemExit): if args and args.debug or ( sections and sections.get('cli', {}).get('debug', False) ): import ipdb with ipdb.launch_ipdb_on_exception(): raise if debug: raise exitcode = exitcode or get_exitcode(exception) return results, exitcode, file_dicts
def test_apply_filters(self): apply_filters_result = apply_filters([('language', 'C', 'Python'), ('can_fix', 'syntax')]) self.assertIsNotNone(apply_filters_result)
def run_coala(console_printer=None, log_printer=None, print_results=do_nothing, acquire_settings=fail_acquire_settings, print_section_beginning=do_nothing, nothing_done=do_nothing, autoapply=True, force_show_patch=False, arg_parser=None, arg_list=None, args=None, debug=False): """ This is a main method that should be usable for almost all purposes and reduces executing coala to one function call. :param console_printer: Object to print messages on the console. :param log_printer: A LogPrinter object to use for logging. :param print_results: A callback that takes a LogPrinter, a section, a list of results to be printed, the file dict and the mutable file diff dict. :param acquire_settings: The method to use for requesting settings. It will get a parameter which is a dictionary with the settings name as key and a list containing a description in [0] and the names of the bears who need this setting in all following indexes. :param print_section_beginning: A callback that will be called with a section name string whenever analysis of a new section is started. :param nothing_done: A callback that will be called with only a log printer that shall indicate that nothing was done. :param autoapply: Set this to false to not autoapply any actions. If you set this to `False`, `force_show_patch` will be ignored. :param force_show_patch: If set to True, a patch will be always shown. (Using ApplyPatchAction.) :param arg_parser: Instance of ArgParser that is used to parse non-setting arguments. :param arg_list: The CLI argument list. :param args: Alternative pre-parsed CLI arguments. :param debug: Run in debug mode, bypassing multiprocessing, and not catching any exceptions. :return: A dictionary containing a list of results for all analyzed sections as key. """ all_actions_possible = provide_all_actions() apply_single = None if getattr(args, 'single_action', None) is not None: while True: for i, action in enumerate(all_actions_possible, 1): console_printer.print( format_lines('{}'.format(action), symbol='[')) line = format_lines(STR_ENTER_LETTER, symbol='[') choice = input(line) if choice.isalpha(): choice = choice.upper() choice = '(' + choice + ')' if choice == '(N)': apply_single = 'Do (N)othing' break for i, action in enumerate(all_actions_possible, 1): if choice in action: apply_single = action break if apply_single: break console_printer.print( format_lines('Please enter a valid letter.', symbol='[')) args.apply_patch = False exitcode = 0 sections = {} results = {} file_dicts = {} try: yielded_results = yielded_unfixed_results = False did_nothing = True sections, local_bears, global_bears, targets = gather_configuration( acquire_settings, arg_parser=arg_parser, arg_list=arg_list, args=args) logging.debug('Platform {} -- Python {}, coalib {}'.format( platform.system(), platform.python_version(), VERSION)) settings_hash = get_settings_hash(sections, targets) flush_cache = bool(sections['cli'].get('flush_cache', False) or settings_changed(None, settings_hash)) cache = None if not sections['cli'].get('disable_caching', False): cache = FileCache(None, os.getcwd(), flush_cache) if targets: sections = OrderedDict((section_name, sections[section_name]) for section_name in targets) # Collect all the filters and try to filter sections filters = collect_filters(args, arg_list, arg_parser) if len(filters) > 0: all_sections = list(sections.values()) try: filtered = apply_filters(filters, sections=all_sections) sections = OrderedDict( (sect.name.lower(), sect) for sect in filtered) except (InvalidFilterException, NotImplementedError) as ex: console_printer.print(ex) for section_name, section in sections.items(): if not section.is_enabled(targets): continue if not autoapply: section['default_actions'] = '' elif force_show_patch: section['default_actions'] = '*: ShowPatchAction' section['show_result_on_top'] = 'yeah' print_section_beginning(section) section_result = execute_section( section=section, global_bear_list=global_bears[section_name], local_bear_list=local_bears[section_name], print_results=print_results, cache=cache, log_printer=None, console_printer=console_printer, debug=debug or args and args.debug, apply_single=(apply_single if apply_single is not None else False)) yielded, yielded_unfixed, results[section_name] = ( simplify_section_result(section_result)) yielded_results = yielded_results or yielded yielded_unfixed_results = (yielded_unfixed_results or yielded_unfixed) did_nothing = False file_dicts[section_name] = section_result[3] update_settings_db(None, settings_hash) if cache: cache.write() if CounterHandler.get_num_calls_for_level('ERROR') > 0: exitcode = 1 elif did_nothing: nothing_done(None) exitcode = 2 elif yielded_unfixed_results: exitcode = 1 elif yielded_results: exitcode = 5 except BaseException as exception: # pylint: disable=broad-except if not isinstance(exception, SystemExit): if args and args.debug or (sections and sections.get( 'cli', {}).get('debug', False)): import ipdb with ipdb.launch_ipdb_on_exception(): raise if debug: raise exitcode = exitcode or get_exitcode(exception) return results, exitcode, file_dicts
def test_apply_filters(self): apply_filters_result = apply_filters({ 'language': ('C', 'Python'), 'can_fix': ('syntax', ) }) self.assertIsNotNone(apply_filters_result)