From 4fad079b8425b7e2c5abb686694538133bc0d545 Mon Sep 17 00:00:00 2001 From: rolux Date: Tue, 9 Oct 2012 14:37:56 +0200 Subject: [PATCH] after remove and rename, remove newly emptied directories --- pandoraclient | 38 +++++++++++++++++++++++++++++++------- 1 file changed, 31 insertions(+), 7 deletions(-) diff --git a/pandoraclient b/pandoraclient index ada687d..2f19e31 100755 --- a/pandoraclient +++ b/pandoraclient @@ -298,7 +298,25 @@ def organize(): def execute_organize(): + def get_empty_directories(): + empty_directories = [] + for absolute_path, dirnames, filenames in os.walk(volume_path, followlinks=True): + if not dirnames and not filenames: + empty_directories.append(absolute_path) + return empty_directories + + def remove_file(path): + print 'Removing "%s"' % path + try: + if os.path.isdir(path): + os.rmdir(path) + else: + os.remove(path) + except: + raise IOError('Could not remove file') + def rename_file(source, target): + print 'Renaming "%s" to "%s"' % (source, target) if not os.path.exists(source): raise IOError('Source does not exist') elif os.path.exists(target): @@ -315,22 +333,18 @@ def execute_organize(): sys.exit('%s not found' % FILES['organize']) data = ox.jsonc.load(open(FILES['organize'])) + old_empty_directories = get_empty_directories() remove = map(lambda x: os.path.join(volume_path, x), data['automatic']['remove']) rename = map(lambda x: map(lambda y: os.path.join(volume_path, y), x), data['automatic']['rename']) errors = [] for path in remove: - print 'Removing "%s"' % path try: - if os.path.isdir(path): - os.rmdir(path) - else: - os.remove(path) + remove_file(path) except: errors.append('Could not remove "%s"' % path) for paths in rename: source = paths[0] target = paths[1] + '.pandora' - print 'Renaming "%s" to "%s"' % (source, target) try: rename_file(source, target) except IOError as error: @@ -338,11 +352,21 @@ def execute_organize(): for paths in rename: source = paths[1] + '.pandora' target = paths[1] - print 'Renaming "%s" to "%s"' % (source, target) try: rename_file(source, target) except IOError as error: errors.append('Could not rename "%s" to "%s" (%s)' % (source, target, error)) + while True: + new_empty_directories = [path for path in get_empty_directories() if not path in old_empty_directories] + if new_empty_directories: + for path in new_empty_directories: + try: + remove_file(path) + except: + errors.append('Could not remove "%s"' % path) + else: + break + for error in errors: print error