Last active
August 29, 2015 14:19
-
-
Save tilboerner/2f84adbf683e411e7001 to your computer and use it in GitHub Desktop.
Get CherryMusic album art filenames for directories
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
"""{script} [-r] [-f DIR] [-h|--help] [STARTDIR] | |
Get CherryMusic album art filenames for subdirectories. | |
-r recursive lookup in subdirectories | |
-f DIR find and print only this directory's art name | |
-h or --help print this text and exit | |
""" | |
from __future__ import unicode_literals | |
from __future__ import print_function | |
import hashlib | |
import os | |
import sys | |
if sys.version_info < (3,): | |
sys.argv = [a.decode('UTF-8') for a in sys.argv] | |
__print = print | |
def print(*args, **kwargs): | |
enc = ((a.encode('UTF-8') if isinstance(a, unicode) else str(a)) for a in args) | |
__print(*enc, **kwargs) | |
try: | |
from shlex import quote | |
except ImportError: | |
from pipes import quote | |
startdir = '.' | |
recurse = False | |
find = None | |
encoding = 'UTF-8' | |
script, args = sys.argv[0], sys.argv[1:] | |
USAGE = __doc__.format(script=script) | |
try: | |
while args and args[0].startswith('-'): | |
option = args.pop(0) | |
if option == '-r': | |
recurse = True | |
elif option == '-f': | |
find = args.pop(0) + '' | |
elif option in ('-h', '--help'): | |
print(USAGE) | |
sys.exit(0) | |
else: | |
raise ValueError("Unknown option: " + repr(option)) | |
if args: | |
startdir = args.pop(0) + '' | |
if args: | |
raise ValueError("Too many argument(s): " + ', '.join(args)) | |
except Exception as e: | |
print(str(e), USAGE, sep='\n', file=sys.stderr) | |
sys.exit(1) | |
if not os.path.isdir(startdir): | |
print('Directory not found:', startdir, file=sys.stderr) | |
sys.exit(1) | |
def md5ify(dirname): | |
encoded_dirname = dirname.encode(encoding) | |
hashed = hashlib.md5(encoded_dirname).hexdigest() | |
return hashed + '.thumb' | |
def dirnames(): | |
walkdir = os.path.abspath(startdir) | |
prefixlen = len(walkdir.rstrip(os.path.sep) + os.path.sep) | |
for dirpath, dirnames, filenames in os.walk(walkdir): | |
reldir = dirpath[prefixlen:] | |
for subdir in sorted(dirnames): | |
dirname = os.path.join(reldir, subdir) | |
if not find: | |
yield dirname | |
elif dirname == find: | |
yield dirname | |
return | |
if not recurse: | |
return | |
for dirname in dirnames(): | |
out = [quote(dirname), md5ify(dirname)] | |
if find: | |
out.pop(0) | |
find = None | |
print(*out, sep='\t') | |
if find: | |
print('directory', quote(find), 'not found', file=sys.stderr) | |
sys.exit(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment