androidbashgitkotlinktlint

Run Ktlint on a specific file


I have a Kotlin project configured with Ktlint. I am executing the command ./gradlew ktlintCheck to get reports from my code according to my .editorconfig file configured. Nonetheless, I would like to execute the ktlintCheck only over my changed files detected from git diff, but it is not working. Here is my script:

#!/bin/bash

BASE_BRANCH="main"

MODIFIED_FILES=$(git diff --name-only "$BASE_BRANCH" -- '*.kt')

if [ -n "$MODIFIED_FILES" ]; then
  echo "Running Ktlint..."
  echo "$MODIFIED_FILES" | xargs ./gradlew ktlintCheck
else
  echo "Any files detected"
fi

Theoretically, this script should get the changed files and run the ./gradlew ktlintCheck over them but is running over the project. Does somebody know how to fix it?


Solution

  •   - name: Get changed Kotlin files
        id: changed-files
        run: |
          echo "Retrieving changed files..."
          CHANGED_FILES=$(git diff --name-only --diff-filter=ACMR -- '*.kt' '*.kts' | tr '\n' ' ')
          echo "Changed files: $CHANGED_FILES"
          echo "::set-output name=changed_files::$CHANGED_FILES"
    
      - name: Run ktlint on changed files
        if: ${{ steps.changed-files.outputs.changed_files != '' }}
        run: |
          echo "Running ktlint on the following files:"
          echo "${{ steps.changed-files.outputs.changed_files }}"
          ./gradlew --quiet ktlintCheck -PinternalKtlintGitFilter="${{ steps.changed-files.outputs.changed_files }}"
    
      - name: No Kotlin files changed
        if: ${{ steps.changed-files.outputs.changed_files == '' }}
        run: echo "No Kotlin files were changed in this pull request."