mbland/custom-links

View on GitHub
scripts/lib/coverage

Summary

Maintainability
Test Coverage
#! /usr/bin/env bash
#
# Coverage report generator

export CL_COVERAGE_DATADIR="${CL_COVERAGE_DATADIR:-$_GO_ROOTDIR/.coverage}"
export CC_TEST_REPORTER="${_GO_ROOTDIR}/cc-test-reporter"

cl.init_code_climate() {
  if [[ -n "$CC_TEST_REPORTER_ID" && -x "$CC_TEST_REPORTER" ]]; then
    if ! "$CC_TEST_REPORTER" before-build; then
      echo 'Failed to initiate Code Climate coverage report.' >&2
      return 1
    fi
    echo 'Code Climate coverage report initiated.'
  fi
}

cl.generate_coverage_report() {
  local test_result="$1"
  local report_dir="${_GO_ROOTDIR}/coverage/lcov-report"
  local report_path="$report_dir/index.html"

  rm -rf "$report_dir"

  if ! istanbul report --root "$CL_COVERAGE_DATADIR" --include '*.json'; then
    @go.printf 'Failed to generate coverage report.\n' >&2
    return 1
  fi
  @go.printf 'Coverage report saved as: file://%s\n' "$report_path"

  if [[ -n "$CI" ]]; then
    cl.send_coverage_report "$test_result"
  elif [[ "$COVERAGE_REPORT_SERVER" == 'false' ]]; then
    return
  elif [[ "$COVERAGE_REPORT_SERVER" == 'true' ]]; then
    @go.printf 'Opening report with live-server; kill with CTRL-C.\n'
    trap 'printf "\nClosing live-server...\n"' INT
    live-server "$report_dir"
    return 0
  elif command -v xdg-open >/dev/null; then
    xdg-open "$report_path"
  elif command -v open >/dev/null; then
    open "$report_path"
  fi
}

cl.send_coverage_report() {
  local test_result="$1"
  local lcov_info_path="${_GO_ROOTDIR}/coverage/lcov.info"
  local github_repo="$(git config remote.origin.url)"

  github_repo="${github_repo##*[@/]github.com[:/]}"
  github_repo="${github_repo%.git}"

  if ! coveralls < "$lcov_info_path"; then
    echo "Failed to send coverage report to Coveralls." >&2
    return 1
  fi
  printf 'Coverage report sent to Coveralls: %s\n' \
    "https://coveralls.io/github/${github_repo}"

  if [[ -n "$CC_TEST_REPORTER_ID" && -x "$CC_TEST_REPORTER" ]]; then
    if ! "$CC_TEST_REPORTER" after-build --exit-code "$test_result"; then
      echo 'Failed to send report to Code Climate.' >&2
      return 1
    fi
    printf 'Report sent to Code Climate: %s\n' \
      "https://codeclimate.com/github/${github_repo}"
  fi
}