Subversion Repositories programming

Rev

Rev 368 | Rev 373 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
181 ira 1
#!/usr/bin/env python
2
 
3
# Copyright: Ira W. Snyder (devel@irasnyder.com)
4
# License: GNU General Public License v2 (or at your option, any later version)
5
 
371 ira 6
import os
7
import re
8
import sys
9
import errno
10
import shutil
181 ira 11
from optparse import OptionParser
12
 
13
### Default Configuration Variables ###
14
DICT_FILE = '~/.config/animesorter2/animesorter.dict'
15
WORK_DIR =  '~/downloads/usenet'
16
SORT_DIR =  '/data/Anime'
17
TYPES_REGEX = '.*(avi|ogm|mkv|mp4|\d\d\d)$'
18
 
368 ira 19
### Functions for the printing system
20
def print_prog_header():
21
    print 'Regular Expression File Sorter (aka animesorter)'
22
    print '================================================================================'
23
    print 'Copyright (c) 2005,2006, Ira W. Snyder (devel@irasnyder.com)'
24
    print 'All rights reserved.'
25
    print 'This program is licensed under the GNU GPL v2'
26
    print
181 ira 27
 
368 ira 28
def print_move_file_suc(f, t):
29
    print 'Moved %s to %s' % (f, t)
30
 
31
def print_move_file_fail(f, t):
32
    print 'FAILED to move %s to %s' % (f, t)
33
 
371 ira 34
def print_move_file_pretend (f, t):
35
    print 'Will move %s to %s' % (f, t)
36
 
368 ira 37
def print_dir_create_suc(d):
38
    print 'Created directory %s' % (d, )
39
 
40
def print_dir_create_fail(d):
41
    print 'Failed to create directory %s' % (d, )
42
 
371 ira 43
def print_dir_create_pretend (d):
44
    print 'Will create directory %s' % (d, )
45
 
368 ira 46
def print_dict_suc(dic, num):
47
    print 'Successfully loaded %d records from %s\n' % (num, dic)
48
 
49
def print_dict_fail(dic):
50
    print 'Opening dictionary: %s FAILED' % (dic, )
51
 
52
def print_dict_bad_line(dic):
53
    print 'Bad line in dictionary: %s' % (dic, )
54
 
181 ira 55
class AnimeSorter2:
56
 
57
    def __init__(self, options):
58
        self.options = options
59
 
60
    def parse_dict(self):
61
        """Parses a dictionary file containing the sort definitions in the form:
62
        DIRECTORY = PATTERN
63
 
64
        Returns a list of tuples of the form (compiled_regex, to_directory)"""
65
 
66
        try:
67
            f = open(self.options.dict_file, 'r', 0)
68
            try:
69
                data = f.read()
70
            finally:
71
                f.close()
72
        except IOError:
368 ira 73
            print_dict_fail (self.options.dict_file)
181 ira 74
            sys.exit()
75
 
76
        ### Get a LIST containing each line in the file
77
        lines = [l for l in data.split('\n') if len(l) > 0]
78
 
366 ira 79
        ### Remove comments / blank lines (zero length lines already removed above)
80
        regex = re.compile ('^\s*#.*$')
81
        lines = [l for l in lines if not re.match (regex, l)]
82
        regex = re.compile ('^\s*$')
83
        lines = [l for l in lines if not re.match (regex, l)]
84
 
181 ira 85
        ### Split each line into a tuple, and strip each element of spaces
86
        result = self.split_lines(lines)
87
        result = [(re.compile(r), d) for r, d in result]
88
 
89
        ### Give some information about the dictionary we are using
368 ira 90
        print_dict_suc (self.options.dict_file, len(result))
181 ira 91
 
92
        return tuple(result)
93
 
94
    def split_lines(self, lines):
95
 
96
        result = []
97
 
98
        for l in lines:
184 ira 99
 
366 ira 100
            try:
101
                r, d = l.split('=')
102
                r = r.strip()
103
                d = d.strip()
104
            except ValueError:
368 ira 105
                print_dict_bad_line (l)
366 ira 106
                continue
181 ira 107
 
366 ira 108
            result.append((r, d))
181 ira 109
 
110
        return result
111
 
112
    def get_matches(self, files, pattern):
113
        """get_matches(files, pattern):
114
 
115
        files is type LIST
116
        pattern is type sre.SRE_Pattern
117
 
118
        Returns a list of the files matching the pattern as type sre.SRE_Match."""
119
 
120
        matches = [m for m in files if pattern.search(m)]
121
        return matches
122
 
371 ira 123
    def as_makedirs (self, dirname):
124
        """Call os.makedirs(dirname), but check first whether we are in pretend
125
           mode, or if we're running interactively."""
126
 
127
        if not os.path.isdir (dirname):
128
 
129
            if self.options.pretend:
130
                print_dir_create_pretend (dirname)
131
                return 0
132
 
133
            if self.get_user_choice ('Make directory?: %s' % (dirname, )):
134
 
135
                try:
136
                    os.makedirs (dirname)
137
                    print_dir_create_suc (dirname)
138
                except:
139
                    print_dir_create_fail (dirname)
140
                    return errno.EIO
141
 
142
        return 0
143
 
144
    def as_move_single_file (self, f, fromdir, todir):
