当前位置: 首页>>代码示例>>Python>>正文


Python Project.validate方法代码示例

本文整理汇总了Python中rope.base.project.Project.validate方法的典型用法代码示例。如果您正苦于以下问题:Python Project.validate方法的具体用法?Python Project.validate怎么用?Python Project.validate使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在rope.base.project.Project的用法示例。


在下文中一共展示了Project.validate方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: getRopeProject

# 需要导入模块: from rope.base.project import Project [as 别名]
# 或者: from rope.base.project.Project import validate [as 别名]
        def getRopeProject( self, fileName = "" ):
            " Provides existed or creates a new rope project "
            if self.project.isLoaded():
                return self.project.getRopeProject()

            # There is no current project so create a temporary one.
            # Two cases: the buffer has been saved
            #            not saved buffer
            if os.path.isabs( fileName ):
                dirName = os.path.dirname( fileName )
            else:
                # Unsaved buffer, make an assumption that
                # it is in home directory
                dirName = str( QDir.homePath() )

            prefs = copy.deepcopy( ropePreferences )

            # Exclude nested dirs as it could take too long
            # Get only dir names and do not get those dirs
            # where __init__.py[3] are present
            subdirsToExclude = getSubdirs( dirName, True, True )

            if "ignored_resources" in prefs:
                prefs[ "ignored_resources" ] += subdirsToExclude
            else:
                prefs[ "ignored_resources" ] = subdirsToExclude

            project = RopeProject( dirName, None, None, **prefs )
            project.validate( project.root )
            return project
开发者ID:eaglexmw,项目名称:codimension,代码行数:32,代码来源:globals.py

示例2: _get_other_projects

# 需要导入模块: from rope.base.project import Project [as 别名]
# 或者: from rope.base.project.Project import validate [as 别名]
 def _get_other_projects(path_only=False):
     """
     Gets the list of secondary projects (all except current).
     """
     projects = []
     current = api.project.get_current_project()
     for path in api.project.get_projects():
         if path == current:
             continue
         if not path_only:
             prj = Project(path, ropefolder=api.project.FOLDER,
                           fscommands=FileSystemCommands())
             prj.validate()
         else:
             prj = path
         projects.append(prj)
     return projects
开发者ID:SirmoGames,项目名称:hackedit-python,代码行数:19,代码来源:refactor.py

示例3: CodimensionProject

# 需要导入模块: from rope.base.project import Project [as 别名]
# 或者: from rope.base.project.Project import validate [as 别名]

#.........这里部分代码省略.........
        self.__createRopeProject()
        self.projectChanged.emit( self.CompleteProject )
        self.emit( SIGNAL( 'restoreProjectExpandedDirs' ) )
        return

    def getImportDirsAsAbsolutePaths( self ):
        " Provides a list of import dirs as absolute paths "
        result = []
        for path in self.importDirs:
            if os.path.isabs( path ):
                result.append( path )
            else:
                result.append( self.getProjectDir() + path )
        return result

    def __getImportDirsForRope( self ):
        " Provides the list of import dirs for the rope library "
        result = []
        for path in self.importDirs:
            if not os.path.isabs( path ):
                # The only relative paths can be accepted by rope
                result.append( path )
        result.sort()
        return result

    def getRopeProject( self ):
        " Provides the rope project "
        if self.__getImportDirsForRope() != self.__ropeSourceDirs:
            # The user changed the project import dirs, so let's
            # re-create the project
            self.__createRopeProject()
        return self.__ropeProject

    def validateRopeProject( self, fileName ):
        " Validates the rope project "
        # Currently rope can validate a directory only so the argument
        # is ignored
        self.__ropeProject.validate()
        return

    def __createRopeProject( self ):
        " Creates a rope library project "
        if self.__ropeProject is not None:
            self.__ropeProject.close()
            self.__ropeProject = None
            self.__ropeSourceDirs = []

        # Deal with import dirs and preferences first
        self.__ropeSourceDirs = self.__getImportDirsForRope()
        prefs = copy.deepcopy( ropePreferences )
        if len( self.__ropeSourceDirs ) != 0:
            prefs[ "source_folders" ] = self.__ropeSourceDirs

        # Rope folder is default here, so it will be created
        self.__ropeProject = RopeProject( self.getProjectDir(),
                                          **prefs )
        self.__ropeProject.validate( self.__ropeProject.root )
        return

    def onFSChanged( self, items ):
        " Triggered when the watcher detects changes "
##        report = "REPORT: "
##        projectItems = []
        for item in items:
            item = str( item )
开发者ID:eaglexmw,项目名称:codimension,代码行数:69,代码来源:project.py

示例4: __init__

# 需要导入模块: from rope.base.project import Project [as 别名]
# 或者: from rope.base.project.Project import validate [as 别名]

#.........这里部分代码省略.........

    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)
开发者ID:patrikha,项目名称:pyrename,代码行数:104,代码来源:pyrename.py

示例5: Refactor

