name: 'Cached checkout'
description: 'Checkout a git repository using local cache if possible'
inputs:
  repository:
    description: 'Repository name with owner'
    default: ${{ github.repository }}
  ref:
    description: 'Commit-ish to checkout'
  merge_ref:
    description: |
      Commit-ish to merge post-checkout if non-empty. Must be reachable from the
      default_branch input paramter.
    default: ''
  path:
    description: 'Path to checkout repo to'
  fetch-depth:
    description: 'Number of commits to fetch'
    default: 1
  cache_path:
    description: 'Path to cache location for all repos'
  default_branch:
    description: 'Name of the default branch'
    default: 'sycl'

runs:
  using: 'composite'
  steps:
  - name: Fetch cache
    shell: bash
    run: |
      mkdir -p ${{ inputs.cache_path }}/${{ inputs.repository }}
      cd ${{ inputs.cache_path }}/${{ inputs.repository }}
      if [ -d ./.git ]; then
        git pull --prune
      else
        git clone https://github.com/${{ inputs.repository }}.git .
      fi
  - name: Checkout
    env:
      GIT_ALTERNATE_OBJECT_DIRECTORIES: ${{ inputs.cache_path }}/${{ inputs.repository }}/.git/objects
    uses: actions/checkout@v3
    with:
      persist-credentials: false
      repository: ${{ inputs.repository }}
      ref: ${{ inputs.ref }}
      path: ${{ inputs.path }}
      fetch-depth: 0
  - name: Setup alternates
    shell: bash
    env:
      GIT_ALTERNATE_OBJECT_DIRECTORIES: ${{ inputs.cache_path }}/${{ inputs.repository }}/.git/objects
    run: |
      echo $GIT_ALTERNATE_OBJECT_DIRECTORIES > ${{ inputs.path }}/.git/objects/info/alternates
  - name: Merge sycl HEAD into current branch
    shell: bash
    if: ${{ inputs.merge_ref != '' }}
    env:
      DEFAULT_BRANCH: ${{ inputs.default_branch }}
    run: |
      cd ${{ inputs.path }}
      git fetch origin $DEFAULT_BRANCH
      echo "FETCHED:"
      git log -1 origin/$DEFAULT_BRANCH
      echo "Merging ${{ inputs.merge_ref }} into the current workspace"
      # Set fake identity to fulfil git requirements
      git config --local user.email "actions@github.com"
      git config --local user.name "GitHub Actions"
      git merge --no-ff --no-commit ${{ inputs.merge_ref }}
