Remove unused regex.
[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
46 class AnimeSorter2:
47
48     def __init__(self, options):
49         self.options = options
50         self.dict = None
51
52     def __valid_dict_line (self, line):
53         if len(line) <= 0:
54             return False
55
56         if '=' not in line:
57             return False
58
59         # Comment lines are not really valid
60         if re.match ('^(\s*#.*|\s*)$', line):
61             return False
62
63         # Make sure that there is a definition and it is valid
64         try:
65             (regex, directory) = line.split('=')
66             regex = regex.strip()
67             directory = directory.strip()
68         except:
69             return False
70
71         # Make sure they have length
72         if len(regex) <= 0 or len(directory) <= 0:
73             return False
74
75         # I guess that it's valid now
76         return True
77
78     def parse_dict(self):
79         """Parses a dictionary file containing the sort definitions in the form:
80         REGEX_PATTERN = DIRECTORY
81
82         Returns a list of tuples of the form (compiled_regex, to_directory)"""
83
84         try:
85             f = open(self.options.dict_file, 'r', 0)
86             try:
87                 raw_lines = f.readlines()
88             finally:
89                 f.close()
90         except IOError:
91             logging.critical ('Opening dictionary: %s FAILED' % self.options.dict_file)
92             sys.exit()
93
94         ### Find all of the valid lines in the file
95         valid_lines = [l for l in raw_lines if self.__valid_dict_line (l)]
96
97         # Set up variable for result
98         result = []
99
100         ### Split each line into a tuple, and strip each element of spaces
101         for l in valid_lines:
102             (regex, directory) = l.split('=')
103             regex = regex.strip()
104             directory = directory.strip()
105
106             # Fix up the directory if necessary
107             if directory[0] != '/':
108                 directory = os.path.join (self.options.output_dir, directory)
109
110             # Fix up the regex
111             if regex[0] != '^':
112                 regex = '^' + regex
113
114             if regex[-1] != '$':
115                 regex += '$'
116
117             # Store the result
118             result.append ( (re.compile (regex), directory) )
119
120         ### Give some information about the dictionary we are using
121         logging.info ('Successfully loaded %d records from %s\n' % \
122                 (len(result), self.options.dict_file))
123
124         return tuple (result)
125
126     def as_makedirs (self, dirname):
127         """Call os.makedirs(dirname), but check first whether we are in pretend
128            mode, or if we're running interactively."""
129
130         if not os.path.isdir (dirname):
131
132             if self.options.pretend:
133                 logging.info ('Will create directory %s' % dirname)
134                 return 0
135
136             if self.get_user_choice ('Make directory?: %s' % (dirname, )):
137
138                 try:
139                     os.makedirs (dirname)
140                     logging.info ('Created directory %s' % dirname)
141                 except:
142                     logging.critical ('Failed to create directory %s' % dirname)
143                     return errno.EIO
144
145         return 0
146
147     def as_move_single_file (self, f, fromdir, todir):
148         """Move the single file named $f from the directory $fromdir to the
149            directory $todir"""
150
151         srcname = os.path.join (fromdir, f)
152         dstname = os.path.join (todir, f)
153
154         if self.options.pretend:
155             logging.info ('Will move %s to %s' % (f, todir))
156             return 0 # success
157
158         if self.get_user_choice ('Move file?: %s --> %s' % (srcname, dstname)):
159             try:
160                 shutil.move (srcname, dstname)
161                 logging.info ('Moved %s to %s' % (f, todir))
162             except:
163                 logging.critical ('FAILED to move %s to %s' % (f, todir))
164                 return errno.EIO
165
166         return 0
167
168     def move_files(self, files, fromdir, todir):
169         """move_files(files, fromdir, todir):
170         Move the files represented by the list FILES from FROMDIR to TODIR"""
171
172         ret = 0
173
174         # Leave immediately if we have nothing to do
175         if len(files) <= 0:
176             return ret
177
178         ## Create the directory if it doesn't exist
179         ret = self.as_makedirs (todir)
180
181         if ret:
182             # we cannot continue, since we can't make the directory
183             return ret
184
185         ## Try to move every file, one at a time
186         for f in files:
187             ret = self.as_move_single_file (f, fromdir, todir)
188
189             if ret:
190                 # something bad happened when moving a file
191                 break
192
193         return ret
194
195     def __dir_walker(self, rootdir, files):
196
197         for (r,d) in self.dict:
198             matches = [f for f in files if r.match(f)]
199             self.move_files (matches, rootdir, d)
200
201     def get_user_choice(self, prompt):
202
203         # If we're not in interactive mode, then always return True
204         if self.options.interactive == False:
205             return True
206
207         # Get the user's choice since we're not in interactive mode
208         done = False
209         while not done:
210             s = raw_input('%s [y/N]: ' % (prompt, )).lower()
211
212             if s == 'y' or s == 'yes':
213                 return True
214
215             if s == 'n' or s == 'no' or s == '':
216                 return False
217
218             print 'Response not understood, try again.'
219
220     def main(self):
221
222         ## Print the program's header
223         logging.info ('Regular Expression File Sorter (aka animesorter)')
224         logging.info ('=' * 80)
225         logging.info ('Copyright (c) 2005-2007, Ira W. Snyder (devel@irasnyder.com)')
226         logging.info ('This program is licensed under the GNU GPL v2')
227         logging.info ('')
228
229         ## Parse the dictionary
230         self.dict = self.parse_dict()
231
232         if self.options.recursive:
233             ## Start walking through directories
234             for root, dirs, files in os.walk(self.options.start_dir):
235                 self.__dir_walker(root, files)
236         else:
237             self.__dir_walker(self.options.start_dir, [f for f in
238                     os.listdir(self.options.start_dir) if os.path.isfile(f)])
239
240
241 ### MAIN IS HERE ###
242 def main():
243
244     # Set up the logger
245     logging.basicConfig (level=logging.INFO, format='%(message)s')
246
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')
263
264     ## Parse the options
265     (options, args) = parser.parse_args()
266
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))
271
272     # Change the loglevel if we're running in quiet mode
273     if options.quiet:
274         logging.getLogger().setLevel (logging.CRITICAL)
275
276     as = AnimeSorter2(options)
277     as.main()
278
279 if __name__ == '__main__':
280     main ()
281