Only run ktlint preupload hook when there are changed kt(s) files

Fixes: 235079038
Test: Manual
Change-Id: Ia9957c6b896d0d1427dd9c24fc955a899d87e2cf
diff --git a/PREUPLOAD.cfg b/PREUPLOAD.cfg
index f0ae583..619fe797 100644
--- a/PREUPLOAD.cfg
+++ b/PREUPLOAD.cfg
@@ -1,6 +1,6 @@
 [Hook Scripts]
 checkstyle_hook = ${REPO_ROOT}/prebuilts/checkstyle/checkstyle.py --sha ${PREUPLOAD_COMMIT} -c ${REPO_ROOT}/frameworks/support/development/checkstyle/config/support-lib.xml -p development/checkstyle/prebuilt/com.android.support.checkstyle.jar
-ktlint_hook = ${REPO_ROOT}/frameworks/support/gradlew -q -p ${REPO_ROOT}/frameworks/support --continue :ktlintCheckFile --configuration-cache --file=${PREUPLOAD_FILES_PREFIXED}
+ktlint_hook = ${REPO_ROOT}/frameworks/support/development/ktlint.sh --file=${PREUPLOAD_FILES_PREFIXED}
 warn_check_api = ${REPO_ROOT}/frameworks/support/development/apilint.py -f ${PREUPLOAD_FILES}
 
 [Builtin Hooks]
diff --git a/development/ktlint.sh b/development/ktlint.sh
new file mode 100755
index 0000000..754bfaf
--- /dev/null
+++ b/development/ktlint.sh
@@ -0,0 +1,18 @@
+#!/bin/bash
+
+function usage() {
+  echo "usage: $0 <gradle_arguments>"
+  echo
+  echo "Runs the ktlint Gradle task with the provided gradle_arguments, if any of the files to check with .kt(s). Specify files to check using --file=<path> arguments."
+  exit 1
+}
+
+if [ "$1" == "" ]; then
+  usage
+fi
+
+PROJECT_ROOT=$(dirname "$0")/..
+
+if echo "$@" | tr ' ' '\n' | grep -q "^--file=.\+\.kts\?$"; then
+  exec "$PROJECT_ROOT"/gradlew -q -p "$PROJECT_ROOT" --continue :ktlintCheckFile --configuration-cache "$@"
+fi