Exemple #1
0
def getJediProject(force=False):
    """Provides a jedi project"""
    global jediProject

    if force or jediProject is None:
        project = GlobalData().project
        if project.isLoaded():
            jPath = project.getProjectDir()

            addedPaths = []
            for path in project.getImportDirsAsAbsolutePaths():
                if path not in addedPaths:
                    addedPaths.append(path)
            projectDir = project.getProjectDir()
            if projectDir not in addedPaths:
                addedPaths.append(projectDir)

        else:
            jPath = os.path.realpath(QDir.homePath())
            addedPaths = ()

        jediProject = Project(jPath,
                              sys_path=GlobalData().originalSysPath[:],
                              added_sys_path=addedPaths)

    return jediProject
Exemple #2
0
    def __viewProperties(self):
        """Handles the 'view properties' context menu item"""
        if self.__projectContextItem is None:
            return
        if not self.__projectContextItem.isValid():
            return

        if self.__projectContextItem.isCurrent():
            # This is the current project - it can be edited
            project = GlobalData().project
            dlg = ProjectPropertiesDialog(project, self)
            if dlg.exec_() == QDialog.Accepted:
                importDirs = []
                for index in range(dlg.importDirList.count()):
                    importDirs.append(dlg.importDirList.item(index).text())

                scriptName = dlg.scriptEdit.text().strip()
                relativePath = os.path.relpath(scriptName,
                                               project.getProjectDir())
                if not relativePath.startswith('..'):
                    scriptName = relativePath

                mdDocFile = dlg.mdDocEdit.text().strip()
                relativePath = os.path.relpath(mdDocFile,
                                               project.getProjectDir())
                if not relativePath.startswith('..'):
                    mdDocFile = relativePath

                project.updateProperties({
                    'scriptname':
                    scriptName,
                    'mddocfile':
                    mdDocFile,
                    'creationdate':
                    dlg.creationDateEdit.text().strip(),
                    'author':
                    dlg.authorEdit.text().strip(),
                    'license':
                    dlg.licenseEdit.text().strip(),
                    'copyright':
                    dlg.copyrightEdit.text().strip(),
                    'version':
                    dlg.versionEdit.text().strip(),
                    'email':
                    dlg.emailEdit.text().strip(),
                    'description':
                    dlg.descriptionEdit.toPlainText().strip(),
                    'uuid':
                    dlg.uuidEdit.text().strip(),
                    'importdirs':
                    importDirs,
                    'encoding':
                    dlg.encodingCombo.currentText().strip()
                })
        else:
            # This is not the current project - it can be viewed
            fName = self.__projectContextItem.getFilename()
            dlg = ProjectPropertiesDialog(fName, self)
            dlg.exec_()
Exemple #3
0
    def __init__(self,
                 fileName=None,
                 lineNumber=None,
                 condition="",
                 temporary=False,
                 enabled=True,
                 ignoreCount=0):
        if fileName is None:
            self.__fileName = fileName
        elif os.path.isabs(fileName):
            project = GlobalData().project
            if project.isLoaded():
                if project.isProjectFile(fileName):
                    # This is a project file; strip the project dir
                    self.__fileName = fileName.replace(project.getProjectDir(),
                                                       "")
                else:
                    # Not a project file, save as is
                    self.__fileName = fileName
            else:
                # Pretty much impossible
                self.__fileName = fileName
        else:
            # Relative path, i.e. a project file
            self.__fileName = fileName

        self.__lineNumber = lineNumber
        self.__condition = condition
        self.__temporary = temporary
        self.__enabled = enabled
        self.__ignoreCount = ignoreCount
Exemple #4
0
    def __getAutoDocFileName(fileName):
        """Forms the auto doc file name"""
        # Markdown is used as a default documentation format
        fBaseName = os.path.basename(fileName)
        if '.' in fBaseName:
            fileExtension = fBaseName.split('.')[-1]
            fBaseName = fBaseName[:-len(fileExtension)] + 'md'
        else:
            fBaseName += '.md'

        project = GlobalData().project
        if project.isProjectFile(fileName):
            projectDir = project.getProjectDir()
            relativePath = fileName[len(projectDir):]
            projectName = project.getProjectName()
            if relativePath.startswith(projectName):
                relativePath = relativePath.replace(projectName, '', 1)
            return os.path.normpath(
                os.path.sep.join([projectDir + 'doc',
                                  os.path.dirname(relativePath),
                                  fBaseName]))
        return os.path.normpath(
            os.path.sep.join([os.path.dirname(fileName),
                              'doc',
                               fBaseName]))
