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
53 def __valid_dict_line (self, line):
60 # Comment lines are not really valid
61 if re.match ('^(\s*#.*|\s*)$', line):
64 # Make sure that there is a definition and it is valid
66 (regex, directory) = line.split('=')
68 directory = directory.strip()
72 # Make sure they have length
73 if len(regex) <= 0 or len(directory) <= 0:
76 # I guess that it's valid now
80 """Parses a dictionary file containing the sort definitions in the form:
81 REGEX_PATTERN = DIRECTORY
83 Returns a list of tuples of the form (compiled_regex, to_directory)"""
86 f = open(self.options.dict_file, 'r', 0)
88 raw_lines = f.readlines()
92 logging.critical ('Opening dictionary: %s FAILED' % self.options.dict_file)
95 ### Find all of the valid lines in the file
96 valid_lines = [l for l in raw_lines if self.__valid_dict_line (l)]
98 # Set up variable for result
101 ### Split each line into a tuple, and strip each element of spaces
102 for l in valid_lines:
103 (regex, directory) = l.split('=')
104 regex = regex.strip()
105 directory = directory.strip()
107 # Fix up the directory if necessary
108 if directory[0] != '/':
109 directory = os.path.join (self.options.output_dir, directory)
119 result.append ( (re.compile (regex), directory) )
121 ### Give some information about the dictionary we are using
122 logging.info ('Successfully loaded %d records from %s\n' % \
123 (len(result), self.options.dict_file))
125 return tuple (result)
127 def get_matches(self, files, pattern):
128 """get_matches(files, pattern):
131 pattern is type sre.SRE_Pattern
133 Returns a list of the files matching the pattern as type sre.SRE_Match."""
135 matches = [m for m in files if pattern.search(m)]
138 def as_makedirs (self, dirname):
139 """Call os.makedirs(dirname), but check first whether we are in pretend
140 mode, or if we're running interactively."""
142 if not os.path.isdir (dirname):
144 if self.options.pretend:
145 logging.info ('Will create directory %s' % dirname)
148 if self.get_user_choice ('Make directory?: %s' % (dirname, )):
151 os.makedirs (dirname)
152 logging.info ('Created directory %s' % dirname)
154 logging.critical ('Failed to create directory %s' % dirname)
159 def as_move_single_file (self, f, fromdir, todir):
160 """Move the single file named $f from the directory $fromdir to the
163 srcname = os.path.join (fromdir, f)
164 dstname = os.path.join (todir, f)
166 if self.options.pretend:
167 logging.info ('Will move %s to %s' % (f, todir))
170 if self.get_user_choice ('Move file?: %s --> %s' % (srcname, dstname)):
172 shutil.move (srcname, dstname)
173 logging.info ('Moved %s to %s' % (f, todir))
175 logging.critical ('FAILED to move %s to %s' % (f, todir))
180 def move_files(self, files, fromdir, todir):
181 """move_files(files, fromdir, todir):
182 Move the files represented by the list FILES from FROMDIR to TODIR"""
186 ## Check for a non-default directory
188 todir = os.path.join(self.options.output_dir, todir)
190 ## Create the directory if it doesn't exist
191 ret = self.as_makedirs (todir)
194 # we cannot continue, since we can't make the directory
197 ## Try to move every file, one at a time
199 ret = self.as_move_single_file (f, fromdir, todir)
202 # something bad happened when moving a file
207 def __dir_walker(self, dict, root, dirs, files):
209 ## Get all of the files in the directory that are of the correct types
210 types_re = re.compile(TYPES_REGEX, re.IGNORECASE)
211 raw_matches = [f for f in files if types_re.match(f)]
213 ### Loop through the dictionary and try to move everything that matches
214 for regex, todir in dict:
215 matches = self.get_matches(raw_matches, regex)
217 ## Move the files if we've found some
219 self.move_files(matches, root, todir)
221 def get_user_choice(self, prompt):
223 # If we're not in interactive mode, then always return True
224 if self.options.interactive == False:
227 # Get the user's choice since we're not in interactive mode
230 s = raw_input('%s [y/N]: ' % (prompt, )).lower()
232 if s == 'y' or s == 'yes':
235 if s == 'n' or s == 'no' or s == '':
238 print 'Response not understood, try again.'
242 ## Print the program's header
243 logging.info ('Regular Expression File Sorter (aka animesorter)')
244 logging.info ('=' * 80)
245 logging.info ('Copyright (c) 2005-2007, Ira W. Snyder (devel@irasnyder.com)')
246 logging.info ('This program is licensed under the GNU GPL v2')
249 ## Parse the dictionary
250 dict = self.parse_dict()
252 if self.options.recursive:
253 ## Start walking through directories
254 for root, dirs, files in os.walk(self.options.start_dir):
255 self.__dir_walker(dict, root, dirs, files)
257 self.__dir_walker(dict, self.options.start_dir,
258 [d for d in os.listdir(self.options.start_dir) if os.path.isdir(d)],
259 [f for f in os.listdir(self.options.start_dir) if os.path.isfile(f)])
266 logging.basicConfig (level=logging.INFO, format='%(message)s')
268 ### Get the program options
269 parser = OptionParser()
270 parser.add_option('-q', '--quiet', action='store_true', dest='quiet',
271 default=False, help="Don't print status messages to stdout")
272 parser.add_option('-d', '--dict', dest='dict_file', default=DICT_FILE,
273 help='Read dictionary from FILE', metavar='FILE')
274 parser.add_option('-n', '--not-recursive', action='store_false', dest='recursive',
275 default=True, help='don\'t run recursively')
276 parser.add_option('-s', '--start-dir', dest='start_dir', default=WORK_DIR,
277 help='Start running at directory DIR', metavar='DIR')
278 parser.add_option('-o', '--output-dir', dest='output_dir', default=SORT_DIR,
279 help='Sort files into DIR', metavar='DIR')
280 parser.add_option('-i', '--interactive', dest='interactive', default=False,
281 help='Confirm each move', action='store_true')
282 parser.add_option('-p', '--pretend', dest='pretend', default=False,
283 help='Enable pretend mode', action='store_true')
286 (options, args) = parser.parse_args()
288 ## Correct directories
289 options.dict_file = os.path.abspath(os.path.expanduser(options.dict_file))
290 options.start_dir = os.path.abspath(os.path.expanduser(options.start_dir))
291 options.output_dir = os.path.abspath(os.path.expanduser(options.output_dir))
293 # Change the loglevel if we're running in quiet mode
295 logging.getLogger().setLevel (logging.CRITICAL)
297 as = AnimeSorter2(options)
300 if __name__ == '__main__':