145
        """Move the single file named $f from the directory $fromdir to the
146
           directory $todir"""
147
 
148
        srcname = os.path.join (fromdir, f)
149
        dstname = os.path.join (todir, f)
150
 
151
        if self.options.pretend:
152
            print_move_file_pretend (f, todir)
153
            return 0 # success
154
 
155
        if self.get_user_choice ('Move file?: %s --> %s' % (srcname, dstname)):
156
            try:
157
                shutil.move (srcname, dstname)
158
                print_move_file_suc (f, todir)
159
            except:
160
                print_move_file_fail (f, todir)
161
                return errno.EIO
162
 
163
        return 0
164
 
181 ira 165
    def move_files(self, files, fromdir, todir):
166
        """move_files(files, fromdir, todir):
167
        Move the files represented by the list FILES from FROMDIR to TODIR"""
371 ira 168
 
169
        ret = 0
170
 
181 ira 171
        ## Check for a non-default directory
172
        if todir[0] != '/':
173
            todir = os.path.join(self.options.output_dir, todir)
174
 
175
        ## Create the directory if it doesn't exist
371 ira 176
        ret = self.as_makedirs (todir)
181 ira 177
 
371 ira 178
        if ret:
179
            # we cannot continue, since we can't make the directory
180
            return ret
181
 
181 ira 182
        ## Try to move every file, one at a time
183
        for f in files:
371 ira 184
            ret = self.as_move_single_file (f, fromdir, todir)
181 ira 185
 
371 ira 186
            if ret:
187
                # something bad happened when moving a file
188
                break
181 ira 189
 
371 ira 190
        return ret
181 ira 191
 
192
    def __dir_walker(self, dict, root, dirs, files):
193
 
194
        ## Get all of the files in the directory that are of the correct types
195
        types_re = re.compile(TYPES_REGEX, re.IGNORECASE)
196
        raw_matches = [f for f in files if types_re.match(f)]
197
 
198
        ### Loop through the dictionary and try to move everything that matches
199
        for regex, todir in dict:
200
            matches = self.get_matches(raw_matches, regex)
201
 
202
            ## Move the files if we've found some
203
            if len(matches) > 0:
204
                self.move_files(matches, root, todir)
205
 
206
    def get_user_choice(self, prompt):
207
 
208
        # If we're not in interactive mode, then always return True
209
        if self.options.interactive == False:
210
            return True
211
 
212
        # Get the user's choice since we're not in interactive mode
213
        done = False
214
        while not done:
371 ira 215
            s = raw_input('%s [y/N]: ' % (prompt, )).lower()
181 ira 216
 
217
            if s == 'y' or s == 'yes':
218
                return True
219
 
371 ira 220
            if s == 'n' or s == 'no' or s == '':
181 ira 221
                return False
222
 
223
            print 'Response not understood, try again.'
224
 
225
    def main(self):
226
 
227
        ## Print the program's header
368 ira 228
        print_prog_header ()
181 ira 229
 
230
        ## Parse the dictionary
231
        dict = self.parse_dict()
232
 
233
        if self.options.recursive:
234
            ## Start walking through directories
235
            for root, dirs, files in os.walk(self.options.start_dir):
236
                self.__dir_walker(dict, root, dirs, files)
237
        else:
238
            self.__dir_walker(dict, self.options.start_dir,
239
                    [d for d in os.listdir(self.options.start_dir) if os.path.isdir(d)],
240
                    [f for f in os.listdir(self.options.start_dir) if os.path.isfile(f)])
241
 
242
### MAIN IS HERE ###
368 ira 243
def main():
181 ira 244
 
245
    ### Get the program options
246
    parser = OptionParser()
371 ira 247
    #parser.add_option('-q', '--quiet', action='store_false', dest='verbose',
248
    #        default=True, help='Don\'t print status messages to stdout')
181 ira 249
    parser.add_option('-d', '--dict', dest='dict_file', default=DICT_FILE,
250
            help='Read dictionary from FILE', metavar='FILE')
251
    parser.add_option('-n', '--not-recursive', action='store_false', dest='recursive',
252
            default=True, help='don\'t run recursively')
253
    parser.add_option('-s', '--start-dir', dest='start_dir', default=WORK_DIR,
254
            help='Start running at directory DIR', metavar='DIR')
255
    parser.add_option('-o', '--output-dir', dest='output_dir', default=SORT_DIR,
256
            help='Sort files into DIR', metavar='DIR')
257
    parser.add_option('-i', '--interactive', dest='interactive', default=False,
258
            help='Confirm each move', action='store_true')
371 ira 259
    parser.add_option('-p', '--pretend', dest='pretend', default=False,
260
            help='Enable pretend mode', action='store_true')
181 ira 261
 
262
    ## Parse the options
263
    (options, args) = parser.parse_args()
264
 
265
    ## Correct directories
266
    options.dict_file = os.path.abspath(os.path.expanduser(options.dict_file))
267
    options.start_dir = os.path.abspath(os.path.expanduser(options.start_dir))
268
    options.output_dir = os.path.abspath(os.path.expanduser(options.output_dir))
269
 
270
    as = AnimeSorter2(options)
271
    as.main()
272
 
368 ira 273
if __name__ == '__main__':
274
    main ()
275
 
276
# vim: set ts=4 sw=4 sts=4 expandtab: