Skip to content

Instantly share code, notes, and snippets.

@WGH-
Created July 9, 2014 17:01
Show Gist options
  • Select an option

  • Save WGH-/28e0e0f5ca683e0b39fc to your computer and use it in GitHub Desktop.

Select an option

Save WGH-/28e0e0f5ca683e0b39fc to your computer and use it in GitHub Desktop.
#!/usr/bin/env python2
# encoding: utf-8
import sys
import os
import codecs
import errno
import re
ALBUM_RE = re.compile(
r"(?P<date>\d{4}\.\d{2}\.\d{2}\ )"
r"(?P<id>\[.*\]\ )?"
r"(?P<name>[^\[]*)"
r"(?P<event>\[.*\])?"
)
def split_path(path):
l = []
separators = set((os.path.altsep, os.path.sep))
while path and path not in separators:
path, tail = os.path.split(path)
l.insert(0, tail)
if path:
l.insert(0, path)
return l
def process_file_everything(filename):
parts = split_path(filename)
while not parts[0].startswith("["):
parts.pop(0)
group, album = parts[:2]
group = re.search(r"\[(.*?)\]", group).group(1)
try:
d = ALBUM_RE.search(album).groupdict("")
except AttributeError:
print >>sys.stderr, "bad directory naming %r" % filename
return
for k, v in d.iteritems():
d[k] = v.strip()
date_inserted = False
with codecs.open(filename, 'r+', 'utf_8_sig') as f:
lines = f.readlines()
f.seek(0)
f.truncate()
for line in lines:
if line.startswith("REM DATE"):
line = "REM DATE %s\r\n" % d['date']
date_inserted = True
if line.startswith("FILE") and not date_inserted:
f.write("REM DATE %s\r\n" % d['date'])
date_inserted = True
if line.startswith("PERFORMER"):
line = 'PERFORMER "%s"\r\n' % group
f.write(line)
def main():
process_file = process_file_everything
for root, dirs, files in os.walk(u'.'):
for file in files:
if file.endswith('.cue'):
file = os.path.join(root, file)
try:
process_file(file)
except IOError as e:
if e.errno == errno.EACCES:
print >>sys.stderr, "RO-flag?"
raise
elif e.errno == errno.ENOENT:
print >>sys.stderr, "File not found? (happens with long names on Windows)"
pass
else:
raise
except UnicodeDecodeError as e:
print >>sys.stderr, `file`
raise
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment