Maris Source Maker...Source Code

#!/usr/bin/python

################################################################
# Name: Source Maker
# Version: 0.9.0
# Author: Rashaud Teague
# Date: 03/01/09
# License: GNU GPL
# Copy: Copyright (c) 2009 Maris Labs
# Description: Creates source files for programming languages.
#################################################################


import sys, os, os.path, re, urllib

if __name__ != '__main__':
        print '[ ERROR: \'(smk) sourcemaker\' can only be run as a stand alone program. ]'
        sys.exit()

#software version
SOFTWARE_VERSION = '0.9.0'

#define a default source (in my case I'll go with a Python source file)
DEFAULT_SOURCE = '.py'

#define the default editor you want to then open this source in
DEFAULT_EDITOR = 'gedit'

#define debugging on/off
DEBUG_MODE = 0

#help function that displays help and information about the shell programming
def program_help():
        print 'Usage: smk [FILENAME]'
        print '\'(smk) sourcemaker\' is a tool that creates source files for programmers.'
        print 'It creates the new sourcefile in the directory you execute the \'smk\' command in.'
        print '\'(smk) sourcemaker\' is geared toward making python, php, perl, c/c++, and c/c++ header files.\n'
        print 'Examples:'
        print ' smk myfile      #Creates a source file, no type specified, default (Python).'
        print ' smk myfile.c    #Creates a source file, source type being C++.'
        print ' smk myfile.php  #Creates a source file, source type being PHP.'
        print ' smk myfile.pl   #Creates a source file, source type being Perl.'
        print ' smk myfile.c    #Creates a source file, source type being C.'
        print ' smk myfile.h    #Creates a source file, source type being C/C++ header file.'
        print '\nOther options:\n'
        print ' --help \t print help list'
        print ' -h \t\t alias of --help'
        print ' --version \t print program version\n'
        print 'Copyright (c) 2009 Maris Labs'
        print 'Report bugs to <bugs@marislabs.org> with subject \'sourcemaker-bug\''

#check if the template file is install in /home/[user]/.smk/smk.tpl.txt
#basically checks to see if the source maker is installed
def check_tpl_file():
        user_dir = '/home/'+os.environ['USER']+'/'
        found = 0
        for contents in os.listdir(user_dir):
                if contents == '.smk':
                        found = 1
        return found

#display program version
def program_version():
        print 'smk v'+SOFTWARE_VERSION

#have the program check for a software update
def check_version_update():
        #http://marislabs.org/ext/apps/?p=desc&app=16
        params = urllib.urlencode({'p':'desc', 'app':16})
        f = urllib.urlopen('http://marislabs.org/ext/apps/?%s' % params)
        lines = f.readlines()
        version = ''
        for line in range(0, len(lines)):
                if re.match("^\<td\>Version:\<\/td\>.*?", lines[line].replace('\t', ''), re.I):
                        version = lines[line+1].replace('\t', '')
                        break
       
        version = re.match('^\<td\>v(.*?)\<\/td\>', version, re.I)
        if SOFTWARE_VERSION != version.group(1):
                print '[ WARING: Possible software update, please check http://marislabs.org/ext/apps/?p=desc&app=16 ]'

#parse templates function
def parse_templates(tpl = 'python'):
        user_dir = '/home/'+os.environ['USER']+'/'
        pFile = open(user_dir+'.smk/smk.tpl.txt', 'r');
        lines = pFile.readlines()
        pFile.close()
        tpl_content = ''
        for i in range(0, len(lines)):
                if re.match("^\["+tpl+"\]", lines[i], re.I):
                        for j in range(i+1, len(lines)):
                                if re.match("^\[.*?\]", lines[j], re.I):
                                        break
                                tpl_content += lines[j]
        return tpl_content

