2 # vim: set ts=4 sts=4 sw=4 textwidth=92 expandtab:
5 The animesorter program
7 This will sort arbitrary files into directories by regular expression.
10 __author__ = "Ira W. Snyder (devel@irasnyder.com)"
11 __copyright__ = "Copyright (c) 2006,2007 Ira W. Snyder (devel@irasnyder.com)"
12 __license__ = "GNU GPL v2 (or, at your option, any later version)"
14 # animesorter2.py -- a regular expression file-sorting utility
16 # Copyright (C) 2006,2007 Ira W. Snyder (devel@irasnyder.com)
18 # This program is free software; you can redistribute it and/or modify
19 # it under the terms of the GNU General Public License as published by
20 # the Free Software Foundation; either version 2 of the License, or
21 # (at your option) any later version.
23 # This program is distributed in the hope that it will be useful,
24 # but WITHOUT ANY WARRANTY; without even the implied warranty of
25 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26 # GNU General Public License for more details.
28 # You should have received a copy of the GNU General Public License
29 # along with this program; if not, write to the Free Software
30 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
39 from optparse import OptionParser
41 ### Default Configuration Variables ###
42 DICT_FILE = os.path.join ('~','.config','animesorter2','animesorter.dict')
43 WORK_DIR = os.path.join ('~','downloads','usenet')
44 SORT_DIR = os.path.join ('/','data','Anime')
45 TYPES_REGEX = '.*(avi|ogm|mkv|mp4|\d\d\d)$'
50 def __init__(self, options):
51 self.options = options
54 """Parses a dictionary file containing the sort definitions in the form:
57 Returns a list of tuples of the form (compiled_regex, to_directory)"""
60 f = open(self.options.dict_file, 'r', 0)
66 logging.critical ('Opening dictionary: %s FAILED' % self.options.dict_file)
69 ### Get a LIST containing each line in the file
70 lines = [l for l in data.split('\n') if len(l) > 0]
72 ### Remove comments / blank lines (zero length lines already removed above)
73 regex = re.compile ('^\s*#.*$')
74 lines = [l for l in lines if not re.match (regex, l)]
75 regex = re.compile ('^\s*$')
76 lines = [l for l in lines if not re.match (regex, l)]
78 ### Split each line into a tuple, and strip each element of spaces
79 result = self.split_lines(lines)
80 result = [(re.compile(r), d) for r, d in result]
82 ### Give some information about the dictionary we are using
83 logging.info ('Successfully loaded %d records from %s\n' % \
84 (len(result), self.options.dict_file))
88 def split_lines(self, lines):
99 logging.warning ('Bad line in dictionary: "%s"' % l)
102 result.append((r, d))
106 def get_matches(self, files, pattern):
107 """get_matches(files, pattern):
110 pattern is type sre.SRE_Pattern
112 Returns a list of the files matching the pattern as type sre.SRE_Match."""
114 matches = [m for m in files if pattern.search(m)]
117 def as_makedirs (self, dirname):
118 """Call os.makedirs(dirname), but check first whether we are in pretend
119 mode, or if we're running interactively."""
121 if not os.path.isdir (dirname):
123 if self.options.pretend:
124 logging.info ('Will create directory %s' % dirname)
127 if self.get_user_choice ('Make directory?: %s' % (dirname, )):
130 os.makedirs (dirname)
131 logging.info ('Created directory %s' % dirname)
133 logging.critical ('Failed to create directory %s' % dirname)
138 def as_move_single_file (self, f, fromdir, todir):
139 """Move the single file named $f from the directory $fromdir to the
142 srcname = os.path.join (fromdir, f)
143 dstname = os.path.join (todir, f)
145 if self.options.pretend:
146 logging.info ('Will move %s to %s' % (f, todir))
149 if self.get_user_choice ('Move file?: %s --> %s' % (srcname, dstname)):
151 shutil.move (srcname, dstname)
152 logging.info ('Moved %s to %s' % (f, todir))
154 logging.critical ('FAILED to move %s to %s' % (f, todir))
159 def move_files(self, files, fromdir, todir):
160 """move_files(files, fromdir, todir):
161 Move the files represented by the list FILES from FROMDIR to TODIR"""
165 ## Check for a non-default directory
167 todir = os.path.join(self.options.output_dir, todir)
169 ## Create the directory if it doesn't exist
170 ret = self.as_makedirs (todir)
173 # we cannot continue, since we can't make the directory
176 ## Try to move every file, one at a time
178 ret = self.as_move_single_file (f, fromdir, todir)
181 # something bad happened when moving a file
186 def __dir_walker(self, dict, root, dirs, files):
188 ## Get all of the files in the directory that are of the correct types
189 types_re = re.compile(TYPES_REGEX, re.IGNORECASE)
190 raw_matches = [f for f in files if types_re.match(f)]
192 ### Loop through the dictionary and try to move everything that matches
193 for regex, todir in dict:
194 matches = self.get_matches(raw_matches, regex)
196 ## Move the files if we've found some
198 self.move_files(matches, root, todir)
200 def get_user_choice(self, prompt):
202 # If we're not in interactive mode, then always return True
203 if self.options.interactive == False:
206 # Get the user's choice since we're not in interactive mode
209 s = raw_input('%s [y/N]: ' % (prompt, )).lower()
211 if s == 'y' or s == 'yes':
214 if s == 'n' or s == 'no' or s == '':
217 print 'Response not understood, try again.'
221 ## Print the program's header
222 logging.info ('Regular Expression File Sorter (aka animesorter)')
223 logging.info ('=' * 80)
224 logging.info ('Copyright (c) 2005-2007, Ira W. Snyder (devel@irasnyder.com)')
225 logging.info ('This program is licensed under the GNU GPL v2')
228 ## Parse the dictionary
229 dict = self.parse_dict()
231 if self.options.recursive:
232 ## Start walking through directories
233 for root, dirs, files in os.walk(self.options.start_dir):
234 self.__dir_walker(dict, root, dirs, files)
236 self.__dir_walker(dict, self.options.start_dir,
237 [d for d in os.listdir(self.options.start_dir) if os.path.isdir(d)],
238 [f for f in os.listdir(self.options.start_dir) if os.path.isfile(f)])
245 logging.basicConfig (level=logging.INFO, format='%(message)s')
247 ### Get the program options
248 parser = OptionParser()
249 parser.add_option('-q', '--quiet', action='store_true', dest='quiet',
250 default=False, help="Don't print status messages to stdout")
251 parser.add_option('-d', '--dict', dest='dict_file', default=DICT_FILE,
252 help='Read dictionary from FILE', metavar='FILE')
253 parser.add_option('-n', '--not-recursive', action='store_false', dest='recursive',
254 default=True, help='don\'t run recursively')
255 parser.add_option('-s', '--start-dir', dest='start_dir', default=WORK_DIR,
256 help='Start running at directory DIR', metavar='DIR')
257 parser.add_option('-o', '--output-dir', dest='output_dir', default=SORT_DIR,
258 help='Sort files into DIR', metavar='DIR')
259 parser.add_option('-i', '--interactive', dest='interactive', default=False,
260 help='Confirm each move', action='store_true')
261 parser.add_option('-p', '--pretend', dest='pretend', default=False,
262 help='Enable pretend mode', action='store_true')
265 (options, args) = parser.parse_args()
267 ## Correct directories
268 options.dict_file = os.path.abspath(os.path.expanduser(options.dict_file))
269 options.start_dir = os.path.abspath(os.path.expanduser(options.start_dir))
270 options.output_dir = os.path.abspath(os.path.expanduser(options.output_dir))
272 # Change the loglevel if we're running in quiet mode
274 logging.getLogger().setLevel (logging.CRITICAL)
276 as = AnimeSorter2(options)
279 if __name__ == '__main__':