#!/usr/bin/python # Usage: see commentator.py -h # # I often have text blocks that I want to convert into comments, for # boilerplate or whatever. I prefer to have one file for everything, # and only maintain that version, rather than boilerplate.java, # boilerplate.sql, boilerplate.cxx, etc. # # Implementation note: I'm a lazy bastard, and I don't bother with # straight c anymore, so c comments will look like garbage. Feel # free to fix it. I left-justify everything to a 72-field text # width, because I'm pretty disciplined about line lengths. This # can be changed if you want. # # It's also going to be pretty slow based on the usage of string.replace # and friends, but really, how often are you going to run this? # # This is my second Python program, so it is indubitably infested with # pessimisms and un-Python thinking. Feel free to email me with any # suggestions as to style, structure, procedure, etc. # # , 25 Dec 2000, God Knows Where, NJ USA # # $Id: commentator.py,v 1.2 2001/10/08 09:15:11 reeses Exp $ import sys, string, getopt comments = { 'ada': '-- ', 'bat': 'REM ', 'c': '/* */', 'c++': '// ', 'cmd': 'REM ', 'java': '// ', 'lisp': ';; ', 'postscript': '% ', 'python': '# ', 'sh': '# ', 'sql': '-- ', 'vb': 'REM ', 'vbs': 'REM ' } defaultLanguage = 'python' def printLangs(): print "Languages supported:" str = " " for l in comments.keys(): str += l + " " print str def determineCommentString(lang): if comments.has_key(lang): return comments[lang] return determineCommentString(defaultLanguage) def changeLine(commentString,str): "Change text line to be a valid comment." str = string.replace(str, '\n', '') # is there a chop or whatever in python? result = string.replace(commentString, "", str) return result + '\n' def printHelp(): print "Usage: python commentator [-l lang] [-n] [-i inputfile] [-o outputfile]" print " -l specifies output language" print " -n do not block-justify to 72 chars" print " -i specifies an input file (otherwise, use stdin)" print " -o specifies an output file (otherwise, use stdout)" printLangs() def main(): try: opts, args = getopt.getopt(sys.argv[1:], "l:i:o:hn") except getopt.error, msg: print msg print "Use -h for help" sys.exit(0) lang = "python" infile = sys.stdin outfile = sys.stdout justify = 1 for o, a in opts: if o == '-l': lang = a if o == '-n': justify = 0 if o == '-i': infileName = a try: infile = open(infileName, "r") except IOError, msg: print infileName, ":", msg sys.exit(-1) if o == '-o': outfileName = a try: outfile = open(outfileName, "w") except IOError, msg: print outfileName, ":", msg sys.exit(-1) if o == '-h': printHelp() sys.exit(0) commentString = determineCommentString(string.lower(lang)) for line in infile.readlines(): if justify == 1: line = string.ljust(line, 72) outfile.write(changeLine(commentString, line)) infile.close() outfile.close() main()