remove empty folders in `storage`

Kyle
2018-08-02T15:18:00Z

zot_rm_empty_folders.py

| #!/usr/bin/env python
| # coding: utf-8
|
| from __future__ import print_function
|
| import configparser
| import re
| import shutil
| import sys
|
| try:
| from pathlib import Path
| except ImportError:
| from pathlib2 import Path
|
|
| def get_zotero_storage_dir():
| '''
| Get the Zotero storage dir and in PosixPath type
| '''
| profile_dirs = {
| 'darwin': Path.home() / 'Library/Application Support/Zotero',
| 'linux': Path.home() / '.zotero/zotero',
| 'linux2': Path.home() / '.zotero/zotero',
| 'win32': Path.home() / 'AppData/Roaming/Zotero/Zotero'
| }
| profile_dir = profile_dirs[sys.platform]
|
| config = configparser.ConfigParser()
| config.read('{}'.format(profile_dir / 'profiles.ini'))
| configs_loc = profile_dir / config['Profile0']['Path'] / 'prefs.js'
| configs = configs_loc.read_text()
|
| zotero_data_pat = re.compile(
| r'user_pref\("extensions.zotero.dataDir",\ "(?P<zotero_data>.+)"\);')
| zotero_data_dir = Path(zotero_data_pat.search(configs).group('zotero_data'))
| storage_dir = zotero_data_dir / 'storage'
| return storage_dir
|
|
| def get_empty_folders(zotero_storage_dir):
| '''
| Get a list of empty dir in string type.
| '''
| return [
| p.as_posix() for p in zotero_storage_dir.iterdir()
| if (not p.is_file()) and (
| not len([f for f in list(p.iterdir()) if f.name[0] != '.']))
| ]
|
|
| if __name__ == '__main__':
| zotero_storage_dir = get_zotero_storage_dir()
| dirs_to_remove = get_empty_folders(zotero_storage_dir)
| try:
| import click
| print('The following folders contain no attachments:')
| print('\n '.join([''] + dirs_to_remove))
| if click.confirm('Do you want remove them?', default=True):
| [shutil.rmtree(p, ignore_errors=True) for p in dirs_to_remove]
| except ImportError:
| print(
| 'The following folders containing no attachments will be removed:')
| print('\n '.join([''] + dirs_to_remove))
| [shutil.rmtree(p, ignore_errors=True) for p in dirs_to_remove]