"""
traceback_utils.py

Copyright 2018 Andres Riancho

This file is part of w3af, http://w3af.org/ .

w3af is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 2 of the License.

w3af is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with w3af; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

"""
import os
import sys
import traceback


def get_traceback():
    _, _, tb = sys.exc_info()
    return tb


def get_exception_location(tb):
    """
    Receives a traceback (like the one generated by get_traceback) and returns
    the filename, function name, and line number where the exception was
    generated.

    :param tb: A traceback
    :return: A tuple similar to
                ('/home/user/tools/w3af/.../',
                 'pool276.py',
                 'get()',
                 643)
    """
    if tb is None:
        return None, None, None, None

    file_path = traceback.extract_tb(tb)[-1][0]
    path = os.path.dirname(file_path)
    file_name = os.path.basename(file_path)

    current = tb
    while getattr(current, 'tb_next', None) is not None:
        current = current.tb_next

    function_name = '%s()' % current.tb_frame.f_code.co_name

    return path, file_name, function_name, current.tb_lineno
