#!/usr/bin/env python
"""
Interactively recursively remove CVS directories
"""

import sys
import os
import shutil
import optparse

__author__ = 'Stephen Norum <snorum@slac.stanford.edu>'
__version__ = '1.0'

# Based on code from http://wiki.osuosl.org/display/howto/Python+Recursive+Generator+Example
# by K Lars Lohn <lars@osuosl.org> 
def matching_files(current_dir, match_function):
    dir_contents = [os.path.join(current_dir, f) for f in os.listdir(current_dir)]
    
    for item in dir_contents:
        if match_function(item):
            yield item
        if os.path.isdir(item):
            for subdir_item in matching_files(item, match_function):
                yield subdir_item


def is_cvs_dir(path):
    if os.path.isdir(path) and os.path.basename(path) == 'CVS':
        return True
    else:
        return False


def process_options(argv):
    """
    Return parsed command-line options found in the list `argv', or
    `sys.argv[1:]' if `argv' is `None'.
    """

    usage = '%prog [path]'
    version = '%prog {0}'.format(__version__)

    parser = optparse.OptionParser(usage=usage, version=version)

    if argv is None:
        argv = sys.argv[1:]

    (options, args) = parser.parse_args(argv)
    
    if args:
        path = args[0]
    else:
        path = os.getcwd()

    return (options, path)


def main(argv):
    (options, path) = process_options(argv)

    print "Searching for CVS directories in {0}".format(path)
    cvs_folders = [filename for filename in matching_files(path, is_cvs_dir)]
    
    if not cvs_folders:
        print "No CVS directories found."
        return 0
        
    message = "Found the following CVS directories:"
    print message
    print '-' * len(message)
    for cvs_folder in cvs_folders:
        print '    {0}'.format(cvs_folder)
    print
    
    try:
        answer = raw_input('Remove these directories [y/N]? ')
    except KeyboardInterrupt:
        answer = ''
    
    if not answer.strip():
        answer = 'n'

    if answer[0].lower() != 'y':
        print 'CVS directories not removed.'
        return 0

    print
    for cvs_folder in cvs_folders:
        print 'Removing {0}...'.format(cvs_folder),
        try:
            shutil.rmtree(cvs_folder)
        except:
            print "Could not remove {0}".format(cvs_folder)
            continue
        print "Done!"
    
    return 0

if __name__ == '__main__':
    status = main(sys.argv[1:])
    sys.exit(status)
