Finish working version of newpath
[ordnung.git] / ordnung.py
blob24b7fc58fadda539c623b765da6de01c1a861e69
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"] # 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 main():
43 # Handle arguments
44 usage = "Usage: %prog [options] directory pattern"
45 parser = OptionParser(usage=usage)
46 parser.add_option("-r", "--recursive", action="store_true",
47 dest="recursive", help="also move/copy files from sub-directories", default=False)
48 parser.add_option("-t", "--target", dest="target",
49 help="create new directory structure in directory TARGET (default=directory)")
50 (options, args) = parser.parse_args()
52 try:
53 base = args[0]
54 except IndexError:
55 print "You must specify a directory"
56 sys.exit()
58 try:
59 pattern = args[1]
60 except IndexError:
61 print "You must specify a pattern"
62 sys.exit()
64 if options.target != None:
65 target = options.target
66 else:
67 target = base
69 basepath = path(base)
70 if options.recursive:
71 files = basepath.walkfiles()
72 else:
73 files = basepath.files()
74 for file in files:
75 if issupportedfile(file):
76 print file
77 print newpath(file, target, pattern)
79 if __name__ == "__main__":
80 main()