|
| 1 | +name: Auto Comment on Labeled PR |
| 2 | + |
| 3 | +on: |
| 4 | + pull_request_target: |
| 5 | + types: |
| 6 | + - labeled |
| 7 | + - unlabeled |
| 8 | + |
| 9 | +permissions: |
| 10 | + pull-requests: write |
| 11 | + |
| 12 | +jobs: |
| 13 | + comment: |
| 14 | + runs-on: ubuntu-latest |
| 15 | + steps: |
| 16 | + # Checkout the repository code to the runner. |
| 17 | + - name: Checkout code |
| 18 | + uses: actions/checkout@v3 |
| 19 | + |
| 20 | + # Create a bin directory in the runner's home |
| 21 | + - name: Create bin directory |
| 22 | + run: | |
| 23 | + mkdir -p $HOME/bin |
| 24 | + echo "$HOME/bin" >> $GITHUB_PATH |
| 25 | +
|
| 26 | + # Install the latest jq and yq from GitHub releases |
| 27 | + - name: Install jq and yq |
| 28 | + run: | |
| 29 | + wget https://github.com/jqlang/jq/releases/latest/download/jq-linux-amd64 -O $HOME/bin/jq |
| 30 | + chmod +x $HOME/bin/jq |
| 31 | + wget https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64 -O $HOME/bin/yq |
| 32 | + chmod +x $HOME/bin/yq |
| 33 | + |
| 34 | + # Main logic for adding comments based on labels. |
| 35 | + - name: Comment on PR based on external config |
| 36 | + run: | |
| 37 | + # Fetch the labels attached to the PR from the GitHub event JSON. |
| 38 | + pr_labels=$(jq -r '.pull_request.labels[] | .name' "$GITHUB_EVENT_PATH" | tr '\n' ' ') |
| 39 | + |
| 40 | + # Define the path to the external YAML config file. |
| 41 | + config_file=".github/auto-comment-config.yaml" |
| 42 | + |
| 43 | + # Get the number of label-comment mappings defined in the config file. |
| 44 | + num_mappings=$(yq e '.label_mappings | length' "$config_file") |
| 45 | + |
| 46 | + # Loop through each label-comment mapping in the config file. |
| 47 | + for (( i=0; i<$num_mappings; i++ )); do |
| 48 | + # Fetch the labels and comment for the current mapping. |
| 49 | + mapfile -t labels < <(yq e ".label_mappings[$i].labels[]" "$config_file") |
| 50 | + comment=$(yq e ".label_mappings[$i].comment" "$config_file") |
| 51 | +
|
| 52 | + # Check if all required labels from the current mapping are present in the PR. |
| 53 | + for label in "${labels[@]}"; do |
| 54 | + if [[ ! $pr_labels == *"$label"* ]]; then |
| 55 | + echo "One or more required labels not found. Skipping." |
| 56 | + continue 2 # Skip to the next iteration of the outer loop. |
| 57 | + fi |
| 58 | + done |
| 59 | + |
| 60 | + # Fetch the PR number from the GitHub event JSON. |
| 61 | + pr_number=$(jq -r '.pull_request.number' "$GITHUB_EVENT_PATH") |
| 62 | + |
| 63 | + # If all required labels are found, add the comment to the PR. |
| 64 | + echo "All required labels found. Adding comment." |
| 65 | + gh pr comment "$pr_number" --body "$comment" |
| 66 | +
|
| 67 | + done |
| 68 | + env: |
| 69 | + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} |
| 70 | + shell: bash |
0 commit comments