#the real work of this...creating the file and whatever.
def source_create(args = {}):
        #validate the dictionary variable passed in the function, make sure the right stuff is there
        if not args.has_key('filename'):
                print '[ ERROR: Some how \'filename\' key is missing from the arguments. ]'
                sys.exit()
        if args.has_key('sourcetype'):
                if args['sourcetype'] == '':
                        print '[ Warning: The \'sourcetype\' key exists but is NULL we will use the default type *',DEFAULT_SOURCE,'. ]'
                        args['sourcetype'] = DEFAULT_SOURCE
       
        #file header...if you want the hashpound of perl and python already set or <?php ?> for php
        file_header = ''
        make_executable = 0
        #set file headers and make perl and python files already executable
        if args['sourcetype'] == '.pl':
                file_header = parse_templates('perl')
                make_executable = 1
        elif args['sourcetype'] == '.py':
                file_header = parse_templates()
                make_executable = 1
        elif args['sourcetype'] == '.php':
                file_header = parse_templates('php')
        elif args['sourcetype'] == '.h':
                file_header = '#ifndef '+str(args['filename'].upper())+'_H_\n#define '+str(args['filename'].upper())+'_H_\n\n#endif'
        elif args['sourcetype'] == '.c':
                file_header = parse_templates('c')
        elif args['sourcetype'] == '.cpp':
                file_header = parse_templates('cpp')
       
        #make the new file and write the header to it
        f = open(args['filename'], 'w')
        f.write(file_header)
        f.close
       
        #if the make_executable is turned on, make the file executable
        if make_executable == 1:
                os.system('chmod 755 '+args['filename'])
       
        #check if the new source file is on the desktop, if not move it there
        #+'/home/'+os.environ['USER']+'/Desktop/sourcemaker'
        #if os.path.abspath('sourcemaker') != '/home/'+os.environ['USER']+'/Desktop/sourcemaker':
        #       os.system('mv '+new_source_filename+' '+os.getcwd())
       
        if DEBUG_MODE == 1:
                print args['filename']

#check the for any updates
check_version_update()

#perform check of the template file smk.tpl.txt
if check_tpl_file() == 0:
        print '[ ERROR: There is no template file detected in /home/'+os.environ['USER']+'/.smk/'
        print 'Please read the latest README.txt and follow the directions there. ]'
        sys.exit()
       

#get command-line arguments
commands = {}
for arg in range(0, len(sys.argv)):
        if len(sys.argv) == 1:
                print '[ ERROR: You must enter a filename. smk <filename> ]\n'
                sys.exit()
       
        #start put the arguments in the the dictionary 'commands'
        #check the filename
        if len(sys.argv) >= 2 and sys.argv[1] != '-t':
                if re.match("^\-[^v|^\-\-help|^\-h|^\-\-version].*$", sys.argv[1], re.I):
                        print '[ ERROR: This is an invalid filename for the second argument. ]\n'
                        sys.exit()
                else:
                        if sys.argv[1] == '--help' or sys.argv[1] == '-h':
                                program_help()
                                sys.exit()
                        if sys.argv[1] == '--version':
                                program_version()
                                sys.exit()
                        commands['filename'] = sys.argv[1]
        else:
                print '[ ERROR: Your arguments are in the wrong order. smk <filename> -t <sourcetype> ]'
                sys.exit()
       
        namesplit = sys.argv[1].split('.')
        if len(namesplit) > 1:
                commands['sourcetype'] = '.'+namesplit[(len(namesplit)-1)]
        else:
                commands['sourcetype'] = DEFAULT_SOURCE
       
        """
        #if the user enters more than file name see if they enter the right stuff
        if len(sys.argv) > 2 and len(sys.argv) <= 4:
                if '-t' in sys.argv and sys.argv[2] == '-t':
                        if len(sys.argv) == 4:
                                commands['sourcetype'] = '.'+sys.argv[3]
                        else:
                                print '[ ERROR: You must enter a source type. smk <filename> -t <sourcetype> ]\n'
                                sys.exit()
                else:
                        print '[ ERROR: You have entered an invalid command. Enter smk --help for help ]\n'
                        sys.exit()
        else:
                if len(sys.argv) <= 4:
                        commands['sourcetype'] = DEFAULT_SOURCE
                else:
                        print '[ ERROR: You have entered an invalid number of commands. ]\n'
                        sys.exit()
        """

        #check debug mode
        if DEBUG_MODE == 1:
                if arg != 0:
                        print sys.argv[arg]

#print off the dictionary of commands for debugging
if DEBUG_MODE == 1:
        print commands
        #sys.exit()

#create the new source file
source_create(commands)