[pyzo] 27/68: Make file browser independent of pyzolib.path. Use os.path insread

Ghislain Vaillant ghisvail-guest at moszumanska.debian.org
Wed Sep 28 09:47:09 UTC 2016


This is an automated email from the git hooks/post-receive script.

ghisvail-guest pushed a commit to branch debian/master
in repository pyzo.

commit 8e0d972b9c079103da0fb1cbc2c50640332b106d
Author: Almar Klein <almar.klein at gmail.com>
Date:   Mon Sep 5 12:24:01 2016 +0200

    Make file browser independent of pyzolib.path. Use os.path insread
---
 pyzo/tools/pyzoFileBrowser/__init__.py     | 26 ++++++-------
 pyzo/tools/pyzoFileBrowser/browser.py      | 38 +++++++++----------
 pyzo/tools/pyzoFileBrowser/importwizard.py |  8 ++--
 pyzo/tools/pyzoFileBrowser/proxies.py      | 33 ++++++++--------
 pyzo/tools/pyzoFileBrowser/tasks.py        |  4 +-
 pyzo/tools/pyzoFileBrowser/tree.py         | 61 +++++++++++++++---------------
 pyzo/tools/pyzoFileBrowser/utils.py        | 15 +++++++-
 7 files changed, 101 insertions(+), 84 deletions(-)

diff --git a/pyzo/tools/pyzoFileBrowser/__init__.py b/pyzo/tools/pyzoFileBrowser/__init__.py
index 1af5a8f..61342d4 100644
--- a/pyzo/tools/pyzoFileBrowser/__init__.py
+++ b/pyzo/tools/pyzoFileBrowser/__init__.py
@@ -22,7 +22,7 @@ The config consists of three fields:
   * list expandedDirs, with each element a directory 
   * list starredDirs, with each element a dict with fields:
       * str path, the directory that is starred
-      * str name, the name of the project (path.basename by default)
+      * str name, the name of the project (op.basename(path) by default)
       * bool addToPythonpath
   * searchMatchCase, searchRegExp, searchSubDirs
   * nameFilter
@@ -39,17 +39,15 @@ The config consists of three fields:
   
 """
 
-import os
 import sys
+import os.path as op
 
 from pyzolib import ssdf
-from pyzolib.path import Path
-
 from pyzolib.qt import QtCore, QtGui
-import pyzo
 
+import pyzo
 from .browser import Browser
-
+from .utils import cleanpath, isdir
 
 
 class PyzoFileBrowser(QtGui.QWidget):
@@ -73,21 +71,21 @@ class PyzoFileBrowser(QtGui.QWidget):
                 self.config[name] = []
         
         # Ensure path in config
-        if 'path' not in self.config or not os.path.isdir(self.config.path):
-            self.config.path = os.path.expanduser('~')
+        if 'path' not in self.config or not isdir(self.config.path):
+            self.config.path = op.expanduser('~')
         
         # Check expandedDirs and starredDirs. 
-        # Make Path instances and remove invalid dirs. Also normalize case, 
+        # Make path objects and remove invalid dirs. Also normalize case, 
         # should not be necessary, but maybe the config was manually edited.
         expandedDirs, starredDirs = [], []
         for d in self.config.starredDirs:
             if 'path' in d and 'name' in d and 'addToPythonpath' in d:
-                if os.path.isdir(d.path):
-                    d.path = Path(d.path).normcase()
+                if isdir(d.path):
+                    d.path = op.normcase(cleanpath(d.path))
                     starredDirs.append(d)
         for p in set([str(p) for p in self.config.expandedDirs]):
-            if os.path.isdir(p):
-                p = Path(p).normcase()
+            if isdir(p):
+                p = op.normcase(cleanpath(p))
                 # Add if it is a subdir of a starred dir
                 for d in starredDirs:
                     if p.startswith(d.path):
@@ -133,7 +131,7 @@ class PyzoFileBrowser(QtGui.QWidget):
         # Select its path
         path = browser._tree.path()
         # Return
-        if os.path.isabs(path) and os.path.isdir(path):
+        if op.isabs(path) and isdir(path):
             return path
     
     
diff --git a/pyzo/tools/pyzoFileBrowser/browser.py b/pyzo/tools/pyzoFileBrowser/browser.py
index 211b6d0..802e8a6 100644
--- a/pyzo/tools/pyzoFileBrowser/browser.py
+++ b/pyzo/tools/pyzoFileBrowser/browser.py
@@ -1,15 +1,15 @@
-import os
 import sys
+import os.path as op
 
-from pyzolib.path import Path
 from pyzolib import ssdf
-from . import QtCore, QtGui
 
 import pyzo
 from pyzo import translate
 
-from .tree import Tree
+from . import QtCore, QtGui
 from . import proxies
+from .tree import Tree
+from .utils import cleanpath, isdir
 
 
 class Browser(QtGui.QWidget):
@@ -38,7 +38,7 @@ class Browser(QtGui.QWidget):
         
         # Create tree widget
         self._tree = Tree(self)
-        self._tree.setPath(Path(self.config.path))
+        self._tree.setPath(cleanpath(self.config.path))
         
         # Create name filter
         self._nameFilter = NameFilter(self)
@@ -133,7 +133,7 @@ class Browser(QtGui.QWidget):
         if not path:
             return None
         for d in self.parent().config.starredDirs:
-            if d['path'] == path:
+            if op.normcase(d['path']) == op.normcase(path):
                 return d
         else:
             return None
@@ -143,8 +143,8 @@ class Browser(QtGui.QWidget):
         """
         # Create new dict
         newProject = ssdf.new()
