示例#1
0
def cpdir(src, dst):
    """
    Recursively copy a directory tree.
    :type src: str
    :type dst: str
    """
    shutil.copytree(expandPath(src), expandPath(dst), copy_function=shutil.copy)
示例#2
0
def frename(src, dst):
    """
    Rename a file or director
    :type src: str
    :type dst: str
    """
    os.rename(expandPath(src), expandPath(dst))
示例#3
0
def cpdir(src, dst):
    """
    Recursively copy a directory tree.
    :type src: str
    :type dst: str
    """
    shutil.copytree(expandPath(src), expandPath(dst), copy_function=shutil.copy)
示例#4
0
文件: setup.py 项目: jonntd/eddy
 def make_plugins(self):
     """
     Package built-in plugins into ZIP archives.
     """
     if isdir('@plugins/'):
         mkdir(os.path.join(self.build_exe, 'plugins'))
         for file_or_directory in os.listdir(expandPath('@plugins/')):
             plugin = os.path.join(expandPath('@plugins/'), file_or_directory)
             if isdir(plugin):
                 distutils.log.info('packaging plugin: %s', file_or_directory)
                 zippath = os.path.join(self.build_exe, 'plugins', '%s.zip' % file_or_directory)
                 with zipfile.ZipFile(zippath, 'w', zipfile.ZIP_STORED) as zipf:
                     for root, dirs, files in os.walk(plugin):
                         if not root.endswith('__pycache__'):
                             for filename in files:
                                 path = expandPath(os.path.join(root, filename))
                                 if path.endswith('.py'):
                                     new_path = '%s.pyc' % rstrip(path, '.py')
                                     py_compile.compile(path, new_path)
                                     arcname = os.path.join(file_or_directory, os.path.relpath(new_path, plugin))
                                     zipf.write(new_path, arcname)
                                     fremove(new_path)
                                 else:
                                     arcname = os.path.join(file_or_directory, os.path.relpath(path, plugin))
                                     zipf.write(path, arcname)
示例#5
0
def frename(src, dst):
    """
    Rename a file or director
    :type src: str
    :type dst: str
    """
    os.rename(expandPath(src), expandPath(dst))
示例#6
0
    def doImportDescriptions(self):
        """
        Start the CSV import process.
        """
        # SELECT CSV FILE VIA FILE DIALOG
        dialog = QtWidgets.QFileDialog(self.session)
        dialog.setAcceptMode(QtWidgets.QFileDialog.AcceptOpen)
        dialog.setDirectory(expandPath('~'))
        dialog.setFileMode(QtWidgets.QFileDialog.ExistingFile)
        dialog.setViewMode(QtWidgets.QFileDialog.Detail)
        dialog.setNameFilters([File.Csv.value])
        if not dialog.exec_():
            return
        selected = expandPath(first(dialog.selectedFiles()))
        self.debug('Importing descriptions from file: {}'.format(selected))
        reader = csv.reader(selected,
                            dialect='excel',
                            quoting=csv.QUOTE_ALL,
                            quotechar='"')

        # PARSE CSV AND GENERATE COMMANDS
        commands = []
        for row in reader:
            try:
                predicate, description = row[:2]

                # GET NODE CORRESPONDING TO PREDICATE
                for node in self.project.predicates(name=predicate):
                    undo = self.project.meta(node.type(), node.text())
                    redo = undo.copy()
                    redo[K_DESCRIPTION] = description
                    undo[K_DESCRIPTION_STATUS] = undo.get(
                        K_DESCRIPTION_STATUS, '')
                    redo[K_DESCRIPTION_STATUS] = undo.get(
                        K_DESCRIPTION_STATUS,
                        '')  # TODO: ADD STATUS COLUMN TO CSV

                    # TODO: there is no conflict handler at the moment,
                    # We need to provide here an interface for the user to
                    # merge the current and imported description
                    if redo != undo:
                        commands.append(
                            CommandNodeSetMeta(self.project, node.type(),
                                               node.text(), undo, redo))
            except Exception as e:
                self.session.addNotification(
                    textwrap.dedent("""
                <b><font color="#7E0B17">ERROR</font></b>: Could not complete description import,
                please see the log for details.
                """))
                return

        # APPLY CHANGES
        with BusyProgressDialog("Applying changes..."):
            self.session.undostack.beginMacro('edit {0} description'.format(
                self.node.name))
            for command in commands:
                self.session.undostack.push(command)
            self.session.undostack.endMacro()
示例#7
0
文件: reasoner.py 项目: Njrob/eddy
 def path(self):
     """
     Returns the path to the the reasoner (either a directory of a ZIP file).
     :rtype: str
     """
     path = lstrip(inspect.getfile(self.__class__), expandPath('@reasoners/'), expandPath('@home/reasoners/'))
     home = first(filter(None, path.split(os.path.sep)))
     root = expandPath('@reasoners/' if self.isBuiltIn() else '@home/reasoners/')
     return os.path.join(root, home)
示例#8
0
 def path(self):
     """
     Returns the path to the the plugin (either a directory of a ZIP file).
     :rtype: str
     """
     path = lstrip(inspect.getfile(self.__class__), expandPath('@plugins/'), expandPath('@home/plugins/'))
     home = first(filter(None, path.split(os.path.sep)))
     root = expandPath('@plugins/' if self.isBuiltIn() else '@home/plugins/')
     return os.path.join(root, home)
示例#9
0
def fcopy(src, dst):
    """
    Copy the contents of the file named src to a file named dst.
    If dst specifies a directory, the file will be copied into
    dst using the base filename from src.
    :type src: str
    :type dst: str
    :rtype: str
    """
    return shutil.copy(expandPath(src), expandPath(dst))
示例#10
0
def fcopy(src, dst):
    """
    Copy the contents of the file named src to a file named dst.
    If dst specifies a directory, the file will be copied into
    dst using the base filename from src.
    :type src: str
    :type dst: str
    :rtype: str
    """
    return shutil.copy(expandPath(src), expandPath(dst))
示例#11
0
 def doOpenProject(self):
     """
     Bring up a modal window used to open a project.
     """
     dialog = QtWidgets.QFileDialog(self)
     dialog.setAcceptMode(QtWidgets.QFileDialog.AcceptOpen)
     dialog.setDirectory(expandPath(self.workspace))
     dialog.setFileMode(QtWidgets.QFileDialog.Directory)
     dialog.setOption(QtWidgets.QFileDialog.ShowDirsOnly, True)
     dialog.setViewMode(QtWidgets.QFileDialog.Detail)
     if dialog.exec_() == QtWidgets.QFileDialog.Accepted:
         self.sgnCreateSession.emit(expandPath(first(dialog.selectedFiles())))
示例#12
0
        def buildDmg(self):
            """Build the DMG image."""
            try:
                import dmgbuild
            except ImportError:
                raise OSError(
                    'Unable to import dmgbuild: please install the dmgbuild package.'
                )

            if fexists(self.dmgName):
                os.unlink(self.dmgName)

            defines = {
                'appname': APPNAME,
                'files': [self.bundleDir],
                'license_file': expandPath('@root/LICENSE'),
                'icon_locations': {
                    '{}.app'.format(APPNAME): (60, 50)
                },
            }

            if self.applications_shortcut:
                defines['symlinks'] = {'Applications': '/Applications'}
                defines['icon_locations']['Applications'] = (60, 130)

            if self.volume_background:
                if not fexists(self.volume_background):
                    raise OSError(
                        'DMG volume background image not found at {0}'.format(
                            self.volume_background))
                print('Using DMG volume background: {0}'.format(
                    self.volume_background))
                from PIL import Image
                w, h = Image.open(self.volume_background).size
                defines['background'] = self.volume_background
                defines['window_rect'] = ((100, 500), (str(w), (str(h))))

            if self.volume_icon:
                if not fexists(self.volume_icon):
                    raise OSError('DMG volume icon not found at {0}'.format(
                        self.volume_icon))
                print('Using DMG volume icon: {0}'.format(self.volume_icon))
                defines['icon'] = self.volume_icon

            # Create the disk image using dmgbuild package.
            dmgbuild.build_dmg(
                self.dmgName,
                self.volume_label,
                settings_file=expandPath('@support/dmgbuild/settings.py'),
                defines=defines,
            )
示例#13
0
def fexists(path):
    """
    Returns True if the given path identifies a regular file, False otherwise.
    :type path: str
    :rtype: bool
    """
    return os.path.isfile(expandPath(path))
示例#14
0
def isdir(path):
    """
    Returns True if the given path identifies a directory, False otherwise.
    :type path: str
    :rtype: bool
    """
    return os.path.isdir(expandPath(path))
示例#15
0
def fexists(path):
    """
    Returns True if the given path identifies a regular file, False otherwise.
    :type path: str
    :rtype: bool
    """
    return os.path.isfile(expandPath(path))
示例#16
0
def fremove(path):
    """
    Removes the file identified by the given 'path'.
    :type path: str
    """
    if fexists(path):
        os.remove(expandPath(path))