Exemple #5
0
    def __init__(self, path, newSearch=True):
        QDialog.__init__(self, GlobalData().mainWindow)

        path = os.path.abspath(path)
        if not os.path.exists(path):
            raise Exception('Dead code analysis path must exist. '
                            'The provide path "' + path + '" does not.')

        self.__path = path

        self.__newSearch = newSearch
        self.candidates = None
        self.__cancelRequest = False
        self.__inProgress = False

        self.__infoLabel = None
        self.__foundLabel = None
        self.__found = 0  # Number of found

        self.__createLayout()
        title = 'Dead code analysis for '
        if os.path.isdir(path):
            project = GlobalData().project
            if project.isLoaded() and project.getProjectDir() == path:
                title += 'all project files'
            else:
                title += 'dir ' + os.path.basename(os.path.normpath(path))
        else:
            title += os.path.basename(path)

        if not self.__newSearch:
            title += ' (do again)'

        self.setWindowTitle(title)
        self.__updateFoundLabel()
Exemple #6
0
    def __init__( self, fileName = None, lineNumber = None, condition = "",
                        temporary = False, enabled = True, ignoreCount = 0 ):

        if fileName is None:
            self.__fileName = fileName
        elif os.path.isabs( fileName ):
            project = GlobalData().project
            if project.isLoaded():
                if project.isProjectFile( fileName ):
                    # This is a project file; strip the project dir
                    self.__fileName = fileName.replace( project.getProjectDir(),
                                                        "" )
                else:
                    # Not a project file, save as is
                    self.__fileName = fileName
            else:
                # Pretty much impossible
                self.__fileName = fileName
        else:
            # Relative path, i.e. a project file
            self.__fileName = fileName

        self.__lineNumber = lineNumber
        self.__condition = condition
        self.__temporary = temporary
        self.__enabled = enabled
        self.__ignoreCount = ignoreCount

        return
Exemple #7
0
def getJediScript(source, line, column, srcPath, needSysPath=True):
    """Provides the jedi Script object considering the current project"""
    jedi.settings.additional_dynamic_modules = []
    paths = GlobalData().originalSysPath[:] if needSysPath else []

    # This make relative imports resolvable
    if os.path.isabs(srcPath):
        dirName = os.path.dirname(srcPath)
        if dirName not in paths:
            paths.append(dirName)

    project = GlobalData().project
    if not project.isLoaded():
        # Add the other opened files if so
        mainWindow = GlobalData().mainWindow
        for path in mainWindow.editorsManager().getOpenedList():
            if path[0]:
                if path[0].lower().endswith('.py'):
                    jedi.settings.additional_dynamic_modules.append(path[0])
        return jedi.Script(source, line, column, srcPath, sys_path=paths)

    for path in project.getImportDirsAsAbsolutePaths():
        if path not in paths:
            paths.append(path)
    projectDir = project.getProjectDir()
    if projectDir not in paths:
        paths.append(projectDir)

    return jedi.Script(source, line, column, srcPath, sys_path=paths)
Exemple #8
0
    def getAbsoluteFileName(self):
        """Provides the absolute file name"""
        if self.__fileName is None:
            return None
        if os.path.isabs(self.__fileName):
            return self.__fileName

        project = GlobalData().project
        if project.isLoaded():
            return project.getProjectDir() + self.__fileName
        return os.path.abspath(self.__fileName)
Exemple #9
0
    def getAbsoluteFileName( self ):
        " Provides the absolute file name "
        if self.__fileName is None:
            return None
        if os.path.isabs( self.__fileName ):
            return self.__fileName

        project = GlobalData().project
        if project.isLoaded():
            return project.getProjectDir() + self.__fileName
        return os.path.abspath( self.__fileName )
Exemple #10
0
    def isValid(self):
        """True if the breakpoint is valid"""
        if self.__fileName is None:
            return False

        if os.path.isabs(self.__fileName):
            if not os.path.exists(self.__fileName):
                return False
        else:
            project = GlobalData().project
            if project.isLoaded():
                path = project.getProjectDir() + self.__fileName
                if not os.path.exists(path):
                    return False
            else:
                if not os.path.exists(self.__fileName):
                    return False

        return self.__lineNumber is not None and self.__lineNumber > 0