-        newProject.path = path.normcase() # Normalize case!
-        newProject.name = path.basename
+        newProject.path = op.normcase(path) # Normalize case!
+        newProject.name = op.basename(path)
         newProject.addToPythonpath = False
         # Add it to the config
         self.parent().config.starredDirs.append(newProject)
@@ -157,9 +157,9 @@ class Browser(QtGui.QWidget):
         """
         # Remove
         starredDirs = self.parent().config.starredDirs
-        pathn = path.normcase()
+        pathn = op.normcase(path)
         for d in starredDirs:
-            if pathn == d.path:
+            if op.normcase(pathn) == op.normcase(d.path):
                 starredDirs.remove(d)
         # Update list
         self._projects.updateProjectList()
@@ -281,7 +281,7 @@ class PathInput(LineEditWithToolButtons):
     """ Line edit for selecting a path.
     """
     
-    dirChanged = QtCore.Signal(Path)  # Emitted when the user changes the path (and is valid)
+    dirChanged = QtCore.Signal(str)  # Emitted when the user changes the path (and is valid)
     dirUp = QtCore.Signal()  # Emitted when user presses the up button
     
     def __init__(self, parent):
@@ -324,8 +324,8 @@ class PathInput(LineEditWithToolButtons):
         # ok for now, but we should find a different approach someday
         # Check
         text = self.text()
-        dir = Path(text)
-        isvalid = text and dir.isdir and os.path.isabs(dir)
+        dir = cleanpath(text)
+        isvalid = text and isdir(dir) and op.isabs(dir)
         # Apply styling
         ss = self.styleSheet().replace('font-style:italic; ', '')
         if not isvalid:
@@ -351,7 +351,7 @@ class PathInput(LineEditWithToolButtons):
     def onTextEdited(self, dummy=None):
         text = self.text()
         if self.checkValid():            
-            self.dirChanged.emit(Path(text))
+            self.dirChanged.emit(cleanpath(text))
     
     
     def focusOutEvent(self, event=None):
@@ -368,7 +368,7 @@ class PathInput(LineEditWithToolButtons):
 
 class Projects(QtGui.QWidget):
     
-    dirChanged = QtCore.Signal(Path) # Emitted when the user changes the project
+    dirChanged = QtCore.Signal(str) # Emitted when the user changes the project
     
     def __init__(self, parent):
         QtGui.QWidget.__init__(self, parent)
@@ -421,9 +421,9 @@ class Projects(QtGui.QWidget):
         self._path = path
         # Find project index
         projectIndex, L = 0, 0
-        pathn = path.normcase() + os.path.sep
+        pathn = op.normcase(path) + op.sep
         for i in range(self._combo.count()):
-            projectPath = self._combo.itemData(i) + os.path.sep
+            projectPath = self._combo.itemData(i) + op.sep
             if pathn.startswith(projectPath) and len(projectPath) > L:
                 projectIndex, L = i, len(projectPath)
         # Select project or not ...
@@ -439,7 +439,7 @@ class Projects(QtGui.QWidget):
     def updateProjectList(self):
         # Get sorted version of starredDirs
         starredDirs = self.parent().starredDirs
-        starredDirs.sort(key=lambda p:p.lower())
+        starredDirs.sort(key=lambda p:self.parent().dictForStarredDir(p).name.lower())
         # Refill the combo box
         self._combo.clear()
         for p in starredDirs:
@@ -533,7 +533,7 @@ class Projects(QtGui.QWidget):
         path = self._combo.itemData(index)
         if path:
             # Go to dir
-            self.dirChanged.emit(Path(path))
+            self.dirChanged.emit(path)
         else:
             # Dummy item, reset
             self.setPath(self._path)
diff --git a/pyzo/tools/pyzoFileBrowser/importwizard.py b/pyzo/tools/pyzoFileBrowser/importwizard.py
index 6868aad..eacca19 100644
--- a/pyzo/tools/pyzoFileBrowser/importwizard.py
+++ b/pyzo/tools/pyzoFileBrowser/importwizard.py
@@ -21,12 +21,14 @@ ResultPage:
 
 """
 
