#!/bin/bash

source scripts/common.sh || exit 1

json_opts=()
if ! echo "$*" | grep -q -- '--message-format json' ; then
  json_opts=(--message-format json)
fi

tmp_file="$(mktemp)"
set +e
cargo "$@" "${json_opts[@]}" > "$tmp_file"
exit_code=$?
set -e
if [[ "$exit_code" != 0 ]]; then
  echo "::error title=check failed:cargo $* failed"
fi

while IFS= read -r line; do
  if [[ -n "$line" ]]; then
    echo "$line"
    exit_code=1
  fi
done < <(
  jq <"$tmp_file" -r '
    select(.message.level and (.message.spans | length > 0)) 
    | {level: (.message.level | sub("note"; "notice")), message: .message.message} as $ctx
    | .message.spans[] 
    | "::\($ctx.level) file=\(.file_name),line=\(.line_start),col=\(.column_start),endLine=\(.line_end),columnEnd=\(.column_end),title=rust check::\($ctx.message)"'
)

exit "$exit_code"
