├── settings.gradle.kts
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── src
└── main
│ ├── resources
│ └── META-INF
│ │ └── plugin.xml
│ └── kotlin
│ └── com
│ └── monzo
│ └── syntheticsmigrator
│ └── KotlinSyntheticsMigrator.kt
├── .gitignore
├── LICENSE
├── snippets
├── ViewCacheUtil.java
└── ViewFinders.kt
├── README.md
├── gradlew.bat
└── gradlew
/settings.gradle.kts:
--------------------------------------------------------------------------------
1 | rootProject.name = "kotlin-synthetics-migrator"
2 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/monzo/kotlin-synthetics-migrator/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-all.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
--------------------------------------------------------------------------------
/src/main/resources/META-INF/plugin.xml:
--------------------------------------------------------------------------------
1 |
2 | com.monzo.syntheticsmigrator
3 | Kotlin Synthetics Migrator
4 |
5 |
6 | com.intellij.modules.lang
7 | org.jetbrains.kotlin
8 |
9 |
10 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Gradle caches.
2 | .gradle/
3 |
4 | # Build output.
5 | /build/
6 | /**/build/
7 |
8 | # Local configuration file (sdk path, etc).
9 | local.properties
10 |
11 | # Ignore everything in the .idea/ directory by default.
12 | .idea/
13 | # Share required plugins.
14 | !.idea/externalDependencies.xml
15 | # Most code style settings are shared via .editorconfig, but some are unsupported
16 | # and are still shared via .idea/ (mostly the Android-specific ones).
17 | !.idea/codeStyles
18 | # Share file templates.
19 | !.idea/fileTemplates
20 |
21 | # Studio profiler/layout inspector output.
22 | captures/
23 |
24 | # Mac.
25 | .DS_Store
26 |
27 | # Generated during UI test runs.
28 | android_shards.json
29 | flank-links.log
30 | results/
31 |
32 | # Gradle profiler defaults.
33 | /gradle-user-home/
34 | /profile-out*/
35 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright (c) 2022 Monzo Bank Limited
2 |
3 | Permission is hereby granted, free of charge, to any person obtaining a copy
4 | of this software and associated documentation files (the "Software"), to deal
5 | in the Software without restriction, including without limitation the rights
6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 | copies of the Software, and to permit persons to whom the Software is
8 | furnished to do so, subject to the following conditions:
9 |
10 | The above copyright notice and this permission notice shall be included in all
11 | copies or substantial portions of the Software.
12 |
13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19 | SOFTWARE.
20 |
--------------------------------------------------------------------------------
/snippets/ViewCacheUtil.java:
--------------------------------------------------------------------------------
1 | package com.monzo.commonui;
2 |
3 | import android.util.SparseArray;
4 | import android.view.View;
5 |
6 | import androidx.annotation.IdRes;
7 |
8 | // This class is intentionally written in Java to ensure the return type is a platform type. This is not
9 | // ideal, but we're replacing kotlin synthetic view imports which already use platform types, and there are
10 | // too many call-sites in our app that rely on these fields _sometimes_ being nullable (e.g. where we
11 | // conditionally inflate layouts in some Fragments/Activities).
12 | class ViewCacheUtil {
13 |
14 | @SuppressWarnings("unchecked")
15 | public static T findCachedView(View container, @IdRes int id) {
16 | if (container == null) {
17 | return null;
18 | }
19 | SparseArray viewCache = (SparseArray) container.getTag(R.id.tag_view_cache);
20 | if (viewCache == null) {
21 | viewCache = new SparseArray<>();
22 | container.setTag(R.id.tag_view_cache, viewCache);
23 | }
24 | View view = viewCache.get(id);
25 | if (view == null) {
26 | view = container.findViewById(id);
27 | viewCache.put(id, view);
28 | }
29 | return (T) view;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## kotlin-synthetics-migrator
2 | An Intellij Plugin for migrating an Android app from Kotlin Synthetics to a custom `findById` function.
3 |
4 | #### Prerequsites
5 | 1. Add the necessary `findById` functions to your app. Here's [ours](https://github.com/monzo/kotlin-synthetics-migrator/blob/main/snippets/ViewFinders.kt).
6 | 2. Update the [hardcoded package](https://github.com/monzo/kotlin-synthetics-migrator/blob/92afc6473d59ba04f2ac5277ef6338892b9a982d/src/main/kotlin/com/monzo/syntheticsmigrator/KotlinSyntheticsMigrator.kt#L25) in the tool to point to your new `findById` functions.
7 | 3. Add a `local.properties` file with the following two properties:
8 |
9 | ```
10 | # Note: /Contents at the end is MacOS specific.
11 | studio.path=/Users/bradley/Library/Application Support/JetBrains/Toolbox/apps/AndroidStudio/ch-0/213.5744.223.2113.8103819/Android Studio Preview.app/Contents
12 | studio.version=213.5744.223
13 | ```
14 |
15 | You can find your studio version in `About Android Studio`:
16 |
17 |
18 |
19 |
20 | 4. (Optional) If you have a large project, you might also want to increase the available RAM. Add the following to that `tasks` dsl in `build.gradle.kts`:
21 |
22 | ```
23 | runIde { maxHeapSize = "4g" }
24 | ```
25 |
26 |
27 | #### Usage
28 | `./gradlew runIde`
29 |
30 | This will run Studio with the plugin installed. Open your project, then click `Run Kotlin Synthetics Migrator...` in the `Refactor` menu.
31 |
--------------------------------------------------------------------------------
/snippets/ViewFinders.kt:
--------------------------------------------------------------------------------
1 | package com.monzo.commonui
2 |
3 | import android.app.Activity
4 | import android.view.View
5 | import androidx.annotation.IdRes
6 | import androidx.fragment.app.Fragment
7 | import androidx.recyclerview.widget.RecyclerView
8 |
9 | // This function intentionally returns a platform type. This is not ideal, but we're replacing kotlinx synthetic
10 | // view imports which already use platform types, and there are too many call-sites in our app that rely on these
11 | // fields _sometimes_ being nullable (e.g. where we conditionally inflate layouts in some Fragments/Activities).
12 | @Suppress("HasPlatformType")
13 | fun View.findById(@IdRes id: Int) = ViewCacheUtil.findCachedView(this, id)
14 |
15 | // This function intentionally returns a platform type. This is not ideal, but we're replacing kotlinx synthetic
16 | // view imports which already use platform types, and there are too many call-sites in our app that rely on these
17 | // fields _sometimes_ being nullable (e.g. where we conditionally inflate layouts in some Fragments/Activities).
18 | @Suppress("HasPlatformType")
19 | fun Fragment.findById(@IdRes id: Int) = ViewCacheUtil.findCachedView(view, id)
20 |
21 | // This function intentionally returns a platform type. This is not ideal, but we're replacing kotlinx synthetic
22 | // view imports which already use platform types, and there are too many call-sites in our app that rely on these
23 | // fields _sometimes_ being nullable (e.g. where we conditionally inflate layouts in some Fragments/Activities).
24 | @Suppress("HasPlatformType")
25 | fun Activity.findById(@IdRes id: Int): T {
26 | // We can't use the actual decorView as the cache container, since doesn't get recreated in some configuration
27 | // changes (like split screen). This would cause the cache to survive these changes, which is something we want to
28 | // avoid. Instead, the 'content' view is safe to use, since it does indeed get recreated in these cases.
29 | return ViewCacheUtil.findCachedView(findViewById(android.R.id.content), id)
30 | }
31 |
32 | // This function intentionally returns a platform type. This is not ideal, but we're replacing kotlinx synthetic
33 | // view imports which already use platform types, and there are too many call-sites in our app that rely on these
34 | // fields _sometimes_ being nullable (e.g. where we conditionally inflate layouts in some Fragments/Activities).
35 | @Suppress("HasPlatformType")
36 | fun RecyclerView.ViewHolder.findById(@IdRes id: Int) = ViewCacheUtil.findCachedView(itemView, id)
37 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MSYS* | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------
/src/main/kotlin/com/monzo/syntheticsmigrator/KotlinSyntheticsMigrator.kt:
--------------------------------------------------------------------------------
1 | package com.monzo.syntheticsmigrator
2 |
3 | import com.intellij.openapi.actionSystem.AnAction
4 | import com.intellij.openapi.actionSystem.AnActionEvent
5 | import com.intellij.openapi.actionSystem.PlatformDataKeys
6 | import com.intellij.openapi.application.ReadAction
7 | import com.intellij.openapi.command.WriteCommandAction
8 | import com.intellij.openapi.project.Project
9 | import com.intellij.openapi.roots.ProjectRootManager
10 | import com.intellij.psi.*
11 | import com.intellij.psi.util.PsiTreeUtil
12 | import com.intellij.psi.util.PsiUtilCore
13 | import org.jetbrains.kotlin.android.synthetic.res.AndroidSyntheticProperty
14 | import org.jetbrains.kotlin.descriptors.PropertyDescriptor
15 | import org.jetbrains.kotlin.idea.caches.resolve.analyze
16 | import org.jetbrains.kotlin.idea.core.ShortenReferences
17 | import org.jetbrains.kotlin.idea.intentions.receiverType
18 | import org.jetbrains.kotlin.idea.refactoring.fqName.fqName
19 | import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors
20 | import org.jetbrains.kotlin.name.FqName
21 | import org.jetbrains.kotlin.psi.*
22 | import org.jetbrains.kotlin.resolve.ImportPath
23 | import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
24 |
25 | private const val FindByIdFqn = "com.monzo.commonui.findById"
26 |
27 | class KotlinSyntheticsMigrator : AnAction("Run Kotlin Synthetics Migrator...") {
28 | override fun actionPerformed(e: AnActionEvent) {
29 | val project = e.getData(PlatformDataKeys.PROJECT)!!
30 |
31 | val psiManager = PsiManager.getInstance(project)
32 |
33 | val fileIndex = ProjectRootManager.getInstance(project).fileIndex
34 |
35 | val filesWithSyntheticReferences = mutableListOf()
36 |
37 | // Collect all KtFiles in the app that have synthetic view imports.
38 | ReadAction.compute {
39 | fileIndex.iterateContent { virtualFile ->
40 | // Ignore library files.
41 | if (!fileIndex.isInSource(virtualFile)) return@iterateContent true
42 |
43 | // Ignore idea templates.
44 | if (virtualFile.path.contains(".idea")) return@iterateContent true
45 |
46 | // Only care about Kotlin files with synthetic imports.
47 | if (virtualFile.name.endsWith(".kt")) {
48 | val psiFile = psiManager.findFile(virtualFile) as KtFile
49 | psiFile.toFileWithSyntheticReferencesOrNull()?.let {
50 | filesWithSyntheticReferences += it
51 | }
52 | }
53 |
54 | return@iterateContent true
55 | }
56 | }
57 |
58 | val filesToModify = filesWithSyntheticReferences.map { it.file }
59 | val filesToModifyArray = PsiUtilCore.toPsiFileArray(filesToModify)
60 |
61 | // Run refactoring in a single write command so that we can undo it if anything goes wrong.
62 | WriteCommandAction.runWriteCommandAction(project, null, null, {
63 | for (file in filesWithSyntheticReferences) {
64 | file.process(project)
65 | }
66 |
67 | println("Shortening fully qualified names...")
68 | ShortenReferences.DEFAULT.process(filesToModify)
69 | }, *filesToModifyArray)
70 |
71 | println("Refactor complete!")
72 | }
73 | }
74 |
75 | private fun KtFile.toFileWithSyntheticReferencesOrNull(): FileWithSyntheticReferences? {
76 | val syntheticImports = findSyntheticImports()
77 | if (syntheticImports.isEmpty()) return null
78 |
79 | println("Looking for synthetic view imports in $name")
80 |
81 | val referenceExpressions = PsiTreeUtil
82 | .findChildrenOfType(this, KtReferenceExpression::class.java)
83 |
84 | val syntheticReferences = mutableSetOf()
85 |
86 | for (referenceExpression in referenceExpressions) {
87 | referenceExpression.toSyntheticReferenceOrNull()?.let {
88 | syntheticReferences += it
89 | }
90 | }
91 |
92 | return FileWithSyntheticReferences(
93 | file = this,
94 | syntheticImports = syntheticImports,
95 | syntheticReferences = syntheticReferences
96 | )
97 | }
98 |
99 | private fun KtReferenceExpression.toSyntheticReferenceOrNull(): SyntheticReference? {
100 | val property = resolveMainReferenceToDescriptors()
101 | .filterIsInstance()
102 | .firstOrNull() ?: return null
103 |
104 | val viewType = resolveViewTypeFqn() ?: return null
105 |
106 | var receiverFqn = (property as PropertyDescriptor).receiverType()!!.fqName!!.asString()
107 | if (receiverFqn == "kotlinx.android.extensions.LayoutContainer") {
108 | receiverFqn = "androidx.recyclerview.widget.RecyclerView.ViewHolder"
109 | }
110 |
111 | return SyntheticReference(
112 | viewTypeFqn = viewType,
113 | resourceId = property.resource.id.name,
114 | receiverFqn = receiverFqn
115 | )
116 | }
117 |
118 | private fun FileWithSyntheticReferences.process(project: Project) {
119 | println("Refactoring ${file.name}")
120 |
121 | val psiFactory = KtPsiFactory(project, markGenerated = false)
122 |
123 | val anchorElement = file.lastChild
124 |
125 | // Add all of the new properties to the file.
126 | for (reference in syntheticReferences.reversed()) {
127 | val resourceId = reference.resourceId
128 | val receiver = reference.receiverFqn
129 | val type = reference.viewTypeFqn
130 | val newElement = psiFactory.createProperty(
131 | "private val $receiver.$resourceId inline get() = findById<$type>(R.id.$resourceId)"
132 | )
133 |
134 | file.addAfter(newElement, anchorElement)
135 | }
136 |
137 | // Add a gap between the anchor and all of the new properties.
138 | file.addAfter(psiFactory.createNewLine(2), anchorElement)
139 |
140 | // Delete synthetic imports which should fix any conflict errors.
141 | for (syntheticImport in syntheticImports) {
142 | syntheticImport.delete()
143 | }
144 |
145 | // We know this is not null because we checked earlier to see if there was at least one
146 | // synthetic view import.
147 | val importList = file.importList!!
148 |
149 | // The typical approach for refactoring is to use fully qualified names and then use
150 | // ShortenReferences.DEFAULT.process to automatically add imports. However fully qualified
151 | // names do not work for extension functions, so we have to insert this import ourselves
152 | if (importList.imports.none { it.importPath?.pathStr == FindByIdFqn }) {
153 | importList.add(
154 | psiFactory.createImportDirective(
155 | ImportPath(
156 | FqName(FindByIdFqn),
157 | false,
158 | null
159 | )
160 | )
161 | )
162 | }
163 | }
164 |
165 | private data class FileWithSyntheticReferences(
166 | val file: KtFile,
167 | val syntheticImports: List,
168 | val syntheticReferences: Set
169 | )
170 |
171 | private data class SyntheticReference(
172 | val viewTypeFqn: String,
173 | val resourceId: String,
174 | val receiverFqn: String
175 | )
176 |
177 | private fun KtReferenceExpression.resolveViewTypeFqn(): String? {
178 | return analyze(BodyResolveMode.PARTIAL).getType(this)?.fqName?.asString()
179 | }
180 |
181 | private fun KtFile.findSyntheticImports(): List {
182 | val importList = importList ?: return emptyList()
183 | val importElements = PsiTreeUtil.findChildrenOfType(importList, KtImportDirective::class.java)
184 | return importElements.filter {
185 | it.importPath?.pathStr?.startsWith("kotlinx.android.synthetic") ?: false
186 | }
187 | }
188 |
--------------------------------------------------------------------------------