]> diplodocus.org Git - flac-archive/blob - rewrite-tags
Implement (and tested) do_write.
[flac-archive] / rewrite-tags
1 #! /usr/bin/python
2
3 import os, sys
4 import subprocess
5 import tempfile
6 from errno import EEXIST
7 from subprocess import Popen, PIPE
8
9 from flac_archive.tags import Tags
10
11 class SubprocessError(Exception):
12 def __init__(self, status, command=None, stderr=None):
13 if command is None:
14 command_msg = None
15 else:
16 command_msg = ': ' + ' '.join(command)
17 if status < 0:
18 msg = 'exited due to signal %d%s'
19 else:
20 msg = 'exit status %d%s'
21 Exception.__init__(self, msg % (abs(status), command_msg))
22 self.status = status
23 self.command = command
24 self.stderr = stderr
25
26 def get_tags(fn):
27 tags = Tags()
28
29 command = ['metaflac', '--no-utf8-convert', '--export-tags-to=-', fn]
30 p = Popen(command, stdout=PIPE)
31 tags.load(p.stdout)
32
33 status = p.wait()
34 if status != 0:
35 raise SubprocessError(status, command=command, stderr=p.stderr)
36
37 return tags
38
39 def rewrite_track_tags(track, tags, fn, tmp):
40 tmp.write('\n'.join(tags.track(track)) + '\n')
41 tmp.close()
42 command = ['metaflac', '--no-utf8-convert', '--dont-use-padding',
43 '--remove-all-tags', '--import-tags-from', tmp.name, fn]
44 p = Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
45 stdout, stderr = p.communicate()
46 status = p.wait()
47 if status != 0:
48 raise SubprocessError(status, command=command, stderr=stdout)
49
50 def do_read(filenames):
51 # Use this mapping of tag names to sets of tag values to detect global tags.
52 all_tags = {}
53 # Build the collated result in this Tags object.
54 coll_tags = Tags()
55 # XXX The Tags interface is horrible. It's gotta be almost 10 years since
56 # I wrote it, so not surprising...
57 for fn in filenames:
58 tags = get_tags(fn)
59 track_tags = tags.get('TRACKNUMBER')
60 # this check belongs in Tags
61 if len(track_tags) != 1:
62 sys.stderr.write('bogus TRACKNUMBER %s: %s\n' % (track_tags, fn))
63 return 3
64 track = int(track_tags[0])
65 for tag, values in tags._global.iteritems():
66 # Makes no sense to save TRACKNUMBER in coll_tags.
67 if tag == 'TRACKNUMBER':
68 continue
69 for value in values:
70 if tag in all_tags:
71 all_tags[tag].add(value)
72 else:
73 all_tags[tag] = set([value])
74 coll_tags.set(tag, value, track)
75 for tag, values in all_tags.iteritems():
76 if len(values) == 1:
77 # Only one value for this tag, so add it to global tags.
78 coll_tags.set(tag, list(values)[0])
79 # And now remove it from each track tags.
80 for track, tags in coll_tags._tracks.iteritems():
81 del tags[tag]
82 print '\n'.join(coll_tags.all())
83 return 0
84
85 def do_write(args):
86 tags = Tags()
87 tags.load(open(args.pop(0)))
88 if len(args) != len(tags):
89 sys.stderr.write('expected %d flac files, got %d\n'
90 % (len(tags), len(args)))
91 return 4
92 artist = tags.get_path_safe('ARTIST')
93 album = tags.get_path_safe('ALBUM')
94 try:
95 os.mkdir(artist)
96 except OSError, e:
97 if e.errno != EEXIST:
98 raise
99 album_path = artist + '/' + album
100 try:
101 os.mkdir(album_path)
102 except OSError, e:
103 if e.errno != EEXIST:
104 raise
105 for i, old_fn in enumerate(args):
106 track = i + 1
107 fn = '%s/%s/%s.flac' % (artist, album, tags.make_filename(track))
108 if fn != old_fn:
109 os.rename(old_fn, fn)
110 tmp = tempfile.NamedTemporaryFile(delete=False)
111 try:
112 rewrite_track_tags(track, tags, fn, tmp)
113 finally:
114 try:
115 os.unlink(tmp.name)
116 except:
117 pass
118 return 0
119
120 def main(args):
121 if len(args) < 3:
122 return usage()
123 if args[1] == 'read':
124 return do_read(args[2:])
125 if args[1] == 'write':
126 return do_write(args[2:])
127 return usage()
128
129 def usage():
130 return 2
131
132 if __name__ == '__main__':
133 sys.exit(main(sys.argv))
134