示例#17
0
def test_load_ontology_from_graphml_2(session, qtbot):
    # GIVEN
    graphml = expandPath('@tests/test_resources/loaders/graphml/movie.graphml')
    project = session.project
    diagram = 'movie'
    with qtbot.waitSignal(session.sgnDiagramFocused):
        session.sgnFocusDiagram.emit(project.diagram('diagram'))
    # WHEN
    loader = GraphMLOntologyLoader(graphml, project, session)
    loader.run()
    # THEN
    assert diagram in map(lambda d: d.name, project.diagrams())
    assert len(project.diagram(diagram).nodes()) == 347
    assert len(project.diagram(diagram).edges()) == 433
    assert len(
        list(
            filter(lambda n: n.type() == Item.ConceptNode,
                   project.diagram(diagram).nodes()))) == 65
    assert len(
        list(
            filter(lambda n: n.type() == Item.RoleNode,
                   project.diagram(diagram).nodes()))) == 60
    assert len(
        list(
            filter(lambda n: n.type() == Item.AttributeNode,
                   project.diagram(diagram).nodes()))) == 27
    assert len(
        list(
            filter(lambda n: n.type() == Item.IndividualNode,
                   project.diagram(diagram).nodes()))) == 0
示例#18
0
def rmdir(path):
    """
    Removes the directory identified by given path if it exists.
    :type path: str
    """
    if isdir(path):
        shutil.rmtree(expandPath(path))
示例#19
0
def test_load_project_from_graphol_v1(session, qtbot, tmpdir):
    # GIVEN
    graphol = tmpdir.join('LUBM')
    cpdir(expandPath('@tests/test_resources/loaders/graphol/v1/LUBM'),
          str(graphol))
    project = session.project
    diagram = 'LUBM'
    with qtbot.waitSignal(session.sgnDiagramFocused):
        session.sgnFocusDiagram.emit(project.diagram('diagram'))
    # WHEN
    loader = GrapholProjectLoader_v1(str(graphol), session)
    loader.run()
    # THEN
    assert diagram in map(lambda d: d.name, loader.project.diagrams())
    assert len(loader.project.diagram(diagram).nodes()) == 71
    assert len(loader.project.diagram(diagram).edges()) == 80
    assert len(
        list(
            filter(lambda n: n.type() == Item.ConceptNode,
                   loader.project.diagram(diagram).nodes()))) == 18
    assert len(
        list(
            filter(lambda n: n.type() == Item.RoleNode,
                   loader.project.diagram(diagram).nodes()))) == 9
    assert len(
        list(
            filter(lambda n: n.type() == Item.AttributeNode,
                   loader.project.diagram(diagram).nodes()))) == 5
    assert len(
        list(
            filter(lambda n: n.type() == Item.IndividualNode,
                   loader.project.diagram(diagram).nodes()))) == 0
示例#20
0
 def do_import(self):
     """
     Import an ontology into the currently active Project.
     """
     self.debug('Open dialog')
     dialog = QtWidgets.QFileDialog(self.session)
     dialog.setAcceptMode(QtWidgets.QFileDialog.AcceptOpen)
     dialog.setDirectory(expandPath('~'))
     dialog.setFileMode(QtWidgets.QFileDialog.ExistingFiles)
     dialog.setViewMode(QtWidgets.QFileDialog.Detail)
     if dialog.exec_():
         selected = [x for x in dialog.selectedFiles() if fexists(x)]
         if selected:
             try:
                 with BusyProgressDialog(parent=self.session) as progress:
                     for path in selected:
                         progress.setWindowTitle('Importing {0}...'.format(
                             os.path.basename(path)))
                         worker = DescriptionsLoader(
                             path, self.session.project, self.session)
                         worker.run()
             except Exception as e:
                 msgbox = QtWidgets.QMessageBox(self.session)
                 msgbox.setDetailedText(format_exception(e))
                 msgbox.setIconPixmap(
                     QtGui.QIcon(
                         ':/icons/48/ic_error_outline_black').pixmap(48))
                 msgbox.setStandardButtons(QtWidgets.QMessageBox.Close)
                 msgbox.setText(
                     'Eddy could not import all the selected files!')
                 msgbox.setWindowIcon(QtGui.QIcon(':/icons/128/ic_eddy'))
                 msgbox.setWindowTitle('Import failed!')
                 msgbox.exec_()
示例#21
0
def fremove(path):
    """
    Removes the file identified by the given 'path'.
    :type path: str
    """
    if fexists(path):
        os.remove(expandPath(path))
示例#22
0
def mkdir(path):
    """
    Create the directory identified by the given path if it doesn't exists.
    :type path: str
    """
    if not isdir(path):
        os.mkdir(expandPath(path))
示例#23
0
def rmdir(path):
    """
    Removes the directory identified by given path if it exists.
    :type path: str
    """
    if isdir(path):
        shutil.rmtree(expandPath(path))
示例#24
0
 def doNewProject(self):
     """
     Bring up a modal window used to create a new project.
     """
     form = NewProjectDialog(self)
     if form.exec_() == NewProjectDialog.Accepted:
         self.sgnCreateSession.emit(expandPath(form.pathField.value()))
示例#25
0
def isdir(path):
    """
    Returns True if the given path identifies a directory, False otherwise.
    :type path: str
    :rtype: bool
    """
    return os.path.isdir(expandPath(path))
示例#26
0
    def find_spec(cls, file_or_directory):
        """
        Searches the given file or directory for a 'plugin.spec' file and tries to load it,
        or returns 'None' if no such file exists.

        :type file_or_directory: str
        :rtype: PluginSpec
        """
        file_or_directory = expandPath(file_or_directory)
        try:
            if os.path.exists(file_or_directory) and os.access(
                    file_or_directory, os.R_OK):
                # READ SPEC FILE FROM DIRECTORY
                if isdir(file_or_directory):
                    plugin_spec_path = os.path.join(file_or_directory,
                                                    'plugin.spec')
                    if fexists(plugin_spec_path):
                        return cls.spec(fread(plugin_spec_path))
                # READ SPEC FILE FROM ZIP ARCHIVE
                elif is_zipfile(file_or_directory):
                    zf = ZipFile(file_or_directory)
                    zf_name_list = zf.namelist()
                    if 'plugin.spec' in zf_name_list:
                        plugin_spec_content = zf.read('plugin.spec').decode(
                            'utf8')
                        return cls.spec(plugin_spec_content)
        except Exception as e:
            LOGGER.exception('Failed to load plugin spec: %s', e)
示例#27
0
def mkdir(path):
    """
    Create the directory identified by the given path if it doesn't exists.
    :type path: str
    """
    if not isdir(path):
        os.mkdir(expandPath(path))
示例#28
0
 def doNewProject(self):
     """
     Bring up a modal window used to create a new project.
     """
     form = ProjectDialog(self)
     if form.exec_() == ProjectDialog.Accepted:
         self.sgnCreateSession.emit(expandPath(form.pathField.value()))
示例#29
0
文件: test_export.py 项目: Njrob/eddy
 def test_export_diagram_to_pdf(self, _):
     # GIVEN
     self.session.sgnFocusDiagram.emit(self.project.diagram('diagram'))
     # WHEN
     worker = PdfDiagramExporter(self.session.mdi.activeDiagram(), self.session)
     worker.run(expandPath('@tests/.tests/diagram.pdf'))
     # THEN
     self.assertFileExists('@tests/.tests/diagram.pdf')
示例#30
0
 def getPath(self, section, option):
     """
     Get the content of the given section/option performing path expansion.
     :type section: str
     :type option: str
     :rtype: str
     """
     return expandPath(self.get(section, option))
示例#31
0
 def getPath(self, section, option):
     """
     Get the content of the given section/option performing path expansion.
     :type section: str
     :type option: str
     :rtype: str
     """
     return expandPath(self.get(section, option))
示例#32
0
def faccess(path, mode=os.R_OK):
    """
    Returns whether the given path is accessible with the given mode.
    :type path:  str
    :type mode: int
    :rtype: bool
    """
    return os.access(expandPath(path), mode)
示例#33
0
 def test_export_diagram_to_pdf(self, _):
     # GIVEN
     self.session.sgnFocusDiagram.emit(self.project.diagram('diagram'))
     # WHEN
     worker = PdfDiagramExporter(self.session.mdi.activeDiagram(), self.session)
     worker.run(expandPath('@tests/.tests/diagram.pdf'))
     # THEN
     self.assertFileExists('@tests/.tests/diagram.pdf')
示例#34
0
 def doOpenProject(self, path):
     """
     Open a recent project in a new session of Eddy.
     :type path: str
     """
     if not self.pending:
         self.pending = True
         self.sgnCreateSession.emit(expandPath(path))