# 需要导入模块: from rope.base.project import Project [as 别名]
# 或者: from rope.base.project.Project import validate [as 别名]
class Refactor(QtGui.QWidget):

    def __init__(self, editorTabWidget, busyWidget, parent=None):
        QtGui.QWidget.__init__(self, parent)

        self.editorTabWidget = editorTabWidget
        self.busyWidget = busyWidget
        self.root = editorTabWidget.pathDict["sourcedir"]
        ropeFolder = editorTabWidget.pathDict["ropeFolder"]

        prefs = {
            'ignored_resources': ['*.pyc', '*~', '.ropeproject',
                                  '.hg', '.svn', '_svn', '.git',
                                  '__pycache__'],
            'python_files': ['*.py'],
            'save_objectdb': True,
            'compress_objectdb': False,
            'automatic_soa': True,
            'soa_followed_calls': 0,
            'perform_doa': True,
            'validate_objectdb': True,
            'max_history_items': 32,
            'save_history': True,
            'compress_history': False,
            'indent_size': 4,
            'extension_modules': [
                "PyQt4", "PyQt4.QtGui", "QtGui", "PyQt4.QtCore", "QtCore",
                "PyQt4.QtScript", "QtScript", "os.path", "numpy", "scipy", "PIL",
                "OpenGL", "array", "audioop", "binascii", "cPickle", "cStringIO",
                "cmath", "collections", "datetime", "errno", "exceptions", "gc",
                "imageop", "imp", "itertools", "marshal", "math", "mmap", "msvcrt",
                "nt", "operator", "os", "parser", "rgbimg", "signal", "strop", "sys",
                "thread", "time", "wx", "wxPython", "xxsubtype", "zipimport", "zlib"
            ],
            'import_dynload_stdmods': True,
            'ignore_syntax_errors': True,
            'ignore_bad_imports': True
        }

        self.ropeProject = Project(
            projectroot=self.root, ropefolder=ropeFolder, **prefs)
        self.ropeProject.prefs.add('python_path', 'c:/Python33')
        self.ropeProject.prefs.add('source_folders', 'c:/Python33/Lib')
        self.ropeProject.validate()

        self.noProject = Project(projectroot="temp", ropefolder=None)

        self.findThread = FindUsageThread()
        self.findThread.finished.connect(self.findOccurrencesFinished)

        self.renameThread = RenameThread()
        self.renameThread.finished.connect(self.renameFinished)

        self.inlineThread = InlineThread()
        self.inlineThread.finished.connect(self.inlineFinished)

        self.localToFieldThread = LocalToFieldThread()
        self.localToFieldThread.finished.connect(self.localToFieldFinished)

        self.moduleToPackageThread = ModuleToPackageThread()
        self.moduleToPackageThread.finished.connect(
            self.moduleToPackageFinished)

        self.createActions()

        self.refactorMenu = QtGui.QMenu("Refactor")
        self.refactorMenu.addAction(self.renameAttributeAct)
        self.refactorMenu.addAction(self.inlineAct)
        self.refactorMenu.addAction(self.localToFieldAct)

    def close(self):
        self.ropeProject.close()

    def createActions(self):
        self.findDefAct = \
            QtGui.QAction(
                QtGui.QIcon(os.path.join("Resources", "images", "map_marker")),
                "Go-to Definition", self, statusTip="Go-to Definition",
                triggered=self.findDefinition)

        self.findOccurrencesAct = \
            QtGui.QAction("Usages", self, statusTip="Usages",
                          triggered=self.findOccurrences)

        self.moduleToPackageAct = \
            QtGui.QAction(
                "Convert to Package", self, statusTip="Convert to Package",
                triggered=self.moduleToPackage)

        self.renameModuleAct = \
            QtGui.QAction("Rename", self, statusTip="Rename",
                          triggered=self.renameModule)

        self.renameAttributeAct = \
            QtGui.QAction("Rename", self, statusTip="Rename",
                          triggered=self.renameAttribute)

        self.inlineAct = \
            QtGui.QAction("Inline", self, statusTip="Inline",
                          triggered=self.inline)
#.........这里部分代码省略.........
开发者ID:takluyver,项目名称:Pcode,代码行数:103,代码来源:Refactor.py

示例6: find_usages

