# cherry-picking.yaml (https://github.com/Bughalla/dynamods_dynamo/blob/1c1d3e29ee9bca81b43d78f22bf953100ef67009/.github/workflows/disabled/cherry-picking.yaml#L45-L51)
#DYN-3364 
#This action is disabled for now due to it not behaving as expected
name: Cherry picking
on:
  push:
    branches:
      - master
permissions: {}
jobs:
  cherry_pick:
    runs-on: ubuntu-latest
    env:
      #Variable for the name of the branch to cherry-pick into.
      #It will remain 'invalid' if no branch is specified
      destination_branch: 'invalid'
      #Name of the autogenerated branch to create the PR from
      auto_branch: 'auto-${{github.event.after}}'
      #Username for the cherrypick
      user_name: "Dynamo-Bot"
    steps:
    - name: checkout
      uses: actions/checkout@v3

    #Removes posible conflicting characters on the commit message
    #This is because the content of the message will be passed to a script as a parameter and quotation marks will split the text as if it where multiple parameters.
    - name: Remove conflicting chars
      uses: frabert/replace-string-action@v1.2
      id: remove_quotations
      with:
        pattern: "\""
        string: ${{github.event.commits[0].message}}
        replace-with: "-"  
        flags: g

    #Checks the message looking for a cherry-pick request and extracts the target branch name
    - name: Check Information
      env:
          ISSUE_BODY_PARSED: ${{steps.remove_quotations.outputs.replaced}}
      id: check-info
      run: |
        echo "destination_branch=$(pwsh .\\.github\\scripts\\cherry_pick_check.ps1 "${{ env.ISSUE_BODY_PARSED }}" )" >> $GITHUB_ENV
    
      #If a target branch was found will run the action
    - if: env.destination_branch != 'invalid'
      name: Create PR to branch
      run: |
        git config user.name "${{env.user_name}}"
        git fetch --all
        git checkout -b ${{env.auto_branch}} origin/${{env.destination_branch}}
        git cherry-pick -x ${{github.event.after}} --strategy-option theirs
        git push -u origin ${{env.auto_branch}}
        hub pull-request -b "${{env.destination_branch}}" -h "${{env.auto_branch}}" -m "${{env.pr_message}}"
      env: 
        #Token used for the pull request. Corresponds to the DynamoBot account
        GITHUB_TOKEN: ${{secrets.DYNAMOBOTTOKEN}}
        ISSUE_BODY_PARSED: ${{steps.remove_quotations.outputs.replaced}}
        #This represents the title and description of the pr in Markdown format
        #Everything before the first blank line will be the title
        #Everything after will be included in the description
        pr_message: |
                  Cherry-Pick from commit: ${{github.event.after}}

                  ### Cherry-picking: 
                  [Commit](https://github.com/DynamoDS/Dynamo/commit/${{github.event.after}})
                  
                  ### Pull request:
                  ${{ env.ISSUE_BODY_PARSED }}