示例#35
0
def test_load_project_from_graphol_v3(session, qtbot, tmpdir):
    # GIVEN
    graphol = tmpdir.join('MovieOntology/MovieOntology_v3.graphol')
    grapholDir = tmpdir.join('MovieOntology')
    mkdir(str(grapholDir))
    os.open(str(graphol), os.O_CREAT)
    fcopy(
        expandPath(
            '@tests/test_resources/loaders/graphol/v3/MovieOntology/MovieOntology_v3.graphol'
        ), str(graphol))

    project = session.project
    diagram1 = 'movie'
    diagram2 = 'territory'
    with qtbot.waitSignal(session.sgnDiagramFocused):
        session.sgnFocusDiagram.emit(project.diagram('diagram'))
    # WHEN
    loader = GrapholIRIProjectLoader_v3(str(graphol), session)
    loader.run()
    # THEN
    assert diagram1 in map(lambda d: d.name, loader.session.project.diagrams())
    assert len(loader.session.project.diagram(diagram1).nodes()) == 347
    assert len(loader.session.project.diagram(diagram1).edges()) == 433
    assert len(
        list(
            filter(lambda n: n.type() == Item.ConceptIRINode,
                   loader.session.project.diagram(diagram1).nodes()))) == 65
    assert len(
        list(
            filter(lambda n: n.type() == Item.RoleIRINode,
                   loader.session.project.diagram(diagram1).nodes()))) == 60
    assert len(
        list(
            filter(lambda n: n.type() == Item.AttributeIRINode,
                   loader.session.project.diagram(diagram1).nodes()))) == 27
    assert len(
        list(
            filter(lambda n: n.type() == Item.IndividualIRINode,
                   loader.session.project.diagram(diagram1).nodes()))) == 0
    assert diagram2 in map(lambda d: d.name, loader.session.project.diagrams())
    assert len(loader.session.project.diagram(diagram2).nodes()) == 8
    assert len(loader.session.project.diagram(diagram2).edges()) == 8
    assert len(
        list(
            filter(lambda n: n.type() == Item.ConceptIRINode,
                   loader.session.project.diagram(diagram2).nodes()))) == 2
    assert len(
        list(
            filter(lambda n: n.type() == Item.RoleIRINode,
                   loader.session.project.diagram(diagram2).nodes()))) == 2
    assert len(
        list(
            filter(lambda n: n.type() == Item.AttributeIRINode,
                   loader.session.project.diagram(diagram2).nodes()))) == 0
    assert len(
        list(
            filter(lambda n: n.type() == Item.IndividualIRINode,
                   loader.session.project.diagram(diagram2).nodes()))) == 0
示例#36
0
 def start(self, options):
     """
     Run the application by showing the welcome dialog.
     :type options: Namespace
     """
     self.welcome = Welcome(self)
     self.welcome.show()
     if options.open and isdir(options.open):
         self.sgnCreateSession.emit(expandPath(options.open))
示例#37
0
def fread(path):
    """
    Read the file identified by the given 'path' and returns its content.
    :type path: str
    :rtype: str
    """
    path = expandPath(path)
    with io.open(path, 'r', encoding='utf8') as ptr:
        return ptr.read()
示例#38
0
 def start(self, options):
     """
     Run the application by showing the welcome dialog.
     :type options: Namespace
     """
     self.welcome = Welcome(self)
     self.welcome.show()
     if options.open and isdir(options.open):
         self.sgnCreateSession.emit(expandPath(options.open))
示例#39
0
def fread(path):
    """
    Read the file identified by the given 'path' and returns its content.
    :type path: str
    :rtype: str
    """
    path = expandPath(path)
    with io.open(path, 'r', encoding='utf8') as ptr:
        return ptr.read()
示例#40
0
def test_import_single_module_plugin_from_directory():
    # GIVEN
    plugin_path = expandPath('@tests/test_resources/plugins/dir/testplugin1')
    # WHEN
    spec, plugin_path, plugin_class = PluginManager.import_plugin_from_path(plugin_path)
    # THEN
    assert spec is not None
    assert plugin_path is not None
    assert plugin_class is None
    assert 'testplugin1' == spec.get('plugin', 'id')
示例#41
0
文件: setup.py 项目: jonntd/eddy
 def find_qt_menu_nib(self):
     """
     Returns the location of the qt_menu.nib.
     """
     if self.qt_menu_nib:
         return self.qt_menu_nib
     path = expandPath(os.path.join(QT_BASE_PATH, 'Src/qtbase/src/plugins/platforms/cocoa/qt_menu.nib'))
     if os.path.exists(path):
         return path
     raise IOError("could not find qt_menu.nib: please install Qt5 source components")
示例#42
0
def test_import_multi_module_plugin_from_zip():
    # GIVEN
    plugin_path = expandPath('@tests/test_resources/plugins/zip/testplugin2.zip')
    # WHEN
    spec, plugin_path, plugin_class = PluginManager.import_plugin_from_path(plugin_path)
    # THEN
    assert spec is not None
    assert plugin_path is not None
    assert plugin_class is None
    assert 'testplugin2' == spec.get('plugin', 'id')
示例#43
0
文件: setup.py 项目: jonntd/eddy
 def make_zip(self):
     """
     Create a ZIP distribution.
     """
     zippath = os.path.join(self.dist_dir, '%s.zip' % DIST_NAME)
     with zipfile.ZipFile(zippath, 'w', zipfile.ZIP_DEFLATED) as zipf:
         for root, dirs, files in os.walk(self.build_exe):
             for filename in files:
                 path = expandPath(os.path.join(root, filename))
                 arcname = os.path.join(DIST_NAME, os.path.relpath(path, self.build_exe))
                 zipf.write(path, arcname)
示例#44
0
 def finalize_options(self):
     """Finalize command options."""
     if self.workpath is None:
         self.workpath = WORK_PATH
     if self.distpath is None:
         self.distpath = DIST_PATH
     if self.dist_dir is None:
         self.dist_dir = DIST_DIR
     if self.applications_shortcut is None:
         self.applications_shortcut = 1
     if self.volume_label is None:
         self.volume_label = '%s %s' % (APPNAME, VERSION)
     if self.volume_background is None:
         self.volume_background = expandPath(
             '@resources/images/macos_background_dmg.png')
     if self.volume_icon is None:
         self.volume_icon = expandPath(
             '@resources/images/macos_icon_dmg.icns')
     if self.skip_build is None:
         self.skip_build = 0
示例#45
0
def findJavaHome():
    """
    Locate and return the path to a valid JRE installation,
    or None if no such path can be found.

    :rtype: str
    """
    # LOOK FOR BUNDLED JRE FIRST
    if os.path.isdir(expandPath('@resources/java/')):
        return expandPath('@resources/java/')
    # PREFER USER-SPECIFIED JAVA_HOME IF AVAILABLE
    if os.getenv('JAVA_HOME'):
        return os.getenv('JAVA_HOME')
    # JPype offers a nice utility to find Java from known locations
    if JniLib.JPYPE in _jvmLibraries:
        from jpype import (
            getDefaultJVMPath,
            JVMNotFoundException,
            JVMNotSupportedException,
        )
        try:
            jni_lib = getDefaultJVMPath()
            # Try to locate the root of the Java installation walking
            # the path backwards and checking for the existence
            # of the `java` executable.
            dirname, filename = os.path.split(jni_lib)
            java_exe = os.path.join('bin',
                                    'java' if not IS_WIN else 'java.exe')
            while dirname != os.path.dirname(dirname):
                parent, subdir = os.path.split(dirname)
                if os.path.isfile(os.path.join(dirname, java_exe)):
                    return parent if subdir == 'jre' else dirname
                dirname, filename = parent, subdir
        except JVMNotFoundException as e:
            LOGGER.error('Unable to locate JAVA_HOME', exc_info=e)
        except JVMNotSupportedException as e:
            LOGGER.exception('Found unsupported JVM', exc_info=e)
        except Exception as e:
            LOGGER.exception('Could not find JAVA_HOME', exc_info=e)
    # FALLBACK TO OTHER COMMON VARIABLES
    return os.getenv('JRE_HOME', os.getenv('JDK_HOME'))
示例#46
0
def fwrite(content, path):
    """
    Safely write the given 'content' in the file identified by the given 'path'.
    If the given path identifies an already existing file, its content is not
    truncated unless the writing operation is completed successfully.
    :type content: T <= bytes|str|unicode
    :type path: str
    """
    components = os.path.split(expandPath(path))
    stage = os.path.join(components[0], '.{0}'.format(components[1]))
    with io.open(stage, 'w', encoding='utf8') as ptr:
        ptr.write(content)
    fremove(path)
    frename(stage, path)
示例#47
0
        def buildDMG(self):
            """
            Build the DMG image.
            """
            if not isdir('@support/createdmg') or not fexists('@support/createdmg/create-dmg'):
                raise OSError('unable to find create-dmg utility: please clone Eddy with all its submodules' )

            if fexists(self.dmgName):
                os.unlink(self.dmgName)

            stagingDir = os.path.join(self.buildDir, 'tmp')
            if isdir(stagingDir):
                rmdir(stagingDir)

            self.mkpath(stagingDir)

            # Move the app bundle into a separate folder that will be used as source folder for the DMG image
            if subprocess.call(['cp', '-R', self.bundleDir, stagingDir]) != 0:
                raise OSError('could not move app bundle in staging directory')

            # We create the DMG disk image using the create-dmg submodule.
            params = [expandPath('@support/createdmg/create-dmg')]
            params.extend(['--volname', self.volume_label])
            params.extend(['--text-size', '12'])
            params.extend(['--icon-size', '48'])
            params.extend(['--icon', '{0}.app'.format(self.bundleName), '60', '50'])
            params.extend(['--hide-extension', '{0}.app'.format(self.bundleName)])

            if self.applications_shortcut:
                params.extend(['--app-drop-link', '60', '130'])

            if self.volume_background:
                if not fexists(self.volume_background):
                    raise OSError('DMG volume background image not found at {0}'.format(self.volume_background))
                print('Using DMG volume background: {0}'.format(self.volume_background))
                from PIL import Image
                w, h = Image.open(self.volume_background).size
                params.extend(['--background', self.volume_background, '--window-size', str(w), str(h)])

            if self.volume_icon:
                if not fexists(self.volume_icon):
                    raise OSError('DMG volume icon not found at {0}'.format(self.volume_icon))
                print('Using DMG volume icon: {0}'.format(self.volume_icon))
                params.extend(['--volicon', self.volume_icon])

            params.extend([self.dmgName, stagingDir])

            subprocess.call(params)
            rmdir(stagingDir)
