Workaround for Windows' broken console
[ordnung.git] / ordnung.py
blobff6f11b19c8536a3401ba75d05b7be39533f9013
1 from path import path
2 import fnmatch
3 import os, sys
5 from optparse import OptionParser
6 from tag_wrapper import tag
8 ACCEPTEXTS = [".ogg", ".mp3"] # Keep it simple for now
10 def issupportedfile(name):
11 for ext in ACCEPTEXTS:
12 if os.path.splitext(name)[1] == ext:
13 return True
14 return False
16 def newpath(file, target, pattern):
17 # Create the tokens dictionary
18 tokens = {}
19 tags = tag(file)
20 # TODO: add tracknumber, disknumber and possibily compilation
21 for t in ["title", "artist", "album artist", "album", "composer", "genre", "date"]:
22 try:
23 tokens[t] = tags[t]
24 except KeyError:
25 tokens[t] = None
26 # %album artist% is %artist% if nothing can be found in the tags
27 if tokens["album artist"] == None:
28 tokens["album artist"] = tokens["artist"]
30 # That appears in no tag
31 tokens["base"] = target
33 # Now replace all tokens by their values
34 for i in tokens:
35 repl = "%" + i + "%"
36 if tokens[i] != None:
37 pattern = pattern.replace(repl, tokens[i][0])
39 # Add the extension and return the new path
40 return pattern + os.path.splitext(file)[1]
42 def safeprint(string):
43 """
44 Print string first trying to normally encode it, sending it to the
45 console in "raw" UTF-8 if it fails.
47 This is a workaround for Windows's broken console
48 """
49 try:
50 print string
51 except UnicodeEncodeError:
52 print string.encode("utf-8")
54 def main():
55 # Handle arguments
56 usage = "Usage: %prog [options] directory pattern"
57 parser = OptionParser(usage=usage)
58 parser.add_option("-r", "--recursive", action="store_true",
59 dest="recursive", help="also move/copy files from sub-directories", default=False)
60 parser.add_option("-t", "--target", dest="target",
61 help="create new directory structure in directory TARGET (default=directory)")
62 (options, args) = parser.parse_args()
64 try:
65 base = args[0]
66 except IndexError:
67 print "You must specify a directory"
68 sys.exit()
70 try:
71 pattern = args[1]
72 except IndexError:
73 print "You must specify a pattern"
74 sys.exit()
76 if options.target != None:
77 target = options.target
78 else:
79 target = base
81 basepath = path(base)
82 if options.recursive:
83 files = basepath.walkfiles()
84 else:
85 files = basepath.files()
86 for file in files:
87 if issupportedfile(file):
88 safeprint(file)
89 safeprint(newpath(file, target, pattern))
91 if __name__ == "__main__":
92 main()