Exemple #11
0
    def isValid( self ):
        " True if the breakpoint is valid "
        if self.__fileName is None:
            return False

        if os.path.isabs( self.__fileName ):
            if not os.path.exists( self.__fileName ):
                return False
        else:
            project = GlobalData().project
            if project.isLoaded():
                path = project.getProjectDir() + self.__fileName
                if not os.path.exists( path ):
                    return False
            else:
                if not os.path.exists( self.__fileName ):
                    return False

        return self.__lineNumber is not None and \
               self.__lineNumber > 0
    def __viewProperties( self ):
        " Handles the 'view properties' context menu item "
        if self.__projectContextItem is None:
            return
        if not self.__projectContextItem.isValid():
            return

        if self.__projectContextItem.isCurrent():
            # This is the current project - it can be edited
            project = GlobalData().project
            dialog = ProjectPropertiesDialog( project )
            if dialog.exec_() == QDialog.Accepted:
                importDirs = []
                for index in xrange( dialog.importDirList.count() ):
                    importDirs.append( dialog.importDirList.item( index ).text() )

                scriptName = dialog.scriptEdit.text().strip()
                relativePath = relpath( scriptName, project.getProjectDir() )
                if not relativePath.startswith( '..' ):
                    scriptName = relativePath

                project.updateProperties(
                    scriptName, importDirs,
                    dialog.creationDateEdit.text().strip(),
                    dialog.authorEdit.text().strip(),
                    dialog.licenseEdit.text().strip(),
                    dialog.copyrightEdit.text().strip(),
                    dialog.versionEdit.text().strip(),
                    dialog.emailEdit.text().strip(),
                    dialog.descriptionEdit.toPlainText().strip() )
        else:
            # This is not the current project - it can be viewed
            fName = self.__projectContextItem.getFilename()
            dialog = ProjectPropertiesDialog( fName )
            dialog.exec_()
        return
Exemple #13
0
    def __viewProperties(self):
        " Handles the 'view properties' context menu item "
        if self.__projectContextItem is None:
            return
        if not self.__projectContextItem.isValid():
            return

        if self.__projectContextItem.isCurrent():
            # This is the current project - it can be edited
            project = GlobalData().project
            dialog = ProjectPropertiesDialog(project, self)
            if dialog.exec_() == QDialog.Accepted:
                importDirs = []
                for index in xrange(dialog.importDirList.count()):
                    importDirs.append(dialog.importDirList.item(index).text())

                scriptName = dialog.scriptEdit.text().strip()
                relativePath = relpath(scriptName, project.getProjectDir())
                if not relativePath.startswith('..'):
                    scriptName = relativePath

                project.updateProperties(
                    scriptName, importDirs,
                    dialog.creationDateEdit.text().strip(),
                    dialog.authorEdit.text().strip(),
                    dialog.licenseEdit.text().strip(),
                    dialog.copyrightEdit.text().strip(),
                    dialog.versionEdit.text().strip(),
                    dialog.emailEdit.text().strip(),
                    dialog.descriptionEdit.toPlainText().strip())
        else:
            # This is not the current project - it can be viewed
            fName = self.__projectContextItem.getFilename()
            dialog = ProjectPropertiesDialog(fName, self)
            dialog.exec_()
        return
