예제 #1
0
def main():
    prj = Project(os.path.realpath("../shuup/core/models"))
    rst = Restructure(prj, "_(${str})", "")
    rst.template = LanguageTwist("./shuup_fi_to_en.po")

    twist_set = rst.get_changes()

    for chg in twist_set.changes:
        print(chg.get_description())  # noqa

    prj.do(twist_set)
예제 #2
0
def inline(inline_fns, dirname, filename):
    project = Project(dirname)
    resource = project.get_resource(filename)
    for inline_fn in inline_fns:
        try:  # FIXME: temporarily handling not implemented error
            changes = create_inline(
                project, resource,
                resource.read().index(inline_fn)).get_changes(remove=True)
            project.do(changes)
        except Exception as e:
            pass
예제 #3
0
def main():
    prj = Project(os.path.realpath("../shuup/core/models"))
    rst = Restructure(prj, "_(${str})", "")
    rst.template = LanguageTwist("./shuup_fi_to_en.po")

    twist_set = rst.get_changes()

    for chg in twist_set.changes:
        print(chg.get_description())

    prj.do(twist_set)
예제 #4
0
def _rename_package(project: Project, old_name: str, new_name: str) -> None:
    """
    Rename a Python package, refactoring relevant imports along the way,
    as well as references in comments.

    Args:
        project: rope.base.Project holding the scope of the refactoring.
        old_name: Old module name. Can be a fully qualified module path,
            e.g. "package.pipelines.pipeline" or "package/pipelines/pipeline",
            relative to the `project` root.
        new_name: New module name. Can't be a fully qualified module path.
    """
    folder = project.get_folder(old_name)
    change = Rename(project, folder).get_changes(new_name, docs=True)
    project.do(change)
예제 #5
0
class Agent(object):
    def __init__(self, target_file, dry_run):
        self.project = Project(os.getcwd())
        self.target_file = target_file
        self.dry_run = dry_run
        self.commands = []

    @property
    def resource(self):
        return File(self.project, self.target_file)

    def add_command_class(self, command_class):
        self.commands.append(command_class)

    def do(self):
        commands = [
            command_class(self.project, self.target_file, self.dry_run)
            for command_class in self.commands
        ]
        changesets = filter(
            lambda x: x is not None,
            [
                command.get_changeset()
                for command in commands
            ]
        )

        # merge changesets
        def merge_changesets(aggregated_changeset, next_changeset):
            for change in next_changeset.changes:
                aggregated_changeset.add_change(change)
            aggregated_changeset.description += next_changeset.description
            return aggregated_changeset

        new_changeset = reduce(
            merge_changesets,
            changesets,
            ChangeSet('')
        )

        if not new_changeset.changes:
            return

        if self.dry_run:
            print new_changeset.get_description()
        else:
            self.project.do(new_changeset)
예제 #6
0
파일: rope.py 프로젝트: smiled0g/vy
    def rename(self, name):
        tmp0    = self.area.get('1.0', 'insert')
        offset  = len(tmp0)
        path    = self.get_root_path()
        project = Project(path)
        mod     = path_to_resource(project, self.area.filename)
        renamer = Rename(project, mod, offset)
        changes = renamer.get_changes(name)
        project.do(changes)

        self.update_instances(changes)

        print('\nRope - Renamed resource ..\n')
        print(changes.get_description())
        self.area.chmode('NORMAL')
        root.status.set_msg('Resources renamed!')
        project.close()
예제 #7
0
def _move_package(project: Project, source: str, target: str) -> None:
    """
    Move a Python package, refactoring relevant imports along the way.
    A target of empty string means moving to the root of the `project`.

    Args:
        project: rope.base.Project holding the scope of the refactoring.
        source: Name of the Python package to be moved. Can be a fully
            qualified module path relative to the `project` root, e.g.
            "package.pipelines.pipeline" or "package/pipelines/pipeline".
        target: Destination of the Python package to be moved. Can be a fully
            qualified module path relative to the `project` root, e.g.
            "package.pipelines.pipeline" or "package/pipelines/pipeline".
    """
    src_folder = project.get_module(source).get_resource()
    target_folder = project.get_module(target).get_resource()
    change = MoveModule(project, src_folder).get_changes(dest=target_folder)
    project.do(change)
