|
| 1 | +name: Devtron-auto-labeller |
| 2 | + |
| 3 | +on: |
| 4 | + issue_comment: |
| 5 | + types: [created] |
| 6 | + pull_request_comment: |
| 7 | + types: [created] |
| 8 | + |
| 9 | +jobs: |
| 10 | + manage-labels: |
| 11 | + runs-on: ubuntu-latest |
| 12 | + |
| 13 | + steps: |
| 14 | + - name: Parse and manage labels |
| 15 | + env: |
| 16 | + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} |
| 17 | + run: | |
| 18 | + #comment body and issue/PR number |
| 19 | + COMMENT_BODY=$(jq -r '.comment.body' "$GITHUB_EVENT_PATH") |
| 20 | + ISSUE_NUMBER=$(jq -r '.issue.number // .pull_request.number' "$GITHUB_EVENT_PATH") |
| 21 | +
|
| 22 | + # check for existing labels on issues and prs |
| 23 | + EXISTING_LABELS=$(curl -s -H "Authorization: token $GITHUB_TOKEN" \ |
| 24 | + -H "Accept: application/vnd.github.v3+json" \ |
| 25 | + "https://api.github.com/repos/${{ github.repository }}/issues/$ISSUE_NUMBER" | jq -r '.labels[].name') |
| 26 | +
|
| 27 | + |
| 28 | + if [[ "$COMMENT_BODY" =~ ^/([^ ]+)$ ]]; then |
| 29 | + LABEL_NAME="${COMMENT_BODY:1}" |
| 30 | +
|
| 31 | + # Existence of label in the repository |
| 32 | + REPO_LABELS=$(curl -s -H "Authorization: token $GITHUB_TOKEN" \ |
| 33 | + -H "Accept: application/vnd.github.v3+json" \ |
| 34 | + "https://api.github.com/repos/${{ github.repository }}/labels") |
| 35 | +
|
| 36 | + if echo "$REPO_LABELS" | jq -e ".[] | select(.name == \"$LABEL_NAME\")" > /dev/null; then |
| 37 | + # Add the requested label, keeping existing ones intact |
| 38 | + UPDATED_LABELS=$(echo "$EXISTING_LABELS" | jq -R 'split("\n") | . + ["'"$LABEL_NAME"'"] | unique') |
| 39 | + curl -s -X PATCH -H "Authorization: token $GITHUB_TOKEN" \ |
| 40 | + -H "Accept: application/vnd.github.v3+json" \ |
| 41 | + -d "{\"labels\": $UPDATED_LABELS}" \ |
| 42 | + "https://api.github.com/repos/${{ github.repository }}/issues/$ISSUE_NUMBER" |
| 43 | +
|
| 44 | + echo "Successfully added label '$LABEL_NAME' to issue/PR #$ISSUE_NUMBER." |
| 45 | + else |
| 46 | + echo "The label '$LABEL_NAME' doesn't exist in the repository. Please create it first." |
| 47 | + fi |
| 48 | + fi |
| 49 | +
|
| 50 | + # Remove labels when asked |
| 51 | + if [[ "$COMMENT_BODY" =~ ^/remove[[:space:]](.+)$ ]]; then |
| 52 | + LABEL_NAME_TO_REMOVE=$(echo "$COMMENT_BODY" | sed -n 's|/remove ||p') |
| 53 | +
|
| 54 | + # Remove the specified label |
| 55 | + if echo "$EXISTING_LABELS" | grep -q "^$LABEL_NAME_TO_REMOVE$"; then |
| 56 | + curl -s -X DELETE -H "Authorization: token $GITHUB_TOKEN" \ |
| 57 | + -H "Accept: application/vnd.github.v3+json" \ |
| 58 | + "https://api.github.com/repos/${{ github.repository }}/issues/$ISSUE_NUMBER/labels/$LABEL_NAME_TO_REMOVE" |
| 59 | +
|
| 60 | + echo "Successfully removed label '$LABEL_NAME_TO_REMOVE' from issue/PR #$ISSUE_NUMBER." |
| 61 | + else |
| 62 | + echo "The label '$LABEL_NAME_TO_REMOVE' is not attached to issue/PR #$ISSUE_NUMBER." |
| 63 | + fi |
| 64 | + fi |
0 commit comments