def secure_filename(filename):
    r"""Borrowed from :mod:`werkzeug.utils`, under the BSD 3-clause license.

    Pass it a filename and it will return a secure version of it.  This
    filename can then safely be stored on a regular file system and passed
    to :func:`os.path.join`.  The filename returned is an ASCII only string
    for maximum portability.

    On windows systems the function also makes sure that the file is not
    named after one of the special device files.

    >>> secure_filename("My cool movie.mov")
    'My_cool_movie.mov'
    >>> secure_filename("../../../etc/passwd")
    'etc_passwd'
    >>> secure_filename(u'i contain cool \xfcml\xe4uts.txt')
    'i_contain_cool_umlauts.txt'

    The function might return an empty filename.  It's your responsibility
    to ensure that the filename is unique and that you generate random
    filename if the function returned an empty one.

    :param filename: the filename to secure
    """
    _filename_ascii_strip_re = re.compile(r'[^A-Za-z0-9_.-]')
    _windows_device_files = ('CON', 'AUX', 'COM1', 'COM2', 'COM3', 'COM4',
                             'LPT1', 'LPT2', 'LPT3', 'PRN', 'NUL')
    if isinstance(filename, text_type):
        from unicodedata import normalize
        filename = normalize('NFKD', filename).encode('ascii', 'ignore')
        if not PY2:
            filename = filename.decode('ascii')
    for sep in os.path.sep, os.path.altsep:
        if sep:
            filename = filename.replace(sep, ' ')
    filename = str(_filename_ascii_strip_re.sub('', '_'.join(
                   filename.split()))).strip('._')

    # on nt a couple of special files are present in each folder.  We
    # have to ensure that the target file is not such a filename.  In
    # this case we prepend an underline
    if os.name == 'nt' and filename and \
       filename.split('.')[0].upper() in _windows_device_files:
        filename = '_' + filename

    return filename
def _log_unhandled_exception_and_exit(
        cls, exc_class=None, exc=None, tb=None, add_newline=False
    ):
        """A sys.excepthook implementation which logs the error and exits with failure."""
        exc_class = exc_class or sys.exc_info()[0]
        exc = exc or sys.exc_info()[1]
        tb = tb or sys.exc_info()[2]

        # This exception was raised by a signal handler with the intent to exit the program.
        if exc_class == SignalHandler.SignalHandledNonLocalExit:
            return cls._handle_signal_gracefully(exc.signum, exc.signame, exc.traceback_lines)

        extra_err_msg = None
        try:
            # Always output the unhandled exception details into a log file, including the traceback.
            exception_log_entry = cls._format_unhandled_exception_log(
                exc, tb, add_newline, should_print_backtrace=True
            )
            cls.log_exception(exception_log_entry)
        except Exception as e:
            extra_err_msg = "Additional error logging unhandled exception {}: {}".format(exc, e)
            logger.error(extra_err_msg)

        # Generate an unhandled exception report fit to be printed to the terminal (respecting the
        # Exiter's should_print_backtrace field).
        if cls._should_print_backtrace_to_terminal:
            stderr_printed_error = cls._format_unhandled_exception_log(
                exc, tb, add_newline, should_print_backtrace=cls._should_print_backtrace_to_terminal
            )
            if extra_err_msg:
                stderr_printed_error = "{}\n{}".format(stderr_printed_error, extra_err_msg)
        else:
            # If the user didn't ask for a backtrace, show a succinct error message without
            # all the exception-related preamble.  A power-user/pants developer can still
            # get all the preamble info along with the backtrace, but the end user shouldn't
            # see that boilerplate by default.
            error_msgs = getattr(exc, "end_user_messages", lambda: [str(exc)])()
            stderr_printed_error = "\n" + "\n".join(f"ERROR: {msg}" for msg in error_msgs)
        cls._exit_with_failure(stderr_printed_error)