
"""
The maya.app.python module contains utilites which Maya uses to communicate
with Python.  These functions are not part of Maya's public API and may be
subject to change.
"""

import sys, StringIO, traceback, re

mayaConsoleExpr = re.compile('[\t ]*File "<maya console>", line (?P<line>[0-9]+)')

def formatException( exceptionType, exceptionObject, traceBack ):
	# Format the exception into a string		
	stringBuffer = StringIO.StringIO()
	traceback.print_exception( exceptionType, exceptionObject, traceBack,
							   32, stringBuffer )
	result = stringBuffer.getvalue().decode('utf8')
	stringBuffer.close()
	
	# Look for stack trace items that are from the Maya Console which will be
	# off-by-one and adjust them
	lines = result.splitlines()
	for i, line in enumerate(lines):
		match = mayaConsoleExpr.match(line)
		if None != match:
			lineNo = int( match.group('line') ) - 1
			line = line[:match.start('line')] + str(lineNo) + line[match.end('line'):]
		lines[i] = u'# ' + line
		
	# Append another copy of the error message onto the front because the 
	# command line will only display the first line of the error
	lines[0:0] = [unicode(exceptionObject).rstrip()]
	result = u'\n'.join(lines)
	
	# return the error message
	return result

		
