---
version: '3'

tasks:
  scan:
    deps:
      - :install:npm:leasot
      - :install:software:jq
    summary: |
      ```shell
      # @description Processes leasot data and returns .variables.json data including charts written in @appnest/readme format
      #
      # @arg $1 The file that the leasot JSON was written to
      # @arg $2 The tag being processed
      function populateChartVar() {
        ...
      }
      ```
    vars:
      DOC_IDS: '@binaryBrew,@npmBrew,@pythonBrew'
    log:
      error: Failed to acquire package information from comments via `leasot`
      start: Scanning and acquiring package information in comments via `leasot`
      success: Acquired package information from comments
    cmds:
      - |
        function populateChartVar() {
          CHART='[["Package", "Description"]'
          jq --arg tag "$(echo $2 | tr '[a-z]' '[A-Z]')" -r '.[] | select(.tag == $tag) | .
          | del(. ["file", "ref", "line", "tag"]) | .text' "$1" | while read COMMENT; do
            if [ "$CHART" != '[' ]; then
              CHART="${CHART},"
            fi
            LINK="$(echo $COMMENT | sed 's/ - .*//')"
            DESCRIPTION="$(echo $COMMENT | sed 's/.* - //' | sed 's/\"/\\\"/g')"
            CHART="${CHART}[\"**$LINK**\",\"$DESCRIPTION\"]"
          done
          CHART="${CHART}]"
          TMP_CHART="$(mktemp)"
          KEY="$(echo $2 | sed 's/^@//')"
          jq --arg chart "$CHART" --arg key "${KEY}_var_chart" '.[$key] = ($chart | fromjson)' .variables.json > "$TMP_CHART"
          mv "$TMP_CHART" .variables.json
        }
        TMP="$(mktemp)"
        leasot --tags '{{.DOC_IDS}}' --reporter json './Formula/**/*' > "$TMP" || true
        VARIABLES_JSON="$(jq '.' .variables.json)"
        for ID in {{replace "," " " .DOC_IDS}}; do
          populateChartVar "$TMP" "$ID"
        done
