# Copyright (c) 2002-2011 IronPort Systems and Cisco Systems
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

"""Compact stack trace functions.

This module provides some functions to get a stack trace string.

These stack traces are much more compact than the ones generated by the
traceback module.
"""

import os
import sys

def _get_module_name(n):
    try:
        path, filename = os.path.split(n)
        path, directory = os.path.split(path)
        # name, ext = os.path.splitext(filename)
        if directory:
            return '/'.join((directory, filename))
        else:
            return filename
    except:
        return '???'

def stack_string(f=None):
    """Return a compact string representing the current call stack.

    :Parameters:
        - `f`: Frame object.  If not specified, will use the current call
          position.

    :Return:
        Returns a string of the current stack trace.
    """
    if f is None:
        try:
            raise ZeroDivisionError
        except ZeroDivisionError:
            f = sys.exc_info()[2].tb_frame.f_back
    stack = []
    while f is not None:
        stack.append(
            _get_module_name(f.f_code.co_filename) + ' ' +
            f.f_code.co_name + '|' +
            str(f.f_lineno)
        )
        f = f.f_back
    return '[' + ('] ['.join(stack)) + ']'

def traceback_string(t=None, v=None, tb=None):
    """Returns a compact string representing the current exception.

    If an exception is not provided as an argument, then it will get the
    current exception from `sys.exc_info`.

    :Parameters:
        - `t`: Exception type.
        - `v`: Exception value.
        - `tb`: Traceback object.

    :Return:
        Returns a string of the current exception and stack trace.
    """
    if t is None:
        t, v, tb = sys.exc_info()
    tbinfo = []
    if tb is None:
        # this should never happen, but then again, lots of things
        # should never happen but do
        return 'traceback is None!!!'
    while tb is not None:
        tbinfo.append (
            _get_module_name (tb.tb_frame.f_code.co_filename) + ' ' +
            tb.tb_frame.f_code.co_name + '|' +
            str(tb.tb_lineno)
        )
        tb = tb.tb_next

    # just to be safe
    del tb
    first = tbinfo[-1]
    info = '[' + ('] ['.join (tbinfo)) + ']'
    return repr(((first), str(t), str(v), info))

def traceback_data (t=None, v=None, tb=None):
    """Returns compact traceback data representing the current exception.

    If an exception is not provided as an argument, then it will get the
    current exception from `sys.exc_info`.

    :Parameters:
        - `t`: Exception type.
        - `v`: Exception value.
        - `tb`: Traceback object.

    :Return:
        Returns [(file_name, fun_name, line_num), ...] for the current exception and stack trace.
    """
    if t is None:
        t, v, tb = sys.exc_info()
    tbinfo = []
    while tb is not None:
        tbinfo.append ((
            _get_module_name (tb.tb_frame.f_code.co_filename),
            tb.tb_frame.f_code.co_name,
            tb.tb_lineno
        ))
        tb = tb.tb_next
    # just to be safe
    del tb
    return (str(t), str(v), tbinfo)
