Skip to content

Commit

Permalink
Merge pull request #28 from 4Catalyzer/defer-check
Browse files Browse the repository at this point in the history
Defer check for root path existence
  • Loading branch information
taion authored Sep 18, 2016
2 parents bb3bbb1 + 401fe04 commit 7143129
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 17 deletions.
42 changes: 26 additions & 16 deletions flask_annex/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,25 +13,27 @@

class FileAnnex(AnnexBase):
def __init__(self, root_path):
if not os.path.exists(root_path):
raise IOError("root path {} does not exist".format(root_path))

self._root_path = root_path

def _get_filename(self, key):
return flask.safe_join(self._root_path, key)

def delete(self, key):
os.unlink(self._get_filename(key))
self._clean_empty_dirs(key)

# Clean up empty directories.
def _clean_empty_dirs(self, key):
key_dir_name = os.path.dirname(key)

while key_dir_name:
dir_name = self._get_filename(key_dir_name)
if os.listdir(dir_name):
try:
os.rmdir(dir_name)
except OSError as e:
if e.errno != errno.ENOTEMPTY:
raise # pragma: no cover
break

os.rmdir(dir_name)
key_dir_name = os.path.dirname(key_dir_name)

def delete_many(self, keys):
Expand All @@ -58,23 +60,31 @@ def list_keys(self, prefix):

def save_file(self, key, in_file):
out_filename = self._get_filename(key)

# Create directory for file if needed.
key_dir_name = os.path.dirname(key)
if key_dir_name:
dir_name = self._get_filename(key_dir_name)
try:
os.makedirs(dir_name)
except OSError as e:
if e.errno != errno.EEXIST: # pragma: no cover
raise
self._ensure_key_dir(key)

if isinstance(in_file, string_types):
shutil.copyfile(in_file, out_filename)
else:
with open(out_filename, 'wb') as out_fp:
shutil.copyfileobj(in_file, out_fp)

def _ensure_key_dir(self, key):
dir_name = self._get_filename(os.path.dirname(key))
if os.path.exists(dir_name):
return

# Verify that we aren't trying to create the root path.
if not os.path.exists(self._root_path):
raise IOError(
"root path {} does not exist".format(self._root_path),
)

try:
os.makedirs(dir_name)
except OSError as e: # pragma: no cover
if e.errno != errno.EEXIST:
raise

def send_file(self, key):
return flask.send_from_directory(
self._root_path, key,
Expand Down
3 changes: 2 additions & 1 deletion tests/test_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,5 @@ def annex_base(self, monkeypatch, file_annex_path):

def test_error_nonexistent_root_path(tmpdir):
with pytest.raises(IOError):
Annex('file', tmpdir.join('nonexistent').strpath)
annex = Annex('file', tmpdir.join('dummy').strpath)
annex.save_file('foo', BytesIO(b''))

0 comments on commit 7143129

Please sign in to comment.