New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gsoc: Add Action: Generate Patches #4634

Merged
merged 1 commit into from Aug 26, 2017
Jump to file or symbol
Failed to load files and symbols.
+180 −2
Diff settings

Always

Just for now

Add Action: Generate Patches

Add action that generates patches depending on the file

Closes #4599
  • Loading branch information...
Nosferatul committed Jul 31, 2017
commit 25e019cdd944532f969d5cf1079afd7d62f41e19
@@ -19,6 +19,8 @@
from coalib.results.result_actions.OpenEditorAction import OpenEditorAction
from coalib.results.result_actions.IgnoreResultAction import IgnoreResultAction
from coalib.results.result_actions.DoNothingAction import DoNothingAction
from coalib.results.result_actions.GeneratePatchesAction import (
GeneratePatchesAction)
from coalib.results.result_actions.ShowAppliedPatchesAction import (
ShowAppliedPatchesAction)
from coalib.results.result_actions.PrintDebugMessageAction import (
@@ -86,7 +88,8 @@ def highlight_text(no_color, text, style, lexer=TextLexer()):
PrintMoreInfoAction(),
ShowPatchAction(),
IgnoreResultAction(),
ShowAppliedPatchesAction())
ShowAppliedPatchesAction(),
GeneratePatchesAction())
DIFF_EXCERPT_MAX_SIZE = 4
@@ -20,6 +20,8 @@
from coalib.results.result_actions.IgnoreResultAction import IgnoreResultAction
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
@@ -34,7 +36,8 @@
PrintDebugMessageAction,
ShowPatchAction,
IgnoreResultAction,
ShowAppliedPatchesAction]
ShowAppliedPatchesAction,
GeneratePatchesAction]
def get_cpu_count():
@@ -0,0 +1,100 @@
from pygments.lexers import guess_lexer_for_filename
from pyprint.ConsolePrinter import ConsolePrinter
from coalib.results.result_actions.ResultAction import ResultAction
from coalib.results.result_actions.ShowPatchAction import ShowPatchAction
from coalib.output.printers.LogPrinter import LogPrinter
from coalib.parsing.FilterHelper import FilterHelper
from coalib.coala_modes import mode_normal
from coalib.parsing.DefaultArgParser import default_arg_parser
OBJECT_INDEX = FILENAME_INDEX = 0
DEFAULT_BEAR = 'SpaceConsistencyBear'
def show_possibilities(console_printer, i, action):
console_printer.print('[{:>4}] {}. Apply patch (\'{}\')'.format('', i,
action))
def create_arg_parser(files, bears):
"""
A function that generates a `default_arg_parser`.
:param files: A list that contains filenames.
:param bears: A list that contains name of bears.
:return: An object of type `default_arg_parser`.
"""
args = default_arg_parser().parse_args()
args.files = files
args.bears = bears
args.default_actions = '*: ApplyPatchAction'

This comment has been minimized.

@shreyans800755

shreyans800755 Aug 25, 2017

Contributor

ApplyPatchAction -> GeneratePatchAction

@shreyans800755

shreyans800755 Aug 25, 2017

Contributor

ApplyPatchAction -> GeneratePatchAction

This comment has been minimized.

@Nosferatul

Nosferatul Aug 25, 2017

Member

you want to apply the patch, not to generate another one :)

@Nosferatul

Nosferatul Aug 25, 2017

Member

you want to apply the patch, not to generate another one :)

return args
def filter_bears(language):
"""
Filter bears by language.
:param language: The language to filter with.
:return: A list of bears.
"""
return list(FilterHelper.apply_filters(
[['language', language]], None)[0]['cli'])
def find_language(filename):
"""
Find the language used in `filename`.
:param filename: The name of the file.
:return: The language used.
"""
return guess_lexer_for_filename(filename, 'Error, no file '
'found').name
class DefaultBear():
def __init__(self):
self.name = DEFAULT_BEAR
class GeneratePatchesAction(ResultAction):
SUCCESS_MESSAGE = 'Patch generated successfully.'
is_applicable = staticmethod(ShowPatchAction.is_applicable)

This comment has been minimized.

@shreyans800755

shreyans800755 Aug 25, 2017

Contributor

ShowPatchAction -> GeneratePatchAction
Copy past worm

@shreyans800755

shreyans800755 Aug 25, 2017

Contributor

ShowPatchAction -> GeneratePatchAction
Copy past worm

This comment has been minimized.

@Nosferatul

Nosferatul Aug 25, 2017

Member

This should not be changed, look in ApplyPatchAction

@Nosferatul

Nosferatul Aug 25, 2017

Member

This should not be changed, look in ApplyPatchAction

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)
@@ -30,6 +30,8 @@
from coalib.results.result_actions.DoNothingAction import DoNothingAction
from coalib.results.result_actions.ShowAppliedPatchesAction \
import ShowAppliedPatchesAction
from coalib.results.result_actions.GeneratePatchesAction import (
GeneratePatchesAction)
from coalib.results.result_actions.ResultAction import ResultAction
from coalib.results.SourceRange import SourceRange
from coalib.settings.Section import Section
@@ -0,0 +1,70 @@
import unittest
import os.path
from coalib.results.Diff import Diff
from coala_utils.ContextManagers import make_temp
from coalib.results.Result import Result
from coalib.results.result_actions.GeneratePatchesAction import (
GeneratePatchesAction)
from coalib.settings.Section import Section, Setting
from coala_utils.ContextManagers import (
make_temp, retrieve_stdout, simulate_console_inputs)
from tests.TestUtilities import (
bear_test_module,
execute_coala,
TEST_BEARS_COUNT,
)
from coala_utils.ContextManagers import prepare_file
class GeneratePatchesActionTest(unittest.TestCase):
def setUp(self):
self.uut = GeneratePatchesAction()
self.file_dict = {'a.py': ['a\n', 'b\n', 'c\n'], 'b': ['old_first\n']}
self.diff_dict = {'a.py': Diff(self.file_dict['a.py']),
'b': Diff(self.file_dict['b'])}
self.diff_dict['a.py'].add_lines(1, ['test\n'])
self.diff_dict['a.py'].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('no_color', 'True'))
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 prepare_file(['fixme '], None) as (lines, filename):
dir_path = os.path.dirname(filename)
file_path = os.path.basename(filename)
newfilename = os.path.join(dir_path, file_path + '.py')
os.rename(filename, newfilename)
file_dict = {newfilename: ['fixme ']}
diff_dict = {newfilename: Diff(file_dict[newfilename])}
diff_dict[newfilename].add_line(1, ['test\n'])
test_result = Result('origin', 'message', diffs=diff_dict)
section = Section('name')
section.append(Setting('no_color', 'True'))
with simulate_console_inputs('1', 'True', '0') as generator:
with retrieve_stdout() as stdout:
self.uut.apply_from_section(test_result, file_dict, {},
section)
self.assertIn('[ ] *0. Do Nothing\n'
'[ ] 1. Apply patch '
'(\'SpaceConsistencyBear\')\n'
'[ ]', stdout.getvalue())
os.rename(newfilename, filename)
def test_apply_no_input(self):
with retrieve_stdout() as stdout:
with simulate_console_inputs('', '0') as generator:
self.assertEqual(self.uut.apply_from_section(self.test_result,
self.file_dict,
{},
self.section),
False)
ProTip! Use n and p to navigate between commits in a pull request.