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