Commit 3ea4efe1 by willmcgugan@gmail.com

Change of api (fs.open, fs.setcontent, fs.getcontents) to support io module in Py2.6+ and Py3

parent c6391b6f
include AUTHORS include AUTHORS
...@@ -19,8 +19,8 @@ __version__ = "0.4.1" ...@@ -19,8 +19,8 @@ __version__ = "0.4.1"
__author__ = "Will McGugan (will@willmcgugan.com)" __author__ = "Will McGugan (will@willmcgugan.com)"
# provide these by default so people can use 'fs.path.basename' etc. # provide these by default so people can use 'fs.path.basename' etc.
import errors from fs import errors
import path from fs import path
_thread_synchronize_default = True _thread_synchronize_default = True
def set_thread_synchronize_default(sync): def set_thread_synchronize_default(sync):
......
...@@ -33,7 +33,7 @@ class UserDataFS(OSFS): ...@@ -33,7 +33,7 @@ class UserDataFS(OSFS):
""" """
app_dirs = AppDirs(appname, appauthor, version, roaming) app_dirs = AppDirs(appname, appauthor, version, roaming)
super(self.__class__, self).__init__(app_dirs.user_data_dir, create=create) super(UserDataFS, self).__init__(app_dirs.user_data_dir, create=create)
class SiteDataFS(OSFS): class SiteDataFS(OSFS):
...@@ -48,7 +48,7 @@ class SiteDataFS(OSFS): ...@@ -48,7 +48,7 @@ class SiteDataFS(OSFS):
""" """
app_dirs = AppDirs(appname, appauthor, version, roaming) app_dirs = AppDirs(appname, appauthor, version, roaming)
super(self.__class__, self).__init__(app_dirs.site_data_dir, create=create) super(SiteDataFS, self).__init__(app_dirs.site_data_dir, create=create)
class UserCacheFS(OSFS): class UserCacheFS(OSFS):
...@@ -63,7 +63,7 @@ class UserCacheFS(OSFS): ...@@ -63,7 +63,7 @@ class UserCacheFS(OSFS):
""" """
app_dirs = AppDirs(appname, appauthor, version, roaming) app_dirs = AppDirs(appname, appauthor, version, roaming)
super(self.__class__, self).__init__(app_dirs.user_cache_dir, create=create) super(UserCacheFS, self).__init__(app_dirs.user_cache_dir, create=create)
class UserLogFS(OSFS): class UserLogFS(OSFS):
...@@ -78,10 +78,11 @@ class UserLogFS(OSFS): ...@@ -78,10 +78,11 @@ class UserLogFS(OSFS):
""" """
app_dirs = AppDirs(appname, appauthor, version, roaming) app_dirs = AppDirs(appname, appauthor, version, roaming)
super(self.__class__, self).__init__(app_dirs.user_log_dir, create=create) super(UserLogFS, self).__init__(app_dirs.user_log_dir, create=create)
if __name__ == "__main__": if __name__ == "__main__":
udfs = UserDataFS('sexytime', appauthor='pyfs') udfs = UserDataFS('exampleapp', appauthor='pyfs')
print udfs print udfs
udfs2 = UserDataFS('sexytime2', appauthor='pyfs', create=False) udfs2 = UserDataFS('exampleapp2', appauthor='pyfs', create=False)
print udfs2 print udfs2
...@@ -8,10 +8,11 @@ Not for general usage, the functionality in this file is exposed elsewhere ...@@ -8,10 +8,11 @@ Not for general usage, the functionality in this file is exposed elsewhere
import six import six
from six import PY3 from six import PY3
def copy_file_to_fs(data, dst_fs, dst_path, chunk_size=64 * 1024, progress_callback=None, finished_callback=None): def copy_file_to_fs(data, dst_fs, dst_path, chunk_size=64 * 1024, progress_callback=None, finished_callback=None):
"""Copy data from a string or a file-like object to a given fs/path""" """Copy data from a string or a file-like object to a given fs/path"""
if progress_callback is None: if progress_callback is None:
progress_callback = lambda bytes_written:None progress_callback = lambda bytes_written: None
bytes_written = 0 bytes_written = 0
f = None f = None
try: try:
...@@ -19,7 +20,7 @@ def copy_file_to_fs(data, dst_fs, dst_path, chunk_size=64 * 1024, progress_callb ...@@ -19,7 +20,7 @@ def copy_file_to_fs(data, dst_fs, dst_path, chunk_size=64 * 1024, progress_callb
if hasattr(data, "read"): if hasattr(data, "read"):
read = data.read read = data.read
chunk = read(chunk_size) chunk = read(chunk_size)
if PY3 and isinstance(chunk, six.text_type): if isinstance(chunk, six.text_type):
f = dst_fs.open(dst_path, 'w') f = dst_fs.open(dst_path, 'w')
else: else:
f = dst_fs.open(dst_path, 'wb') f = dst_fs.open(dst_path, 'wb')
...@@ -30,7 +31,7 @@ def copy_file_to_fs(data, dst_fs, dst_path, chunk_size=64 * 1024, progress_callb ...@@ -30,7 +31,7 @@ def copy_file_to_fs(data, dst_fs, dst_path, chunk_size=64 * 1024, progress_callb
progress_callback(bytes_written) progress_callback(bytes_written)
chunk = read(chunk_size) chunk = read(chunk_size)
else: else:
if PY3 and isinstance(data, six.text_type): if isinstance(data, six.text_type):
f = dst_fs.open(dst_path, 'w') f = dst_fs.open(dst_path, 'w')
else: else:
f = dst_fs.open(dst_path, 'wb') f = dst_fs.open(dst_path, 'wb')
......
...@@ -112,10 +112,10 @@ class ArchiveFS(FS): ...@@ -112,10 +112,10 @@ class ArchiveFS(FS):
return SizeUpdater(entry, self.archive.writestream(path)) return SizeUpdater(entry, self.archive.writestream(path))
@synchronize @synchronize
def getcontents(self, path, mode="rb"): def getcontents(self, path, mode="rb", encoding=None, errors=None, newline=None):
if not self.exists(path): if not self.exists(path):
raise ResourceNotFoundError(path) raise ResourceNotFoundError(path)
f = self.open(path) with self.open(path, mode, encoding=encoding, errors=errors, newline=newline) as f:
return f.read() return f.read()
def desc(self, path): def desc(self, path):
......
...@@ -41,11 +41,13 @@ from fs.base import * ...@@ -41,11 +41,13 @@ from fs.base import *
from fs.path import * from fs.path import *
from fs.errors import * from fs.errors import *
from fs.remote import RemoteFileBuffer from fs.remote import RemoteFileBuffer
from fs import iotools
from fs.contrib.davfs.util import * from fs.contrib.davfs.util import *
from fs.contrib.davfs import xmlobj from fs.contrib.davfs import xmlobj
from fs.contrib.davfs.xmlobj import * from fs.contrib.davfs.xmlobj import *
import six
from six import b from six import b
import errno import errno
...@@ -343,8 +345,10 @@ class DAVFS(FS): ...@@ -343,8 +345,10 @@ class DAVFS(FS):
msg = str(e) msg = str(e)
raise RemoteConnectionError("",msg=msg,details=e) raise RemoteConnectionError("",msg=msg,details=e)
def setcontents(self,path, contents, chunk_size=1024*64): def setcontents(self,path, data=b'', encoding=None, errors=None, chunk_size=1024 * 64):
resp = self._request(path,"PUT",contents) if isinstance(data, six.text_type):
data = data.encode(encoding=encoding, errors=errors)
resp = self._request(path, "PUT", data)
resp.close() resp.close()
if resp.status == 405: if resp.status == 405:
raise ResourceInvalidError(path) raise ResourceInvalidError(path)
...@@ -353,7 +357,8 @@ class DAVFS(FS): ...@@ -353,7 +357,8 @@ class DAVFS(FS):
if resp.status not in (200,201,204): if resp.status not in (200,201,204):
raise_generic_error(resp,"setcontents",path) raise_generic_error(resp,"setcontents",path)
def open(self,path,mode="r"): @iotools.filelike_to_stream
def open(self,path,mode="r", **kwargs):
mode = mode.replace("b","").replace("t","") mode = mode.replace("b","").replace("t","")
# Truncate the file if requested # Truncate the file if requested
contents = b("") contents = b("")
......
...@@ -26,6 +26,7 @@ from pyftpdlib import ftpserver ...@@ -26,6 +26,7 @@ from pyftpdlib import ftpserver
from fs.path import * from fs.path import *
from fs.osfs import OSFS from fs.osfs import OSFS
from fs.errors import convert_fs_errors from fs.errors import convert_fs_errors
from fs import iotools
# Get these once so we can reuse them: # Get these once so we can reuse them:
...@@ -96,8 +97,9 @@ class FTPFS(ftpserver.AbstractedFS): ...@@ -96,8 +97,9 @@ class FTPFS(ftpserver.AbstractedFS):
@convert_fs_errors @convert_fs_errors
@decode_args @decode_args
def open(self, path, mode): @iotools.filelike_to_stream
return self.fs.open(path, mode) def open(self, path, mode, **kwargs):
return self.fs.open(path, mode, **kwargs)
@convert_fs_errors @convert_fs_errors
def chdir(self, path): def chdir(self, path):
......
...@@ -221,8 +221,8 @@ class SFTPHandle(paramiko.SFTPHandle): ...@@ -221,8 +221,8 @@ class SFTPHandle(paramiko.SFTPHandle):
""" """
def __init__(self, owner, path, flags): def __init__(self, owner, path, flags):
super(SFTPHandle,self).__init__(flags) super(SFTPHandle, self).__init__(flags)
mode = flags_to_mode(flags) + "b" mode = flags_to_mode(flags)
self.owner = owner self.owner = owner
if not isinstance(path, unicode): if not isinstance(path, unicode):
path = path.decode(self.owner.encoding) path = path.decode(self.owner.encoding)
......
...@@ -18,9 +18,11 @@ an FS object, which can then be exposed using whatever server you choose ...@@ -18,9 +18,11 @@ an FS object, which can then be exposed using whatever server you choose
import xmlrpclib import xmlrpclib
from SimpleXMLRPCServer import SimpleXMLRPCServer from SimpleXMLRPCServer import SimpleXMLRPCServer
from datetime import datetime from datetime import datetime
import base64
import six import six
from six import PY3, b from six import PY3
class RPCFSInterface(object): class RPCFSInterface(object):
"""Wrapper to expose an FS via a XML-RPC compatible interface. """Wrapper to expose an FS via a XML-RPC compatible interface.
...@@ -40,26 +42,23 @@ class RPCFSInterface(object): ...@@ -40,26 +42,23 @@ class RPCFSInterface(object):
must return something that can be represented in ASCII. The default must return something that can be represented in ASCII. The default
is base64-encoded UTF-8. is base64-encoded UTF-8.
""" """
if PY3: #return path
return path return six.text_type(base64.b64encode(path.encode("utf8")), 'ascii')
return path.encode("utf8").encode("base64")
def decode_path(self, path): def decode_path(self, path):
"""Decode paths arriving over the wire.""" """Decode paths arriving over the wire."""
if PY3: return six.text_type(base64.b64decode(path.encode('ascii')), 'utf8')
return path
return path.decode("base64").decode("utf8")
def getmeta(self, meta_name): def getmeta(self, meta_name):
meta = self.fs.getmeta(meta_name) meta = self.fs.getmeta(meta_name)
if isinstance(meta, basestring): if isinstance(meta, basestring):
meta = meta.decode('base64') meta = self.decode_path(meta)
return meta return meta
def getmeta_default(self, meta_name, default): def getmeta_default(self, meta_name, default):
meta = self.fs.getmeta(meta_name, default) meta = self.fs.getmeta(meta_name, default)
if isinstance(meta, basestring): if isinstance(meta, basestring):
meta = meta.decode('base64') meta = self.decode_path(meta)
return meta return meta
def hasmeta(self, meta_name): def hasmeta(self, meta_name):
...@@ -72,7 +71,7 @@ class RPCFSInterface(object): ...@@ -72,7 +71,7 @@ class RPCFSInterface(object):
def set_contents(self, path, data): def set_contents(self, path, data):
path = self.decode_path(path) path = self.decode_path(path)
self.fs.setcontents(path,data.data) self.fs.setcontents(path, data.data)
def exists(self, path): def exists(self, path):
path = self.decode_path(path) path = self.decode_path(path)
...@@ -88,7 +87,7 @@ class RPCFSInterface(object): ...@@ -88,7 +87,7 @@ class RPCFSInterface(object):
def listdir(self, path="./", wildcard=None, full=False, absolute=False, dirs_only=False, files_only=False): def listdir(self, path="./", wildcard=None, full=False, absolute=False, dirs_only=False, files_only=False):
path = self.decode_path(path) path = self.decode_path(path)
entries = self.fs.listdir(path,wildcard,full,absolute,dirs_only,files_only) entries = self.fs.listdir(path, wildcard, full, absolute, dirs_only, files_only)
return [self.encode_path(e) for e in entries] return [self.encode_path(e) for e in entries]
def makedir(self, path, recursive=False, allow_recreate=False): def makedir(self, path, recursive=False, allow_recreate=False):
...@@ -149,7 +148,7 @@ class RPCFSInterface(object): ...@@ -149,7 +148,7 @@ class RPCFSInterface(object):
dst = self.decode_path(dst) dst = self.decode_path(dst)
return self.fs.copy(src, dst, overwrite, chunk_size) return self.fs.copy(src, dst, overwrite, chunk_size)
def move(self,src,dst,overwrite=False,chunk_size=16384): def move(self, src, dst, overwrite=False, chunk_size=16384):
src = self.decode_path(src) src = self.decode_path(src)
dst = self.decode_path(dst) dst = self.decode_path(dst)
return self.fs.move(src, dst, overwrite, chunk_size) return self.fs.move(src, dst, overwrite, chunk_size)
...@@ -187,11 +186,10 @@ class RPCFSServer(SimpleXMLRPCServer): ...@@ -187,11 +186,10 @@ class RPCFSServer(SimpleXMLRPCServer):
if logRequests is not None: if logRequests is not None:
kwds['logRequests'] = logRequests kwds['logRequests'] = logRequests
self.serve_more_requests = True self.serve_more_requests = True
SimpleXMLRPCServer.__init__(self,addr,**kwds) SimpleXMLRPCServer.__init__(self, addr, **kwds)
self.register_instance(RPCFSInterface(fs)) self.register_instance(RPCFSInterface(fs))
def serve_forever(self): def serve_forever(self):
"""Override serve_forever to allow graceful shutdown.""" """Override serve_forever to allow graceful shutdown."""
while self.serve_more_requests: while self.serve_more_requests:
self.handle_request() self.handle_request()
...@@ -531,7 +531,7 @@ class FileLikeBase(object): ...@@ -531,7 +531,7 @@ class FileLikeBase(object):
self._assert_mode("w-") self._assert_mode("w-")
# If we were previously reading, ensure position is correct # If we were previously reading, ensure position is correct
if self._rbuffer is not None: if self._rbuffer is not None:
self.seek(0,1) self.seek(0, 1)
# If we're actually behind the apparent position, we must also # If we're actually behind the apparent position, we must also
# write the data in the gap. # write the data in the gap.
if self._sbuffer: if self._sbuffer:
...@@ -544,14 +544,16 @@ class FileLikeBase(object): ...@@ -544,14 +544,16 @@ class FileLikeBase(object):
string = self._do_read(s) + string string = self._do_read(s) + string
except NotReadableError: except NotReadableError:
raise NotSeekableError("File not readable, could not complete simulation of seek") raise NotSeekableError("File not readable, could not complete simulation of seek")
self.seek(0,0) self.seek(0, 0)
if self._wbuffer: if self._wbuffer:
string = self._wbuffer + string string = self._wbuffer + string
leftover = self._write(string) leftover = self._write(string)
if leftover is None or isinstance(leftover, int): if leftover is None or isinstance(leftover, int):
self._wbuffer = b("") self._wbuffer = b("")
return len(string) - (leftover or 0)
else: else:
self._wbuffer = leftover self._wbuffer = leftover
return len(string) - len(leftover)
def writelines(self,seq): def writelines(self,seq):
"""Write a sequence of lines to the file.""" """Write a sequence of lines to the file."""
...@@ -660,7 +662,7 @@ class FileWrapper(FileLikeBase): ...@@ -660,7 +662,7 @@ class FileWrapper(FileLikeBase):
return data return data
def _write(self,string,flushing=False): def _write(self,string,flushing=False):
return self.wrapped_file.write(string) self.wrapped_file.write(string)
def _seek(self,offset,whence): def _seek(self,offset,whence):
self.wrapped_file.seek(offset,whence) self.wrapped_file.seek(offset,whence)
......
...@@ -14,6 +14,7 @@ import fs ...@@ -14,6 +14,7 @@ import fs
from fs.base import * from fs.base import *
from fs.errors import * from fs.errors import *
from fs.path import pathsplit, abspath, dirname, recursepath, normpath, pathjoin, isbase from fs.path import pathsplit, abspath, dirname, recursepath, normpath, pathjoin, isbase
from fs import iotools
from ftplib import FTP, error_perm, error_temp, error_proto, error_reply from ftplib import FTP, error_perm, error_temp, error_proto, error_reply
...@@ -1152,8 +1153,9 @@ class FTPFS(FS): ...@@ -1152,8 +1153,9 @@ class FTPFS(FS):
url = 'ftp://%s@%s%s' % (credentials, self.host.rstrip('/'), abspath(path)) url = 'ftp://%s@%s%s' % (credentials, self.host.rstrip('/'), abspath(path))
return url return url
@iotools.filelike_to_stream
@ftperrors @ftperrors
def open(self, path, mode='r'): def open(self, path, mode, buffering=-1, encoding=None, errors=None, newline=None, line_buffering=False, **kwargs):
path = normpath(path) path = normpath(path)
mode = mode.lower() mode = mode.lower()
if self.isdir(path): if self.isdir(path):
...@@ -1168,19 +1170,21 @@ class FTPFS(FS): ...@@ -1168,19 +1170,21 @@ class FTPFS(FS):
return f return f
@ftperrors @ftperrors
def setcontents(self, path, data, chunk_size=1024*64): def setcontents(self, path, data=b'', encoding=None, errors=None, chunk_size=1024*64):
path = normpath(path) path = normpath(path)
if isinstance(data, basestring): data = iotools.make_bytes_io(data, encoding=encoding, errors=errors)
data = StringIO(data)
self.refresh_dircache(dirname(path)) self.refresh_dircache(dirname(path))
self.ftp.storbinary('STOR %s' % _encode(path), data, blocksize=chunk_size) self.ftp.storbinary('STOR %s' % _encode(path), data, blocksize=chunk_size)
@ftperrors @ftperrors
def getcontents(self, path, mode="rb"): def getcontents(self, path, mode="rb", encoding=None, errors=None, newline=None):
path = normpath(path) path = normpath(path)
contents = StringIO() contents = StringIO()
self.ftp.retrbinary('RETR %s' % _encode(path), contents.write, blocksize=1024*64) self.ftp.retrbinary('RETR %s' % _encode(path), contents.write, blocksize=1024*64)
return contents.getvalue() data = contents.getvalue()
if 'b' in data:
return data
return iotools.decode_binary(data, encoding=encoding, errors=errors)
@ftperrors @ftperrors
def exists(self, path): def exists(self, path):
......
...@@ -8,9 +8,12 @@ fs.httpfs ...@@ -8,9 +8,12 @@ fs.httpfs
from fs.base import FS from fs.base import FS
from fs.path import normpath from fs.path import normpath
from fs.errors import ResourceNotFoundError, UnsupportedError from fs.errors import ResourceNotFoundError, UnsupportedError
from fs.filelike import FileWrapper
from fs import iotools
from urllib2 import urlopen, URLError from urllib2 import urlopen, URLError
from datetime import datetime from datetime import datetime
from fs.filelike import FileWrapper
class HTTPFS(FS): class HTTPFS(FS):
...@@ -22,8 +25,8 @@ class HTTPFS(FS): ...@@ -22,8 +25,8 @@ class HTTPFS(FS):
""" """
_meta = {'read_only':True, _meta = {'read_only': True,
'network':True,} 'network': True}
def __init__(self, url): def __init__(self, url):
""" """
...@@ -38,7 +41,8 @@ class HTTPFS(FS): ...@@ -38,7 +41,8 @@ class HTTPFS(FS):
url = '%s/%s' % (self.root_url.rstrip('/'), path.lstrip('/')) url = '%s/%s' % (self.root_url.rstrip('/'), path.lstrip('/'))
return url return url
def open(self, path, mode="r"): @iotools.filelike_to_stream
def open(self, path, mode='r', buffering=-1, encoding=None, errors=None, newline=None, line_buffering=False, **kwargs):
if '+' in mode or 'w' in mode or 'a' in mode: if '+' in mode or 'w' in mode or 'a' in mode:
raise UnsupportedError('write') raise UnsupportedError('write')
......
from __future__ import unicode_literals from __future__ import unicode_literals
from __future__ import print_function from __future__ import print_function
import io import io
from functools import wraps
import six
class RawWrapper(object): class RawWrapper(object):
"""Convert a Python 2 style file-like object in to a IO object""" """Convert a Python 2 style file-like object in to a IO object"""
def __init__(self, f, mode=None, name=None): def __init__(self, f, mode=None, name=None):
self._f = f self._f = f
self.is_io = isinstance(f, io.IOBase)
if mode is None and hasattr(f, 'mode'): if mode is None and hasattr(f, 'mode'):
mode = f.mode mode = f.mode
self.mode = mode self.mode = mode
self.name = name self.name = name
self.closed = False self.closed = False
super(RawWrapper, self).__init__() super(RawWrapper, self).__init__()
def __repr__(self): def __repr__(self):
...@@ -35,12 +39,18 @@ class RawWrapper(object): ...@@ -35,12 +39,18 @@ class RawWrapper(object):
return self._f.seek(offset, whence) return self._f.seek(offset, whence)
def readable(self): def readable(self):
if hasattr(self._f, 'readable'):
return self._f.readable()
return 'r' in self.mode return 'r' in self.mode
def writable(self): def writable(self):
if hasattr(self._f, 'writeable'):
return self._fs.writeable()
return 'w' in self.mode return 'w' in self.mode
def seekable(self): def seekable(self):
if hasattr(self._f, 'seekable'):
return self._f.seekable()
try: try:
self.seek(0, io.SEEK_CUR) self.seek(0, io.SEEK_CUR)
except IOError: except IOError:
...@@ -51,11 +61,14 @@ class RawWrapper(object): ...@@ -51,11 +61,14 @@ class RawWrapper(object):
def tell(self): def tell(self):
return self._f.tell() return self._f.tell()
def truncate(self, size): def truncate(self, size=None):
return self._f.truncate(size) return self._f.truncate(size)
def write(self, data): def write(self, data):
if self.is_io:
return self._f.write(data) return self._f.write(data)
self._f.write(data)
return len(data)
def read(self, n=-1): def read(self, n=-1):
if n == -1: if n == -1:
...@@ -63,21 +76,21 @@ class RawWrapper(object): ...@@ -63,21 +76,21 @@ class RawWrapper(object):
return self._f.read(n) return self._f.read(n)
def read1(self, n=-1): def read1(self, n=-1):
if self.is_io:
return self.read1(n)
return self.read(n) return self.read(n)
def readall(self): def readall(self):
return self._f.read() return self._f.read()
def readinto(self, b): def readinto(self, b):
if self.is_io:
return self._f.readinto(b)
data = self._f.read(len(b)) data = self._f.read(len(b))
bytes_read = len(data) bytes_read = len(data)
b[:len(data)] = data b[:len(data)] = data
return bytes_read return bytes_read
def write(self, b):
bytes_written = self._f.write(b)
return bytes_written
def writelines(self, sequence): def writelines(self, sequence):
return self._f.writelines(sequence) return self._f.writelines(sequence)
...@@ -87,6 +100,32 @@ class RawWrapper(object): ...@@ -87,6 +100,32 @@ class RawWrapper(object):
def __exit__(self, *args, **kwargs): def __exit__(self, *args, **kwargs):
self.close() self.close()
def __iter__(self):
return iter(self._f)
def filelike_to_stream(f):
@wraps(f)
def wrapper(self, path, mode='rt', buffering=-1, encoding=None, errors=None, newline=None, line_buffering=False, **kwargs):
file_like = f(self,
path,
mode=mode,
buffering=buffering,
encoding=encoding,
errors=errors,
newline=newline,
line_buffering=line_buffering,
**kwargs)
return make_stream(path,
file_like,
mode=mode,
buffering=buffering,
encoding=encoding,
errors=errors,
newline=newline,
line_buffering=line_buffering)
return wrapper
def make_stream(name, def make_stream(name,
f, f,
...@@ -95,9 +134,8 @@ def make_stream(name, ...@@ -95,9 +134,8 @@ def make_stream(name,
encoding=None, encoding=None,
errors=None, errors=None,
newline=None, newline=None,
closefd=True,
line_buffering=False, line_buffering=False,
**params): **kwargs):
"""Take a Python 2.x binary file and returns an IO Stream""" """Take a Python 2.x binary file and returns an IO Stream"""
r, w, a, binary = 'r' in mode, 'w' in mode, 'a' in mode, 'b' in mode r, w, a, binary = 'r' in mode, 'w' in mode, 'a' in mode, 'b' in mode
if '+' in mode: if '+' in mode:
...@@ -122,6 +160,51 @@ def make_stream(name, ...@@ -122,6 +160,51 @@ def make_stream(name,
return io_object return io_object
def decode_binary(data, encoding=None, errors=None, newline=None):
"""Decode bytes as though read from a text file"""
return io.TextIOWrapper(io.BytesIO(data), encoding=encoding, errors=errors, newline=newline).read()
def make_bytes_io(data, encoding=None, errors=None):
"""Make a bytes IO object from either a string or an open file"""
if hasattr(data, 'mode') and 'b' in data.mode:
# It's already a binary file
return data
if not isinstance(data, basestring):
# It's a file, but we don't know if its binary
# TODO: Is there a better way than reading the entire file?
data = data.read() or b''
if isinstance(data, six.text_type):
# If its text, encoding in to bytes
data = data.encode(encoding=encoding, errors=errors)
return io.BytesIO(data)
def copy_file_to_fs(f, fs, path, encoding=None, errors=None, progress_callback=None, chunk_size=64 * 1024):
"""Copy an open file to a path on an FS"""
if progress_callback is None:
progress_callback = lambda bytes_written: None
read = f.read
chunk = read(chunk_size)
if isinstance(chunk, six.text_type):
f = fs.open(path, 'wt', encoding=encoding, errors=errors)
else:
f = fs.open(path, 'wb')
write = f.write
bytes_written = 0
try:
while chunk:
write(chunk)
bytes_written += len(chunk)
progress_callback(bytes_written)
chunk = read(chunk_size)
finally:
f.close()
return bytes_written
if __name__ == "__main__": if __name__ == "__main__":
print("Reading a binary file") print("Reading a binary file")
bin_file = open('tests/data/UTF-8-demo.txt', 'rb') bin_file = open('tests/data/UTF-8-demo.txt', 'rb')
......
...@@ -17,6 +17,7 @@ from fs.base import * ...@@ -17,6 +17,7 @@ from fs.base import *
from fs.errors import * from fs.errors import *
from fs import _thread_synchronize_default from fs import _thread_synchronize_default
from fs.filelike import StringIO from fs.filelike import StringIO
from fs import iotools
from os import SEEK_END from os import SEEK_END
import threading import threading
...@@ -408,8 +409,10 @@ class MemoryFS(FS): ...@@ -408,8 +409,10 @@ class MemoryFS(FS):
# for f in file_dir_entry.open_files[:]: # for f in file_dir_entry.open_files[:]:
# f.close() # f.close()
@synchronize @synchronize
def open(self, path, mode="r", **kwargs): @iotools.filelike_to_stream
def open(self, path, mode='r', buffering=-1, encoding=None, errors=None, newline=None, line_buffering=False, **kwargs):
path = normpath(path) path = normpath(path)
filepath, filename = pathsplit(path) filepath, filename = pathsplit(path)
parent_dir_entry = self._get_dir_entry(filepath) parent_dir_entry = self._get_dir_entry(filepath)
...@@ -455,7 +458,7 @@ class MemoryFS(FS): ...@@ -455,7 +458,7 @@ class MemoryFS(FS):
raise ResourceNotFoundError(path) raise ResourceNotFoundError(path)
if dir_entry.isdir(): if dir_entry.isdir():
raise ResourceInvalidError(path,msg="That's a directory, not a file: %(path)s") raise ResourceInvalidError(path, msg="That's a directory, not a file: %(path)s")
pathname, dirname = pathsplit(path) pathname, dirname = pathsplit(path)
parent_dir = self._get_dir_entry(pathname) parent_dir = self._get_dir_entry(pathname)
...@@ -628,27 +631,43 @@ class MemoryFS(FS): ...@@ -628,27 +631,43 @@ class MemoryFS(FS):
dst_dir_entry.xattrs.update(src_xattrs) dst_dir_entry.xattrs.update(src_xattrs)
@synchronize @synchronize
def getcontents(self, path, mode="rb"): def getcontents(self, path, mode="rb", encoding=None, errors=None, newline=None):
dir_entry = self._get_dir_entry(path) dir_entry = self._get_dir_entry(path)
if dir_entry is None: if dir_entry is None:
raise ResourceNotFoundError(path) raise ResourceNotFoundError(path)
if not dir_entry.isfile(): if not dir_entry.isfile():
raise ResourceInvalidError(path, msg="not a file: %(path)s") raise ResourceInvalidError(path, msg="not a file: %(path)s")
return dir_entry.data or b('') data = dir_entry.data or b('')
if 'b' not in mode:
return iotools.decode_binary(data, encoding=encoding, errors=errors, newline=newline)
return data
@synchronize @synchronize
def setcontents(self, path, data, chunk_size=1024*64): def setcontents(self, path, data=b'', encoding=None, errors=None, chunk_size=1024*64):
if not isinstance(data, six.binary_type): if isinstance(data, six.binary_type):
return super(MemoryFS, self).setcontents(path, data, chunk_size)
if not self.exists(path): if not self.exists(path):
self.open(path, 'wb').close() self.open(path, 'wb').close()
dir_entry = self._get_dir_entry(path) dir_entry = self._get_dir_entry(path)
if not dir_entry.isfile(): if not dir_entry.isfile():
raise ResourceInvalidError('Not a directory %(path)s', path) raise ResourceInvalidError('Not a directory %(path)s', path)
new_mem_file = StringIO() new_mem_file = StringIO()
new_mem_file.write(data) new_mem_file.write(data)
dir_entry.mem_file = new_mem_file dir_entry.mem_file = new_mem_file
return len(data)
return super(MemoryFS, self).setcontents(path, data=data, encoding=encoding, errors=errors, chunk_size=chunk_size)
# if isinstance(data, six.text_type):
# return super(MemoryFS, self).setcontents(path, data, encoding=encoding, errors=errors, chunk_size=chunk_size)
# if not self.exists(path):
# self.open(path, 'wb').close()
# dir_entry = self._get_dir_entry(path)
# if not dir_entry.isfile():
# raise ResourceInvalidError('Not a directory %(path)s', path)
# new_mem_file = StringIO()
# new_mem_file.write(data)
# dir_entry.mem_file = new_mem_file
@synchronize @synchronize
def setxattr(self, path, key, value): def setxattr(self, path, key, value):
......
...@@ -46,6 +46,7 @@ from fs.base import * ...@@ -46,6 +46,7 @@ from fs.base import *
from fs.errors import * from fs.errors import *
from fs.path import * from fs.path import *
from fs import _thread_synchronize_default from fs import _thread_synchronize_default
from fs import iotools
class DirMount(object): class DirMount(object):
...@@ -286,7 +287,7 @@ class MountFS(FS): ...@@ -286,7 +287,7 @@ class MountFS(FS):
def makedir(self, path, recursive=False, allow_recreate=False): def makedir(self, path, recursive=False, allow_recreate=False):
fs, _mount_path, delegate_path = self._delegate(path) fs, _mount_path, delegate_path = self._delegate(path)
if fs is self or fs is None: if fs is self or fs is None:
raise UnsupportedError("make directory", msg="Can only makedir for mounted paths" ) raise UnsupportedError("make directory", msg="Can only makedir for mounted paths")
if not delegate_path: if not delegate_path:
if allow_recreate: if allow_recreate:
return return
...@@ -295,7 +296,7 @@ class MountFS(FS): ...@@ -295,7 +296,7 @@ class MountFS(FS):
return fs.makedir(delegate_path, recursive=recursive, allow_recreate=allow_recreate) return fs.makedir(delegate_path, recursive=recursive, allow_recreate=allow_recreate)
@synchronize @synchronize
def open(self, path, mode="r", **kwargs): def open(self, path, mode='r', buffering=-1, encoding=None, errors=None, newline=None, line_buffering=False, **kwargs):
obj = self.mount_tree.get(path, None) obj = self.mount_tree.get(path, None)
if type(obj) is MountFS.FileMount: if type(obj) is MountFS.FileMount:
callable = obj.open_callable callable = obj.open_callable
...@@ -309,20 +310,24 @@ class MountFS(FS): ...@@ -309,20 +310,24 @@ class MountFS(FS):
return fs.open(delegate_path, mode, **kwargs) return fs.open(delegate_path, mode, **kwargs)
@synchronize @synchronize
def setcontents(self, path, data, chunk_size=64*1024): def setcontents(self, path, data=b'', encoding=None, errors=None, chunk_size=64*1024):
obj = self.mount_tree.get(path, None) obj = self.mount_tree.get(path, None)
if type(obj) is MountFS.FileMount: if type(obj) is MountFS.FileMount:
return super(MountFS,self).setcontents(path, data, chunk_size=chunk_size) return super(MountFS, self).setcontents(path,
data,
encoding=encoding,
errors=errors,
chunk_size=chunk_size)
fs, _mount_path, delegate_path = self._delegate(path) fs, _mount_path, delegate_path = self._delegate(path)
if fs is self or fs is None: if fs is self or fs is None:
raise ParentDirectoryMissingError(path) raise ParentDirectoryMissingError(path)
return fs.setcontents(delegate_path, data, chunk_size) return fs.setcontents(delegate_path, data, encoding=encoding, errors=errors, chunk_size=chunk_size)
@synchronize @synchronize
def createfile(self, path, wipe=False): def createfile(self, path, wipe=False):
obj = self.mount_tree.get(path, None) obj = self.mount_tree.get(path, None)
if type(obj) is MountFS.FileMount: if type(obj) is MountFS.FileMount:
return super(MountFS,self).createfile(path, wipe=wipe) return super(MountFS, self).createfile(path, wipe=wipe)
fs, _mount_path, delegate_path = self._delegate(path) fs, _mount_path, delegate_path = self._delegate(path)
if fs is self or fs is None: if fs is self or fs is None:
raise ParentDirectoryMissingError(path) raise ParentDirectoryMissingError(path)
...@@ -430,7 +435,7 @@ class MountFS(FS): ...@@ -430,7 +435,7 @@ class MountFS(FS):
"""Unmounts a path. """Unmounts a path.
:param path: Path to unmount :param path: Path to unmount
:return: True if a dir was unmounted, False if the path was already unmounted :return: True if a path was unmounted, False if the path was already unmounted
:rtype: bool :rtype: bool
""" """
......
...@@ -238,14 +238,14 @@ class MultiFS(FS): ...@@ -238,14 +238,14 @@ class MultiFS(FS):
return "%s, on %s (%s)" % (fs.desc(path), name, fs) return "%s, on %s (%s)" % (fs.desc(path), name, fs)
@synchronize @synchronize
def open(self, path, mode="r", **kwargs): def open(self, path, mode='r', buffering=-1, encoding=None, errors=None, newline=None, line_buffering=False, **kwargs):
if 'w' in mode or '+' in mode or 'a' in mode: if 'w' in mode or '+' in mode or 'a' in mode:
if self.writefs is None: if self.writefs is None:
raise OperationFailedError('open', path=path, msg="No writeable FS set") raise OperationFailedError('open', path=path, msg="No writeable FS set")
return self.writefs.open(path, mode) return self.writefs.open(path, mode=mode, buffering=buffering, encoding=encoding, errors=errors, newline=newline, line_buffering=line_buffering, **kwargs)
for fs in self: for fs in self:
if fs.exists(path): if fs.exists(path):
fs_file = fs.open(path, mode, **kwargs) fs_file = fs.open(path, mode=mode, buffering=buffering, encoding=encoding, errors=errors, newline=newline, line_buffering=line_buffering, **kwargs)
return fs_file return fs_file
raise ResourceNotFoundError(path) raise ResourceNotFoundError(path)
......
...@@ -250,7 +250,7 @@ class OpenerRegistry(object): ...@@ -250,7 +250,7 @@ class OpenerRegistry(object):
return fs, fs_path or '' return fs, fs_path or ''
def open(self, fs_url, mode='rb'): def open(self, fs_url, mode='r', **kwargs):
"""Opens a file from a given FS url """Opens a file from a given FS url
If you intend to do a lot of file manipulation, it would likely be more If you intend to do a lot of file manipulation, it would likely be more
...@@ -271,15 +271,14 @@ class OpenerRegistry(object): ...@@ -271,15 +271,14 @@ class OpenerRegistry(object):
file_object.fs = fs file_object.fs = fs
return file_object return file_object
def getcontents(self, fs_url, mode="rb"): def getcontents(self, fs_url, node='rb', encoding=None, errors=None, newline=None):
"""Gets the contents from a given FS url (if it references a file) """Gets the contents from a given FS url (if it references a file)
:param fs_url: a FS URL e.g. ftp://ftp.mozilla.org/README :param fs_url: a FS URL e.g. ftp://ftp.mozilla.org/README
""" """
fs, path = self.parse(fs_url) fs, path = self.parse(fs_url)
return fs.getcontents(path, mode) return fs.getcontents(path, mode, encoding=encoding, errors=errors, newline=newline)
def opendir(self, fs_url, writeable=True, create_dir=False): def opendir(self, fs_url, writeable=True, create_dir=False):
"""Opens an FS object from an FS URL """Opens an FS object from an FS URL
......
...@@ -20,6 +20,7 @@ import sys ...@@ -20,6 +20,7 @@ import sys
import errno import errno
import datetime import datetime
import platform import platform
import io
from fs.base import * from fs.base import *
from fs.path import * from fs.path import *
...@@ -76,16 +77,15 @@ class OSFS(OSFSXAttrMixin, OSFSWatchMixin, FS): ...@@ -76,16 +77,15 @@ class OSFS(OSFSXAttrMixin, OSFSWatchMixin, FS):
methods in the os and os.path modules. methods in the os and os.path modules.
""" """
_meta = { 'thread_safe' : True, _meta = {'thread_safe': True,
'network' : False, 'network': False,
'virtual' : False, 'virtual': False,
'read_only' : False, 'read_only': False,
'unicode_paths' : os.path.supports_unicode_filenames, 'unicode_paths': os.path.supports_unicode_filenames,
'case_insensitive_paths' : os.path.normcase('Aa') == 'aa', 'case_insensitive_paths': os.path.normcase('Aa') == 'aa',
'atomic.makedir' : True, 'atomic.makedir': True,
'atomic.rename' : True, 'atomic.rename': True,
'atomic.setcontents' : False, 'atomic.setcontents': False}
}
if platform.system() == 'Windows': if platform.system() == 'Windows':
_meta["invalid_path_chars"] = ''.join(chr(n) for n in xrange(31)) + '\\:*?"<>|' _meta["invalid_path_chars"] = ''.join(chr(n) for n in xrange(31)) + '\\:*?"<>|'
...@@ -215,11 +215,11 @@ class OSFS(OSFSXAttrMixin, OSFSWatchMixin, FS): ...@@ -215,11 +215,11 @@ class OSFS(OSFSXAttrMixin, OSFSWatchMixin, FS):
return super(OSFS, self).getmeta(meta_name, default) return super(OSFS, self).getmeta(meta_name, default)
@convert_os_errors @convert_os_errors
def open(self, path, mode="r", **kwargs): def open(self, path, mode='r', buffering=-1, encoding=None, errors=None, newline=None, line_buffering=False, **kwargs):
mode = ''.join(c for c in mode if c in 'rwabt+') mode = ''.join(c for c in mode if c in 'rwabt+')
sys_path = self.getsyspath(path) sys_path = self.getsyspath(path)
try: try:
return open(sys_path, mode, kwargs.get("buffering", -1)) return io.open(sys_path, mode=mode, buffering=buffering, encoding=encoding, errors=errors, newline=newline)
except EnvironmentError, e: except EnvironmentError, e:
# Win32 gives EACCES when opening a directory. # Win32 gives EACCES when opening a directory.
if sys.platform == "win32" and e.errno in (errno.EACCES,): if sys.platform == "win32" and e.errno in (errno.EACCES,):
...@@ -228,8 +228,8 @@ class OSFS(OSFSXAttrMixin, OSFSWatchMixin, FS): ...@@ -228,8 +228,8 @@ class OSFS(OSFSXAttrMixin, OSFSWatchMixin, FS):
raise raise
@convert_os_errors @convert_os_errors
def setcontents(self, path, contents, chunk_size=64 * 1024): def setcontents(self, path, data=b'', encoding=None, errors=None, chunk_size=64 * 1024):
return super(OSFS, self).setcontents(path, contents, chunk_size) return super(OSFS, self).setcontents(path, data, encoding=encoding, errors=errors, chunk_size=chunk_size)
@convert_os_errors @convert_os_errors
def exists(self, path): def exists(self, path):
......
...@@ -41,6 +41,7 @@ _SENTINAL = object() ...@@ -41,6 +41,7 @@ _SENTINAL = object()
from six import PY3, b from six import PY3, b
class RemoteFileBuffer(FileWrapper): class RemoteFileBuffer(FileWrapper):
"""File-like object providing buffer for local file operations. """File-like object providing buffer for local file operations.
...@@ -82,7 +83,7 @@ class RemoteFileBuffer(FileWrapper): ...@@ -82,7 +83,7 @@ class RemoteFileBuffer(FileWrapper):
self._readlen = 0 # How many bytes already loaded from rfile self._readlen = 0 # How many bytes already loaded from rfile
self._rfile = None # Reference to remote file object self._rfile = None # Reference to remote file object
self._eof = False # Reached end of rfile? self._eof = False # Reached end of rfile?
if getattr(fs,"_lock",None) is not None: if getattr(fs, "_lock", None) is not None:
self._lock = fs._lock.__class__() self._lock = fs._lock.__class__()
else: else:
self._lock = threading.RLock() self._lock = threading.RLock()
...@@ -315,8 +316,8 @@ class ConnectionManagerFS(LazyFS): ...@@ -315,8 +316,8 @@ class ConnectionManagerFS(LazyFS):
self._poll_sleeper = threading.Event() self._poll_sleeper = threading.Event()
self.connected = connected self.connected = connected
def setcontents(self, path, data, chunk_size=64*1024): def setcontents(self, path, data=b'', encoding=None, errors=None, chunk_size=64*1024):
return self.wrapped_fs.setcontents(path, data, chunk_size=chunk_size) return self.wrapped_fs.setcontents(path, data, encoding=encoding, errors=errors, chunk_size=chunk_size)
def __getstate__(self): def __getstate__(self):
state = super(ConnectionManagerFS,self).__getstate__() state = super(ConnectionManagerFS,self).__getstate__()
...@@ -536,12 +537,12 @@ class CacheFSMixin(FS): ...@@ -536,12 +537,12 @@ class CacheFSMixin(FS):
except KeyError: except KeyError:
pass pass
def open(self,path,mode="r",**kwds): def open(self, path, mode='r', buffering=-1, encoding=None, errors=None, newline=None, line_buffering=False, **kwargs):
# Try to validate the entry using the cached info # Try to validate the entry using the cached info
try: try:
ci = self.__get_cached_info(path) ci = self.__get_cached_info(path)
except KeyError: except KeyError:
if path in ("","/"): if path in ("", "/"):
raise ResourceInvalidError(path) raise ResourceInvalidError(path)
try: try:
ppath = dirname(path) ppath = dirname(path)
...@@ -549,38 +550,38 @@ class CacheFSMixin(FS): ...@@ -549,38 +550,38 @@ class CacheFSMixin(FS):
except KeyError: except KeyError:
pass pass
else: else:
if not fs.utils.isdir(super(CacheFSMixin,self),ppath,pci.info): if not fs.utils.isdir(super(CacheFSMixin, self), ppath, pci.info):
raise ResourceInvalidError(path) raise ResourceInvalidError(path)
if pci.has_full_children: if pci.has_full_children:
raise ResourceNotFoundError(path) raise ResourceNotFoundError(path)
else: else:
if not fs.utils.isfile(super(CacheFSMixin,self),path,ci.info): if not fs.utils.isfile(super(CacheFSMixin, self), path, ci.info):
raise ResourceInvalidError(path) raise ResourceInvalidError(path)
f = super(CacheFSMixin,self).open(path,mode,**kwds) f = super(CacheFSMixin, self).open(path, mode=mode, buffering=buffering, encoding=encoding, errors=errors, newline=newline, line_buffering=line_buffering, **kwargs)
if "w" in mode or "a" in mode or "+" in mode: if "w" in mode or "a" in mode or "+" in mode:
with self.__cache_lock: with self.__cache_lock:
self.__cache.clear(path) self.__cache.clear(path)
f = self._CacheInvalidatingFile(self,path,f,mode) f = self._CacheInvalidatingFile(self, path, f, mode)
return f return f
class _CacheInvalidatingFile(FileWrapper): class _CacheInvalidatingFile(FileWrapper):
def __init__(self,owner,path,wrapped_file,mode=None): def __init__(self, owner, path, wrapped_file, mode=None):
self.path = path self.path = path
sup = super(CacheFSMixin._CacheInvalidatingFile,self) sup = super(CacheFSMixin._CacheInvalidatingFile, self)
sup.__init__(wrapped_file,mode) sup.__init__(wrapped_file, mode)
self.owner = owner self.owner = owner
def _write(self,string,flushing=False): def _write(self, string, flushing=False):
with self.owner._CacheFSMixin__cache_lock: with self.owner._CacheFSMixin__cache_lock:
self.owner._CacheFSMixin__cache.clear(self.path) self.owner._CacheFSMixin__cache.clear(self.path)
sup = super(CacheFSMixin._CacheInvalidatingFile,self) sup = super(CacheFSMixin._CacheInvalidatingFile, self)
return sup._write(string,flushing=flushing) return sup._write(string, flushing=flushing)
def _truncate(self,size): def _truncate(self, size):
with self.owner._CacheFSMixin__cache_lock: with self.owner._CacheFSMixin__cache_lock:
self.owner._CacheFSMixin__cache.clear(self.path) self.owner._CacheFSMixin__cache.clear(self.path)
sup = super(CacheFSMixin._CacheInvalidatingFile,self) sup = super(CacheFSMixin._CacheInvalidatingFile, self)
return sup._truncate(size) return sup._truncate(size)
def exists(self,path): def exists(self, path):
try: try:
self.getinfo(path) self.getinfo(path)
except ResourceNotFoundError: except ResourceNotFoundError:
...@@ -588,7 +589,7 @@ class CacheFSMixin(FS): ...@@ -588,7 +589,7 @@ class CacheFSMixin(FS):
else: else:
return True return True
def isdir(self,path): def isdir(self, path):
try: try:
self.__cache.iternames(path).next() self.__cache.iternames(path).next()
return True return True
...@@ -601,9 +602,9 @@ class CacheFSMixin(FS): ...@@ -601,9 +602,9 @@ class CacheFSMixin(FS):
except ResourceNotFoundError: except ResourceNotFoundError:
return False return False
else: else:
return fs.utils.isdir(super(CacheFSMixin,self),path,info) return fs.utils.isdir(super(CacheFSMixin, self), path, info)
def isfile(self,path): def isfile(self, path):
try: try:
self.__cache.iternames(path).next() self.__cache.iternames(path).next()
return False return False
...@@ -616,17 +617,17 @@ class CacheFSMixin(FS): ...@@ -616,17 +617,17 @@ class CacheFSMixin(FS):
except ResourceNotFoundError: except ResourceNotFoundError:
return False return False
else: else:
return fs.utils.isfile(super(CacheFSMixin,self),path,info) return fs.utils.isfile(super(CacheFSMixin, self), path, info)
def getinfo(self,path): def getinfo(self, path):
try: try:
ci = self.__get_cached_info(path) ci = self.__get_cached_info(path)
if not ci.has_full_info: if not ci.has_full_info:
raise KeyError raise KeyError
info = ci.info info = ci.info
except KeyError: except KeyError:
info = super(CacheFSMixin,self).getinfo(path) info = super(CacheFSMixin, self).getinfo(path)
self.__set_cached_info(path,CachedInfo(info)) self.__set_cached_info(path, CachedInfo(info))
return info return info
def listdir(self,path="",*args,**kwds): def listdir(self,path="",*args,**kwds):
...@@ -670,9 +671,9 @@ class CacheFSMixin(FS): ...@@ -670,9 +671,9 @@ class CacheFSMixin(FS):
def getsize(self,path): def getsize(self,path):
return self.getinfo(path)["size"] return self.getinfo(path)["size"]
def setcontents(self, path, contents=b(""), chunk_size=64*1024): def setcontents(self, path, data=b'', encoding=None, errors=None, chunk_size=64*1024):
supsc = super(CacheFSMixin,self).setcontents supsc = super(CacheFSMixin, self).setcontents
res = supsc(path, contents, chunk_size=chunk_size) res = supsc(path, data, encoding=None, errors=None, chunk_size=chunk_size)
with self.__cache_lock: with self.__cache_lock:
self.__cache.clear(path) self.__cache.clear(path)
self.__cache[path] = CachedInfo.new_file_stub() self.__cache[path] = CachedInfo.new_file_stub()
......
...@@ -26,7 +26,9 @@ from fs.path import * ...@@ -26,7 +26,9 @@ from fs.path import *
from fs.errors import * from fs.errors import *
from fs.remote import * from fs.remote import *
from fs.filelike import LimitBytesFile from fs.filelike import LimitBytesFile
from fs import iotools
import six
# Boto is not thread-safe, so we need to use a per-thread S3 connection. # Boto is not thread-safe, so we need to use a per-thread S3 connection.
if hasattr(threading,"local"): if hasattr(threading,"local"):
...@@ -253,9 +255,9 @@ class S3FS(FS): ...@@ -253,9 +255,9 @@ class S3FS(FS):
k = self._s3bukt.get_key(s3path) k = self._s3bukt.get_key(s3path)
# Is there AllUsers group with READ permissions? # Is there AllUsers group with READ permissions?
is_public = True in [grant.permission == 'READ' and \ is_public = True in [grant.permission == 'READ' and
grant.uri == 'http://acs.amazonaws.com/groups/global/AllUsers' grant.uri == 'http://acs.amazonaws.com/groups/global/AllUsers'
for grant in k.get_acl().acl.grants ] for grant in k.get_acl().acl.grants]
url = k.generate_url(expires, force_http=is_public) url = k.generate_url(expires, force_http=is_public)
...@@ -270,11 +272,14 @@ class S3FS(FS): ...@@ -270,11 +272,14 @@ class S3FS(FS):
return url return url
def setcontents(self, path, data, chunk_size=64*1024): def setcontents(self, path, data=b'', encoding=None, errors=None, chunk_size=64*1024):
s3path = self._s3path(path) s3path = self._s3path(path)
if isinstance(data, six.text_type):
data = data.encode(encoding=encoding, errors=errors)
self._sync_set_contents(s3path, data) self._sync_set_contents(s3path, data)
def open(self,path,mode="r"): @iotools.filelike_to_stream
def open(self, path, mode='r', buffering=-1, encoding=None, errors=None, newline=None, line_buffering=False, **kwargs):
"""Open the named file in the given mode. """Open the named file in the given mode.
This method downloads the file contents into a local temporary file This method downloads the file contents into a local temporary file
......
...@@ -19,6 +19,8 @@ from fs.base import * ...@@ -19,6 +19,8 @@ from fs.base import *
from fs.path import * from fs.path import *
from fs.errors import * from fs.errors import *
from fs.utils import isdir, isfile from fs.utils import isdir, isfile
from fs import iotools
class WrongHostKeyError(RemoteConnectionError): class WrongHostKeyError(RemoteConnectionError):
pass pass
...@@ -108,7 +110,6 @@ class SFTPFS(FS): ...@@ -108,7 +110,6 @@ class SFTPFS(FS):
if other authentication is not succesful if other authentication is not succesful
""" """
credentials = dict(username=username, credentials = dict(username=username,
password=password, password=password,
pkey=pkey) pkey=pkey)
...@@ -300,12 +301,12 @@ class SFTPFS(FS): ...@@ -300,12 +301,12 @@ class SFTPFS(FS):
self._transport.close() self._transport.close()
self.closed = True self.closed = True
def _normpath(self,path): def _normpath(self, path):
if not isinstance(path,unicode): if not isinstance(path, unicode):
path = path.decode(self.encoding) path = path.decode(self.encoding)
npath = pathjoin(self.root_path,relpath(normpath(path))) npath = pathjoin(self.root_path, relpath(normpath(path)))
if not isprefix(self.root_path,npath): if not isprefix(self.root_path, npath):
raise PathError(path,msg="Path is outside root: %(path)s") raise PathError(path, msg="Path is outside root: %(path)s")
return npath return npath
def getpathurl(self, path, allow_none=False): def getpathurl(self, path, allow_none=False):
...@@ -325,17 +326,19 @@ class SFTPFS(FS): ...@@ -325,17 +326,19 @@ class SFTPFS(FS):
@synchronize @synchronize
@convert_os_errors @convert_os_errors
def open(self,path,mode="rb",bufsize=-1): @iotools.filelike_to_stream
def open(self, path, mode='r', buffering=-1, encoding=None, errors=None, newline=None, line_buffering=False, bufsize=-1, **kwargs):
npath = self._normpath(path) npath = self._normpath(path)
if self.isdir(path): if self.isdir(path):
msg = "that's a directory: %(path)s" msg = "that's a directory: %(path)s"
raise ResourceInvalidError(path,msg=msg) raise ResourceInvalidError(path, msg=msg)
# paramiko implements its own buffering and write-back logic, # paramiko implements its own buffering and write-back logic,
# so we don't need to use a RemoteFileBuffer here. # so we don't need to use a RemoteFileBuffer here.
f = self.client.open(npath,mode,bufsize) f = self.client.open(npath, mode, bufsize)
# Unfortunately it has a broken truncate() method. # Unfortunately it has a broken truncate() method.
# TODO: implement this as a wrapper # TODO: implement this as a wrapper
old_truncate = f.truncate old_truncate = f.truncate
def new_truncate(size=None): def new_truncate(size=None):
if size is None: if size is None:
size = f.tell() size = f.tell()
...@@ -354,7 +357,7 @@ class SFTPFS(FS): ...@@ -354,7 +357,7 @@ class SFTPFS(FS):
@synchronize @synchronize
@convert_os_errors @convert_os_errors
def exists(self,path): def exists(self, path):
if path in ('', '/'): if path in ('', '/'):
return True return True
npath = self._normpath(path) npath = self._normpath(path)
...@@ -369,7 +372,7 @@ class SFTPFS(FS): ...@@ -369,7 +372,7 @@ class SFTPFS(FS):
@synchronize @synchronize
@convert_os_errors @convert_os_errors
def isdir(self,path): def isdir(self,path):
if path in ('', '/'): if normpath(path) in ('', '/'):
return True return True
npath = self._normpath(path) npath = self._normpath(path)
try: try:
...@@ -378,7 +381,7 @@ class SFTPFS(FS): ...@@ -378,7 +381,7 @@ class SFTPFS(FS):
if getattr(e,"errno",None) == 2: if getattr(e,"errno",None) == 2:
return False return False
raise raise
return statinfo.S_ISDIR(stat.st_mode) return statinfo.S_ISDIR(stat.st_mode) != 0
@synchronize @synchronize
@convert_os_errors @convert_os_errors
...@@ -390,7 +393,7 @@ class SFTPFS(FS): ...@@ -390,7 +393,7 @@ class SFTPFS(FS):
if getattr(e,"errno",None) == 2: if getattr(e,"errno",None) == 2:
return False return False
raise raise
return statinfo.S_ISREG(stat.st_mode) return statinfo.S_ISREG(stat.st_mode) != 0
@synchronize @synchronize
@convert_os_errors @convert_os_errors
......
...@@ -10,13 +10,14 @@ import os ...@@ -10,13 +10,14 @@ import os
import os.path import os.path
import time import time
import tempfile import tempfile
import platform
from fs.base import synchronize
from fs.osfs import OSFS from fs.osfs import OSFS
from fs.errors import * from fs.errors import *
from fs import _thread_synchronize_default from fs import _thread_synchronize_default
class TempFS(OSFS): class TempFS(OSFS):
"""Create a Filesystem in a temporary directory (with tempfile.mkdtemp), """Create a Filesystem in a temporary directory (with tempfile.mkdtemp),
...@@ -38,7 +39,7 @@ class TempFS(OSFS): ...@@ -38,7 +39,7 @@ class TempFS(OSFS):
self.identifier = identifier self.identifier = identifier
self.temp_dir = temp_dir self.temp_dir = temp_dir
self.dir_mode = dir_mode self.dir_mode = dir_mode
self._temp_dir = tempfile.mkdtemp(identifier or "TempFS",dir=temp_dir) self._temp_dir = tempfile.mkdtemp(identifier or "TempFS", dir=temp_dir)
self._cleaned = False self._cleaned = False
super(TempFS, self).__init__(self._temp_dir, dir_mode=dir_mode, thread_synchronize=thread_synchronize) super(TempFS, self).__init__(self._temp_dir, dir_mode=dir_mode, thread_synchronize=thread_synchronize)
...@@ -65,6 +66,7 @@ class TempFS(OSFS): ...@@ -65,6 +66,7 @@ class TempFS(OSFS):
# dir_mode=self.dir_mode, # dir_mode=self.dir_mode,
# thread_synchronize=self.thread_synchronize) # thread_synchronize=self.thread_synchronize)
@synchronize
def close(self): def close(self):
"""Removes the temporary directory. """Removes the temporary directory.
...@@ -73,13 +75,13 @@ class TempFS(OSFS): ...@@ -73,13 +75,13 @@ class TempFS(OSFS):
Note that once this method has been called, the FS object may Note that once this method has been called, the FS object may
no longer be used. no longer be used.
""" """
super(TempFS,self).close() super(TempFS, self).close()
# Depending on how resources are freed by the OS, there could # Depending on how resources are freed by the OS, there could
# be some transient errors when freeing a TempFS soon after it # be some transient errors when freeing a TempFS soon after it
# was used. If they occur, do a small sleep and try again. # was used. If they occur, do a small sleep and try again.
try: try:
self._close() self._close()
except (ResourceLockedError,ResourceInvalidError): except (ResourceLockedError, ResourceInvalidError):
time.sleep(0.5) time.sleep(0.5)
self._close() self._close()
...@@ -97,20 +99,23 @@ class TempFS(OSFS): ...@@ -97,20 +99,23 @@ class TempFS(OSFS):
try: try:
# shutil.rmtree doesn't handle long paths on win32, # shutil.rmtree doesn't handle long paths on win32,
# so we walk the tree by hand. # so we walk the tree by hand.
entries = os.walk(self.root_path,topdown=False) entries = os.walk(self.root_path, topdown=False)
for (dir,dirnames,filenames) in entries: for (dir, dirnames, filenames) in entries:
for filename in filenames: for filename in filenames:
try: try:
os_remove(os.path.join(dir,filename)) os_remove(os.path.join(dir, filename))
except ResourceNotFoundError: except ResourceNotFoundError:
pass pass
for dirname in dirnames: for dirname in dirnames:
try: try:
os_rmdir(os.path.join(dir,dirname)) os_rmdir(os.path.join(dir, dirname))
except ResourceNotFoundError: except ResourceNotFoundError:
pass pass
try:
os.rmdir(self.root_path) os.rmdir(self.root_path)
except OSError:
pass
self._cleaned = True self._cleaned = True
finally: finally:
self._lock.release() self._lock.release()
super(TempFS,self).close() super(TempFS, self).close()
...@@ -6,7 +6,8 @@ ...@@ -6,7 +6,8 @@
import unittest import unittest
import sys import sys
import os, os.path import os
import os.path
import socket import socket
import threading import threading
import time import time
...@@ -32,6 +33,12 @@ try: ...@@ -32,6 +33,12 @@ try:
except ImportError: except ImportError:
if not PY3: if not PY3:
raise raise
import logging
logging.getLogger('paramiko').setLevel(logging.ERROR)
logging.getLogger('paramiko.transport').setLevel(logging.ERROR)
class TestSFTPFS(TestRPCFS): class TestSFTPFS(TestRPCFS):
__test__ = not PY3 __test__ = not PY3
...@@ -55,7 +62,7 @@ except ImportError: ...@@ -55,7 +62,7 @@ except ImportError:
pass pass
else: else:
from fs.osfs import OSFS from fs.osfs import OSFS
class TestFUSE(unittest.TestCase,FSTestCases,ThreadingTestCases): class TestFUSE(unittest.TestCase, FSTestCases, ThreadingTestCases):
def setUp(self): def setUp(self):
self.temp_fs = TempFS() self.temp_fs = TempFS()
...@@ -64,7 +71,7 @@ else: ...@@ -64,7 +71,7 @@ else:
self.mounted_fs = self.temp_fs.opendir("root") self.mounted_fs = self.temp_fs.opendir("root")
self.mount_point = self.temp_fs.getsyspath("mount") self.mount_point = self.temp_fs.getsyspath("mount")
self.fs = OSFS(self.temp_fs.getsyspath("mount")) self.fs = OSFS(self.temp_fs.getsyspath("mount"))
self.mount_proc = fuse.mount(self.mounted_fs,self.mount_point) self.mount_proc = fuse.mount(self.mounted_fs, self.mount_point)
def tearDown(self): def tearDown(self):
self.mount_proc.unmount() self.mount_proc.unmount()
...@@ -76,7 +83,7 @@ else: ...@@ -76,7 +83,7 @@ else:
fuse.unmount(self.mount_point) fuse.unmount(self.mount_point)
self.temp_fs.close() self.temp_fs.close()
def check(self,p): def check(self, p):
return self.mounted_fs.exists(p) return self.mounted_fs.exists(p)
......
...@@ -12,6 +12,7 @@ from fs.zipfs import ZipFS ...@@ -12,6 +12,7 @@ from fs.zipfs import ZipFS
from six import b from six import b
class TestFSImportHook(unittest.TestCase): class TestFSImportHook(unittest.TestCase):
def setUp(self): def setUp(self):
...@@ -140,4 +141,3 @@ class TestFSImportHook(unittest.TestCase): ...@@ -140,4 +141,3 @@ class TestFSImportHook(unittest.TestCase):
sys.path_hooks.remove(FSImportHook) sys.path_hooks.remove(FSImportHook)
sys.path.pop() sys.path.pop()
t.close() t.close()
from __future__ import unicode_literals
from fs import iotools
import io
import unittest
from os.path import dirname, join, abspath
try:
unicode
except NameError:
unicode = str
class OpenFilelike(object):
def __init__(self, make_f):
self.make_f = make_f
@iotools.filelike_to_stream
def open(self, path, mode='r', buffering=-1, encoding=None, errors=None, newline=None, line_buffering=False, **kwargs):
return self.make_f()
def __enter__(self):
return self
def __exit__(self, *args, **kwargs):
self.f.close()
class TestIOTools(unittest.TestCase):
def get_bin_file(self):
path = join(dirname(abspath(__file__)), 'data/UTF-8-demo.txt')
return io.open(path, 'rb')
def test_make_stream(self):
"""Test make_stream"""
with self.get_bin_file() as f:
text = f.read()
self.assert_(isinstance(text, bytes))
with self.get_bin_file() as f:
with iotools.make_stream("data/UTF-8-demo.txt", f, 'rt') as f2:
text = f2.read()
self.assert_(isinstance(text, unicode))
def test_decorator(self):
"""Test filelike_to_stream decorator"""
o = OpenFilelike(self.get_bin_file)
with o.open('file', 'rb') as f:
text = f.read()
self.assert_(isinstance(text, bytes))
with o.open('file', 'rt') as f:
text = f.read()
self.assert_(isinstance(text, unicode))
...@@ -2,10 +2,11 @@ from fs.mountfs import MountFS ...@@ -2,10 +2,11 @@ from fs.mountfs import MountFS
from fs.memoryfs import MemoryFS from fs.memoryfs import MemoryFS
import unittest import unittest
class TestMultiFS(unittest.TestCase):
class TestMountFS(unittest.TestCase):
def test_auto_close(self): def test_auto_close(self):
"""Test MultiFS auto close is working""" """Test MountFS auto close is working"""
multi_fs = MountFS() multi_fs = MountFS()
m1 = MemoryFS() m1 = MemoryFS()
m2 = MemoryFS() m2 = MemoryFS()
...@@ -18,7 +19,7 @@ class TestMultiFS(unittest.TestCase): ...@@ -18,7 +19,7 @@ class TestMultiFS(unittest.TestCase):
self.assert_(m2.closed) self.assert_(m2.closed)
def test_no_auto_close(self): def test_no_auto_close(self):
"""Test MultiFS auto close can be disabled""" """Test MountFS auto close can be disabled"""
multi_fs = MountFS(auto_close=False) multi_fs = MountFS(auto_close=False)
m1 = MemoryFS() m1 = MemoryFS()
m2 = MemoryFS() m2 = MemoryFS()
...@@ -32,7 +33,7 @@ class TestMultiFS(unittest.TestCase): ...@@ -32,7 +33,7 @@ class TestMultiFS(unittest.TestCase):
def test_mountfile(self): def test_mountfile(self):
"""Test mounting a file""" """Test mounting a file"""
quote = """If you wish to make an apple pie from scratch, you must first invent the universe.""" quote = b"""If you wish to make an apple pie from scratch, you must first invent the universe."""
mem_fs = MemoryFS() mem_fs = MemoryFS()
mem_fs.makedir('foo') mem_fs.makedir('foo')
mem_fs.setcontents('foo/bar.txt', quote) mem_fs.setcontents('foo/bar.txt', quote)
...@@ -58,11 +59,11 @@ class TestMultiFS(unittest.TestCase): ...@@ -58,11 +59,11 @@ class TestMultiFS(unittest.TestCase):
# Check changes are written back # Check changes are written back
mem_fs.setcontents('foo/bar.txt', 'baz') mem_fs.setcontents('foo/bar.txt', 'baz')
self.assertEqual(mount_fs.getcontents('bar.txt'), 'baz') self.assertEqual(mount_fs.getcontents('bar.txt'), b'baz')
self.assertEqual(mount_fs.getsize('bar.txt'), len('baz')) self.assertEqual(mount_fs.getsize('bar.txt'), len('baz'))
# Check changes are written to the original fs # Check changes are written to the original fs
self.assertEqual(mem_fs.getcontents('foo/bar.txt'), 'baz') self.assertEqual(mem_fs.getcontents('foo/bar.txt'), b'baz')
self.assertEqual(mem_fs.getsize('foo/bar.txt'), len('baz')) self.assertEqual(mem_fs.getsize('foo/bar.txt'), len('baz'))
# Check unmount # Check unmount
......
...@@ -24,23 +24,27 @@ from fs.local_functools import wraps ...@@ -24,23 +24,27 @@ from fs.local_functools import wraps
from six import PY3, b from six import PY3, b
class RemoteTempFS(TempFS): class RemoteTempFS(TempFS):
""" """
Simple filesystem implementing setfilecontents Simple filesystem implementing setfilecontents
for RemoteFileBuffer tests for RemoteFileBuffer tests
""" """
def open(self, path, mode='rb', write_on_flush=True): def open(self, path, mode='rb', write_on_flush=True, **kwargs):
if 'a' in mode or 'r' in mode or '+' in mode: if 'a' in mode or 'r' in mode or '+' in mode:
f = super(RemoteTempFS, self).open(path, 'rb') f = super(RemoteTempFS, self).open(path, mode='rb', **kwargs)
f = TellAfterCloseFile(f) f = TellAfterCloseFile(f)
else: else:
f = None f = None
return RemoteFileBuffer(self, path, mode, f, return RemoteFileBuffer(self,
path,
mode,
f,
write_on_flush=write_on_flush) write_on_flush=write_on_flush)
def setcontents(self, path, data, chunk_size=64*1024): def setcontents(self, path, data, encoding=None, errors=None, chunk_size=64*1024):
f = super(RemoteTempFS, self).open(path, 'wb') f = super(RemoteTempFS, self).open(path, 'wb', encoding=encoding, errors=errors, chunk_size=chunk_size)
if getattr(data, 'read', False): if getattr(data, 'read', False):
f.write(data.read()) f.write(data.read())
else: else:
...@@ -51,7 +55,7 @@ class RemoteTempFS(TempFS): ...@@ -51,7 +55,7 @@ class RemoteTempFS(TempFS):
class TellAfterCloseFile(object): class TellAfterCloseFile(object):
"""File-like object that allows calling tell() after it's been closed.""" """File-like object that allows calling tell() after it's been closed."""
def __init__(self,file): def __init__(self, file):
self._finalpos = None self._finalpos = None
self.file = file self.file = file
...@@ -65,8 +69,8 @@ class TellAfterCloseFile(object): ...@@ -65,8 +69,8 @@ class TellAfterCloseFile(object):
return self._finalpos return self._finalpos
return self.file.tell() return self.file.tell()
def __getattr__(self,attr): def __getattr__(self, attr):
return getattr(self.file,attr) return getattr(self.file, attr)
class TestRemoteFileBuffer(unittest.TestCase, FSTestCases, ThreadingTestCases): class TestRemoteFileBuffer(unittest.TestCase, FSTestCases, ThreadingTestCases):
...@@ -315,8 +319,8 @@ class DisconnectingFS(WrapFS): ...@@ -315,8 +319,8 @@ class DisconnectingFS(WrapFS):
time.sleep(random.random()*0.1) time.sleep(random.random()*0.1)
self._connected = not self._connected self._connected = not self._connected
def setcontents(self, path, contents=b(''), chunk_size=64*1024): def setcontents(self, path, data=b(''), encoding=None, errors=None, chunk_size=64*1024):
return self.wrapped_fs.setcontents(path, contents) return self.wrapped_fs.setcontents(path, data, encoding=encoding, errors=errors, chunk_size=chunk_size)
def close(self): def close(self):
if not self.closed: if not self.closed:
......
...@@ -29,6 +29,10 @@ if sys.platform == "win32": ...@@ -29,6 +29,10 @@ if sys.platform == "win32":
else: else:
watch_win32 = None watch_win32 = None
import logging
logging.getLogger('pyinotify').setLevel(logging.ERROR)
import six import six
from six import PY3, b from six import PY3, b
...@@ -53,7 +57,7 @@ class WatcherTestCases: ...@@ -53,7 +57,7 @@ class WatcherTestCases:
self.watchfs._poll_cond.wait() self.watchfs._poll_cond.wait()
self.watchfs._poll_cond.release() self.watchfs._poll_cond.release()
else: else:
time.sleep(2)#0.5) time.sleep(2)
def assertEventOccurred(self,cls,path=None,event_list=None,**attrs): def assertEventOccurred(self,cls,path=None,event_list=None,**attrs):
if not self.checkEventOccurred(cls,path,event_list,**attrs): if not self.checkEventOccurred(cls,path,event_list,**attrs):
...@@ -222,4 +226,3 @@ class TestWatchers_MemoryFS_polling(TestWatchers_MemoryFS): ...@@ -222,4 +226,3 @@ class TestWatchers_MemoryFS_polling(TestWatchers_MemoryFS):
def setUp(self): def setUp(self):
self.fs = memoryfs.MemoryFS() self.fs = memoryfs.MemoryFS()
self.watchfs = ensure_watchable(self.fs,poll_interval=0.1) self.watchfs = ensure_watchable(self.fs,poll_interval=0.1)
...@@ -17,6 +17,7 @@ from fs import zipfs ...@@ -17,6 +17,7 @@ from fs import zipfs
from six import PY3, b from six import PY3, b
class TestReadZipFS(unittest.TestCase): class TestReadZipFS(unittest.TestCase):
def setUp(self): def setUp(self):
...@@ -46,20 +47,22 @@ class TestReadZipFS(unittest.TestCase): ...@@ -46,20 +47,22 @@ class TestReadZipFS(unittest.TestCase):
def test_reads(self): def test_reads(self):
def read_contents(path): def read_contents(path):
f = self.fs.open(path) f = self.fs.open(path, 'rb')
contents = f.read() contents = f.read()
return contents return contents
def check_contents(path, expected): def check_contents(path, expected):
self.assert_(read_contents(path)==expected) self.assert_(read_contents(path) == expected)
check_contents("a.txt", b("Hello, World!")) check_contents("a.txt", b("Hello, World!"))
check_contents("1.txt", b("1")) check_contents("1.txt", b("1"))
check_contents("foo/bar/baz.txt", b("baz")) check_contents("foo/bar/baz.txt", b("baz"))
def test_getcontents(self): def test_getcontents(self):
def read_contents(path): def read_contents(path):
return self.fs.getcontents(path) return self.fs.getcontents(path, 'rb')
def check_contents(path, expected): def check_contents(path, expected):
self.assert_(read_contents(path)==expected) self.assert_(read_contents(path) == expected)
check_contents("a.txt", b("Hello, World!")) check_contents("a.txt", b("Hello, World!"))
check_contents("1.txt", b("1")) check_contents("1.txt", b("1"))
check_contents("foo/bar/baz.txt", b("baz")) check_contents("foo/bar/baz.txt", b("baz"))
...@@ -82,7 +85,7 @@ class TestReadZipFS(unittest.TestCase): ...@@ -82,7 +85,7 @@ class TestReadZipFS(unittest.TestCase):
dir_list = self.fs.listdir(path) dir_list = self.fs.listdir(path)
self.assert_(sorted(dir_list) == sorted(expected)) self.assert_(sorted(dir_list) == sorted(expected))
for item in dir_list: for item in dir_list:
self.assert_(isinstance(item,unicode)) self.assert_(isinstance(item, unicode))
check_listing('/', ['a.txt', '1.txt', 'foo', 'b.txt']) check_listing('/', ['a.txt', '1.txt', 'foo', 'b.txt'])
check_listing('foo', ['second.txt', 'bar']) check_listing('foo', ['second.txt', 'bar'])
check_listing('foo/bar', ['baz.txt']) check_listing('foo/bar', ['baz.txt'])
......
...@@ -72,6 +72,7 @@ def copyfile(src_fs, src_path, dst_fs, dst_path, overwrite=True, chunk_size=64*1 ...@@ -72,6 +72,7 @@ def copyfile(src_fs, src_path, dst_fs, dst_path, overwrite=True, chunk_size=64*1
if src_lock is not None: if src_lock is not None:
src_lock.release() src_lock.release()
def copyfile_non_atomic(src_fs, src_path, dst_fs, dst_path, overwrite=True, chunk_size=64*1024): def copyfile_non_atomic(src_fs, src_path, dst_fs, dst_path, overwrite=True, chunk_size=64*1024):
"""A non atomic version of copyfile (will not block other threads using src_fs or dst_fst) """A non atomic version of copyfile (will not block other threads using src_fs or dst_fst)
......
...@@ -291,29 +291,36 @@ class WatchableFS(WatchableFSMixin,WrapFS): ...@@ -291,29 +291,36 @@ class WatchableFS(WatchableFSMixin,WrapFS):
that might be made through other interfaces to the same filesystem. that might be made through other interfaces to the same filesystem.
""" """
def __init__(self,*args,**kwds): def __init__(self, *args, **kwds):
super(WatchableFS,self).__init__(*args,**kwds) super(WatchableFS, self).__init__(*args, **kwds)
def close(self): def close(self):
super(WatchableFS,self).close() super(WatchableFS, self).close()
self.notify_watchers(CLOSED) self.notify_watchers(CLOSED)
def open(self,path,mode="r",**kwargs): def open(self, path, mode='r', buffering=-1, encoding=None, errors=None, newline=None, line_buffering=False, **kwargs):
existed = self.wrapped_fs.isfile(path) existed = self.wrapped_fs.isfile(path)
f = super(WatchableFS,self).open(path,mode,**kwargs) f = super(WatchableFS, self).open(path,
mode=mode,
buffering=buffering,
encoding=encoding,
errors=errors,
newline=newline,
line_buffering=line_buffering,
**kwargs)
if not existed: if not existed:
self.notify_watchers(CREATED,path) self.notify_watchers(CREATED, path)
self.notify_watchers(ACCESSED,path) self.notify_watchers(ACCESSED, path)
return WatchedFile(f,self,path,mode) return WatchedFile(f, self, path, mode)
def setcontents(self, path, data=b(''), chunk_size=64*1024): def setcontents(self, path, data=b'', encoding=None, errors=None, chunk_size=64*1024):
existed = self.wrapped_fs.isfile(path) existed = self.wrapped_fs.isfile(path)
ret = super(WatchableFS, self).setcontents(path, data, chunk_size=chunk_size) ret = super(WatchableFS, self).setcontents(path, data, chunk_size=chunk_size)
if not existed: if not existed:
self.notify_watchers(CREATED,path) self.notify_watchers(CREATED, path)
self.notify_watchers(ACCESSED,path) self.notify_watchers(ACCESSED, path)
if data: if data:
self.notify_watchers(MODIFIED,path,True) self.notify_watchers(MODIFIED, path, True)
return ret return ret
def createfile(self, path): def createfile(self, path):
......
...@@ -150,21 +150,21 @@ class WrapFS(FS): ...@@ -150,21 +150,21 @@ class WrapFS(FS):
return self.wrapped_fs.hassyspath(self._encode(path)) return self.wrapped_fs.hassyspath(self._encode(path))
@rewrite_errors @rewrite_errors
def open(self, path, mode="r", **kwargs): def open(self, path, mode='r', **kwargs):
(mode, wmode) = self._adjust_mode(mode) (mode, wmode) = self._adjust_mode(mode)
f = self.wrapped_fs.open(self._encode(path), wmode, **kwargs) f = self.wrapped_fs.open(self._encode(path), wmode, **kwargs)
return self._file_wrap(f, mode) return self._file_wrap(f, mode)
@rewrite_errors @rewrite_errors
def setcontents(self, path, data, chunk_size=64*1024): def setcontents(self, path, data, encoding=None, errors=None, chunk_size=64*1024):
# We can't pass setcontents() through to the wrapped FS if the # We can't pass setcontents() through to the wrapped FS if the
# wrapper has defined a _file_wrap method, as it would bypass # wrapper has defined a _file_wrap method, as it would bypass
# the file contents wrapping. # the file contents wrapping.
#if self._file_wrap.im_func is WrapFS._file_wrap.im_func: #if self._file_wrap.im_func is WrapFS._file_wrap.im_func:
if getattr(self.__class__, '_file_wrap', None) is getattr(WrapFS, '_file_wrap', None): if getattr(self.__class__, '_file_wrap', None) is getattr(WrapFS, '_file_wrap', None):
return self.wrapped_fs.setcontents(self._encode(path), data, chunk_size=chunk_size) return self.wrapped_fs.setcontents(self._encode(path), data, encoding=encoding, errors=errors, chunk_size=chunk_size)
else: else:
return super(WrapFS,self).setcontents(path, data, chunk_size=chunk_size) return super(WrapFS, self).setcontents(path, data, encoding=encoding, errors=errors, chunk_size=chunk_size)
@rewrite_errors @rewrite_errors
def createfile(self, path): def createfile(self, path):
......
...@@ -58,14 +58,20 @@ class LimitSizeFS(WrapFS): ...@@ -58,14 +58,20 @@ class LimitSizeFS(WrapFS):
raise NoSysPathError(path) raise NoSysPathError(path)
return None return None
def open(self, path, mode="r"): def open(self, path, mode='r', buffering=-1, encoding=None, errors=None, newline=None, line_buffering=False, **kwargs):
path = relpath(normpath(path)) path = relpath(normpath(path))
with self._size_lock: with self._size_lock:
try: try:
size = self.getsize(path) size = self.getsize(path)
except ResourceNotFoundError: except ResourceNotFoundError:
size = 0 size = 0
f = super(LimitSizeFS,self).open(path,mode) f = super(LimitSizeFS,self).open(path,
mode=mode,
buffering=buffering,
errors=errors,
newline=newline,
line_buffering=line_buffering,
**kwargs)
if "w" not in mode: if "w" not in mode:
self._set_file_size(path,None,1) self._set_file_size(path,None,1)
else: else:
......
...@@ -10,6 +10,7 @@ from fs.base import NoDefaultMeta ...@@ -10,6 +10,7 @@ from fs.base import NoDefaultMeta
from fs.wrapfs import WrapFS from fs.wrapfs import WrapFS
from fs.errors import UnsupportedError, NoSysPathError from fs.errors import UnsupportedError, NoSysPathError
class ReadOnlyFS(WrapFS): class ReadOnlyFS(WrapFS):
""" Makes a FS object read only. Any operation that could potentially modify """ Makes a FS object read only. Any operation that could potentially modify
the underlying file system will throw an UnsupportedError the underlying file system will throw an UnsupportedError
...@@ -38,11 +39,18 @@ class ReadOnlyFS(WrapFS): ...@@ -38,11 +39,18 @@ class ReadOnlyFS(WrapFS):
return None return None
raise NoSysPathError(path) raise NoSysPathError(path)
def open(self, path, mode='r', **kwargs): def open(self, path, mode='r', buffering=-1, encoding=None, errors=None, newline=None, line_buffering=False, **kwargs):
""" Only permit read access """ """ Only permit read access """
if 'w' in mode or 'a' in mode or '+' in mode: if 'w' in mode or 'a' in mode or '+' in mode:
raise UnsupportedError('write') raise UnsupportedError('write')
return super(ReadOnlyFS, self).open(path, mode, **kwargs) return super(ReadOnlyFS, self).open(path,
mode=mode,
buffering=buffering,
encoding=encoding,
errors=errors,
newline=newline,
line_buffering=line_buffering,
**kwargs)
def _no_can_do(self, *args, **kwargs): def _no_can_do(self, *args, **kwargs):
""" Replacement method for methods that can modify the file system """ """ Replacement method for methods that can modify the file system """
......
...@@ -21,7 +21,7 @@ class SubFS(WrapFS): ...@@ -21,7 +21,7 @@ class SubFS(WrapFS):
def __init__(self, wrapped_fs, sub_dir): def __init__(self, wrapped_fs, sub_dir):
self.sub_dir = abspath(normpath(sub_dir)) self.sub_dir = abspath(normpath(sub_dir))
super(SubFS,self).__init__(wrapped_fs) super(SubFS, self).__init__(wrapped_fs)
def _encode(self, path): def _encode(self, path):
return pathjoin(self.sub_dir, relpath(normpath(path))) return pathjoin(self.sub_dir, relpath(normpath(path)))
...@@ -44,7 +44,7 @@ class SubFS(WrapFS): ...@@ -44,7 +44,7 @@ class SubFS(WrapFS):
return self.wrapped_fs.desc(self.sub_dir) return self.wrapped_fs.desc(self.sub_dir)
return '%s!%s' % (self.wrapped_fs.desc(self.sub_dir), path) return '%s!%s' % (self.wrapped_fs.desc(self.sub_dir), path)
def setcontents(self, path, data, chunk_size=64*1024): def setcontents(self, path, data, encoding=None, errors=None, chunk_size=64*1024):
path = self._encode(path) path = self._encode(path)
return self.wrapped_fs.setcontents(path, data, chunk_size=chunk_size) return self.wrapped_fs.setcontents(path, data, chunk_size=chunk_size)
...@@ -62,11 +62,11 @@ class SubFS(WrapFS): ...@@ -62,11 +62,11 @@ class SubFS(WrapFS):
path = normpath(path) path = normpath(path)
if path in ('', '/'): if path in ('', '/'):
raise RemoveRootError(path) raise RemoveRootError(path)
super(SubFS,self).removedir(path,force=force) super(SubFS, self).removedir(path, force=force)
if recursive: if recursive:
try: try:
if dirname(path) not in ('', '/'): if dirname(path) not in ('', '/'):
self.removedir(dirname(path),recursive=True) self.removedir(dirname(path), recursive=True)
except DirectoryNotEmptyError: except DirectoryNotEmptyError:
pass pass
......
...@@ -13,6 +13,7 @@ from fs.base import * ...@@ -13,6 +13,7 @@ from fs.base import *
from fs.path import * from fs.path import *
from fs.errors import * from fs.errors import *
from fs.filelike import StringIO from fs.filelike import StringIO
from fs import iotools
from zipfile import ZipFile, ZIP_DEFLATED, ZIP_STORED, BadZipfile, LargeZipFile from zipfile import ZipFile, ZIP_DEFLATED, ZIP_STORED, BadZipfile, LargeZipFile
from memoryfs import MemoryFS from memoryfs import MemoryFS
...@@ -21,6 +22,7 @@ import tempfs ...@@ -21,6 +22,7 @@ import tempfs
from six import PY3 from six import PY3
class ZipOpenError(CreateFailedError): class ZipOpenError(CreateFailedError):
"""Thrown when the zip file could not be opened""" """Thrown when the zip file could not be opened"""
pass pass
...@@ -76,13 +78,13 @@ class _ExceptionProxy(object): ...@@ -76,13 +78,13 @@ class _ExceptionProxy(object):
class ZipFS(FS): class ZipFS(FS):
"""A FileSystem that represents a zip file.""" """A FileSystem that represents a zip file."""
_meta = { 'thread_safe' : True, _meta = {'thread_safe': True,
'virtual' : False, 'virtual': False,
'read_only' : False, 'read_only': False,
'unicode_paths' : True, 'unicode_paths': True,
'case_insensitive_paths' : False, 'case_insensitive_paths': False,
'network' : False, 'network': False,
'atomic.setcontents' : False 'atomic.setcontents': False
} }
def __init__(self, zip_file, mode="r", compression="deflated", allow_zip_64=False, encoding="CP437", thread_synchronize=True): def __init__(self, zip_file, mode="r", compression="deflated", allow_zip_64=False, encoding="CP437", thread_synchronize=True):
...@@ -189,7 +191,8 @@ class ZipFS(FS): ...@@ -189,7 +191,8 @@ class ZipFS(FS):
self.zf = _ExceptionProxy() self.zf = _ExceptionProxy()
@synchronize @synchronize
def open(self, path, mode="r", **kwargs): @iotools.filelike_to_stream
def open(self, path, mode='r', buffering=-1, encoding=None, errors=None, newline=None, line_buffering=False, **kwargs):
path = normpath(relpath(path)) path = normpath(relpath(path))
if 'r' in mode: if 'r' in mode:
...@@ -222,7 +225,7 @@ class ZipFS(FS): ...@@ -222,7 +225,7 @@ class ZipFS(FS):
raise ValueError("Mode must contain be 'r' or 'w'") raise ValueError("Mode must contain be 'r' or 'w'")
@synchronize @synchronize
def getcontents(self, path, mode="rb"): def getcontents(self, path, mode="rb", encoding=None, errors=None, newline=None):
if not self.exists(path): if not self.exists(path):
raise ResourceNotFoundError(path) raise ResourceNotFoundError(path)
path = normpath(relpath(path)) path = normpath(relpath(path))
...@@ -232,7 +235,9 @@ class ZipFS(FS): ...@@ -232,7 +235,9 @@ class ZipFS(FS):
raise ResourceNotFoundError(path) raise ResourceNotFoundError(path)
except RuntimeError: except RuntimeError:
raise OperationFailedError("read file", path=path, msg="3 Zip file must be opened with 'r' or 'a' to read") raise OperationFailedError("read file", path=path, msg="3 Zip file must be opened with 'r' or 'a' to read")
if 'b' in mode:
return contents return contents
return iotools.decode_binary(contents, encoding=encoding, errors=errors, newline=newline)
@synchronize @synchronize
def _on_write_close(self, filename): def _on_write_close(self, filename):
......
...@@ -28,7 +28,6 @@ classifiers = [ ...@@ -28,7 +28,6 @@ classifiers = [
'License :: OSI Approved :: BSD License', 'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent', 'Operating System :: OS Independent',
'Programming Language :: Python', 'Programming Language :: Python',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3',
...@@ -49,12 +48,12 @@ setup(install_requires=['distribute', 'six'], ...@@ -49,12 +48,12 @@ setup(install_requires=['distribute', 'six'],
version=VERSION, version=VERSION,
description="Filesystem abstraction", description="Filesystem abstraction",
long_description=long_desc, long_description=long_desc,
license = "BSD", license="BSD",
author="Will McGugan", author="Will McGugan",
author_email="will@willmcgugan.com", author_email="will@willmcgugan.com",
url="http://code.google.com/p/pyfilesystem/", url="http://code.google.com/p/pyfilesystem/",
download_url="http://code.google.com/p/pyfilesystem/downloads/list", download_url="http://code.google.com/p/pyfilesystem/downloads/list",
platforms = ['any'], platforms=['any'],
packages=['fs', packages=['fs',
'fs.expose', 'fs.expose',
'fs.expose.dokan', 'fs.expose.dokan',
...@@ -68,8 +67,8 @@ setup(install_requires=['distribute', 'six'], ...@@ -68,8 +67,8 @@ setup(install_requires=['distribute', 'six'],
'fs.contrib.davfs', 'fs.contrib.davfs',
'fs.contrib.tahoelafs', 'fs.contrib.tahoelafs',
'fs.commands'], 'fs.commands'],
package_data={'fs': ['tests/data/*.txt']},
scripts=['fs/commands/%s' % command for command in COMMANDS], scripts=['fs/commands/%s' % command for command in COMMANDS],
classifiers=classifiers, classifiers=classifiers,
**extra **extra
) )
[tox] [tox]
envlist = py25,py26,py27,py31,py32,pypy envlist = py26,py27,py31,py32,pypy
sitepackages = False sitepackages = False
[testenv] [testenv]
...@@ -10,24 +10,11 @@ deps = distribute ...@@ -10,24 +10,11 @@ deps = distribute
boto boto
nose nose
mako mako
python-libarchive
pyftpdlib pyftpdlib
changedir=.tox changedir=.tox
commands = nosetests fs.tests -v \ commands = nosetests fs.tests -v \
[] []
[testenv:py25]
deps = distribute
six
dexml
paramiko
boto
nose
mako
python-libarchive
pyftpdlib
simplejson
[testenv:py32] [testenv:py32]
commands = nosetests fs.tests -v \ commands = nosetests fs.tests -v \
[] []
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment