]> diplodocus.org Git - flac-archive/blob - rewrite-tags
Start on a script to help rewrite tags en masse.
[flac-archive] / rewrite-tags
1 #! /usr/bin/python
2
3 import sys
4 from subprocess import Popen, PIPE
5
6 from org.diplodocus.util import run_or_die
7
8 from flac_archive.tags import Tags
9
10 class SubprocessError(Exception):
11 def __init__(self, status, stderr=None):
12 if status < 0:
13 msg = 'exited due to signal %d'
14 else:
15 msg = 'exit status %d'
16 Exception.__init__(self, msg % (status,))
17 self.status = status
18 self.stderr = stderr
19
20 def get_tags(fn):
21 tags = Tags()
22 p = Popen(['metaflac', '--no-utf8-convert', '--export-tags-to=-', fn],
23 stdout=PIPE)
24 tags.load(p.stdout)
25
26 status = p.wait()
27 if status != 0:
28 raise SubprocessError(status, p.stderr)
29
30 return tags
31
32 def do_read(filenames):
33 # Use this mapping of tag names to sets of tag values to detect global tags.
34 all_tags = {}
35 # Build the collated result in this Tags object.
36 coll_tags = Tags()
37 for fn in filenames:
38 tags = get_tags(fn)
39 track_tags = tags.get('TRACKNUMBER')
40 if len(track_tags) != 1:
41 raise Exception('bogus TRACKNUMBER %s for %s' % (track_tags, fn))
42 track = int(track_tags[0])
43 for tag, values in tags._global.iteritems():
44 for value in values:
45 if tag in all_tags:
46 all_tags[tag].add(value)
47 else:
48 all_tags[tag] = set([value])
49 coll_tags.set(tag, value, track)
50 for tag, values in all_tags.iteritems():
51 if len(values) == 1:
52 # Only one value for this tag, so add it to global tags.
53 coll_tags.set(tag, list(values)[0])
54 # And now remove it from each track tags.
55 for track, tags in coll_tags._tracks.iteritems():
56 del tags[tag]
57 print '\n'.join(coll_tags.all())
58
59 def main(args):
60 if len(args) < 3:
61 return usage()
62 if args[1] == 'read':
63 return do_read(args[2:])
64 if args[1] == 'write':
65 return do_write(args[2:])
66 return usage()
67
68 def usage():
69 return 2
70
71 if __name__ == '__main__':
72 sys.exit(main(sys.argv))
73