def choose_action(console_printer, actions, apply_single=False): """ Presents the actions available to the user and takes as input the action the user wants to choose. :param console_printer: Object to print messages on the console. :param actions: Actions available to the user. :param apply_single: The action that should be applied for all results. If it's not selected, has a value of False. :return: Return a tuple of lists, a list with the names of actions that needs to be applied and a list with with the description of the actions. """ actions_desc = [] actions_name = [] if apply_single: for i, action in enumerate(actions, 0): if apply_single == action.desc: return ([action.desc], [action.name]) return (['Do (N)othing'], ['Do (N)othing']) else: while True: for i, action in enumerate(actions, 0): output = '{:>2}. {}' if i != 0 else '*{}. {}' color_letter( console_printer, format_lines(output.format(i, action.desc), symbol='[')) line = format_lines(STR_ENTER_NUMBER, symbol='[') choice = input(line) choice = str(choice) for c in choice: c = str(c) str_c = c actions_desc_len = len(actions_desc) if c.isnumeric(): for i, action in enumerate(actions, 0): c = int(c) if i == c: actions_desc.append(action.desc) actions_name.append(action.name) break elif c.isalpha(): c = c.upper() c = '(' + c + ')' for i, action in enumerate(actions, 1): if c in action.desc: actions_desc.append(action.desc) actions_name.append(action.name) break if actions_desc_len == len(actions_desc): console_printer.print(STR_INVALID_OPTION.format(str_c), color=WARNING_COLOR) if not choice: actions_desc.append(DoNothingAction().get_metadata().desc) actions_name.append(DoNothingAction().get_metadata().name) return (actions_desc, actions_name)
class ShowPatchActionTest(unittest.TestCase): def setUp(self): self.uut = DoNothingAction() self.file_dict = {'a': ['a\n', 'b\n', 'c\n'], 'b': ['old_first\n']} self.diff_dict = { 'a': Diff(self.file_dict['a']), 'b': Diff(self.file_dict['b']) } self.diff_dict['a'].add_lines(1, ['test\n']) self.diff_dict['a'].delete_line(3) self.diff_dict['b'].add_lines(0, ['first\n']) self.test_result = Result('origin', 'message', diffs=self.diff_dict) self.section = Section('name') self.section.append(Setting('colored', 'false')) def test_is_applicable(self): diff = Diff([], rename='new_name') result = Result('', '', diffs={'f': diff}) self.assertTrue(self.uut.is_applicable(result, {}, {'f': diff})) def test_apply(self): with retrieve_stdout() as stdout: self.assertEqual( self.uut.apply(self.test_result, self.file_dict, {}), None)
def test_ask_for_actions_and_apply(self): failed_actions = set() action = TestAction() do_nothing_action = DoNothingAction() args = [ self.console_printer, Section(''), [do_nothing_action.get_metadata(), action.get_metadata()], { 'DoNothingAction': do_nothing_action, 'TestAction': action }, failed_actions, Result('origin', 'message'), {}, {}, {} ] with simulate_console_inputs('a', 'param1', 'a', 'param2') as generator: action.apply = unittest.mock.Mock(side_effect=AssertionError) ask_for_action_and_apply(*args) self.assertEqual(generator.last_input, 1) self.assertIn('TestAction', failed_actions) action.apply = lambda *args, **kwargs: {} ask_for_action_and_apply(*args) self.assertEqual(generator.last_input, 3) self.assertNotIn('TestAction', failed_actions)
class DoNothingActionTest(unittest.TestCase): def setUp(self): self.uut = DoNothingAction() self.file_dict = {'a': ['a\n', 'b\n', 'c\n'], 'b': ['old_first\n']} self.diff_dict = {'a': Diff(self.file_dict['a']), 'b': Diff(self.file_dict['b'])} self.diff_dict['a'].add_lines(1, ['test\n']) self.diff_dict['a'].delete_line(3) self.diff_dict['b'].add_lines(0, ['first\n']) self.test_result = Result('origin', 'message', diffs=self.diff_dict) self.section = Section('name') self.section.append(Setting('colored', 'false')) def test_is_applicable(self): diff = Diff([], rename='new_name') result = Result('', '', diffs={'f': diff}) self.assertTrue(self.uut.is_applicable(result, {}, {'f': diff})) def test_apply(self): with retrieve_stdout() as stdout: self.assertEqual(self.uut.apply(self.test_result, self.file_dict, {}), None)
def test_default_input_apply_single_test(self): action = TestAction() do_nothing_action = DoNothingAction() apply_single = 'Test (A)ction' se = Section('cli') args = [self.console_printer, se, [do_nothing_action.get_metadata(), action.get_metadata()], {'DoNothingAction': do_nothing_action, 'TestAction': action}, set(), Result('origin', 'message'), {}, {}, {}, apply_single] with simulate_console_inputs('a') as generator: self.assertFalse(ask_for_action_and_apply(*args))
def setUp(self): self.uut = DoNothingAction() self.file_dict = {'a': ['a\n', 'b\n', 'c\n'], 'b': ['old_first\n']} self.diff_dict = {'a': Diff(self.file_dict['a']), 'b': Diff(self.file_dict['b'])} self.diff_dict['a'].add_lines(1, ['test\n']) self.diff_dict['a'].delete_line(3) self.diff_dict['b'].add_lines(0, ['first\n']) self.test_result = Result('origin', 'message', diffs=self.diff_dict) self.section = Section('name') self.section.append(Setting('colored', 'false'))
def test_default_input_apply_single_test(self): action = TestAction() do_nothing_action = DoNothingAction() apply_single = 'Test (A)ction' se = Section('cli') args = [self.console_printer, se, [do_nothing_action.get_metadata(), action.get_metadata()], {'DoNothingAction': do_nothing_action, 'TestAction': action}, set(), Result('origin', 'message'), {}, {}, {}, apply_single] with simulate_console_inputs('a') as generator: self.assertTrue(ask_for_action_and_apply(*args))
def test_default_input2(self): action = TestAction() do_nothing_action = DoNothingAction() args = [ self.console_printer, Section(''), [do_nothing_action.get_metadata(), action.get_metadata()], { 'DoNothingAction': do_nothing_action, 'TestAction': action }, set(), Result('origin', 'message'), {}, {}, {} ] with simulate_console_inputs(1, 1) as generator: self.assertTrue(ask_for_action_and_apply(*args))
def provide_all_actions(): return [DoNothingAction().get_metadata().desc, ShowPatchAction().get_metadata().desc, ApplyPatchAction().get_metadata().desc, IgnoreResultAction().get_metadata().desc, OpenEditorAction().get_metadata().desc, PrintAspectAction().get_metadata().desc, PrintDebugMessageAction().get_metadata().desc, PrintMoreInfoAction().get_metadata().desc]
def test_ask_for_actions_and_apply(self): failed_actions = set() action = TestAction() do_nothing_action = DoNothingAction() args = [self.console_printer, Section(''), [do_nothing_action.get_metadata(), action.get_metadata()], {'DoNothingAction': do_nothing_action, 'TestAction': action}, failed_actions, Result('origin', 'message'), {}, {}, {}] with simulate_console_inputs('a', 'param1', 'a', 'param2') as generator: action.apply = unittest.mock.Mock(side_effect=AssertionError) ask_for_action_and_apply(*args) self.assertEqual(generator.last_input, 1) self.assertIn('TestAction', failed_actions) action.apply = lambda *args, **kwargs: {} ask_for_action_and_apply(*args) self.assertEqual(generator.last_input, 3) self.assertNotIn('TestAction', failed_actions)
def choose_action(console_printer, actions, apply_single=False): """ Presents the actions available to the user and takes as input the action the user wants to choose. :param console_printer: Object to print messages on the console. :param actions: Actions available to the user. :param apply_single: The action that should be applied for all results. If it's not selected, has a value of False. :return: Return choice of action of user. """ actions.insert(0, DoNothingAction().get_metadata()) if apply_single: for i, action in enumerate(actions, 0): if apply_single == action.desc: return i return 0 else: while True: for i, action in enumerate(actions, 0): output = '{:>2}. {}' if i != 0 else '*{}. {}' color_letter(console_printer, format_lines(output.format( i, action.desc), symbol='[')) line = format_lines(STR_ENTER_NUMBER, symbol='[') choice = input(line) if not choice: return 0 choice = str(choice) if choice.isalpha(): choice = choice.upper() choice = '(' + choice + ')' for i, action in enumerate(actions, 0): if choice in action.desc: return i elif choice.isnumeric(): choice = int(choice) if 0 <= choice <= len(actions): return choice console_printer.print(format_lines( 'Please enter a valid letter.', symbol='['))
def ask_for_action_and_apply(console_printer, section, metadata_list, action_dict, failed_actions, result, file_diff_dict, file_dict, applied_actions, apply_single=False): """ Asks the user for an action and applies it. :param console_printer: Object to print messages on the console. :param section: Currently active section. :param metadata_list: Contains metadata for all the actions. :param action_dict: Contains the action names as keys and their references as values. :param failed_actions: A set of all actions that have failed. A failed action remains in the list until it is successfully executed. :param result: Result corresponding to the actions. :param file_diff_dict: If it is an action which applies a patch, this contains the diff of the patch to be applied to the file with filename as keys. :param file_dict: Dictionary with filename as keys and its contents as values. :param apply_single: The action that should be applied for all results. If it's not selected, has a value of False. :param applied_actions: A dictionary that contains the result, file_dict, file_diff_dict and the section for an action. :return: Returns a boolean value. True will be returned, if it makes sense that the user may choose to execute another action, False otherwise. If apply_single isn't set, always return False. """ do_nothing_action = DoNothingAction() metadata_list.insert(0, do_nothing_action.get_metadata()) action_dict[do_nothing_action.get_metadata().id] = DoNothingAction() actions_desc, actions_id = choose_action(console_printer, metadata_list, apply_single) if apply_single: for index, action_details in enumerate(metadata_list, 1): if apply_single == action_details.desc: action_name, section = get_action_info( section, metadata_list[index - 1], failed_actions) chosen_action = action_dict[action_details.id] try_to_apply_action(action_name, chosen_action, console_printer, section, metadata_list, action_dict, failed_actions, result, file_diff_dict, file_dict, applied_actions) break return False else: for action_choice, action_choice_id in zip(actions_desc, actions_id): chosen_action = action_dict[action_choice_id] action_choice_made = action_choice for index, action_details in enumerate(metadata_list, 1): if action_choice_made == action_details.desc: action_name, section = get_action_info( section, metadata_list[index - 1], failed_actions) try_to_apply_action(action_name, chosen_action, console_printer, section, metadata_list, action_dict, failed_actions, result, file_diff_dict, file_dict, applied_actions) if action_choice == 'Do (N)othing': return False return True
from coalib.results.result_actions.ShowAppliedPatchesAction import ( ShowAppliedPatchesAction) from coalib.results.result_actions.GeneratePatchesAction import ( GeneratePatchesAction) from coalib.results.result_actions.PrintDebugMessageAction import ( PrintDebugMessageAction) from coalib.results.result_actions.ShowPatchAction import ShowPatchAction from coalib.results.RESULT_SEVERITY import RESULT_SEVERITY from coalib.results.SourceRange import SourceRange from coalib.settings.Setting import glob_list, typed_list from coalib.parsing.Globbing import fnmatch from coalib.io.FileProxy import FileDictGenerator from coalib.io.File import File ACTIONS = [ DoNothingAction(), ApplyPatchAction(), PrintDebugMessageAction(), ShowPatchAction(), IgnoreResultAction(), ShowAppliedPatchesAction(), GeneratePatchesAction() ] def get_cpu_count(): # cpu_count is not implemented for some CPU architectures/OSes return os.cpu_count() or 2 def fill_queue(queue_fill, any_list):
def ask_for_action_and_apply(console_printer, section, metadata_list, action_dict, failed_actions, result, file_diff_dict, file_dict, applied_actions, apply_single=False): """ Asks the user for an action and applies it. :param console_printer: Object to print messages on the console. :param section: Currently active section. :param metadata_list: Contains metadata for all the actions. :param action_dict: Contains the action names as keys and their references as values. :param failed_actions: A set of all actions that have failed. A failed action remains in the list until it is successfully executed. :param result: Result corresponding to the actions. :param file_diff_dict: If it is an action which applies a patch, this contains the diff of the patch to be applied to the file with filename as keys. :param file_dict: Dictionary with filename as keys and its contents as values. :param apply_single: The action that should be applied for all results. If it's not selected, has a value of False. :param applied_actions: A dictionary that contains the result, file_dict, file_diff_dict and the section for an action. :return: Returns a boolean value. True will be returned, if it makes sense that the user may choose to execute another action, False otherwise. If apply_single isn't set, always return False. """ do_nothing_action = DoNothingAction() metadata_list.insert(0, do_nothing_action.get_metadata()) action_dict[do_nothing_action.get_metadata().name] = DoNothingAction() actions_desc, actions_name = choose_action(console_printer, metadata_list, apply_single) if apply_single: for index, action_details in enumerate(metadata_list, 1): if apply_single == action_details.desc: action_name, section = get_action_info( section, metadata_list[index - 1], failed_actions) chosen_action = action_dict[action_details.name] try_to_apply_action(action_name, chosen_action, console_printer, section, metadata_list, action_dict, failed_actions, result, file_diff_dict, file_dict, applied_actions) return False else: for action_choice, action_choice_name in zip(actions_desc, actions_name): chosen_action = action_dict[action_choice_name] action_choice_made = action_choice for index, action_details in enumerate(metadata_list, 1): if action_choice_made in action_details.desc: action_name, section = get_action_info( section, metadata_list[index-1], failed_actions) try_to_apply_action(action_name, chosen_action, console_printer, section, metadata_list, action_dict, failed_actions, result, file_diff_dict, file_dict, applied_actions) if action_choice == 'Do (N)othing': return False return True