예제 #8
0
파일: rope.py 프로젝트: smiled0g/vy
    def move(self, name):
        """
        """
        tmp0    = self.area.get('1.0', 'insert')
        offset  = len(tmp0)

        path    = self.get_root_path()
        project = Project(path)

        project = Project(path)
        mod     = path_to_resource(project, self.area.filename)
        mover   = create_move(project, mod, offset)
        destin  = path_to_resource(project, name)
        changes = mover.get_changes(destin)
        project.do(changes)

        self.update_instances(changes)
        project.close()

        self.area.chmode('NORMAL')
        root.status.set_msg('Resources moved!')
예제 #9
0
class rename:

    def __init__(self, project_path=None, module_path=None):
        """ initialize using project path and optional sub module path to limit rename scope """
        if project_path:
            self.project = Project(project_path)
        self.module_path = module_path
        self.words = set()
        self.files = []
        self.namemap = {}
        self.classname_regex = re.compile('class\s+(?P<name>[a-zA-Z0-9_]+)')
        self.methodname_regex = re.compile('def\s+(?P<name>[a-zA-Z0-9_]+)')

    def load_words(self):
        """ load all known words """
        with open('words') as f:
            for line in f:
                self.words.add(line.strip().lower())

    def load_dict(self, dictionary_path):
        """ load a custom dict with new (recognized) and restricted (unrecognized) words """
        doc = etree.parse(dictionary_path)
        for recognized in doc.xpath('/dictionary/recognized/word'):
            self.words.add(recognized.text)
        for unrecognized in doc.xpath('/dictionary/unrecognized/word'):
            if unrecognized.text in self.words:
                self.words.remove(unrecognized.text)

    def wash_word(self, string):
        """ clean up word by separating prefix, suffix and word without underscores """
        prefix = string[:string.find(string.lstrip('_'))]
        suffix = string[len(string.rstrip('_')):]
        word = string.lower().replace('_', '')
        return (prefix, word, suffix)

    def find_word(self, string, index):
        """ find the longest word from index """
        word = ''
        i = index + 1
        while i <= len(string):
            if string[index:i] in self.words:
                word = string[index:i]
            i += 1
        return word

    def reverse_find_word(self, string, index):
        """ backwards find the longest word from index """
        word = ''
        i = index - 1
        while i >= 0:
            if string[i:index] in self.words:
                word = string[i:index]
            i -= 1
        return word

    def find_words(self, string, index=-1):
        """ find all known words in a string """
        words = []
        if index == -1:
            index = len(string)
        if index == 0:
            return words
        word = self.reverse_find_word(string, index)
        if word:
            words.insert(0, word)
            index -= len(word)
        else:
            index -= 1
        w = self.find_words(string, index)
        w.extend(words)
        words = w
        #words.extend(self.find_words(string, index))
        return words

    def rename(self, string):
        """ rename string to PEP8 standard """
        index = 0
        last_index = 0
        new_name = ''
        prefix, old_name, suffix = self.wash_word(string)
        for word in self.find_words(old_name):
            index = old_name.find(word, index)
            if last_index != index:
                new_name += old_name[last_index: index]
            if len(new_name) > 0:
                new_name += '_'
            new_name += word
            index += len(word)
            last_index = index
        if last_index != len(old_name):
            if len(new_name) > 0:
                new_name += '_'
            new_name += old_name[last_index:]
        return '%s%s%s' % (prefix, new_name, suffix)

    def index_file(self, content):
        """ get all indexes for methods to rename in context
            return list of old name, position and new name """
        index = 0
        methods = []
        running = True
        while running:
            method = self.methodname_regex.search(content, index)
            if method:
                old_name = method.group('name')
                pos = method.start() + method.string[method.start():].find(old_name)
                new_name = self.rename(old_name)
                if old_name != new_name:
                    methods.append((old_name, pos, new_name))
                index = pos + len(old_name)
            else:
                running = False
        return methods

    def get_files(self):
        """ iterator for all valid project files """
        for file_resource in self.project.get_files():
            if self.module_path and not self.module_path in file_resource.real_path:
                continue
            yield file_resource

    def dry_run(self):
        """ list all methods to be renamed without updating any files """
        for file_resource in self.get_files():
            methods = self.index_file(file_resource.read())
            print('%s' % file_resource.path)
            for method in methods:
                print('    %s:%d->%s' % (method[0], method[1], method[2]))

    def refactor(self):
        """ renames all methods to PEP8 standard """
        for file_resource in self.get_files():
            while True:
                self.project.validate()
                methods = self.index_file(file_resource.read())
                if len(methods) == 0:
                    break
                method = methods[0]
                old_name = method[0]
                pos = method[1]
                new_name = method[2]
                print('rename: %s:%d->%s' % (old_name, pos, new_name))
                changes = Rename(self.project, file_resource, pos).get_changes(new_name)
                self.project.do(changes)