示例#48
0
 def make_win32(self):
     """
     Makes sure text files from directory have 'Windows style' end of lines.
     """
     if sys.platform == 'win32':
         for root, dirs, files in os.walk(self.build_exe):
             for filename in files:
                 path = expandPath(os.path.join(root, filename))
                 if not isdir(path) and path.rsplit('.', 1)[-1] in ('txt', 'md'):
                     with open(path, mode='rb') as f:
                         data = f.read()
                     new_data = re.sub("\r?\n", "\r\n", data.decode(encoding='UTF-8'))
                     if new_data != data:
                         with open(path, mode='wb') as f:
                             f.write(new_data.encode(encoding='UTF-8'))
示例#49
0
 def __init__(self, path, prefix, iri, profile, session=None):
     """
     Initialize the graphol project.
     :type path: str
     :type prefix: str
     :type iri: str
     :type profile: AbstractProfile
     :type session: Session
     """
     super().__init__(session)
     self.index = ProjectIndex()
     self.iri = iri
     self.path = expandPath(path)
     self.prefix = prefix
     self.profile = profile
     self.profile.setParent(self)
示例#50
0
    def choosePath(self):
        """
        Bring up a modal window that allows the user to choose a valid workspace path.
        """
        path = self.workspaceField.value()
        if not isPathValid(path):
            path = expandPath('~')

        dialog = QtWidgets.QFileDialog(self)
        dialog.setAcceptMode(QtWidgets.QFileDialog.AcceptOpen)
        dialog.setDirectory(path)
        dialog.setFileMode(QtWidgets.QFileDialog.Directory)
        dialog.setOption(QtWidgets.QFileDialog.ShowDirsOnly, True)
        dialog.setViewMode(QtWidgets.QFileDialog.Detail)

        if dialog.exec_() == QtWidgets.QFileDialog.Accepted:
            self.workspaceField.setValue(first(dialog.selectedFiles()))
示例#51
0
    def selectPlugin(self):
        """
        Bring up a modal window that allows the user to choose a valid plugin archive.
        """
        path = os.path.dirname(self.pluginField.value())
        if not isPathValid(path):
            path = expandPath('~')

        dialog = QtWidgets.QFileDialog(self)
        dialog.setAcceptMode(QtWidgets.QFileDialog.AcceptOpen)
        dialog.setDirectory(path)
        dialog.setFileMode(QtWidgets.QFileDialog.ExistingFile)
        dialog.setViewMode(QtWidgets.QFileDialog.Detail)
        dialog.setNameFilters([File.Zip.value])

        if dialog.exec_() == QtWidgets.QFileDialog.Accepted:
            self.pluginField.setValue(first(dialog.selectedFiles()))
            self.confirmationBox.setEnabled(not isEmpty(self.pluginField.value()))
示例#52
0
 def setUp(self):
     """
     Initialize test case environment.
     """
     # MAKE SURE TO USE CORRECT SETTINGS
     settings = QtCore.QSettings(ORGANIZATION, APPNAME)
     settings.setValue('workspace/home', WORKSPACE)
     settings.setValue('update/check_on_startup', False)
     settings.sync()
     # MAKE SURE THE WORKSPACE DIRECTORY EXISTS
     mkdir(expandPath(WORKSPACE))
     # MAKE SURE TO HAVE A CLEAN TEST ENVIRONMENT
     rmdir('@tests/.tests/')
     mkdir('@tests/.tests/')
     # INITIALIZED VARIABLES
     self.eddy = None
     self.project = None
     self.session = None
