Subversion Repositories programming

Rev

Rev 129 | Blame | Last modification | View Log | RSS feed

#!/usr/bin/python

import os, re, shutil, sys
from optparse import OptionParser

### DEFAULT CONFIGURATION VARIABLES ###
DICT_FILE = os.path.expanduser('~/.config/animesorter/animesorter.dict')
WORK_DIR =  os.path.expanduser('~/downloads/usenet')
SORT_DIR =  os.path.expanduser('/data/Anime')

### Globals
options = {}
move_status = []


def parse_dict():
    """Parses a dictionary file containing the sort definitions in the form:
    DIRECTORY = PATTERN

    Returns a list of tuples of the form (compiled_regex, to_directory)"""
    try:
        f = open(options.dict_file, 'r', 0)
        try:
            data = f.read()
        finally:
            f.close()
    except IOError:
        print 'Error opening %s ... exiting!' % options.dict_file
        sys.exit()

    ### Get a LIST containing each line in the file
    lines = [l for l in data.split('\n') if len(l) > 0]

    ### Split each line into a tuple, and strip each element of spaces
    result = [(r, d) for r, d in [l.split('=') for l in lines]]
    result = [(r.strip() ,d.strip()) for r, d in result]
    result = [(re.compile(r), d) for r, d in result]

    return tuple(result)

def get_types_re():
    """Returns a compiled regular expression which will find objects of the
    types specified in this function's definition."""
    types = ('avi', 'ogm', 'mkv', 'mp4')
    types_regex = ''

    for i in types:
        types_regex += '%s|' % i

    types_regex = '.*(%s)$' % types_regex[:-1]

    return re.compile(types_regex, re.IGNORECASE)

def get_matches(files, pattern):
    """get_matches(files, pattern):

    files is type LIST
    pattern is type sre.SRE_Pattern

    Returns a list of the files matching the pattern as type sre.SRE_Match."""
    matches = [m for m in files if pattern.search(m)]
    return matches

def move_files(files, fromdir, todir):
    """move_files(files, fromdir, todir):
    Move the files represented by the list FILES from FROMDIR to TODIR"""
    ## Check for a non-default directory
    if todir[0] != '/':
        todir = os.path.join(options.output_dir, todir)

    ## Create the directory if it doesn't exist
    if not os.path.isdir(todir):
        try:
            os.makedirs(todir)
        except:
            move_status.append('FAILED to create directory: %s' % todir)

    ## Try to move every file, one at a time
    for f in files:
        srcname = os.path.join(fromdir, f)
        dstname = os.path.join(todir, f)

        try:
            shutil.move(srcname, dstname)
        except:
            move_status.append('FAILED to move %s to %s' % (f, todir))
            return

        move_status.append('Moved %s to %s' % (f, todir))

def print_prog_header():
    if options.verbose:
        print 'Regular Expression File Sorter (aka animesorter)'
        print '================================================================================'
        print 'Copyright (c) 2005, Ira W. Snyder (devel@irasnyder.com)'
        print 'All rights reserved.'
        print 'This program is licensed under the GNU GPL v2'
        print

def print_dir_header(dir):
    if options.verbose:
        print 'Working in directory: %s' % dir
        print '================================================================================'

def print_move_status():
    if options.verbose:
        for i in move_status:
            print i

        print

def get_parsed_options():
    parser = OptionParser()
    parser.add_option('-q', '--quiet', action='store_false', dest='verbose',
                      default=True, help='don\'t print status messages to stdout')
    parser.add_option('-d', '--dict', dest='dict_file', default=DICT_FILE,
                      help='read dictionary from FILE', metavar='FILE')
    #parser.add_option('-n', '--not-recursive', action='store_false', dest='recursive',
    #                   default=True, help='don\'t run recursively')
    parser.add_option('-s', '--start-dir', dest='start_dir', default=WORK_DIR,
                      help='start running at directory DIR', metavar='DIR')
    parser.add_option('-o', '--output-dir', dest='output_dir', default=SORT_DIR,
                      help='sort files into DIR', metavar='DIR')

    ## Parse the options
    (options, args) = parser.parse_args()

    ## Correct directories
    options.dict_file = os.path.abspath(options.dict_file)
    options.start_dir = os.path.abspath(options.start_dir)
    options.output_dir = os.path.abspath(options.output_dir)

    return options

def main():

    ## Get Options
    options = get_parsed_options()

    ## Print the program's header
    print_prog_header()

    ## Parse the dictionary
    dict = parse_dict()

    ## Start walking through directories
    for root, dirs, files in os.walk(options.start_dir):

        ## Blank the status variable
        move_status = []

        ## Get all of the files in the directory that are of the correct types
        types_re = get_types_re()
        raw_matches = [f for f in files if types_re.match(f)]

        ### Loop through the dictionary and try to move everything that matches
        for regex, todir in dict:
            matches = get_matches(raw_matches, regex)

            ## Move the files if we've found some
            if len(matches) > 0:
                move_files(matches, root, todir)

        if len(move_status) > 0:
            ## print header
            print_dir_header(root)

            ## print status
            print_move_status()

### MAIN IS HERE ###
if __name__ == '__main__':
    main()