Exemple #14
0
    def __selectFile(self, extension):
        """Picks a file of a certain extension"""
        dialog = QFileDialog(self, 'Save flowchart as')
        dialog.setFileMode(QFileDialog.AnyFile)
        dialog.setLabelText(QFileDialog.Accept, "Save")
        dialog.setNameFilter(extension.upper() + " files (*." +
                             extension.lower() + ")")
        urls = []
        for dname in QDir.drives():
            urls.append(QUrl.fromLocalFile(dname.absoluteFilePath()))
        urls.append(QUrl.fromLocalFile(QDir.homePath()))
        project = GlobalData().project
        if project.isLoaded():
            urls.append(QUrl.fromLocalFile(project.getProjectDir()))
        dialog.setSidebarUrls(urls)

        suggestedFName = self.__parentWidget.getFileName()
        if '.' in suggestedFName:
            dotIndex = suggestedFName.rindex('.')
            suggestedFName = suggestedFName[:dotIndex]

        dialog.setDirectory(self.__getDefaultSaveDir())
        dialog.selectFile(suggestedFName + "." + extension.lower())
        dialog.setOption(QFileDialog.DontConfirmOverwrite, False)
        dialog.setOption(QFileDialog.DontUseNativeDialog, True)
        if dialog.exec_() != QDialog.Accepted:
            return None

        fileNames = dialog.selectedFiles()
        fileName = os.path.abspath(str(fileNames[0]))
        if os.path.isdir(fileName):
            logging.error("A file must be selected")
            return None

        if "." not in fileName:
            fileName += "." + extension.lower()

        # Check permissions to write into the file or to a directory
        if os.path.exists(fileName):
            # Check write permissions for the file
            if not os.access(fileName, os.W_OK):
                logging.error("There is no write permissions for " + fileName)
                return None
        else:
            # Check write permissions to the directory
            dirName = os.path.dirname(fileName)
            if not os.access(dirName, os.W_OK):
                logging.error("There is no write permissions for the "
                              "directory " + dirName)
                return None

        if os.path.exists(fileName):
            res = QMessageBox.warning(
                self, "Save flowchart as",
                "<p>The file <b>" + fileName + "</b> already exists.</p>",
                QMessageBox.StandardButtons(QMessageBox.Abort |
                                            QMessageBox.Save),
                QMessageBox.Abort)
            if res == QMessageBox.Abort or res == QMessageBox.Cancel:
                return None

        # All prerequisites are checked, return a file name
        return fileName
Exemple #15
0
 def __getDefaultSaveDir():
     """Provides the default directory to save files to"""
     project = GlobalData().project
     if project.isLoaded():
         return project.getProjectDir()
     return QDir.currentPath()
Exemple #16
0
 def __getDefaultSaveDir( self ):
     " Provides the default directory to save files to "
     project = GlobalData().project
     if project.isLoaded():
         return project.getProjectDir()
     return QDir.currentPath()
Exemple #17
0
    def __selectFile( self, extension ):
        " Picks a file of a certain extension "
        dialog = QFileDialog( self, 'Save flowchart as' )
        dialog.setFileMode( QFileDialog.AnyFile )
        dialog.setLabelText( QFileDialog.Accept, "Save" )
        dialog.setNameFilter( extension.upper() + " files (*." +
                              extension.lower() + ")" )
        urls = []
        for dname in QDir.drives():
            urls.append( QUrl.fromLocalFile( dname.absoluteFilePath() ) )
        urls.append( QUrl.fromLocalFile( QDir.homePath() ) )
        project = GlobalData().project
        if project.isLoaded():
            urls.append( QUrl.fromLocalFile( project.getProjectDir() ) )
        dialog.setSidebarUrls( urls )

        suggestedFName = self.__parentWidget.getFileName()
        if '.' in suggestedFName:
            dotIndex = suggestedFName.rindex( '.' )
            suggestedFName = suggestedFName[ : dotIndex ]

        dialog.setDirectory( self.__getDefaultSaveDir() )
        dialog.selectFile( suggestedFName + "." + extension.lower() )
        dialog.setOption( QFileDialog.DontConfirmOverwrite, False )
        if dialog.exec_() != QDialog.Accepted:
            return None

        fileNames = dialog.selectedFiles()
        fileName = os.path.abspath( str( fileNames[0] ) )
        if os.path.isdir( fileName ):
            logging.error( "A file must be selected" )
            return None

        if "." not in fileName:
            fileName += "." + extension.lower()

        # Check permissions to write into the file or to a directory
        if os.path.exists( fileName ):
            # Check write permissions for the file
            if not os.access( fileName, os.W_OK ):
                logging.error( "There is no write permissions for " + fileName )
                return None
        else:
            # Check write permissions to the directory
            dirName = os.path.dirname( fileName )
            if not os.access( dirName, os.W_OK ):
                logging.error( "There is no write permissions for the "
                               "directory " + dirName )
                return None

        if os.path.exists( fileName ):
            res = QMessageBox.warning( self, "Save flowchart as",
                    "<p>The file <b>" + fileName + "</b> already exists.</p>",
                    QMessageBox.StandardButtons( QMessageBox.Abort |
                                                 QMessageBox.Save ),
                    QMessageBox.Abort )
            if res == QMessageBox.Abort or res == QMessageBox.Cancel:
                return None

        # All prerequisites are checked, return a file name
        return fileName