Refactoring: Began to phase out to the use of hscommon.io in favor of Path methods.

This commit is contained in:
Virgil Dupras 2012-08-09 10:53:24 -04:00
parent 91f3a59523
commit df30a31782
4 changed files with 23 additions and 27 deletions

View File

@ -14,7 +14,6 @@ from appscript import app, its, k, CommandError, ApplicationNotFoundError
from . import tunes from . import tunes
from cocoa import as_fetch, proxy from cocoa import as_fetch, proxy
from hscommon import io
from hscommon.trans import trget from hscommon.trans import trget
from hscommon.path import Path from hscommon.path import Path
from hscommon.util import remove_invalid_xml from hscommon.util import remove_invalid_xml
@ -78,9 +77,9 @@ def get_itunes_database_path():
return Path(plistpath) return Path(plistpath)
def get_itunes_songs(plistpath): def get_itunes_songs(plistpath):
if not io.exists(plistpath): if not plistpath.exists():
return [] return []
s = io.open(plistpath, 'rt', encoding='utf-8').read() s = plistpath.open('rt', encoding='utf-8').read()
# iTunes sometimes produces XML files with invalid characters in it. # iTunes sometimes produces XML files with invalid characters in it.
s = remove_invalid_xml(s, replace_with='') s = remove_invalid_xml(s, replace_with='')
plist = plistlib.readPlistFromBytes(s.encode('utf-8')) plist = plistlib.readPlistFromBytes(s.encode('utf-8'))
@ -92,7 +91,7 @@ def get_itunes_songs(plistpath):
song = ITunesSong(song_data) song = ITunesSong(song_data)
except KeyError: # No "Track Type", "Location" or "Track ID" key in track except KeyError: # No "Track Type", "Location" or "Track ID" key in track
continue continue
if io.exists(song.path): if song.path.exists():
result.append(song) result.append(song)
return result return result

View File

@ -15,7 +15,6 @@ import time
import shutil import shutil
from send2trash import send2trash from send2trash import send2trash
from hscommon import io
from hscommon.reg import RegistrableApplication from hscommon.reg import RegistrableApplication
from hscommon.notify import Broadcaster from hscommon.notify import Broadcaster
from hscommon.path import Path from hscommon.path import Path
@ -168,7 +167,7 @@ class DupeGuru(RegistrableApplication, Broadcaster):
self.results.perform_on_marked(op, True) self.results.perform_on_marked(op, True)
def _do_delete_dupe(self, dupe, link_deleted, use_hardlinks, direct_deletion): def _do_delete_dupe(self, dupe, link_deleted, use_hardlinks, direct_deletion):
if not io.exists(dupe.path): if not dupe.path.exists():
return return
logging.debug("Sending '%s' to trash", dupe.path) logging.debug("Sending '%s' to trash", dupe.path)
str_path = str(dupe.path) str_path = str(dupe.path)
@ -253,7 +252,7 @@ class DupeGuru(RegistrableApplication, Broadcaster):
result = [] result = []
for file in files: for file in files:
try: try:
inode = io.stat(file.path).st_ino inode = file.path.stat().st_ino
except OSError: except OSError:
# The file was probably deleted or something # The file was probably deleted or something
continue continue
@ -324,8 +323,8 @@ class DupeGuru(RegistrableApplication, Broadcaster):
if dest_type == DestType.Relative: if dest_type == DestType.Relative:
source_base = source_base[location_path:] source_base = source_base[location_path:]
dest_path = dest_path + source_base dest_path = dest_path + source_base
if not io.exists(dest_path): if not dest_path.exists():
io.makedirs(dest_path) dest_path.makedirs()
# Add filename to dest_path. For file move/copy, it's not required, but for folders, yes. # Add filename to dest_path. For file move/copy, it's not required, but for folders, yes.
dest_path = dest_path + source_path[-1] dest_path = dest_path + source_path[-1]
logging.debug("Copy/Move operation from '%s' to '%s'", source_path, dest_path) logging.debug("Copy/Move operation from '%s' to '%s'", source_path, dest_path)

View File

@ -10,7 +10,6 @@ from xml.etree import ElementTree as ET
import logging import logging
from jobprogress import job from jobprogress import job
from hscommon import io
from hscommon.path import Path from hscommon.path import Path
from hscommon.util import FileOrPath from hscommon.util import FileOrPath
@ -73,9 +72,9 @@ class Directories:
file.is_ref = state == DirectoryState.Reference file.is_ref = state == DirectoryState.Reference
filepaths.add(file.path) filepaths.add(file.path)
yield file yield file
subpaths = [from_path + name for name in io.listdir(from_path)] subpaths = [from_path + name for name in from_path.listdir()]
# it's possible that a folder (bundle) gets into the file list. in that case, we don't want to recurse into it # it's possible that a folder (bundle) gets into the file list. in that case, we don't want to recurse into it
subfolders = [p for p in subpaths if not io.islink(p) and io.isdir(p) and p not in filepaths] subfolders = [p for p in subpaths if not p.islink() and p.isdir() and p not in filepaths]
for subfolder in subfolders: for subfolder in subfolders:
for file in self._get_files(subfolder, j): for file in self._get_files(subfolder, j):
yield file yield file
@ -106,7 +105,7 @@ class Directories:
""" """
if path in self: if path in self:
raise AlreadyThereError() raise AlreadyThereError()
if not io.exists(path): if not path.exists():
raise InvalidPathError() raise InvalidPathError()
self._dirs = [p for p in self._dirs if p not in path] self._dirs = [p for p in self._dirs if p not in path]
self._dirs.append(path) self._dirs.append(path)
@ -115,7 +114,7 @@ class Directories:
def get_subfolders(path): def get_subfolders(path):
"""returns a sorted list of paths corresponding to subfolders in `path`""" """returns a sorted list of paths corresponding to subfolders in `path`"""
try: try:
names = [name for name in io.listdir(path) if io.isdir(path + name)] names = [name for name in path.listdir() if (path + name).isdir()]
names.sort(key=lambda x:x.lower()) names.sort(key=lambda x:x.lower())
return [path + name for name in names] return [path + name for name in names]
except EnvironmentError: except EnvironmentError:

