#!/usr/bin/env zsh

typeset -a lines
typeset -i prev_time=0
typeset prev_command

while read -r line; do
  # Anything between the beginning of the line and the "+" is just ignored.
  #
  # In particular, in cases where one logging line stops abruptly and a new
  # one begins without an intervening newline, the ".*" in this pattern
  # slurps up the incomplete logging line and leaves only the full line that
  # comes after. This kind of thing can happen if your zshrc contains an
  # assignment like now=$(date); the XTRACE module prints a line
  # corresponding to "now=" but then neglects to print a newline before the
  # line corresponding to the "date" command. The net effect is that the
  # report outputted by this script ignores the "now=" part, which shouldn't
  # have taken any time anyway.
  if [[ "${line}" =~ '^.*\+([0-9]{10})\.([0-9]{6})[0-9]* (.+)' ]]; then
    # Form a time in microseconds by concatenating the digits before the
    # decimal point with the first six digits after the decimal point.
    integer this_time=$match[1]$match[2]

    if [ "${prev_time}" -gt 0 ]; then
      time_difference=$((this_time - prev_time))
      lines+="${time_difference} ${prev_command}"
    fi

    prev_time=${this_time}

    # If the command is longer than 80 characters, truncate it with "...".
    this_command=$match[3]
    if [ "${#this_command}" -le 80 ]; then
      prev_command=${this_command}
    else
      prev_command="${this_command:0:77}..."
    fi
  fi
done <${1:-/dev/stdin}

# combination "On": elements of `$lines` are sorted numerically in desc. order
# "-l" flag: each element is printed on its own line.
print -l ${(@On)lines}
