name: Linter upload results

# Upload linter results after succesful linter run
# This is done in a separate workflow to safely use the read-write GitHub token
# See https://securitylab.github.com/research/github-actions-preventing-pwn-requests

on:
  workflow_run:
    workflows: ["Linter"]
    types:
      - completed

jobs:
  lint_upload:
    runs-on: ubuntu-16.04
    steps:
    - run: pip install requests
    - name: Download linter results
      uses: dawidd6/action-download-artifact@v2
      with:
        github_token: ${{ secrets.GITHUB_TOKEN }}
        workflow: lint.yml
        run_id: ${{ github.event.workflow_run.id }}
        name: JSON results
        path: results
    - name: Send linter results to GitHub
      shell: python
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        RUN_ID: ${{ github.event.workflow_run.id }}
      run: |
        import os
        import json
        import requests

        # Load the results from the lint job artifact
        with open("results/stable_annotations.json", "r") as f:
            annotations = json.load(f)
        summary = 'colobot-lint found {} issues'.format(len(annotations))

        # None of the available actions seem to do what I want, they all do stupid things like adding another check... let's just do it manually
        # GitHub also doesn't seem to provide you with the check suite or check run ID, so we have to get it from the action ID via the API
        s = requests.Session()
        s.headers.update({
            'Authorization': 'token ' + os.environ['GITHUB_TOKEN'],
            'Accept': 'application/vnd.github.antiope-preview+json'  # Annotations are still technically a preview feature of the API
        })
        action_run = s.get(os.environ['GITHUB_API_URL'] + "/repos/" + os.environ['GITHUB_REPOSITORY'] + "/actions/runs/" + os.environ['RUN_ID']).json()
        check_suite = s.get(action_run['check_suite_url']).json()
        check_suite_runs = s.get(check_suite['check_runs_url']).json()
        check_run = check_suite_runs['check_runs'][0]  # NOTE: This assumes that the 'lint' job is the first one in the workflow. You could find it by name if you really wanted.

        # Annotations have to be sent in batches of 50
        first = True
        while first or len(annotations) > 0:
            first = False
            to_send = annotations[:50]
            annotations = annotations[50:]
            data = {
                'output': {
                    'title': summary,
                    'summary': summary,
                    'annotations': to_send
                }
            }
            r = s.patch(check_run['url'], json=data)
            r.raise_for_status()