-import os
 import itertools
+import unicodedata
+import os.path as op
+
 import pyzo.codeeditor
 from pyzolib.qt import QtCore, QtGui
 from pyzo import translate
-import unicodedata
+
 
 # All keywords in Python 2 and 3. Obtained using: import keyword; keyword.kwlist
 # Merged from Py2 and 3
@@ -97,7 +99,7 @@ class SelectFilePage(QtGui.QWizardPage):
         if isinstance(filename, tuple):
             filename = filename[0]
         
-        filename = str(filename).replace('/', os.sep) # Show native file separator
+        filename = str(filename).replace('/', op.sep) # Show native file separator
             
         self.txtFilename.setText(filename)
         self.updatePreview()
diff --git a/pyzo/tools/pyzoFileBrowser/proxies.py b/pyzo/tools/pyzoFileBrowser/proxies.py
index 690a699..abf97f2 100644
--- a/pyzo/tools/pyzoFileBrowser/proxies.py
+++ b/pyzo/tools/pyzoFileBrowser/proxies.py
@@ -13,12 +13,13 @@ will make Pyzo truly powerful for use in remote computing.
 
 """
 
-from . import QtCore, QtGui
-
 import time
 import threading
 from queue import Queue, Empty
+import os.path as op
 
+from . import QtCore, QtGui
+from .utils import isdir
 
 class Task:
     """ Task(**params)
@@ -408,25 +409,25 @@ class NativeFSProxy(BaseFSProxy):
     """
     
     def listDirs(self, path):
-        if os.path.isdir(path):
-            pp = [os.path.join(path, p) for p in os.listdir(path)]
-            return [str(p) for p in pp if os.path.isdir(p)]
+        if isdir(path):
+            pp = [op.join(path, p) for p in os.listdir(path)]
+            return [str(p) for p in pp if isdir(p)]
     
     def listFiles(self, path):
-        if os.path.isdir(path):
-            pp = [os.path.join(path, p) for p in os.listdir(path)]
-            return [str(p) for p in pp if os.path.isfile(p)]
+        if isdir(path):
+            pp = [op.join(path, p) for p in os.listdir(path)]
+            return [str(p) for p in pp if op.isfile(p)]
     
     def modified(self, path):
-        if os.path.isfile(path):
-            return os.path.getmtime(path)
+        if op.isfile(path):
+            return op.getmtime(path)
     
     def fileSize(self, path):
-        if os.path.isfile(path):
-            return os.path.getsize(path)
+        if op.isfile(path):
+            return op.getsize(path)
     
     def read(self, path):
-        if os.path.isfile(path):
+        if op.isfile(path):
             return open(path, 'rb').read()
     
     def write(self, path, bb):
@@ -437,11 +438,11 @@ class NativeFSProxy(BaseFSProxy):
         os.rename(path1, path2)
     
     def remove(self, path):
-        if os.path.isfile(path):
+        if op.isfile(path):
             os.remove(path)
-        elif os.path.isdir(path):
+        elif isdir(path):
             os.rmdir(path)
     
     def createDir(self, path):
-        if not os.path.isdir(path):
+        if not isdir(path):
             os.makedirs(path)
diff --git a/pyzo/tools/pyzoFileBrowser/tasks.py b/pyzo/tools/pyzoFileBrowser/tasks.py
index d32d54f..0fc8677 100644
--- a/pyzo/tools/pyzoFileBrowser/tasks.py
+++ b/pyzo/tools/pyzoFileBrowser/tasks.py
@@ -7,6 +7,8 @@ These inherit from proxies.Task and implement that specific interface.
 """
 
 import re
+import os.path as op
+
 from . import proxies
 
 
@@ -191,7 +193,7 @@ class PeekTask(proxies.Task):
             linenr += 1
             
             # If we are in a triple-quoted multi-line string, find the end
-            if stringEndProg == None:
+            if stringEndProg is None:
                 pos = 0
             else:
                 endMatch = stringEndProg.search(line)
diff --git a/pyzo/tools/pyzoFileBrowser/tree.py b/pyzo/tools/pyzoFileBrowser/tree.py
index 475f735..36b00fd 100644
--- a/pyzo/tools/pyzoFileBrowser/tree.py
+++ b/pyzo/tools/pyzoFileBrowser/tree.py
@@ -11,14 +11,15 @@ import sys
 import time
 import subprocess
 import fnmatch
-from pyzolib.path import Path
+import os.path as op
 
-from . import QtCore, QtGui
 import pyzo
 from pyzo import translate
+from . import QtCore, QtGui
 
 from . import tasks
-from .utils import hasHiddenAttribute, getMounts
+from .utils import hasHiddenAttribute, getMounts, cleanpath, isdir, ext
+
 
 # How to name the list of drives/mounts (i.e. 'my computer')
 MOUNTS = 'drives'
@@ -82,7 +83,7 @@ def createMounts(browser, tree):
     mountPoints = getMounts()
     mountPoints.sort(key=lambda x: x.lower())
     for entry in mountPoints:
-        entry = Path(entry)
+        entry = cleanpath(entry)
         item = DriveItem(tree, fsProxy.dir(entry))
 
 
@@ -106,23 +107,23 @@ def createItemsFun(browser, parent):
     try:
         dirs = []
         for entry in dirProxy.dirs():
-            entry = Path(entry)
-            if entry.basename.startswith('.'):
+            entry = cleanpath(entry)
+            if op.basename(entry).startswith('.'):
                 continue # Skip hidden files
             if hasHiddenAttribute(entry):
                 continue # Skip hidden files on Windows
-            if entry.basename == '__pycache__':
+            if op.basename(entry) == '__pycache__':
                 continue
             dirs.append(entry)
         
         files = []
         for entry in dirProxy.files():