示例#53
0
    def __init__(self, project, parent=None):
        """
        Initialize the project block.
        :type project: str
        :type parent: QtWidgets.QWidget
        """
        super().__init__(parent)

        self.nameLabel = QtWidgets.QLabel(os.path.basename(project), self)
        self.nameLabel.setContentsMargins(20, 0, 20, 0)
        self.nameLabel.setProperty('class', 'name')
        self.nameLabel.setFont(Font('Roboto', 12, bold=True))
        self.pathLabel = QtWidgets.QLabel(compressPath(shortPath(project), 34), self)
        self.pathLabel.setContentsMargins(20, 0, 20, 0)
        self.pathLabel.setProperty('class', 'path')
        self.pathLabel.setFont(Font('Roboto', 12))
        self.deleteBtn = PHCQPushButton(self)
        self.deleteBtn.setIcon(QtGui.QIcon(':/icons/24/ic_delete_black'))
        self.deleteBtn.setVisible(not isSubPath(expandPath('@examples/'), project))
        connect(self.deleteBtn.clicked, self.onDeleteButtonClicked)
        self.leftWidget = QtWidgets.QWidget(self)
        self.leftWidget.setContentsMargins(0, 0, 0, 0)
        self.leftLayout = QtWidgets.QVBoxLayout(self.leftWidget)
        self.leftLayout.setContentsMargins(0, 0, 0, 0)
        self.leftLayout.setSpacing(0)
        self.leftLayout.addWidget(self.nameLabel)
        self.leftLayout.addWidget(self.pathLabel)
        self.rightWidget = QtWidgets.QWidget(self)
        self.rightWidget.setContentsMargins(0, 0, 10, 0)
        self.rightLayout = QtWidgets.QVBoxLayout(self.rightWidget)
        self.rightLayout.setContentsMargins(0, 0, 0, 0)
        self.rightLayout.setSpacing(0)
        self.rightLayout.addWidget(self.deleteBtn)
        self.mainLayout = QtWidgets.QHBoxLayout(self)
        self.mainLayout.setContentsMargins(0, 0, 0, 0)
        self.mainLayout.addWidget(self.leftWidget)
        self.mainLayout.addWidget(self.rightWidget, 1, QtCore.Qt.AlignRight)
        self.setContentsMargins(0, 0, 0, 0)
        self.setFixedHeight(40)
        self.path = project
示例#54
0
from eddy.core.functions.fsystem import mkdir, rmdir
from eddy.core.functions.path import expandPath

from PyQt5 import QtCore


###################################
# SETUP CONSTANTS DECLARATION
###########################


LINUX = sys.platform.startswith('linux')
MACOS = sys.platform.startswith('darwin')
WIN32 = sys.platform.startswith('win32')

BUILD_DIR = os.path.join(expandPath(os.path.dirname(__file__)), 'build')
DIST_DIR = os.path.join(expandPath(os.path.dirname(__file__)), 'dist')
DIST_NAME = '%s-%s-%s_%s' % (APPNAME, VERSION, platform.system().lower(), platform.machine().lower())
DIST_PATH = os.path.join(BUILD_DIR, DIST_NAME)
EXEC_BASE = None
EXEC_ICON = None
EXEC_NAME = None

if LINUX:
    EXEC_BASE = None
    EXEC_ICON = expandPath('@resources/images/eddy.png')
    EXEC_NAME = APPNAME

if MACOS:
    EXEC_BASE = None
    EXEC_ICON = expandPath('@resources/images/eddy.icns')
示例#55
0
 def assertFileExists(self, filepath, msg=None):
     """Assert for the given path to represent a file"""
     if not fexists(filepath):
         standardMsg = '%s is not a file' % safe_repr(expandPath(filepath))
         self.fail(self._formatMessage(msg, standardMsg))
示例#56
0
 def assertDirectoryExists(self, dirpath, msg=None):
     """Assert for the given path to represent a file"""
     if not isdir(dirpath):
         standardMsg = '%s is not a directory' % safe_repr(expandPath(dirpath))
         self.fail(self._formatMessage(msg, standardMsg))
示例#57
0
import jnius_config
import os
import sys

from eddy.core.functions.path import expandPath
from eddy.core.functions.fsystem import cpdir, isdir, mkdir, rmdir, fexists

LINUX = sys.platform.startswith('linux')
MACOS = sys.platform.startswith('darwin')
WIN32 = sys.platform.startswith('win32')

#############################################
# BEGIN JAVA VIRTUAL MACHINE SETUP
#################################

if os.path.isdir(expandPath('@resources/java/')):
    os.environ['JAVA_HOME'] = expandPath('@resources/java/')

if WIN32:
    path = os.getenv('Path', '')
    path = path.split(os.pathsep)
    path.insert(0, os.path.join(os.environ['JAVA_HOME'], 'bin', 'client'))
    os.environ['Path'] = os.pathsep.join(path)

classpath = []
resources = expandPath('@resources/lib/')
for name in os.listdir(resources):
    path = os.path.join(resources, name)
    if os.path.isfile(path):
        classpath.append(path)