# 需要导入模块: from rope.base.project import Project [as 别名]
# 或者: from rope.base.project.Project import validate [as 别名]
def find_usages(_, main_project, other_projects, file_path, offset):
    """
    Find usages of symbol under cursor.
    """
    try:
        occurrences = []
        if other_projects:
            for path in [main_project] + other_projects:
                prj = Project(path, ropefolder=api.project.FOLDER,
                              fscommands=FileSystemCommands())
                prj.validate()
                mod = libutils.path_to_resource(prj, file_path)
                occurrences += find_occurrences(
                    prj, mod, offset, unsure=False, in_hierarchy=True)
                prj.close()
        else:
            prj = Project(main_project, ropefolder=api.project.FOLDER,
                          fscommands=FileSystemCommands())
            prj.validate()
            mod = libutils.path_to_resource(prj, file_path)
            occurrences = find_occurrences(prj, mod, offset, unsure=False,
                                           in_hierarchy=True)
        # transform results to a serialisable list of usages that is ready
        # to use by the find_results widget.
        occurrences_map = {}
        for location in occurrences:
            path = location.resource.real_path
            lineno = location.lineno - 1
            # convert file region to line region
            content = location.resource.read()
            offset = location.offset
            char = content[offset]
            while char != '\n':  # find start of line
                offset -= 1
                char = content[offset]
            # update offsets
            start = location.offset - offset - 1
            end = location.region[1] - offset - 1
            line_text = content.splitlines()[lineno]
            data = (lineno, line_text, [(start, end)])
            if path not in occurrences_map:
                occurrences_map[path] = [data]
            else:
                occurrences_map[path].append(data)
        results = []
        for key, value in occurrences_map.items():
            results.append((key, value))
        results = sorted(results, key=lambda x: x[0])
        return results
    except RopeError as e:
        error = RefactoringError()
        error.exc = str(e)
        error.traceback = traceback.format_exc()
        error.critical = False
        return error
    except Exception as e:
        error = RefactoringError()
        error.exc = str(e)
        error.traceback = traceback.format_exc()
        error.critical = True
        return error
开发者ID:SirmoGames,项目名称:hackedit-python,代码行数:63,代码来源:refactor.py

示例7: PyRefactor

# 需要导入模块: from rope.base.project import Project [as 别名]
# 或者: from rope.base.project.Project import validate [as 别名]
class PyRefactor(plugins.WorkspacePlugin):
    """
    Adds some refactoring capabilities to the IDE (using the rope library).

    Supported operations:
        - Rename
        - Extract method
        - Extract variable
        - Find occurrences
        - Organize imports

    """
    def activate(self):
        self._preview_dock = None
        self._occurrences_dock = None
        self._occurrences_results = None
        self._review_widget = None
        api.signals.connect_slot(api.signals.CURRENT_PROJECT_CHANGED,
                                 self._on_current_project_changed)
        api.signals.connect_slot(api.signals.EDITOR_CREATED,
                                 self._on_editor_created)
        api.signals.connect_slot(api.signals.CURRENT_EDITOR_CHANGED,
                                 self._update_edit_actions_state)
        path = api.project.get_current_project()
        self._main_project = Project(path, ropefolder=api.project.FOLDER,
                                     fscommands=FileSystemCommands())
        self._main_project.validate()
        api.signals.connect_slot(api.signals.DOCUMENT_SAVED,
                                 self._on_document_saved)

    def close(self):
        self._main_project.close()

    def rename(self):
        """
        Renames word under cursor.
        """
        editor = api.editor.get_current_editor()
        if editor is None:
            return
        editor.file.save()
        assert isinstance(editor, PyCodeEdit)
        module = libutils.path_to_resource(
            self._main_project, editor.file.path)
        self._main_project.validate()
        cursor_position = self._get_real_position(
            editor.textCursor().position())
        try:
            renamer = Rename(self._main_project, module, cursor_position)
        except RopeError:
            return
        if not renamer.get_old_name():
            return
        preview, replacement = DlgRope.rename(
            self.main_window, renamer.get_old_name())
        if preview is None and replacement is None:
            return
        multiproj = self._has_multiple_projects()
        other_projects = self._get_other_projects()
        main_project = self._main_project
        self._preview = preview
        api.tasks.start(_('Refactoring: rename'), rename_symbol,
                        self._on_changes_available,
                        args=(
                            main_project, multiproj, other_projects,
                            editor.file.path, cursor_position, replacement),
                        cancellable=True, use_thread=True)

    def organise_imports(self):
        editor = api.editor.get_current_editor()
        api.editor.save_all_editors()
        if editor is None:
            return
        self._preview = True
        file_path = editor.file.path
        project = self.get_project_for_file(file_path)
        if project:
            api.tasks.start(
                _('Refactoring: organize imports'), organize_imports,
                self._on_changes_available,
                args=(project, file_path),
                cancellable=True, use_thread=True)

    def extract_method(self):
        """
        Extracts a method from the selected text (if possible, otherwise a
        warning message will appear).
        """
        api.editor.save_all_editors()
        self._main_project.validate()
        editor = api.editor.get_current_editor()
        if editor is None or not editor.textCursor().hasSelection():
            return
        editor.file.save()
        if not editor.textCursor().hasSelection():
            TextHelper(editor).select_whole_line()
        start = self._get_real_position(editor.textCursor().selectionStart())
        end = self._get_real_position(editor.textCursor().selectionEnd())
        preview, replacement = DlgRope.extract_method(self.main_window)
        if preview is None and replacement is None:
#.........这里部分代码省略.........
开发者ID:SirmoGames,项目名称:hackedit-python,代码行数:103,代码来源:refactor.py


注:本文中的rope.base.project.Project.validate方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。