예제 #10
0
def compile_with_top(source_path, api_path):
    # parse the inputs to get the path subcomponents
    source_path = op.abspath(source_path)
    api_path = op.abspath(api_path)
    api_root, api_name = op.split(api_path)
    api_module = op.basename(op.normpath(api_root))
    source_root, source_name = op.split(source_path)

    # Create the two projects that we will be using
    from rope.base.project import Project
    project_const = Project(source_root, **prefs)  # original project, used as a source and will not be modified
    project_swap = Project(op.join(source_root, 'top_compiled'), **prefs)

    if(op.isdir(source_path)):
        pass

    # copy over the files that will be compiled
    source_mod = project_const.root.get_child(source_name)
    try:
        mod_code = project_swap.root.get_child(source_name)
    except ResourceNotFoundError:
        mod_code = project_swap.root.create_file(source_name)

    mod_code.write(source_mod.read())

    # Generate the api library package and copy it over
    from rope.contrib import generate
    api_pkg = None
    if api_root != source_root: # If the api is in its own module, reproduce it
        try:
            api_pkg = project_swap.root.get_child(api_module)
        except ResourceNotFoundError:
            api_pkg = generate.create_package(project_swap, api_module)
    try:
        mod_api = project_swap.root.get_child('{}/{}'.format(api_module, api_name))
    except ResourceNotFoundError:
        mod_api = generate.create_module(project_swap, 'api', api_pkg)
    # copy over the contents of the api so that rope can modify it
    with open(api_path, 'r') as a:
        api_content = a.read()

    # mod_api.truncate().write(api_content)
    mod_api.write(api_content)

    # inline each API call
    # first, get the list of all API function calls possible
    import imp, types
    api = imp.load_source(api_name, api_path)
    api_calls = [a for a in dir(api) if isinstance(api.__dict__.get(a), types.FunctionType)]
    # perform the replacement
    for a in api_calls:
        # We did not use this API call in the code, so skip replacing it
        if re.search(r'\b{}\b'.format(a), mod_code.read()) is None:
            continue
        # print re.search(r'\b{}\b'.format(a), mod_code.read())
        ind = re.search(r'\b{}\b'.format(a), mod_code.read()).start()
        try:
            inl = inline.create_inline(project_swap, mod_code, ind)
            change = inl.get_changes()
            project_const.do(change)
        except RefactoringError:
            print "The api cannot be properly connected from the code. Please ensure that you are importing the file with the API commands directly."

    # Cleaning up
    api_pkg.remove() # remove the API library from the compiled files
    project_const.close()
    project_swap.close()
예제 #11
0
from rope.base.project import Project
from rope.refactor.rename import Rename

proj = Project('../lib/ansible')

context = proj.get_file('context.py')

change = Rename(proj, context).get_changes('new_context')

proj.do(change)
예제 #12
0
from rope.base.project import Project
from rope.refactor.rename import Rename
from rope.contrib import generate
project = Project('.')
pycore = project.pycore
package = pycore.find_module('sindice')
changes = Rename(project, package).get_changes('core')
project.do(changes)
예제 #13
0
from rope.base.project import Project
from rope.base import libutils
from rope.refactor.move import create_move

myProj = Project('src')
# resource = myProj.get_resource(r'app/services/gridMaker/grid.py')
# resource = libutils.path_to_resource(myProj, r'src/app/services/gridMaker')
resource = myProj.get_resource(r'app/services/theGrid/windowSetter.py')
offset = None
destination = libutils.path_to_resource(
    myProj, r'src/app/services/theGrid/windowSetter')

mover = create_move(myProj, resource, offset)
myProj.do(mover.get_changes(destination))
예제 #14
0
       from rope.contrib import generate

      args
       project: type=rope.base.project.Project

    Example #4::

      pattern ${pow}(${param1}, ${param2})
      goal ${param1} ** ${param2}
      args pow: name=mod.pow, exact

    Example #5::

      pattern ${inst}.longtask(${p1}, ${p2})
      goal
       ${inst}.subtask1(${p1})
       ${inst}.subtask2(${p2})
      args
       inst: type=mod.A,unsure

"""
restructuring = restructure.Restructure(project, pattern, goal, args)

project.do(restructuring.get_changes())
mod2.read()
u'import mod1\nprint(2 ** 3)\n'

# Cleaning up
# mod1.remove()
# mod2.remove()
project.close()