Subversion Repositories programming

Rev

Rev 371 | Go to most recent revision | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 371 Rev 373
Line 14... Line 14...
14
DICT_FILE = '~/.config/animesorter2/animesorter.dict'
14
DICT_FILE = '~/.config/animesorter2/animesorter.dict'
15
WORK_DIR =  '~/downloads/usenet'
15
WORK_DIR =  '~/downloads/usenet'
16
SORT_DIR =  '/data/Anime'
16
SORT_DIR =  '/data/Anime'
17
TYPES_REGEX = '.*(avi|ogm|mkv|mp4|\d\d\d)$'
17
TYPES_REGEX = '.*(avi|ogm|mkv|mp4|\d\d\d)$'
18
 
18
 
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
-
 
27
 
-
 
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
 
-
 
34
def print_move_file_pretend (f, t):
-
 
35
    print 'Will move %s to %s' % (f, t)
-
 
36
 
-
 
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
 
-
 
43
def print_dir_create_pretend (d):
-
 
44
    print 'Will create directory %s' % (d, )
-
 
45
 
-
 
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
 
19
 
55
class AnimeSorter2:
20
class AnimeSorter2:
56
 
21
 
57
    def __init__(self, options):
22
    def __init__(self, options):
58
        self.options = options
23
        self.options = options
Line 68... Line 33...
68
            try:
33
            try:
69
                data = f.read()
34
                data = f.read()
70
            finally:
35
            finally:
71
                f.close()
36
                f.close()
72
        except IOError:
37
        except IOError:
73
            print_dict_fail (self.options.dict_file)
38
            self.print_dict_fail (self.options.dict_file)
74
            sys.exit()
39
            sys.exit()
75
 
40
 
76
        ### Get a LIST containing each line in the file
41
        ### Get a LIST containing each line in the file
77
        lines = [l for l in data.split('\n') if len(l) > 0]
42
        lines = [l for l in data.split('\n') if len(l) > 0]
78
 
43
 
Line 85... Line 50...
85
        ### Split each line into a tuple, and strip each element of spaces
50
        ### Split each line into a tuple, and strip each element of spaces
86
        result = self.split_lines(lines)
51
        result = self.split_lines(lines)
87
        result = [(re.compile(r), d) for r, d in result]
52
        result = [(re.compile(r), d) for r, d in result]
88
 
53
 
89
        ### Give some information about the dictionary we are using
54
        ### Give some information about the dictionary we are using
90
        print_dict_suc (self.options.dict_file, len(result))
55
        self.print_dict_suc (self.options.dict_file, len(result))
91
 
56
 
92
        return tuple(result)
57
        return tuple(result)
93
 
58
 
94
    def split_lines(self, lines):
59
    def split_lines(self, lines):
95
 
60
 
Line 100... Line 65...
100
            try:
65
            try:
101
                r, d = l.split('=')
66
                r, d = l.split('=')
102
                r = r.strip()
67
                r = r.strip()
103
                d = d.strip()
68
                d = d.strip()
104
            except ValueError:
69
            except ValueError:
105
                print_dict_bad_line (l)
70
                self.print_dict_bad_line (l)
106
                continue
71
                continue
107
 
72
 
108
            result.append((r, d))
73
            result.append((r, d))
109
 
74
 
110
        return result
75
        return result
Line 123... Line 88...
123
    def as_makedirs (self, dirname):
88
    def as_makedirs (self, dirname):
124
        """Call os.makedirs(dirname), but check first whether we are in pretend
89
        """Call os.makedirs(dirname), but check first whether we are in pretend
125
           mode, or if we're running interactively."""
90
           mode, or if we're running interactively."""
126
 
91
 
127
        if not os.path.isdir (dirname):
92
        if not os.path.isdir (dirname):
128
            
93
 
129
            if self.options.pretend:
94
            if self.options.pretend:
130
                print_dir_create_pretend (dirname)
95
                self.print_dir_create_pretend (dirname)
131
                return 0
96
                return 0
132
 
97
 
133
            if self.get_user_choice ('Make directory?: %s' % (dirname, )):
98
            if self.get_user_choice ('Make directory?: %s' % (dirname, )):
134
            
99
 
135
                try:
100
                try:
136
                    os.makedirs (dirname)
101
                    os.makedirs (dirname)
137
                    print_dir_create_suc (dirname)
102
                    self.print_dir_create_suc (dirname)
138
                except:
103
                except:
139
                    print_dir_create_fail (dirname)
104
                    self.print_dir_create_fail (dirname)
140
                    return errno.EIO
105
                    return errno.EIO
141
 
106
 
142
        return 0
107
        return 0
143
 
108
 
144
    def as_move_single_file (self, f, fromdir, todir):
109
    def as_move_single_file (self, f, fromdir, todir):
145
        """Move the single file named $f from the directory $fromdir to the
110
        """Move the single file named $f from the directory $fromdir to the
146
           directory $todir"""
111
           directory $todir"""
147
 
112
 
148
        srcname = os.path.join (fromdir, f)
113
        srcname = os.path.join (fromdir, f)
149
        dstname = os.path.join (todir, f)
114
        dstname = os.path.join (todir, f)
150
        
115
 
151
        if self.options.pretend:
116
        if self.options.pretend:
152
            print_move_file_pretend (f, todir)
117
            self.print_move_file_pretend (f, todir)
153
            return 0 # success
118
            return 0 # success
154
 
119
 
155
        if self.get_user_choice ('Move file?: %s --> %s' % (srcname, dstname)):
120
        if self.get_user_choice ('Move file?: %s --> %s' % (srcname, dstname)):
156
            try:
121
            try:
157
                shutil.move (srcname, dstname)
122
                shutil.move (srcname, dstname)
158
                print_move_file_suc (f, todir)
123
                self.print_move_file_suc (f, todir)
159
            except:
124
            except:
160
                print_move_file_fail (f, todir)
125
                self.print_move_file_fail (f, todir)
161
                return errno.EIO
126
                return errno.EIO
162
 
127
 
163
        return 0
128
        return 0
164
 
129
 
165
    def move_files(self, files, fromdir, todir):
130
    def move_files(self, files, fromdir, todir):
Line 223... Line 188...
223
            print 'Response not understood, try again.'
188
            print 'Response not understood, try again.'
224
 
189
 
225
    def main(self):
190
    def main(self):
226
 
191
 
227
        ## Print the program's header
192
        ## Print the program's header
228
        print_prog_header ()
193
        self.print_prog_header ()
229
 
194
 
230
        ## Parse the dictionary
195
        ## Parse the dictionary
231
        dict = self.parse_dict()
196
        dict = self.parse_dict()
232
 
197
 
233
        if self.options.recursive:
198
        if self.options.recursive:
Line 237... Line 202...
237
        else:
202
        else:
238
            self.__dir_walker(dict, self.options.start_dir,
203
            self.__dir_walker(dict, self.options.start_dir,
239
                    [d for d in os.listdir(self.options.start_dir) if os.path.isdir(d)],
204
                    [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)])
205
                    [f for f in os.listdir(self.options.start_dir) if os.path.isfile(f)])
241
 
206
 
-
 
207
    ############################################################################
-
 
208
    ### Functions for the printing system
-
 
209
    ############################################################################
-
 
210
 
-
 
211
    def print_prog_header(self):
-
 
212
        if self.options.quiet:
-
 
213
            return
-
 
214
 
-
 
215
        print 'Regular Expression File Sorter (aka animesorter)'
-
 
216
        print '================================================================================'
-
 
217
        print 'Copyright (c) 2005,2006, Ira W. Snyder (devel@irasnyder.com)'
-
 
218
        print 'All rights reserved.'
-
 
219
        print 'This program is licensed under the GNU GPL v2'
-
 
220
        print
-
 
221
 
-
 
222
    def print_move_file_suc(self, f, t):
-
 
223
        if self.options.quiet:
-
 
224
            return
-
 
225
 
-
 
226
        print 'Moved %s to %s' % (f, t)
-
 
227
 
-
 
228
    def print_move_file_fail(self, f, t):
-
 
229
        print 'FAILED to move %s to %s' % (f, t)
-
 
230
 
-
 
231
    def print_move_file_pretend (self, f, t):
-
 
232
        print 'Will move %s to %s' % (f, t)
-
 
233
 
-
 
234
    def print_dir_create_suc(self, d):
-
 
235
        if self.options.quiet:
-
 
236
            return
-
 
237
 
-
 
238
        print 'Created directory %s' % (d, )
-
 
239
 
-
 
240
    def print_dir_create_fail(self, d):
-
 
241
        print 'Failed to create directory %s' % (d, )
-
 
242
 
-
 
243
    def print_dir_create_pretend (self, d):
-
 
244
        print 'Will create directory %s' % (d, )
-
 
245
 
-
 
246
    def print_dict_suc(self, dic, num):
-
 
247
        if self.options.quiet:
-
 
248
            return
-
 
249
 
-
 
250
        print 'Successfully loaded %d records from %s\n' % (num, dic)
-
 
251
 
-
 
252
    def print_dict_fail(self, dic):
-
 
253
        print 'Opening dictionary: %s FAILED' % (dic, )
-
 
254
 
-
 
255
    def print_dict_bad_line(self, dic):
-
 
256
        print 'Bad line in dictionary: %s' % (dic, )
-
 
257
 
-
 
258
 
-
 
259
 
242
### MAIN IS HERE ###
260
### MAIN IS HERE ###
243
def main():
261
def main():
244
 
262
 
245
    ### Get the program options
263
    ### Get the program options
246
    parser = OptionParser()
264
    parser = OptionParser()
247
    #parser.add_option('-q', '--quiet', action='store_false', dest='verbose',
265
    parser.add_option('-q', '--quiet', action='store_true', dest='quiet',
248
    #        default=True, help='Don\'t print status messages to stdout')
266
            default=True, help="Don't print status messages to stdout")
249
    parser.add_option('-d', '--dict', dest='dict_file', default=DICT_FILE,
267
    parser.add_option('-d', '--dict', dest='dict_file', default=DICT_FILE,
250
            help='Read dictionary from FILE', metavar='FILE')
268
            help='Read dictionary from FILE', metavar='FILE')
251
    parser.add_option('-n', '--not-recursive', action='store_false', dest='recursive',
269
    parser.add_option('-n', '--not-recursive', action='store_false', dest='recursive',
252
            default=True, help='don\'t run recursively')
270
            default=True, help='don\'t run recursively')
253
    parser.add_option('-s', '--start-dir', dest='start_dir', default=WORK_DIR,
271
    parser.add_option('-s', '--start-dir', dest='start_dir', default=WORK_DIR,