View File

@ -14,7 +14,6 @@
import hashlib import hashlib
import logging import logging
from hscommon import io
from hscommon.util import nonone, get_file_ext from hscommon.util import nonone, get_file_ext
NOT_SET = object() NOT_SET = object()
@ -89,12 +88,12 @@ class File:
def _read_info(self, field): def _read_info(self, field):
if field in ('size', 'mtime'): if field in ('size', 'mtime'):
stats = io.stat(self.path) stats = self.path.stat()
self.size = nonone(stats.st_size, 0) self.size = nonone(stats.st_size, 0)
self.mtime = nonone(stats.st_mtime, 0) self.mtime = nonone(stats.st_mtime, 0)
elif field == 'md5partial': elif field == 'md5partial':
try: try:
fp = io.open(self.path, 'rb') fp = self.path.open('rb')
offset, size = self._get_md5partial_offset_and_size() offset, size = self._get_md5partial_offset_and_size()
fp.seek(offset) fp.seek(offset)
partialdata = fp.read(size) partialdata = fp.read(size)
@ -105,7 +104,7 @@ class File:
pass pass
elif field == 'md5': elif field == 'md5':
try: try:
fp = io.open(self.path, 'rb') fp = self.path.open('rb')
md5 = hashlib.md5() md5 = hashlib.md5()
CHUNK_SIZE = 8192 CHUNK_SIZE = 8192
filedata = fp.read(CHUNK_SIZE) filedata = fp.read(CHUNK_SIZE)
@ -130,19 +129,19 @@ class File:
#--- Public #--- Public
@classmethod @classmethod
def can_handle(cls, path): def can_handle(cls, path):
return not io.islink(path) and io.isfile(path) return not path.islink() and path.isfile()
def rename(self, newname): def rename(self, newname):
if newname == self.name: if newname == self.name:
return return
destpath = self.path[:-1] + newname destpath = self.path[:-1] + newname
if io.exists(destpath): if destpath.exists():
raise AlreadyExistsError(newname, self.path[:-1]) raise AlreadyExistsError(newname, self.path[:-1])
try: try:
io.rename(self.path, destpath) self.path.rename(destpath)
except EnvironmentError: except EnvironmentError:
raise OperationError(self) raise OperationError(self)
if not io.exists(destpath): if not destpath.exists():
raise OperationError(self) raise OperationError(self)
self.path = destpath self.path = destpath
@ -180,7 +179,7 @@ class Folder(File):
if field in {'size', 'mtime'}: if field in {'size', 'mtime'}:
size = sum((f.size for f in self._all_items()), 0) size = sum((f.size for f in self._all_items()), 0)
self.size = size self.size = size
stats = io.stat(self.path) stats = self.path.stat()
self.mtime = nonone(stats.st_mtime, 0) self.mtime = nonone(stats.st_mtime, 0)
elif field in {'md5', 'md5partial'}: elif field in {'md5', 'md5partial'}:
# What's sensitive here is that we must make sure that subfiles' # What's sensitive here is that we must make sure that subfiles'
@ -199,14 +198,14 @@ class Folder(File):
@property @property
def subfolders(self): def subfolders(self):
if self._subfolders is None: if self._subfolders is None:
subpaths = [self.path + name for name in io.listdir(self.path)] subpaths = [self.path + name for name in self.path.listdir()]
subfolders = [p for p in subpaths if not io.islink(p) and io.isdir(p)] subfolders = [p for p in subpaths if not p.islink() and p.isdir()]
self._subfolders = [Folder(p) for p in subfolders] self._subfolders = [Folder(p) for p in subfolders]
return self._subfolders return self._subfolders
@classmethod @classmethod
def can_handle(cls, path): def can_handle(cls, path):
return not io.islink(path) and io.isdir(path) return not path.islink() and path.isdir()
def get_file(path, fileclasses=[File]): def get_file(path, fileclasses=[File]):
@ -225,7 +224,7 @@ def get_files(path, fileclasses=[File]):
raise raise
try: try:
paths = [combine_paths(path, name) for name in io.listdir(path)] paths = [combine_paths(path, name) for name in path.listdir()]
result = [] result = []
for path in paths: for path in paths:
file = get_file(path, fileclasses=fileclasses) file = get_file(path, fileclasses=fileclasses)