def apply(self, result, original_file_dict, file_diff_dict): """ (G)enerate patches """ console_printer = ConsolePrinter() log_printer = LogPrinter() to_filename = sorted( result.diffs.items())[OBJECT_INDEX][FILENAME_INDEX] filtered_bears = filter_bears(find_language(to_filename)) filtered_bears.insert(0, DefaultBear()) possible_options = [b.name for b in filtered_bears] console_printer.print('[{:>4}] *0. Do Nothing'.format('')) # Let the user choose a bear that wants to apply on the files for i, action in enumerate(possible_options, 1): show_possibilities(console_printer, i, action) choose_action = str(input('[{:>4}] Enter a number: '.format(''))) if choose_action is '' or choose_action is '0': return False choose_action = int(choose_action) chosen_bear = [possible_options[choose_action - 1]] return mode_normal(console_printer, log_printer, create_arg_parser([to_filename], chosen_bear), debug=False)
def apply(self, result, original_file_dict, file_diff_dict): """ (G)enerate patches """ console_printer = ConsolePrinter() log_printer = LogPrinter() to_filename = sorted(result.diffs.items())[OBJECT_INDEX][FILENAME_INDEX] filtered_bears = filter_bears(find_language(to_filename)) filtered_bears.insert(0, DefaultBear()) possible_options = [b.name for b in filtered_bears] console_printer.print('[{:>4}] *0. Do Nothing'.format('')) # Let the user choose a bear that wants to apply on the files for i, action in enumerate(possible_options, 1): show_possibilities(console_printer, i, action) choose_action = str(input('[{:>4}] Enter a number: '.format(''))) if choose_action is '' or choose_action is '0': return False choose_action = int(choose_action) chosen_bear = [possible_options[choose_action - 1]] return mode_normal(console_printer, log_printer, create_arg_parser([ to_filename], chosen_bear), debug=False)
def setUp(self): config_path = os.path.abspath(os.path.join( os.path.dirname(__file__), 'section_executor_test_files', '.coafile')) self.testcode_c_path = os.path.join(os.path.dirname(config_path), 'testcode.c') self.unreadable_path = os.path.join(os.path.dirname(config_path), 'unreadable') self.result_queue = queue.Queue() self.queue = queue.Queue() self.log_queue = queue.Queue() self.console_printer = ConsolePrinter() log_printer = LogPrinter(ConsolePrinter()) self.log_printer = ProcessingTestLogPrinter(self.log_queue) (self.sections, self.local_bears, self.global_bears, targets) = gather_configuration(lambda *args: True, log_printer, arg_list=['--config', re.escape(config_path)]) self.assertEqual(len(self.local_bears['cli']), 1) self.assertEqual(len(self.global_bears['cli']), 1) self.assertEqual(targets, [])
def test_run_coala_no_autoapply(self, debug=False): with bear_test_module(), \ prepare_file(['#fixme '], None) as (lines, filename): self.assertEqual( 1, len( run_coala(console_printer=ConsolePrinter(), log_printer=LogPrinter(), arg_list=('-c', os.devnull, '-f', filename, '-b', 'SpaceConsistencyTestBear', '--apply-patches', '-S', 'use_spaces=yeah'), autoapply=False, debug=debug)[0]['cli'])) self.assertEqual( 0, len( run_coala(console_printer=ConsolePrinter(), log_printer=LogPrinter(), arg_list=('-c', os.devnull, '-f', filename, '-b', 'SpaceConsistencyTestBear', '--apply-patches', '-S', 'use_spaces=yeah'), debug=debug)[0]['cli']))
class TestLogo(unittest.TestCase): def setUp(self): self.printer = ConsolePrinter() def test_print_side_by_side(self): with retrieve_stdout() as custom_stdout: print_side_by_side( self.printer, ["Left side content."], ["Right side content", "that is longer than the", "left side."], limit=80) self.assertIn( "side content.\x1b[0m \x1b[34mRight side", custom_stdout.getvalue()) def test_print_welcome_message(self): with retrieve_stdout() as custom_stdout: print_welcome_message(self.printer) self.assertIn("o88Oo", custom_stdout.getvalue()) def test_print_ask_dir_help_message(self): with retrieve_stdout() as custom_stdout: self.printer.print(PROJECT_DIR_HELP) self.assertIn(PROJECT_DIR_HELP, custom_stdout.getvalue())
def main(): configure_logging() try: console_printer = ConsolePrinter() log_printer = LogPrinter(console_printer) # Note: We parse the args here once to check whether to show bears or # not. args = default_arg_parser().parse_args() # 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.json: # needs to be checked in order to display bears in json return mode_json(args) if args.show_bears: from coalib.settings.ConfigurationGathering import ( get_filtered_bears) local_bears, global_bears = get_filtered_bears( args.filter_by_language, log_printer) show_bears(local_bears, global_bears, args.show_description or args.show_details, args.show_details, console_printer) return 0 elif args.show_capabilities: from coalib.collecting.Collectors import ( filter_capabilities_by_languages) from coalib.settings.ConfigurationGathering import ( get_filtered_bears) local_bears, global_bears = get_filtered_bears( args.filter_by_language, log_printer) capabilities = filter_capabilities_by_languages( local_bears, args.show_capabilities) show_language_bears_capabilities(capabilities, console_printer) return 0 except BaseException as exception: # pylint: disable=broad-except return get_exitcode(exception, log_printer) if args.format: return mode_format() if args.non_interactive: return mode_non_interactive(console_printer, args) return mode_normal(console_printer, log_printer)
def __init__(self, parallel=False, timestamp_format="%X"): """ :param parallel: Set to true for parallel execution. :param timestamp_format: The format string for the datetime.today().strftime(format) method. """ ConsolePrinter.__init__(self) self.parallel = parallel self.timestamp_format = timestamp_format
def main(): configure_logging() try: console_printer = ConsolePrinter() log_printer = LogPrinter(console_printer) # Note: We parse the args here once to check whether to show bears or # not. args = default_arg_parser().parse_args() console_printer = ConsolePrinter(print_colored=not args.no_color) if args.show_bears: from coalib.settings.ConfigurationGathering import ( get_filtered_bears) local_bears, global_bears = get_filtered_bears( args.filter_by_language, log_printer) show_bears(local_bears, global_bears, args.show_description or args.show_details, args.show_details, console_printer) return 0 elif args.show_capabilities: from coalib.collecting.Collectors import ( filter_capabilities_by_languages) from coalib.settings.ConfigurationGathering import ( get_filtered_bears) local_bears, global_bears = get_filtered_bears( args.filter_by_language, log_printer) capabilities = filter_capabilities_by_languages( local_bears, args.show_capabilities) show_language_bears_capabilities(capabilities, console_printer) return 0 except BaseException as exception: # pylint: disable=broad-except return get_exitcode(exception, log_printer) import functools from coalib.coala_main import run_coala partial_print_sec_beg = functools.partial(print_section_beginning, console_printer) results, exitcode, _ = run_coala( print_results=print_results, acquire_settings=acquire_settings, print_section_beginning=partial_print_sec_beg, nothing_done=nothing_done, console_printer=console_printer) return exitcode
def setUp(self): config_path = os.path.abspath( os.path.join(os.path.dirname(__file__), 'section_executor_test_files', '.coafile')) self.testcode_c_path = os.path.join(os.path.dirname(config_path), 'testcode.c') self.unreadable_path = os.path.join(os.path.dirname(config_path), 'unreadable') factory_test_path = os.path.abspath( os.path.join(os.path.dirname(__file__), 'file_factory_test_files')) self.factory_test_file = os.path.join(factory_test_path, 'factory_test.txt') self.a_bear_test_path = os.path.join(factory_test_path, 'a_bear_test.txt') self.b_bear_test_path = os.path.join(factory_test_path, 'b_bear_test.txt') self.c_bear_test_path = os.path.join(factory_test_path, 'c_bear_test.txt') self.d_bear_test_path = os.path.join(factory_test_path, 'd_bear_test.txt') self.e_bear_test_path = os.path.join(factory_test_path, 'e_bear_test.txt') self.n_bear_test_path = os.path.join(factory_test_path, 'n_bear_test.txt') self.n_bear_test_path_2 = os.path.join(factory_test_path, 'n_bear_test2.txt') self.x_bear_test_path = os.path.join(factory_test_path, 'x_bear_test.txt') filename_list = [ self.factory_test_file, self.a_bear_test_path, self.b_bear_test_path, self.c_bear_test_path, self.d_bear_test_path, self.e_bear_test_path, self.n_bear_test_path, self.n_bear_test_path_2, self.x_bear_test_path ] self.file_dict = get_file_dict(filename_list) self.result_queue = queue.Queue() self.queue = queue.Queue() self.log_queue = queue.Queue() self.console_printer = ConsolePrinter() log_printer = LogPrinter(ConsolePrinter()) self.log_printer = ProcessingTestLogPrinter(self.log_queue) (self.sections, self.local_bears, self.global_bears, targets) = gather_configuration(lambda *args: True, log_printer, arg_list=['--config', config_path]) self.assertEqual(len(self.local_bears['cli']), 1) self.assertEqual(len(self.global_bears['cli']), 1) self.assertEqual(targets, [])
def main(): arg_parser = _get_arg_parser() args = arg_parser.parse_args() logging.basicConfig(stream=sys.stdout) printer = ConsolePrinter() logging.getLogger(__name__) fpc = None project_dir = os.getcwd() if args.green_mode: args.non_interactive = None args.no_filter_by_capabilities = None args.incomplete_sections = None if not args.non_interactive and not args.green_mode: fpc = FilePathCompleter() fpc.activate() print_welcome_message(printer) printer.print(PROJECT_DIR_HELP) project_dir = ask_question('What is your project directory?', default=project_dir, typecast=valid_path) fpc.deactivate() project_files, ignore_globs = get_project_files(None, printer, project_dir, fpc, args.non_interactive) used_languages = list(get_used_languages(project_files)) print_used_languages(printer, used_languages) extracted_information = collect_info(project_dir) relevant_bears = filter_relevant_bears(used_languages, printer, arg_parser, extracted_information) if args.green_mode: collect_bear_settings(relevant_bears) print_relevant_bears(printer, relevant_bears) if args.non_interactive and not args.incomplete_sections: unusable_bears = get_non_optional_settings_bears(relevant_bears) remove_unusable_bears(relevant_bears, unusable_bears) print_relevant_bears(printer, relevant_bears, 'usable') settings = generate_settings(project_dir, project_files, ignore_globs, relevant_bears, extracted_information, args.incomplete_sections) write_coafile(printer, project_dir, settings)
def setUp(self): self.log_printer = LogPrinter(ConsolePrinter(print_colored=False)) self.console_printer = ConsolePrinter(print_colored=False) self.file_diff_dict = {} self.local_bears = OrderedDict([("default", [SomelocalBear]), ("test", [SomelocalBear])]) self.global_bears = OrderedDict([("default", [SomeglobalBear]), ("test", [SomeglobalBear])]) self.old_open_editor_applicable = OpenEditorAction.is_applicable OpenEditorAction.is_applicable = staticmethod(lambda *args: False) self.old_apply_patch_applicable = ApplyPatchAction.is_applicable ApplyPatchAction.is_applicable = staticmethod(lambda *args: False)
def apply(self, result, original_file_dict, file_diff_dict): """ Show Applied (P)atches """ console_printer = ConsolePrinter() applied_actions = result.get_applied_actions() show_patch_action = ShowPatchAction() RESULT_INDEX = 0 FILE_DICT_INDEX = 1 FILE_DIFF_DICT_INDEX = 2 SECTION_INDEX = 3 for key, val in applied_actions.items(): this_result = val[RESULT_INDEX] this_section = val[SECTION_INDEX] color_res = RESULT_SEVERITY_COLORS[this_result.severity] console_printer.print( '\n**** {bear} [Section: {section}] ***' '*\n**** Action Applied: {action} ****\n'.format( bear=this_result.origin, section=this_section.name, action=key), color=color_res) console_printer.print(format_lines( '[Severity: {sev}]'.format( sev=RESULT_SEVERITY.__str__(this_result.severity)), '!'), color=color_res) show_patch_action.apply_from_section(val[RESULT_INDEX], val[FILE_DICT_INDEX], val[FILE_DIFF_DICT_INDEX], val[SECTION_INDEX]) console_printer.print('\n**************\n', color=color_res) return True
def test_profiler_dependency(self, debug=False): with bear_test_module(): with prepare_file(['#fixme '], None) as (lines, filename): results = run_coala(console_printer=ConsolePrinter(), log_printer=LogPrinter(), arg_list=( '-c', os.devnull, '-f', filename, '-b', 'DependentBear', '-S', 'use_spaces=yeah', '--profile', 'profiled_bears', ), autoapply=False, debug=debug) cli_result = results[0]['cli'] self.assertEqual(len(cli_result), 1) profiled_files = os.listdir('profiled_bears') self.assertEqual(len(profiled_files), 1) self.assertEqual(profiled_files[0], 'cli_SpaceConsistencyTestBear.prof') shutil.rmtree('profiled_bears')
def apply(self, result, original_file_dict, file_diff_dict, colored: bool=True): """ Print a diff of the patch that would be applied. :param colored: Whether or not to use colored output. """ printer = ConsolePrinter(colored) for filename, this_diff in sorted(result.diffs.items()): to_filename = this_diff.rename if this_diff.rename else filename to_filename = "/dev/null" if this_diff.delete else to_filename original_file = original_file_dict[filename] try: current_file = file_diff_dict[filename].modified new_file = (file_diff_dict[filename] + this_diff).modified except KeyError: current_file = original_file new_file = this_diff.modified if tuple(current_file) != tuple(new_file): print_beautified_diff(difflib.unified_diff(current_file, new_file, fromfile=filename, tofile=to_filename), printer) elif filename != to_filename: print_from_name(printer, join('a', relpath(filename))) print_to_name(printer, join('b', relpath(to_filename))) return file_diff_dict
def main(): # Note: We parse the args here once to check whether to show bears or not. arg_parser = default_arg_parser() args = arg_parser.parse_args() console_printer = ConsolePrinter() if args.show_bears or args.show_all_bears: log_printer = LogPrinter(console_printer) sections, _ = load_configuration(arg_list=None, log_printer=log_printer) if args.show_all_bears: local_bears, global_bears = collect_all_bears_from_sections( sections, log_printer) else: # We ignore missing settings as it's not important. local_bears, global_bears = fill_settings( sections, acquire_settings=lambda *args, **kwargs: {}, log_printer=log_printer) show_bears(local_bears, global_bears, args.show_all_bears, console_printer) return 0 partial_print_sec_beg = functools.partial( print_section_beginning, console_printer) results, exitcode, _ = run_coala( print_results=print_results, acquire_settings=acquire_settings, print_section_beginning=partial_print_sec_beg, nothing_done=nothing_done) return exitcode
def main(): try: console_printer = ConsolePrinter() log_printer = LogPrinter(console_printer) # Note: We parse the args here once to check whether to show bears or # not. args = default_arg_parser().parse_args() if args.show_bears: sections, _ = load_configuration(arg_list=None, log_printer=log_printer) local_bears, global_bears = collect_all_bears_from_sections( sections, log_printer) if args.filter_by_language: local_bears = filter_section_bears_by_languages( local_bears, args.filter_by_language) global_bears = filter_section_bears_by_languages( global_bears, args.filter_by_language) show_bears(local_bears, global_bears, args.show_description or args.show_details, args.show_details, console_printer) return 0 except BaseException as exception: # pylint: disable=broad-except return get_exitcode(exception, log_printer) partial_print_sec_beg = functools.partial(print_section_beginning, console_printer) results, exitcode, _ = run_coala( print_results=print_results, acquire_settings=acquire_settings, print_section_beginning=partial_print_sec_beg, nothing_done=nothing_done) return exitcode
def main(): arg_parser = _get_arg_parser() args = arg_parser.parse_args() printer = ConsolePrinter() log_printer = LogPrinter(printer) project_dir = os.getcwd() if not args.non_interactive: print_welcome_message(printer) project_dir = ask_question("What is your project directory?", default=project_dir, typecast=valid_path) project_files, ignore_globs = get_project_files(log_printer, printer, project_dir) used_languages = list(get_used_languages(project_files)) print_used_languages(printer, used_languages) relevant_bears = filter_relevant_bears(used_languages, arg_parser) print_relevant_bears(printer, relevant_bears) if args.non_interactive: unusable_bears = get_non_optional_settings_bears(relevant_bears) remove_unusable_bears(relevant_bears, unusable_bears) print_relevant_bears(printer, relevant_bears, 'usable') settings = generate_settings(project_dir, project_files, ignore_globs, relevant_bears) write_coafile(printer, project_dir, settings)
def print_results(log_printer, section, result_list, file_dict, file_diff_dict, color=True): """ Print all the results in a section. :param log_printer: Printer responsible for logging the messages. :param section: The section to which the results belong to. :param result_list: List containing the results :param file_dict: A dictionary containing all files with filename as key. :param file_diff_dict: A dictionary that contains filenames as keys and diff objects as values. :param color: Boolean variable to print the results in color or not. Can be used for testing. """ console_printer = ConsolePrinter(print_colored=color) for result in sorted(result_list): print_affected_files(console_printer, log_printer, section, result, file_dict, color=color) print_result(console_printer, log_printer, section, file_diff_dict, result, file_dict)
def main(log_printer=None, section: Section = None): configure_logging() start_path = get_config_directory(section) log_printer = (LogPrinter(ConsolePrinter()) if log_printer is None else log_printer) if start_path is None: return 255 # start_path may have unintended glob characters orig_files = Globbing.glob( os.path.join(glob_escape(start_path), '**', '*.orig')) not_deleted = 0 for ofile in orig_files: log_printer.info('Deleting old backup file... ' + os.path.relpath(ofile)) try: os.remove(ofile) except OSError as oserror: not_deleted += 1 log_printer.warn("Couldn't delete {}. {}".format( os.path.relpath(ofile), oserror.strerror)) if not_deleted: log_printer.warn( str(not_deleted) + ' .orig backup files could not be' ' deleted, possibly because you lack the permission' ' to do so. coala may not be able to create' ' backup files when patches are applied.') return 0
def apply(self, result, original_file_dict, file_diff_dict, colored: bool = True): ''' Print a diff of the patch that would be applied. :param colored: Wether or not to use colored output. ''' printer = ConsolePrinter(colored) for filename, this_diff in sorted(result.diffs.items()): original_file = original_file_dict[filename] try: current_file = file_diff_dict[filename].modified new_file = (file_diff_dict[filename] + this_diff).modified except KeyError: current_file = original_file new_file = this_diff.modified print_beautified_diff( difflib.unified_diff(current_file, new_file, fromfile=filename, tofile=filename), printer) return file_diff_dict
def test_bear_test_fun_4(self): from pyprint.ConsolePrinter import ConsolePrinter printer = ConsolePrinter() bears = {'Python': [AnotherTestLocalDepBear]} relevant_bears = {'test': {AnotherTestLocalDepBear}} bear_settings_obj = collect_bear_settings(relevant_bears) file_dict = {'A.py': {'a\n', 'b\n'}, 'C.py': {'c\n', 'd\n'}} dir_path = str(Path(__file__).parent) + os.sep contents = initialize_project_data(dir_path, []) file_names = ['A.py', 'C.py'] non_op_results, unified_results = bear_test_fun( bears, bear_settings_obj, file_dict, [], contents, file_names, 1, 1, printer) print('nonop:', non_op_results) print('op:', unified_results) test_results = [{ AnotherTestLocalDepBear: [{ 'filename': 'A.py' }, { 'filename': 'C.py' }] }] self.assertCountEqual(non_op_results[0][AnotherTestLocalDepBear], test_results[0][AnotherTestLocalDepBear]) self.assertCountEqual(unified_results, [None])
def test_file_cache_proxy_integration(self, debug=False): with bear_test_module(), \ prepare_file(['disk-copy\n'], None) as (_, filename): memory_data = 'in-memory\n' proxy = FileProxy(filename, None, memory_data) proxymap = FileProxyMap([proxy]) self.cache.set_proxymap(proxymap) results, exitcode, file_dicts = run_coala( console_printer=ConsolePrinter(), log_printer=LogPrinter(), arg_list=( '-c', os.devnull, '-f', filename, '-b', 'TestBear', ), autoapply=False, debug=debug, cache=self.cache) self.assertEqual(exitcode, 0) self.assertEqual(len(results), 1) # run_coala() output's name is always lower case self.assertEqual(file_dicts['cli'][filename.lower()], (memory_data, ))
def main(log_printer=None, section: Section = None): start_path = get_config_directory(section) log_printer = log_printer or LogPrinter(ConsolePrinter()) if start_path is None: log_printer.err("Can only delete .orig files if .coafile is found") return 255 orig_files = Globbing.glob( os.path.abspath(os.path.join(start_path, '**', '*.orig'))) not_deleted = 0 for ofile in orig_files: log_printer.info("Deleting old backup file... " + os.path.relpath(ofile)) try: os.remove(ofile) except OSError as oserror: not_deleted += 1 log_printer.warn("Couldn't delete... {}. {}".format( os.path.relpath(ofile), oserror.strerror)) if not_deleted: log_printer.warn( str(not_deleted) + " .orig backup files could not be" " deleted, possibly because you lack the permission" " to do so. coala may not be able to create" " backup files when patches are applied.") return 0
def setUp(self): self.log_printer = ListLogPrinter() self.console_printer = ConsolePrinter(print_colored=False) self.no_color = not self.console_printer.print_colored self.file_diff_dict = {} self.section = Section('t') self.local_bears = OrderedDict([('default', [SomelocalBear]), ('test', [SomelocalBear])]) self.global_bears = OrderedDict([('default', [SomeglobalBear]), ('test', [SomeglobalBear])]) self.old_open_editor_applicable = OpenEditorAction.is_applicable OpenEditorAction.is_applicable = staticmethod( lambda *args: 'OpenEditorAction cannot be applied') self.old_apply_patch_applicable = ApplyPatchAction.is_applicable ApplyPatchAction.is_applicable = staticmethod( lambda *args: 'ApplyPatchAction cannot be applied') self.lexer = TextLexer() self.lexer.add_filter( VisibleWhitespaceFilter(spaces=True, tabs=True, tabsize=SpacingHelper.DEFAULT_TAB_WIDTH)) patcher = patch('coalib.results.result_actions.OpenEditorAction.' 'subprocess') self.addCleanup(patcher.stop) patcher.start()
def setUp(self): self.project_dir = os.getcwd() self.printer = ConsolePrinter() self.coafile = os.path.join(tempfile.gettempdir(), '.coafile') self.writer = ConfWriter(self.coafile) self.arg_parser = _get_arg_parser() self.old_argv = deepcopy(sys.argv) del sys.argv[1:]
def apply(self, result, original_file_dict, file_diff_dict): """ Show Applied (P)atches """ console_printer = ConsolePrinter() applied_actions = result.get_applied_actions() show_patch_action = ShowPatchAction() RESULT_INDEX = 0 FILE_DICT_INDEX = 1 FILE_DIFF_DICT_INDEX = 2 SECTION_INDEX = 3 for key, val in applied_actions.items(): this_result = val[RESULT_INDEX] this_section = val[SECTION_INDEX] color_res = RESULT_SEVERITY_COLORS[this_result.severity] console_printer.print('\n**** {bear} [Section: {section}] ***' '*\n**** Action Applied: {action} ****\n' .format(bear=this_result.origin, section=this_section.name, action=key), color=color_res) console_printer.print(format_lines('[Severity: {sev}]'.format( sev=RESULT_SEVERITY.__str__(this_result.severity)), '!'), color=color_res) show_patch_action.apply_from_section(val[RESULT_INDEX], val[FILE_DICT_INDEX], val[FILE_DIFF_DICT_INDEX], val[SECTION_INDEX]) console_printer.print( '\n**************\n', color=color_res) return True
def print_results(log_printer, section, result_list, file_dict, file_diff_dict, color=True): """ Print all the results in a section. :param log_printer: Printer responsible for logging the messages. :param section: The section to which the results belong to. :param result_list: List containing the results :param file_dict: A dictionary containing all files with filename as key. :param file_diff_dict: A dictionary that contains filenames as keys and diff objects as values. :param color: Boolean variable to print the results in color or not. Can be used for testing. """ console_printer = ConsolePrinter(print_colored=color) for result in sorted(result_list): if len(result.affected_code) == 0: console_printer.print("\n" + STR_PROJECT_WIDE, color=FILE_NAME_COLOR) else: for sourcerange in result.affected_code: if ( sourcerange.file is not None and sourcerange.file not in file_dict): log_printer.warn("The context for the result ({}) cannot " "be printed because it refers to a file " "that doesn't seem to exist ({})" ".".format(str(result), sourcerange.file)) else: print_affected_lines(console_printer, file_dict, sourcerange) print_result(console_printer, log_printer, section, file_diff_dict, result, file_dict)
def setUp(self): self.project_dir = os.path.join( os.path.dirname(os.path.realpath(__file__)), "project_dir") os.makedirs(self.project_dir, exist_ok=True) self.arg_parser = _get_arg_parser() self.printer = ConsolePrinter() self.log_printer = None self.old_argv = deepcopy(sys.argv) del sys.argv[1:]
def generate_settings(project_dir, project_files, ignore_globs, relevant_bears, incomplete_sections=False): """ Generates the settings for the given project. :param project_dir: Full path of the user's project directory. :param project_files: A list of file paths matched in the user's project directory. :param ignore_globs: The list of ignore glob expressions. :param relevant_bears: A dict with language name as key and bear classes as value. :param incomplete_sections: When bears with non optional settings are found, user is asked for setting value of non optional bears and then a ``Section`` object having ``files`` field, ``bears`` field and settings, is returned. If incomplete_sections is set to ``True``, then no user input will be asked and a ``Section`` object having only the ``files`` and ``bears`` field will be returned. In CI mode, bears with non optional setting are not added in coafile. But if incomplete_sections is set to ``True`` in CI mode, then those bears are also added in the coafile. :return: A dict with section name as key and a ``Section`` object as value. """ lang_map = {lang.lower(): lang for lang in relevant_bears} lang_files = split_by_language(project_files) extset = get_extensions(project_files) settings = OrderedDict() settings["default"] = generate_section( "default", [ext for lang in lang_files for ext in extset[lang]], relevant_bears[lang_map["all"]]) ignored_files = generate_ignore_field(project_dir, lang_files.keys(), extset, ignore_globs) if ignored_files: settings["default"]["ignore"] = ignored_files for lang in lang_files: if lang != "unknown" and lang != "all": settings[lang_map[lang]] = generate_section( lang, extset[lang], relevant_bears[lang_map[lang]]) log_printer = LogPrinter(ConsolePrinter()) if not incomplete_sections: fill_settings(settings, acquire_settings, log_printer) return settings
def main(): console_printer = ConsolePrinter() partial_print_sec_beg = functools.partial( print_section_beginning, console_printer) results, exitcode, _ = run_coala( print_results=print_results_no_input, print_section_beginning=partial_print_sec_beg) return exitcode
def test_printing(self): self.assertEqual(ConsolePrinter.colorama_initialized, False) self.uut = ConsolePrinter(print_colored=True) self.assertEqual(ConsolePrinter.colorama_initialized, True) with retrieve_stdout() as stdout: self.uut.print("\ntest", "message", color="green") self.assertRegex(stdout.getvalue(), "\033.*\ntest message.*") with retrieve_stdout() as stdout: self.uut.print("\ntest", "message", color="greeeeen") self.assertEqual(stdout.getvalue(), "\ntest message\n") with retrieve_stdout() as stdout: self.uut.print("\ntest", "message") self.assertEqual(stdout.getvalue(), "\ntest message\n") self.uut = ConsolePrinter() self.assertEqual(ConsolePrinter.colorama_initialized, True)
def test_run_coala_bear_run_raises(self): configure_logging() with bear_test_module(), \ prepare_file(['#fixme '], None) as (lines, filename), \ self.assertRaisesRegex( RuntimeError, r"^That's all the RaiseTestBear can do\.$"): run_coala(console_printer=ConsolePrinter(), log_printer=LogPrinter(), arg_list=('-c', os.devnull, '-f', re.escape(filename), '-b', 'RaiseTestBear'), debug=True)
def setUp(self): self.log_printer = LogPrinter(ConsolePrinter(print_colored=False)) self.console_printer = ConsolePrinter(print_colored=False) self.file_diff_dict = {} self.section = Section("t") self.local_bears = OrderedDict([("default", [SomelocalBear]), ("test", [SomelocalBear])]) self.global_bears = OrderedDict([("default", [SomeglobalBear]), ("test", [SomeglobalBear])]) self.old_open_editor_applicable = OpenEditorAction.is_applicable OpenEditorAction.is_applicable = staticmethod(lambda *args: False) self.old_apply_patch_applicable = ApplyPatchAction.is_applicable ApplyPatchAction.is_applicable = staticmethod(lambda *args: False) self.lexer = TextLexer() self.lexer.add_filter( VisibleWhitespaceFilter(spaces="•", tabs=True, tabsize=SpacingHelper.DEFAULT_TAB_WIDTH))
def main(): args = default_arg_parser().parse_args() console_printer = ConsolePrinter(print_colored=not args.no_color) partial_print_sec_beg = functools.partial(print_section_beginning, console_printer) results, exitcode, _ = run_coala( print_results=print_results_no_input, print_section_beginning=partial_print_sec_beg, force_show_patch=True, console_printer=console_printer) return exitcode
def test_logged_error_causes_non_zero_exitcode(self): configure_logging() with bear_test_module(), \ prepare_file(['#fixme '], None) as (lines, filename): _, exitcode, _ = run_coala(console_printer=ConsolePrinter(), log_printer=LogPrinter(), arg_list=('-c', os.devnull, '-f', filename, '-b', 'ErrorTestBear'), autoapply=False) assert exitcode == 1
class ConsolePrinterTest(unittest.TestCase): def test_printing(self): self.uut = ConsolePrinter(print_colored=True) with retrieve_stdout() as stdout: self.uut.print("\ntest", "message", color="green") self.assertRegex(stdout.getvalue(), "\033.*\ntest message.*") with retrieve_stdout() as stdout: self.uut.print("\ntest", "message", color="greeeeen") self.assertEqual(stdout.getvalue(), "\ntest message\n") with retrieve_stdout() as stdout: self.uut.print("\ntest", "message") self.assertEqual(stdout.getvalue(), "\ntest message\n")
def setUp(self): self.printer = ConsolePrinter()
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 main(): global MAX_ARGS_GREEN_MODE, MAX_VALUES_GREEN_MODE arg_parser = _get_arg_parser() args = arg_parser.parse_args() logging.basicConfig(stream=sys.stdout) printer = ConsolePrinter() logging.getLogger(__name__) fpc = None project_dir = os.getcwd() if args.green_mode: args.no_filter_by_capabilities = None args.incomplete_sections = None if args.max_args: MAX_ARGS_GREEN_MODE = args.max_args if args.max_values: MAX_VALUES_GREEN_MODE = args.max_values if not args.green_mode and (args.max_args or args.max_values): logging.warning(' --max-args and --max-values can be used ' 'only with --green-mode. The arguments will ' 'be ignored.') if not args.non_interactive and not args.green_mode: fpc = FilePathCompleter() fpc.activate() print_welcome_message(printer) printer.print(PROJECT_DIR_HELP) project_dir = ask_question( 'What is your project directory?', default=project_dir, typecast=valid_path) fpc.deactivate() project_files, ignore_globs = get_project_files( None, printer, project_dir, fpc, args.non_interactive) used_languages = list(get_used_languages(project_files)) used_languages = ask_to_select_languages(used_languages, printer, args.non_interactive) extracted_information = collect_info(project_dir) relevant_bears = filter_relevant_bears( used_languages, printer, arg_parser, extracted_information) if args.green_mode: bear_settings_obj = collect_bear_settings(relevant_bears) green_mode( project_dir, ignore_globs, relevant_bears, bear_settings_obj, MAX_ARGS_GREEN_MODE, MAX_VALUES_GREEN_MODE, project_files, printer, ) exit() print_relevant_bears(printer, relevant_bears) if args.non_interactive and not args.incomplete_sections: unusable_bears = get_non_optional_settings_bears(relevant_bears) remove_unusable_bears(relevant_bears, unusable_bears) print_relevant_bears(printer, relevant_bears, 'usable') settings = generate_settings( project_dir, project_files, ignore_globs, relevant_bears, extracted_information, args.incomplete_sections) write_coafile(printer, project_dir, settings)