-            entry = Path(entry)
-            if entry.basename.startswith('.'):
+            entry = cleanpath(entry)
+            if op.basename(entry).startswith('.'):
                 continue # Skip hidden files
             if hasHiddenAttribute(entry):
                 continue # Skip hidden files on Windows
-            if not _filterFileByName(entry.basename, nameFilter):
+            if not _filterFileByName(op.basename(entry), nameFilter):
                 continue
             files.append(entry)
     
@@ -136,19 +137,19 @@ def createItemsFun(browser, parent):
     # Sort files 
     # (first by name, then by type, so finally they are by type, then name)
     files.sort(key=lambda x: x.lower())
-    files.sort(key=lambda x: x.ext.lower())
+    files.sort(key=lambda x: ext(x).lower())
         
     
     if not searchFilter:
         
         # Create dirs 
         for path in dirs:
-            starred = path.normcase() in starredDirs
+            starred = op.normcase(path) in starredDirs
             item = DirItem(parent, fsProxy.dir(path), starred)
             # Set hidden, we can safely expand programmatically when hidden
             item.setHidden(True)
             # Set expanded and visibility
-            if path.normcase() in expandedDirs:
+            if op.normcase(path) in expandedDirs:
                 item.setExpanded(True)
             item.setHidden(False)
         
@@ -288,7 +289,7 @@ class DirItem(BrowserItem):
     def onExpanded(self):
         # Update list of expanded dirs
         expandedDirs = self.treeWidget().parent().expandedDirs
-        p = self.path().normcase()  # Normalize case!
+        p = op.normcase(self.path())  # Normalize case!
         if p not in expandedDirs:
             expandedDirs.append(p) 
         # Keep track of changes in our contents
@@ -298,7 +299,7 @@ class DirItem(BrowserItem):
     def onCollapsed(self):
         # Update list of expanded dirs
         expandedDirs = self.treeWidget().parent().expandedDirs
-        p = self.path().normcase()   # Normalize case!
+        p = op.normcase(self.path())   # Normalize case!
         while p in expandedDirs:
             expandedDirs.remove(p)
         # Stop tracking changes in our contents
@@ -335,11 +336,11 @@ class FileItem(BrowserItem):
     
     def setFileIcon(self):
         # Create dummy file in pyzo user dir
-        dummy_filename = Path(pyzo.appDataDir) / 'dummyFiles' / 'dummy' + self.path().ext
+        dummy_filename = op.join(cleanpath(pyzo.appDataDir), 'dummyFiles', 'dummy' + ext(self.path()))
         # Create file?
-        if not dummy_filename.isfile:
-            if not dummy_filename.dirname.isdir:
-                os.makedirs(dummy_filename.dirname)
+        if not op.isfile(dummy_filename):
+            if not isdir(op.dirname(dummy_filename)):
+                os.makedirs(op.dirname(dummy_filename))
             f = open(dummy_filename, 'wb')
             f.close()
         # Use that file
@@ -359,7 +360,7 @@ class FileItem(BrowserItem):
         # todo: someday we should be able to simply pass the proxy object to the editors
         # so that we can open files on any file system
         path = self.path()
-        if path.ext not in ['.pyc','.pyo','.png','.jpg','.ico']:
+        if ext(path) not in ['.pyc','.pyo','.png','.jpg','.ico']:
             # Load and get editor
             fileItem = pyzo.editors.loadFile(path)
             editor = fileItem._editor
@@ -436,7 +437,7 @@ class SubFileItem(QtGui.QTreeWidgetItem):
     
     def onActivated(self):
         path = self.path()
-        if path.ext not in ['.pyc','.pyo','.png','.jpg','.ico']:
+        if ext(path) not in ['.pyc','.pyo','.png','.jpg','.ico']:
             # Load and get editor
             fileItem = pyzo.editors.loadFile(path)
             editor = fileItem._editor
@@ -580,7 +581,7 @@ class Tree(QtGui.QTreeWidget):
     up-to-date. The Item classes above are dumb objects.
     """
     
-    dirChanged = QtCore.Signal(Path) # Emitted when user goes into a subdir
+    dirChanged = QtCore.Signal(str) # Emitted when user goes into a subdir
     
     def __init__(self, parent):
         QtGui.QTreeWidget.__init__(self, parent)
@@ -654,10 +655,10 @@ class Tree(QtGui.QTreeWidget):
     def setPathUp(self):
         """ Go one directory up.
         """
-        newPath = self.path().dirname
+        newPath = op.dirname(self.path())
         
-        if newPath == self.path():
-            self.setPath(Path(MOUNTS))
+        if op.normcase(newPath) == op.normcase(self.path()):
+            self.setPath(cleanpath(MOUNTS))
         else:
             self.setPath(newPath)
     
@@ -754,8 +755,8 @@ class Tree(QtGui.QTreeWidget):
             self.setCurrentItem(self.topLevelItem(0))       
         # Restore selection
         if self._selectedPath:
-            items = self.findItems(self._selectedPath.basename, QtCore.Qt.MatchExactly, 0)
-            items = [item for item in items if item.path() == self._selectedPath]
+            items = self.findItems(op.basename(self._selectedPath), QtCore.Qt.MatchExactly, 0)
+            items = [item for item in items if op.normcase(item.path()) == op.normcase(self._selectedPath)]
             if items:
                 self.setCurrentItem(items[0])
         # Restore scrolling
@@ -931,7 +932,7 @@ class PopupMenu(pyzo.core.menu.Menu):
         
         # Push rename task
         if s:
-            newpath = os.path.join(self._item.path(), s)
+            newpath = op.join(self._item.path(), s)
             task = tasks.CreateTask(newpath=newpath, file=file)
             self._item._proxy.pushTask(task)
     
@@ -939,7 +940,7 @@ class PopupMenu(pyzo.core.menu.Menu):
     def _duplicateOrRename(self, rename):
         
         # Get dirname and filename
-        dirname, filename = os.path.split(self._item.path())
+        dirname, filename = op.split(self._item.path())
         
         # Get title and label
         if rename:
@@ -961,7 +962,7 @@ class PopupMenu(pyzo.core.menu.Menu):
         
         # Push rename task
         if s:
-            newpath = os.path.join(dirname, s)
+            newpath = op.join(dirname, s)
             task = tasks.RenameTask(newpath=newpath, removeold=rename)
             self._item._proxy.pushTask(task)
     
diff --git a/pyzo/tools/pyzoFileBrowser/utils.py b/pyzo/tools/pyzoFileBrowser/utils.py
index 89fa1f4..f8d1906 100644
--- a/pyzo/tools/pyzoFileBrowser/utils.py
+++ b/pyzo/tools/pyzoFileBrowser/utils.py
@@ -3,6 +3,19 @@ import os
 import ctypes
 import sys
 import string
+import os.path as op
+
+
+def cleanpath(p):
+    return op.normpath(op.expanduser(op.expandvars(p)))
+
+def isdir(p):
+    # Add os.sep, because trailing spaces seem to be ignored on Windows
+    return op.isdir(p + op.sep)
+
+def ext(p):
+    return os.path.splitext(p)[1]
+
 
 # todo: also include available remote file systems
 def getMounts():
@@ -11,7 +24,7 @@ def getMounts():
     elif sys.platform.startswith('darwin'):
         return '/'
     elif sys.platform.startswith('linux'):
-        return ['/'] + [os.path.join('/media', e) for e in os.listdir('/media')]
+        return ['/'] + [op.join('/media', e) for e in os.listdir('/media')]
     else:
         return '/'
 

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/debian-science/packages/pyzo.git



More information about the debian-science-commits mailing list