# Name:		dirPyDemo.py
# Author:	Dave Renner	dmrenne@comcast.net
# Date:		08/28/11	1600
# Rev:		01/09/13	0315
# Note:		this is a called module of 'pyDemo.py'
#
# Note:		'dirPyDemo.py' demos recursion as applied to file directory
#			listings
#
#
import os
import os.path

top = os.getcwd()
subdirlist = []
my_extension = '.py'
DEBUG = 'False'
PRINT_SUBDIRS = 'False'
PRINT_FILE_EXTENSIONS = 'False'
VERBOSE_PATH = 'False'


# ########################### BOILERPLATE ###########################
import pickle
myConfigFile = 'pyDemoConfig.dat'

# version has been stored in our calling module 'pyDemo.py'
PythonVersFile = 'version.obj'
versfile = open(PythonVersFile, 'rb')
PythonVers = pickle.load(versfile)
versfile.close()

if PythonVers == '30':
    import configparser
    config = configparser.ConfigParser()
    input_cmd = 'input'
else:
    import ConfigParser
    config = ConfigParser.ConfigParser()
    input_cmd = 'raw_input'

config.read(myConfigFile)
interactive = config.get('Mode', 'interactive')
continue_cmd = config.get('Strings', 'continue_cmd')

# easier to just include this boilerplate function into every module 
# than to import it
def printf(arg):
    cmdText = "print "
    arg_nonSlash = arg.strip('\\')
    if PythonVers == '30':
        cmdFull = cmdText + '("' + arg_nonSlash + '")'
    else:
        cmdFull = cmdText + '"' + arg_nonSlash + '"'
    exec( cmdFull )
	
def dirprintf(arg, topdir):
    if PythonVers == '30':
        print(topdir)
    else:
        cmdPrint = 'print "'
        cmdFull = cmdPrint + topdir + '"'
        exec( cmdFull )

	
# ####################################################################
	
printf("We are now in module 'dirPyDemo.py'.\
\\nHere we will list all the files and directories within\
\\nour current directory. This program uses recursion\
\\nto descend into nested subdirectories.\
\\nRecursion is a tricky topic; too complex to explain here.\
\\n\
\\nActually, we use both recursion and 'for' loops:\
\\nrecursion, to process all files within a directory, and a\
\\n'for' loop to process all directories within a directory,\
\\n that is, to recursively descend into each.\
\\n\
\\n\
\\nThis module also demonstrates Python's 'os' module,\
\\nspecifically file-related functions. Of note here\
\\nis that Python considers a 'file name' to include\
\\nany subpaths of the current directory.\
\\n So 'os.path.isfile('myFile')' won't work properly\
\\nunless the path-from-the-current-directory is included.\
\\n")
if interactive == '1':
	printf("")
	full_cmd = input_cmd + '("' + continue_cmd + '")'
	eval(full_cmd)
	printf("")
	
printf("When I say 'does not work properly' I mean that -- apparantly --\
\\nit sometimes works, sometimes doesn't.\
\\n\
\\nSo we will use 'listdir' to find all the files\
\\nin the current directory, then 'os.path.join' to\
\\ncombine each file name with its directory name,\
\\nTHEN test whether each file 'isdir' or 'isfile'.\
\\n\
\\nNot really intuitive.\
\\n\
\\nOK, now for the program results...")
printf("")
printf("")

# #############################################################
def my_dir_recursion(curtop, subdir_list):
    global my_extension

    printf("")
    printf("")
    printf("AT TOP OF MY RECURSION")
    dirtopstr = "DIRECTORY:" + str(curtop)
    dirprintf(dirtopstr, curtop)

    if DEBUG == 'True':
        printf("Here's a list of all the files:")
        printf("")

    file_list = []
    my_files = os.listdir(curtop)
       
    for fil in my_files:
        filename = os.path.join(curtop, fil)
        if DEBUG == 'True':
            printf("Here is a list of all files:")
            printf(filenames)
        if os.path.isdir(filename):
            if PRINT_SUBDIRS == 'True':
                printf('SUBDIR:      ')
                printf( filename )
            subdir_list.append(filename)
            if DEBUG == 'True':
                printf('subdir list: ')
                printf( subdir_list )
        else:
            if DEBUG == 'True':
                printf('filename: ')
                printf(filename)
            if os.path.isfile(filename):
                head, tail = os.path.split(filename)
                file_list.append(tail)
                base, ext = os.path.splitext(filename)
                if ext == my_extension:
                    if PRINT_FILE_EXTENSIONS == True:
                        printf('PYTHON FILE: ')
                        printf( tail )
                else:
                    if PRINT_FILE_EXTENSIONS == True:
                        printf('other file:  ')
                        printf(tail)
            else:
                # shouldn't happen. Parent and cur dirs
                # won't be here
                printf("")
                printf("What kinda file is this?")
                printf(filename)				

    printf("")
    printf('SUBDIRECTORIES:')
    subdir_list.sort()
    for sub in subdir_list:
        dirprintf( sub, curtop )

    printf("")
    printf('FILES:')
    file_list.sort()
    for fil in file_list:
        printf( fil )

    if subdir_list != []:
        for subdir in subdir_list:
            curtop = subdir_list.pop()
            if VERBOSE_PATH == 'True':
                printf("")
                printf('Leaving this recursion. Top dir now set to')
                printf(curtop)
            my_dir_recursion( curtop, subdir_list )


# ###################################################################

my_dir_recursion( top, subdirlist )
printf("")
printf("Doesn't that look good, though???")
# ###################################################################
