7 from optparse
import OptionParser
, OptionGroup
8 from tag_wrapper
import tag
10 ACCEPTEXTS
= [".ogg", ".mp3"] # Keep it simple for now
12 def issupportedfile(name
):
13 for ext
in ACCEPTEXTS
:
14 if os
.path
.splitext(name
)[1] == ext
:
20 if not os
.path
.isdir(newdir
):
24 def newpath(file, pattern
):
25 # Create the tokens dictionary
28 # TODO: add tracknumber, disknumber and possibily compilation
29 for t
in ["title", "artist", "album artist", "album", "composer", "genre", "date"]:
34 # %album artist% is %artist% if nothing can be found in the tags
35 if tokens
["album artist"] is None:
36 tokens
["album artist"] = tokens
["artist"]
38 # Now replace all tokens by their values
41 if tokens
[i
] is not None:
42 pattern
= pattern
.replace(repl
, tokens
[i
][0])
44 # Add the extension and return the new path
45 return pattern
+ os
.path
.splitext(file)[1]
48 def safeprint(string
):
50 Print string first trying to normally encode it, sending it to the
51 console in "raw" UTF-8 if it fails.
53 This is a workaround for Windows's broken console
57 except UnicodeEncodeError:
58 print string
.encode("utf-8")
61 def files_to_move(base_dir
, pattern
, recursive
=False):
62 # Figure out which files to move where
63 basepath
= path(base_dir
)
65 files
= basepath
.walkfiles()
67 files
= basepath
.files()
72 if issupportedfile(file):
73 t
= [ file, newpath(file, pattern
) ]
74 files_return
.append(t
)
79 # Pseudo-enum for actions
85 usage
= "Usage: %prog [options] directory pattern"
86 parser
= OptionParser(usage
=usage
)
87 parser
.add_option("-r", "--recursive", action
="store_true",
88 dest
="recursive", help="also move/copy files from sub-directories", default
=False)
90 actions
= OptionGroup(parser
, "Possible actions")
91 actions
.add_option("--preview", "-p", action
="store_const",
92 const
=PREVIEW
, dest
="action", help="preview, don't make any changes (default)")
93 actions
.add_option("--copy", "-c", action
="store_const",
94 const
=COPY
, dest
="action", help="copy files")
95 actions
.add_option("--move", "-m", action
="store_const",
96 const
=MOVE
, dest
="action", help="move files")
97 parser
.add_option_group(actions
)
98 (options
, args
) = parser
.parse_args()
103 print "You must specify a directory"
109 print "You must specify a pattern"
113 for i
in files_to_move(base_dir
=base
,
114 pattern
=pattern
, recursive
=options
.recursive
):
115 if options
.action
== MOVE
:
116 mkdir(os
.path
.split(i
[1])[0])
117 shutil
.move(i
[0], i
[1])
118 elif options
.action
== COPY
:
119 mkdir(os
.path
.split(i
[1])[0])
120 shutil
.copy2(i
[0], i
[1])
122 safeprint (i
[0] + " --> " + i
[1])
125 if __name__
== "__main__":