Update parser
[animesorter.git] / animesorter2.py
1 #!/usr/bin/env python
2 # vim: set ts=4 sts=4 sw=4 textwidth=92 expandtab:
3
4 """
5 The animesorter program
6
7 This will sort arbitrary files into directories by regular expression.
8 """
9
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)"
13
14 #    animesorter2.py -- a regular expression file-sorting utility
15 #
16 #    Copyright (C) 2006,2007  Ira W. Snyder (devel@irasnyder.com)
17 #
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.
22 #
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.
27 #
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
31
32
33 import os
34 import re
35 import sys
36 import errno
37 import shutil
38 import logging
39 from optparse import OptionParser
40
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)$'
46
47
48 class AnimeSorter2:
49
50     def __init__(self, options):
51         self.options = options
52
53     def __valid_dict_line (self, line):
54         if len(line) <= 0:
55             return False
56
57         if '=' not in line:
58             return False
59
60         # Comment lines are not really valid
61         if re.match ('^(\s*#.*|\s*)$', line):
62             return False
63
64         # Make sure that there is a definition and it is valid
65         try:
66             (regex, directory) = line.split('=')
67             regex = regex.strip()
68             directory = directory.strip()
69         except:
70             return False
71
72         # Make sure they have length
73         if len(regex) <= 0 or len(directory) <= 0:
74             return False
75
76         # I guess that it's valid now
77         return True
78
79     def parse_dict(self):
80         """Parses a dictionary file containing the sort definitions in the form:
81         REGEX_PATTERN = DIRECTORY
82
83         Returns a list of tuples of the form (compiled_regex, to_directory)"""
84
85         try:
86             f = open(self.options.dict_file, 'r', 0)
87             try:
88                 raw_lines = f.readlines()
89             finally:
90                 f.close()
91         except IOError:
92             logging.critical ('Opening dictionary: %s FAILED' % self.options.dict_file)
93             sys.exit()
94
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)]
97
98         # Set up variable for result
99         result = []
100
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()
106
107             # Fix up the directory if necessary
108             if directory[0] != '/':
109                 directory = os.path.join (self.options.output_dir, directory)
110
111             # Fix up the regex
112             if regex[0] != '^':
113                 regex = '^' + regex
114
115             if regex[-1] != '$':
116                 regex += '$'
117
118             # Store the result
119             result.append ( (re.compile (regex), directory) )
120
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))
124
125         return tuple (result)
126
127     def get_matches(self, files, pattern):
128         """get_matches(files, pattern):
129
130         files is type LIST
131         pattern is type sre.SRE_Pattern
132
133         Returns a list of the files matching the pattern as type sre.SRE_Match."""
134
135         matches = [m for m in files if pattern.search(m)]
136         return matches
137
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."""
141
142         if not os.path.isdir (dirname):
143
144             if self.options.pretend:
145                 logging.info ('Will create directory %s' % dirname)
146                 return 0
147
148             if self.get_user_choice ('Make directory?: %s' % (dirname, )):
149
150                 try:
151                     os.makedirs (dirname)
152                     logging.info ('Created directory %s' % dirname)
153                 except:
154                     logging.critical ('Failed to create directory %s' % dirname)
155                     return errno.EIO
156
157         return 0
158
159     def as_move_single_file (self, f, fromdir, todir):
160         """Move the single file named $f from the directory $fromdir to the
161            directory $todir"""
162
163         srcname = os.path.join (fromdir, f)
164         dstname = os.path.join (todir, f)
165
166         if self.options.pretend:
167             logging.info ('Will move %s to %s' % (f, todir))
168             return 0 # success
169
170         if self.get_user_choice ('Move file?: %s --> %s' % (srcname, dstname)):
171             try:
172                 shutil.move (srcname, dstname)
173                 logging.info ('Moved %s to %s' % (f, todir))
174             except:
175                 logging.critical ('FAILED to move %s to %s' % (f, todir))
176                 return errno.EIO
177
178         return 0
179
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"""
183
184         ret = 0
185
186         ## Check for a non-default directory
187         if todir[0] != '/':
188             todir = os.path.join(self.options.output_dir, todir)
189
190         ## Create the directory if it doesn't exist
191         ret = self.as_makedirs (todir)
192
193         if ret:
194             # we cannot continue, since we can't make the directory
195             return ret
196
197         ## Try to move every file, one at a time
198         for f in files:
199             ret = self.as_move_single_file (f, fromdir, todir)
200
201             if ret:
202                 # something bad happened when moving a file
203                 break
204
205         return ret
206
207     def __dir_walker(self, dict, root, dirs, files):
208
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)]
212
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)
216
217             ## Move the files if we've found some
218             if len(matches) > 0:
219                 self.move_files(matches, root, todir)
220
221     def get_user_choice(self, prompt):
222
223         # If we're not in interactive mode, then always return True
224         if self.options.interactive == False:
225             return True
226
227         # Get the user's choice since we're not in interactive mode
228         done = False
229         while not done:
230             s = raw_input('%s [y/N]: ' % (prompt, )).lower()
231
232             if s == 'y' or s == 'yes':
233                 return True
234
235             if s == 'n' or s == 'no' or s == '':
236                 return False
237
238             print 'Response not understood, try again.'
239
240     def main(self):
241
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')
247         logging.info ('')
248
249         ## Parse the dictionary
250         dict = self.parse_dict()
251
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)
256         else:
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)])
260
261
262 ### MAIN IS HERE ###
263 def main():
264
265     # Set up the logger
266     logging.basicConfig (level=logging.INFO, format='%(message)s')
267
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')
284
285     ## Parse the options
286     (options, args) = parser.parse_args()
287
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))
292
293     # Change the loglevel if we're running in quiet mode
294     if options.quiet:
295         logging.getLogger().setLevel (logging.CRITICAL)
296
297     as = AnimeSorter2(options)
298     as.main()
299
300 if __name__ == '__main__':
301     main ()
302