├── settings.gradle
├── art
├── logo.png
└── logo.svg
├── .gitignore
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── src
├── main
│ └── java
│ │ └── io
│ │ └── noties
│ │ └── enhance
│ │ ├── options
│ │ ├── SourceFormat.java
│ │ ├── EnhanceOptions.java
│ │ └── EnhanceOptionsImpl.java
│ │ ├── Log.java
│ │ ├── ApiInfo.java
│ │ ├── EnhanceWriter.java
│ │ ├── ApiVersionFormatter.java
│ │ ├── ApiInfoStore.java
│ │ ├── SdkHelper.java
│ │ ├── Api.java
│ │ ├── Stats.java
│ │ ├── ByteCodeSignature.java
│ │ ├── Enhance.java
│ │ ├── ApiInfoStoreImpl.java
│ │ └── EnhanceWriterImpl.java
└── test
│ └── java
│ └── io
│ └── noties
│ └── enhance
│ ├── ApiInfoStoreImplTest.java
│ └── ApiTest.java
├── CHANGELOG.md
├── .run
└── Enhance.run.xml
├── gradlew.bat
├── README.md
├── gradlew
└── LICENSE
/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'enhance'
2 |
3 |
--------------------------------------------------------------------------------
/art/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/noties/Enhance/HEAD/art/logo.png
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /.gradle
2 | /.idea
3 | **/build
4 | **/out
5 | **/gen
6 | *.DS_Store
7 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/noties/Enhance/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/src/main/java/io/noties/enhance/options/SourceFormat.java:
--------------------------------------------------------------------------------
1 | package io.noties.enhance.options;
2 |
3 | public enum SourceFormat {
4 | NONE,
5 | AOSP,
6 | GOOGLE
7 | }
8 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-all.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 |
--------------------------------------------------------------------------------
/src/main/java/io/noties/enhance/Log.java:
--------------------------------------------------------------------------------
1 | package io.noties.enhance;
2 |
3 | import javax.annotation.Nonnull;
4 |
5 | public abstract class Log {
6 |
7 | public static void log(@Nonnull String msg, Object... args) {
8 | System.out.printf(msg, args);
9 | System.out.println();
10 | }
11 |
12 | private Log() {
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/io/noties/enhance/options/EnhanceOptions.java:
--------------------------------------------------------------------------------
1 | package io.noties.enhance.options;
2 |
3 | import javax.annotation.Nonnull;
4 |
5 | public abstract class EnhanceOptions {
6 |
7 | @Nonnull
8 | public static EnhanceOptions create(String[] args) {
9 | return new EnhanceOptionsImpl(args);
10 | }
11 |
12 | @Nonnull
13 | public abstract String androidSdkPath();
14 |
15 | @Nonnull
16 | public abstract SourceFormat sourceFormat();
17 |
18 | public abstract boolean emitDiff();
19 |
20 | public abstract int sdk();
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/io/noties/enhance/ApiInfo.java:
--------------------------------------------------------------------------------
1 | package io.noties.enhance;
2 |
3 | import javax.annotation.Nullable;
4 |
5 | public class ApiInfo {
6 |
7 | @Nullable
8 | public final Integer since;
9 | @Nullable public final Integer deprecated;
10 |
11 | public ApiInfo(@Nullable Integer since, @Nullable Integer deprecated) {
12 | this.since = since;
13 | this.deprecated = deprecated;
14 | }
15 |
16 | @Override
17 | public String toString() {
18 | return "ApiInfo{" +
19 | "since='" + since + '\'' +
20 | ", deprecated='" + deprecated + '\'' +
21 | '}';
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/io/noties/enhance/EnhanceWriter.java:
--------------------------------------------------------------------------------
1 | package io.noties.enhance;
2 |
3 | import io.noties.enhance.options.SourceFormat;
4 |
5 | import javax.annotation.Nonnull;
6 | import java.io.File;
7 |
8 | public abstract class EnhanceWriter {
9 |
10 | @Nonnull
11 | public static EnhanceWriter create(
12 | int sdk,
13 | @Nonnull SourceFormat format,
14 | @Nonnull ApiInfoStore apiInfoStore,
15 | @Nonnull ApiVersionFormatter apiVersionFormatter
16 | ) {
17 | return new EnhanceWriterImpl(sdk, format, apiInfoStore, apiVersionFormatter);
18 | }
19 |
20 | public abstract void write(@Nonnull File source, @Nonnull File destination);
21 | }
22 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # CHANGELOG
2 |
3 | # 34
4 | Applied new version-name strategy - now version equals latest supported Android SDK platform
5 | ### Added
6 | * Upside Down Cake (34)
7 |
8 | ### Changed
9 | * Updated code structure, moved to `io.noties` package (no change for clients)
10 |
11 |
12 | # 1.3.0
13 | ### Added
14 | * Android S_V2 (32)
15 | * Tiramisu (33)
16 |
17 |
18 | # 1.2.0
19 | ### Added
20 | * Android 12, SDK 31 API version
21 |
22 | # 1.1.1
23 | ### Fixed
24 | * Error message when SDK path is missing ([#2])
Thanks [@drakeet]
25 |
26 | [#2]: https://github.com/noties/Enhance/pull/2
27 | [@drakeet]: https://github.com/drakeet
28 |
29 | # 1.1.0
30 | ### Added
31 | * Android 11 (R) api version
32 | * Ability to generate just the diff with the `diff` command line option
33 |
34 | ### Fixed
35 | * signature generation in `ApiInfoStoreImpl`
--------------------------------------------------------------------------------
/src/main/java/io/noties/enhance/ApiVersionFormatter.java:
--------------------------------------------------------------------------------
1 | package io.noties.enhance;
2 |
3 | import javax.annotation.Nonnull;
4 |
5 | public abstract class ApiVersionFormatter {
6 |
7 | @Nonnull
8 | public static ApiVersionFormatter create() {
9 | return new Impl();
10 | }
11 |
12 | @Nonnull
13 | public abstract String format(int version);
14 |
15 |
16 | private static class Impl extends ApiVersionFormatter {
17 |
18 | @Nonnull
19 | @Override
20 | public String format(int version) {
21 | final Api api = Api.of(version);
22 | if (api != null) {
23 | // for example - @since 5.1 Lollipop (22)
24 | return api.versionName + " " + api.codeName + " (" + api.sdkInt + ")";
25 | }
26 | return "unknown (" + version + ")";
27 | }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/.run/Enhance.run.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/src/main/java/io/noties/enhance/ApiInfoStore.java:
--------------------------------------------------------------------------------
1 | package io.noties.enhance;
2 |
3 | import javax.annotation.Nonnull;
4 | import javax.annotation.Nullable;
5 | import java.io.File;
6 | import java.util.HashMap;
7 | import java.util.Map;
8 |
9 | public abstract class ApiInfoStore {
10 |
11 | @Nonnull
12 | public static ApiInfoStore create(@Nonnull File apiVersions) {
13 | return new ApiInfoStoreImpl(apiVersions);
14 | }
15 |
16 | public static class TypeVersion extends ApiInfo {
17 |
18 | final Map fields = new HashMap<>(3);
19 | final Map methods = new HashMap<>(3);
20 |
21 | TypeVersion(@Nullable Integer since, @Nullable Integer deprecated) {
22 | super(since, deprecated);
23 | }
24 | }
25 |
26 | @Nullable
27 | public abstract ApiInfo type(@Nonnull String type);
28 |
29 | @Nullable
30 | public abstract ApiInfo field(@Nonnull String type, @Nonnull String name);
31 |
32 | @Nullable
33 | public abstract ApiInfo method(@Nonnull String type, @Nonnull String signature);
34 |
35 | @Nonnull
36 | public abstract Map info();
37 | }
38 |
--------------------------------------------------------------------------------
/src/test/java/io/noties/enhance/ApiInfoStoreImplTest.java:
--------------------------------------------------------------------------------
1 | package io.noties.enhance;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.HashMap;
6 | import java.util.Map;
7 |
8 | import static org.junit.Assert.assertEquals;
9 | import static io.noties.enhance.ApiInfoStoreImpl.Parser.normalizeMethodSignature;
10 |
11 | public class ApiInfoStoreImplTest {
12 |
13 | @Test
14 | public void test() {
15 |
16 | final Map map = new HashMap() {{
17 | put("instantiateClassLoader(Ljava/lang/ClassLoader;Landroid/content/pm/ApplicationInfo;)Ljava/lang/ClassLoader;", "instantiateClassLoader(LClassLoader;LApplicationInfo;)LClassLoader;");
18 | put("setSingleChoiceItems([Ljava/lang/CharSequence;ILandroid/content/DialogInterface$OnClickListener;)Landroid/app/AlertDialog$Builder;", "setSingleChoiceItems([LCharSequence;ILOnClickListener;)LBuilder;");
19 | put("readFloat()F", "readFloat()F");
20 | put("readDoubleArray([D)V", "readDoubleArray([D)V");
21 | put("obtain(I)Landroid/os/Parcel;", "obtain(I)LParcel;");
22 | put("isPseudoLocale(Landroid/icu/util/ULocale;)Z", "isPseudoLocale(LULocale;)Z");
23 | put("readParcelableList(Ljava/util/List;Ljava/lang/ClassLoader;)Ljava/util/List;", "readParcelableList(LList;LClassLoader;)LList;");
24 | }};
25 |
26 | for (Map.Entry entry : map.entrySet()) {
27 | assertEquals(entry.getKey(), entry.getValue(), normalizeMethodSignature(entry.getKey()));
28 | }
29 | }
30 | }
--------------------------------------------------------------------------------
/src/test/java/io/noties/enhance/ApiTest.java:
--------------------------------------------------------------------------------
1 | package io.noties.enhance;
2 |
3 | import org.checkerframework.checker.units.qual.A;
4 | import org.junit.Assert;
5 | import org.junit.Test;
6 |
7 | import static org.junit.Assert.*;
8 |
9 | public class ApiTest {
10 |
11 | @Test
12 | public void testOf() {
13 | final int length = Api.values().length;
14 | // index starts at 0, but values start at 1
15 | for (int i = 1, max = length + 1; i < max; i++) {
16 | final Api api = Api.of(i);
17 | assertNotNull(String.valueOf(i), api);
18 | assertEquals(String.valueOf(i), i, api.sdkInt);
19 | }
20 | }
21 |
22 | @Test
23 | public void testUnknown() {
24 | final Api[] values = Api.values();
25 | final int max = values[values.length - 1].sdkInt;
26 |
27 | final int[] inputs = {
28 | Integer.MIN_VALUE,
29 | -1,
30 | 0,
31 | max + 1,
32 | max + 2,
33 | Integer.MAX_VALUE
34 | };
35 |
36 | for (int input: inputs) {
37 | assertNull(String.valueOf(input), Api.of(input));
38 | }
39 | }
40 |
41 | @Test
42 | public void testSequential() {
43 | final Api[] values = Api.values();
44 |
45 | // verify all go without interruption from 1 to max
46 | assertEquals(1, values[0].sdkInt);
47 |
48 | for (int i = 1, length = values.length; i < length; i++) {
49 | final Api api = values[i];
50 | assertEquals(
51 | "i:" + i + ", api:" + api,
52 | values[i - 1].sdkInt + 1,
53 | api.sdkInt
54 | );
55 | }
56 | }
57 | }
--------------------------------------------------------------------------------
/src/main/java/io/noties/enhance/SdkHelper.java:
--------------------------------------------------------------------------------
1 | package io.noties.enhance;
2 |
3 | import io.noties.enhance.options.EnhanceOptions;
4 |
5 | import javax.annotation.Nonnull;
6 | import java.io.File;
7 |
8 | public abstract class SdkHelper {
9 |
10 | @Nonnull
11 | public static SdkHelper create(@Nonnull EnhanceOptions options) {
12 | return new Impl(options);
13 | }
14 |
15 | @Nonnull
16 | public abstract String folder();
17 |
18 | @Nonnull
19 | public abstract File apiVersions();
20 |
21 | @Nonnull
22 | public abstract File source();
23 |
24 |
25 | private static class Impl extends SdkHelper {
26 |
27 | private final String folder;
28 |
29 | private final File apiVersions;
30 | private final File source;
31 |
32 | private Impl(@Nonnull EnhanceOptions options) {
33 |
34 | final File platforms = new File(options.androidSdkPath(), "platforms");
35 | final File sources = new File(options.androidSdkPath(), "sources");
36 |
37 | if (!platforms.exists()) {
38 | throw new IllegalStateException("Cannot find 'platforms' folder at specified path: " + platforms.getPath());
39 | }
40 |
41 | if (!sources.exists()) {
42 | throw new IllegalStateException("Cannot find 'sources' folder at specified path: " + sources.getPath());
43 | }
44 |
45 | folder = "android-" + options.sdk();
46 |
47 | apiVersions = new File(platforms, folder + "/data/api-versions.xml");
48 |
49 | if (!apiVersions.exists()) {
50 | throw new IllegalStateException("Cannot find 'api-versions.xml' file at the specified path: " + apiVersions.getPath());
51 | }
52 |
53 | source = new File(sources, folder);
54 |
55 | if (!source.exists()) {
56 | throw new IllegalStateException("Cannot find '" + folder + "' folder at specified path: " + source.getPath());
57 | }
58 | }
59 |
60 | @Nonnull
61 | @Override
62 | public String folder() {
63 | return folder;
64 | }
65 |
66 | @Nonnull
67 | @Override
68 | public File apiVersions() {
69 | return apiVersions;
70 | }
71 |
72 | @Nonnull
73 | @Override
74 | public File source() {
75 | return source;
76 | }
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/src/main/java/io/noties/enhance/Api.java:
--------------------------------------------------------------------------------
1 | package io.noties.enhance;
2 |
3 | import javax.annotation.Nonnull;
4 | import javax.annotation.Nullable;
5 | import java.util.EnumMap;
6 | import java.util.List;
7 |
8 | public enum Api {
9 | SDK_1(1, "1.0", "(initial)"),
10 | SDK_2(2, "1.1", "(initial)"),
11 | SDK_3(3, "1.5", "Cupcake"),
12 | SDK_4(4, "1.6", "Donut"),
13 | SDK_5(5, "2.0", "Eclair"),
14 | SDK_6(6, "2.0.1", "Eclair"),
15 | SDK_7(7, "2.1", "Eclair"),
16 | SDK_8(8, "2.2", "Froyo"),
17 | SDK_9(9, "2.3", "Gingerbread"),
18 | SDK_10(10, "2.3.3", "Gingerbread"),
19 | SDK_11(11, "3.0", "Honeycomb"),
20 | SDK_12(12, "3.1", "Honeycomb"),
21 | SDK_13(13, "3.2", "Honeycomb"),
22 | SDK_14(14, "4.0", "Ice Scream Sandwich"),
23 | SDK_15(15, "4.0.3", "Ice Scream Sandwich"),
24 | SDK_16(16, "4.1", "Jelly Bean"),
25 | SDK_17(17, "4.2", "Jelly Bean"),
26 | SDK_18(18, "4.3", "Jelly Bean"),
27 | SDK_19(19, "4.4", "Kitkat"),
28 | SDK_20(20, "4.4W", "Kitkat"),
29 | SDK_21(21, "5.0", "Lollipop"),
30 | SDK_22(22, "5.1", "Lollipop"),
31 | SDK_23(23, "6.0", "Marshmallow"),
32 | SDK_24(24, "7.0", "Nougat"),
33 | SDK_25(25, "7.1", "Nougat"),
34 | SDK_26(26, "8.0", "Oreo"),
35 | SDK_27(27, "8.1", "Oreo"),
36 | SDK_28(28, "9.0", "Pie"),
37 | SDK_29(29, "10", "Android Q"),
38 | SDK_30(30, "11", "Android R"),
39 | SDK_31(31, "12", "Android S"),
40 | SDK_32(32, "12", "Android S_V2"),
41 | SDK_33(33, "13", "Tiramisu"),
42 | SDK_34(34, "14", "Upside Down Cake")
43 | ;
44 |
45 | public final int sdkInt;
46 | public final String versionName;
47 | public final String codeName;
48 |
49 | Api(int sdkInt, @Nonnull String versionName, @Nonnull String codeName) {
50 | this.sdkInt = sdkInt;
51 | this.versionName = versionName;
52 | this.codeName = codeName;
53 | }
54 |
55 | @Override
56 | public String toString() {
57 | return "Api.SDK{" +
58 | "sdkInt=" + sdkInt +
59 | ", versionName='" + versionName + '\'' +
60 | ", codeName='" + codeName + '\'' +
61 | '}';
62 | }
63 |
64 | private static final List VALUES = List.of(values());
65 |
66 | @Nonnull
67 | public static Api latest() {
68 | return VALUES.get(VALUES.size() - 1);
69 | }
70 |
71 | @Nullable
72 | public static Api of(int sdkInt) {
73 | // NB! we assume that it starts at 1
74 | // so, SDK_1 is at 0, SDK_2 at 1, etc
75 | final int ordinal = sdkInt - 1;
76 | if (ordinal < 0 || ordinal >= VALUES.size()) {
77 | return null;
78 | }
79 | return VALUES.get(ordinal);
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/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% equ 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% equ 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 | set EXIT_CODE=%ERRORLEVEL%
84 | if %EXIT_CODE% equ 0 set EXIT_CODE=1
85 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
86 | exit /b %EXIT_CODE%
87 |
88 | :mainEnd
89 | if "%OS%"=="Windows_NT" endlocal
90 |
91 | :omega
92 |
--------------------------------------------------------------------------------
/src/main/java/io/noties/enhance/options/EnhanceOptionsImpl.java:
--------------------------------------------------------------------------------
1 | package io.noties.enhance.options;
2 |
3 | import org.apache.commons.cli.*;
4 |
5 | import javax.annotation.Nonnull;
6 |
7 | class EnhanceOptionsImpl extends EnhanceOptions {
8 |
9 | private static final String SDK_PATH = "sp";
10 | private static final String FORMAT = "format";
11 | private static final String SDK = "sdk";
12 | private static final String HELP = "h";
13 | private static final String DIFF = "diff";
14 |
15 | private final CommandLine commandLine;
16 |
17 | EnhanceOptionsImpl(String[] args) {
18 |
19 | final Options options = createOptions();
20 | final CommandLineParser parser = new DefaultParser();
21 |
22 | try {
23 | commandLine = parser.parse(options, args);
24 | } catch (ParseException e) {
25 | // print help and exit
26 | new HelpFormatter().printHelp("Enhance", options);
27 | throw new IllegalStateException(e);
28 | }
29 |
30 | if (commandLine.hasOption('h')) {
31 | new HelpFormatter().printHelp("Enhance", options);
32 | }
33 | }
34 |
35 | @Nonnull
36 | @Override
37 | public String androidSdkPath() {
38 | final String out;
39 | if (commandLine.hasOption(SDK_PATH)) {
40 | out = commandLine.getOptionValue(SDK_PATH);
41 | } else {
42 | final String system = System.getenv("ANDROID_HOME");
43 | if (system == null
44 | || system.length() == 0) {
45 | throw new IllegalStateException("Cannot find 'ANDROID_HOME' system variable. Define it on " +
46 | "the system level or specify with `-" + SDK_PATH + "` option");
47 | }
48 | out = system;
49 | }
50 | return out;
51 | }
52 |
53 | @Nonnull
54 | @Override
55 | public SourceFormat sourceFormat() {
56 |
57 | final SourceFormat format;
58 |
59 | final String value = commandLine.getOptionValue(FORMAT, "");
60 |
61 | if ("aosp".equals(value)) {
62 | format = SourceFormat.AOSP;
63 | } else if ("google".equals(value)) {
64 | format = SourceFormat.GOOGLE;
65 | } else {
66 | format = SourceFormat.NONE;
67 | }
68 |
69 | return format;
70 | }
71 |
72 | @Override
73 | public boolean emitDiff() {
74 | return commandLine.hasOption(DIFF);
75 | }
76 |
77 | @Override
78 | public int sdk() {
79 | final String value = commandLine.getOptionValue(SDK, "0");
80 | return Integer.parseInt(value);
81 | }
82 |
83 | @Nonnull
84 | private static Options createOptions() {
85 |
86 | final Options options = new Options();
87 |
88 | options.addOption(SDK_PATH, "sdk-path", true, "Path to Android SDK. If not " +
89 | "specified 'ANDROID_HOME' system variable will be used");
90 |
91 | options.addOption(FORMAT, true, "Format sources. Accepts (aosp|google). Everything else " +
92 | "would keep original formatting");
93 |
94 | options.addOption(Option.builder(SDK)
95 | .required(true)
96 | .hasArg(true)
97 | .desc("Specify which SDK version to process.")
98 | .build());
99 |
100 | options.addOption(DIFF, false, "Emit diff");
101 |
102 | options.addOption(HELP, "help", false, "Prints help");
103 |
104 | return options;
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/src/main/java/io/noties/enhance/Stats.java:
--------------------------------------------------------------------------------
1 | package io.noties.enhance;
2 |
3 | import javax.annotation.Nonnull;
4 | import java.util.*;
5 |
6 | abstract class Stats {
7 |
8 | static void printStatsFor(@Nonnull Integer version, @Nonnull Map info) {
9 |
10 | // filter
11 | final Map filtered = new HashMap<>();
12 |
13 | for (Map.Entry types : info.entrySet()) {
14 |
15 | final ApiInfoStore.TypeVersion original = types.getValue();
16 | final ApiInfoStore.TypeVersion typeVersion = new ApiInfoStore.TypeVersion(original.since, original.deprecated);
17 |
18 | for (Map.Entry fields : original.fields.entrySet()) {
19 | if (shouldEmit(version, fields.getValue())) {
20 | typeVersion.fields.put(fields.getKey(), fields.getValue());
21 | }
22 | }
23 |
24 | for (Map.Entry methods : original.methods.entrySet()) {
25 | if (shouldEmit(version, methods.getValue())) {
26 | typeVersion.methods.put(methods.getKey(), methods.getValue());
27 | }
28 | }
29 |
30 | if (shouldEmit(version, original)
31 | || (!typeVersion.fields.isEmpty() || !typeVersion.methods.isEmpty())) {
32 | filtered.put(types.getKey(), typeVersion);
33 | }
34 | }
35 |
36 | final StringBuilder builder = new StringBuilder();
37 |
38 | for (String type : sorted(filtered.keySet())) {
39 | builder.setLength(0);
40 | builder.append("```diff\n");
41 |
42 | final ApiInfoStore.TypeVersion typeVersion = filtered.get(type);
43 | appendDiffed(builder, version, typeVersion);
44 | builder
45 | .append(type)
46 | .append('\n');
47 |
48 | final Map fields = typeVersion.fields;
49 | final Map methods = typeVersion.methods;
50 |
51 | for (String field : sorted(fields.keySet())) {
52 | if (appendDiffed(builder, version, fields.get(field))) {
53 | builder.append(" ")
54 | .append(field)
55 | .append("\n");
56 | }
57 | }
58 |
59 | for (String method : sorted(methods.keySet())) {
60 | if (appendDiffed(builder, version, methods.get(method))) {
61 | builder.append(" ")
62 | .append(method)
63 | .append("\n");
64 | }
65 | }
66 |
67 | builder.append("```\n\n");
68 | System.out.println(builder);
69 | }
70 | }
71 |
72 | private static boolean shouldEmit(@Nonnull Integer version, @Nonnull ApiInfo info) {
73 | return version.equals(info.since) || version.equals(info.deprecated);
74 | }
75 |
76 | private static List sorted(@Nonnull Collection collection) {
77 | final List list = new ArrayList<>(collection);
78 | Collections.sort(list);
79 | return list;
80 | }
81 |
82 | private static boolean appendDiffed(
83 | @Nonnull StringBuilder builder,
84 | @Nonnull Integer version,
85 | @Nonnull ApiInfo info) {
86 |
87 | // priority for deprecated (some nodes are both added and deprecated in the same version)
88 |
89 | boolean result = false;
90 |
91 | if (version.equals(info.deprecated)) {
92 | builder.append('-');
93 | result = true;
94 | }
95 |
96 | if (version.equals(info.since)) {
97 | builder.append('+');
98 | result = true;
99 | }
100 |
101 | return result;
102 | }
103 |
104 | private Stats() {
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Enhance!
2 |
3 |
4 |
5 | Command line utility to process Android source files distributed via SDK manager and add API version information as javadoc tags:
6 |
7 | ```java
8 | /**
9 | * Called by the system when the activity changes from fullscreen mode to multi-window mode and
10 | * visa-versa.
11 | *
12 | * @see android.R.attr#resizeableActivity
13 | * @param isInMultiWindowMode True if the activity is in multi-window mode.
14 | * @deprecated Use {@link #onMultiWindowModeChanged(boolean, Configuration)} instead.
15 | * @since 7.0 Nougat (24)
16 | * @deprecated 8.0 Oreo (26)
17 | */
18 | @Deprecated
19 | public void onMultiWindowModeChanged(boolean isInMultiWindowMode) {
20 | // Left deliberately empty. There should be no side effects if a direct
21 | // subclass of Activity does not call super.
22 | }
23 | ```
24 |
25 | Ironically allows to **actually format** processed code with **AOSP** code style specification (and as [google-java-format](https://github.com/google/google-java-format) is used - `GOOGLE` style is also supported).
26 |
27 | ---
28 |
29 | Pick the `jar` file from the latest [release](https://github.com/noties/Enhance/releases/latest/).
30 |
31 | There are few configuration options:
32 | * `sdk`: (required) Android SDK version (for example 25)
33 | * `format`: Allows to format processed Java source files. Available options are: `aosp` and `google`. Everything else (including empty argument) won't format processed code
34 | * `sp`: path to Android SDK
35 | * `diff`: just generate statistics info/diff for specified SDK version
36 |
37 | ```
38 | usage: Enhance
39 | -diff Emit diff
40 | -format Format sources. Accepts (aosp|google). Everything
41 | else would keep original formatting
42 | -h,--help Prints help
43 | -sdk Specify which SDK version to process.
44 | -sp,--sdk-path Path to Android SDK. If not specified
45 | 'ANDROID_HOME' system variable will be used
46 | ```
47 |
48 | Please note that you Android SDK folder must already contain sources for specified `sdk` version.
49 |
50 | So, usage would be like that:
51 |
52 | ```bash
53 | # just add api information to source code, no formatting
54 | java -jar enhance.jar -sdk 26
55 |
56 | # also format with AOSP
57 | java -jar enhance.jar -sdk 26 -format aosp
58 |
59 | # or GOOGLE
60 | java -jar enhance.jar -sdk 26 -format google
61 |
62 | # or with custom SDK path
63 | java -jar enhance.jar -sdk 26 -sp "/Users/not_me/android/sdk"
64 | ```
65 |
66 | If you would like to restore unmodified copy of source code you can find it: `{your-home-directory}/.enhance-backup/android-{sdk}`
67 |
68 | ## Formatting on JDK 17
69 | Formatting is done with the [google-java-format](https://github.com/google/google-java-format) library
70 | which requires access to the internals of the JDK. This is why on JDK-17 in order to format
71 | the sources additional commandline arguments are required:
72 |
73 | ```bash
74 | java \
75 | --add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED \
76 | --add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED \
77 | --add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED \
78 | --add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED \
79 | --add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED \
80 | --add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED \
81 | -jar enhance-34-all.jar -sdk 34 -format google
82 | ```
83 |
84 | ## Thanks
85 |
86 | Big kudos to the maintainers of amazing [javaparser](https://github.com/javaparser/javaparser)!
87 |
88 | ## License
89 |
90 | ```
91 | Copyright 2018 Dimitry Ivanov (legal@noties.io)
92 |
93 | Licensed under the Apache License, Version 2.0 (the "License");
94 | you may not use this file except in compliance with the License.
95 | You may obtain a copy of the License at
96 |
97 | http://www.apache.org/licenses/LICENSE-2.0
98 |
99 | Unless required by applicable law or agreed to in writing, software
100 | distributed under the License is distributed on an "AS IS" BASIS,
101 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
102 | See the License for the specific language governing permissions and
103 | limitations under the License.
104 | ```
--------------------------------------------------------------------------------
/src/main/java/io/noties/enhance/ByteCodeSignature.java:
--------------------------------------------------------------------------------
1 | package io.noties.enhance;
2 |
3 | import com.github.javaparser.ast.body.CallableDeclaration;
4 | import com.github.javaparser.ast.body.MethodDeclaration;
5 | import com.github.javaparser.ast.body.Parameter;
6 | import com.github.javaparser.ast.type.ArrayType;
7 | import com.github.javaparser.ast.type.ClassOrInterfaceType;
8 | import com.github.javaparser.ast.type.PrimitiveType;
9 | import com.github.javaparser.ast.type.Type;
10 |
11 | import javax.annotation.Nonnull;
12 |
13 | public abstract class ByteCodeSignature {
14 |
15 | @Nonnull
16 | public static String create(@Nonnull CallableDeclaration> declaration) {
17 | return new Creator(declaration).get();
18 | }
19 |
20 | private ByteCodeSignature() {
21 | }
22 |
23 | private static class Creator {
24 |
25 | private final CallableDeclaration> declaration;
26 |
27 | private final StringBuilder builder = new StringBuilder();
28 |
29 | Creator(@Nonnull CallableDeclaration> declaration) {
30 | this.declaration = declaration;
31 | name();
32 | parameters();
33 | returnType();
34 | }
35 |
36 | @Nonnull
37 | String get() {
38 | return builder.toString();
39 | }
40 |
41 | private void name() {
42 | if (declaration.isConstructorDeclaration()) {
43 | builder.append("");
44 | } else {
45 | builder.append(declaration.getNameAsString());
46 | }
47 | }
48 |
49 | private void parameters() {
50 | builder.append('(');
51 | for (Parameter parameter : declaration.getParameters()) {
52 | type(parameter.getType());
53 | }
54 | builder.append(')');
55 | }
56 |
57 | private void returnType() {
58 | if (declaration.isConstructorDeclaration()) {
59 | builder.append('V');
60 | } else {
61 | type(((MethodDeclaration) declaration).getType());
62 | }
63 | }
64 |
65 | private void type(@Nonnull Type type) {
66 |
67 | while (type.isArrayType()) {
68 | builder.append('[');
69 | type = ((ArrayType) type).getComponentType();
70 | }
71 |
72 | if (type.isVoidType()) {
73 | builder.append('V');
74 | } else if (type.isPrimitiveType()) {
75 | primitiveType((PrimitiveType) type);
76 | } else {
77 | classOrInterfaceType((ClassOrInterfaceType) type);
78 | }
79 | }
80 |
81 | private void primitiveType(@Nonnull PrimitiveType primitiveType) {
82 | switch (primitiveType.getType()) {
83 |
84 | case BOOLEAN:
85 | builder.append('Z');
86 | break;
87 |
88 | case CHAR:
89 | builder.append('C');
90 | break;
91 |
92 | case BYTE:
93 | builder.append('B');
94 | break;
95 |
96 | case SHORT:
97 | builder.append('S');
98 | break;
99 |
100 | case INT:
101 | builder.append('I');
102 | break;
103 |
104 | case LONG:
105 | builder.append('J');
106 | break;
107 |
108 | case FLOAT:
109 | builder.append('F');
110 | break;
111 |
112 | case DOUBLE:
113 | builder.append('D');
114 | break;
115 | }
116 | }
117 |
118 | // NB simplified signature here (no package info nor parent)
119 | private void classOrInterfaceType(@Nonnull ClassOrInterfaceType classOrInterfaceType) {
120 | builder.append('L');
121 |
122 | String value = classOrInterfaceType.asString();
123 |
124 | final int index = value.lastIndexOf('.');
125 | if (index > -1) {
126 | value = value.substring(index + 1);
127 | }
128 | builder.append(value);
129 | builder.append(';');
130 | }
131 | }
132 | }
133 |
--------------------------------------------------------------------------------
/src/main/java/io/noties/enhance/Enhance.java:
--------------------------------------------------------------------------------
1 | package io.noties.enhance;
2 |
3 | import io.noties.enhance.options.EnhanceOptions;
4 | import org.apache.commons.io.FileUtils;
5 |
6 | import javax.annotation.Nonnull;
7 | import java.io.BufferedReader;
8 | import java.io.File;
9 | import java.io.IOException;
10 | import java.io.InputStreamReader;
11 | import java.util.Locale;
12 |
13 | import static io.noties.enhance.Log.log;
14 | import static io.noties.enhance.Stats.printStatsFor;
15 |
16 | public class Enhance {
17 |
18 | private static final String APP_FOLDER = ".enhance-backup";
19 |
20 | public static void main(String[] args) {
21 |
22 | final ApiVersionFormatter apiVersionFormatter = ApiVersionFormatter.create();
23 |
24 | log("[Enhance] version: %s", EnhanceVersion.NAME);
25 | log("[Enhance] latest Android SDK version: %s", apiVersionFormatter.format(Api.latest().sdkInt));
26 | log("[Enhance] https://github.com/noties/Enhance");
27 |
28 | final EnhanceOptions options = EnhanceOptions.create(args);
29 |
30 | // @since 1.0.2
31 | // check if we have this version info included and ask user if he/she want to proceed if
32 | // supplied sdk is not known to this library version
33 | final int sdk = options.sdk();
34 | final Api api = Api.of(sdk);
35 |
36 | if (api == null) {
37 |
38 | System.err.printf(Locale.US, "[Enhance] WARNING: specified SDK version %d is unknown to this " +
39 | "library version, do you wish to proceed anyway? (Y|N)%n", sdk);
40 |
41 | try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
42 | final String line = reader.readLine();
43 | if (!"y".equalsIgnoreCase(line)) {
44 | return;
45 | }
46 | } catch (IOException e) {
47 | throw new RuntimeException(e);
48 | }
49 | }
50 |
51 | final long start = System.currentTimeMillis();
52 |
53 | log("[Enhance] obtaining required files/folders");
54 |
55 | final SdkHelper sdkHelper = SdkHelper.create(options);
56 |
57 | log("[Enhance] obtaining application backup directory");
58 |
59 | final File appFolder = new File(System.getProperty("user.home"), APP_FOLDER);
60 | if (!appFolder.exists()) {
61 | if (!appFolder.mkdirs()) {
62 | throw new RuntimeException("Cannot create application backup directory at path: " + appFolder.getPath());
63 | }
64 | }
65 |
66 | log("[Enhance] parsing api-versions.xml");
67 |
68 | final ApiInfoStore store = ApiInfoStore.create(sdkHelper.apiVersions());
69 | if (options.emitDiff()) {
70 | log("[Enhance] emit diff for api:%s", api != null ? api : sdk);
71 | printStatsFor(sdk, store.info());
72 | return;
73 | }
74 |
75 | final File sdkSources = sdkHelper.source();
76 |
77 | final File source;
78 | {
79 | final String folder = sdkHelper.folder();
80 | final File file = new File(appFolder, folder);
81 | if (!file.exists()) {
82 |
83 | if (!file.mkdirs()) {
84 | throw new RuntimeException("Cannot create android sources backup folder at: " + file.getPath());
85 | }
86 |
87 | // backup sources first
88 |
89 | log("[Enhance] backing up android sources, from: `%s` to: `%s`", sdkSources.getPath(), file.getPath());
90 |
91 | try {
92 | FileUtils.copyDirectory(sdkSources, file);
93 | } catch (IOException e) {
94 |
95 | // let's try to remove backup directory
96 | try {
97 | FileUtils.cleanDirectory(file);
98 | //noinspection ResultOfMethodCallIgnored
99 | file.delete();
100 | } catch (IOException e1) {
101 | // no op
102 | }
103 |
104 | throw new RuntimeException(e);
105 | }
106 |
107 | }
108 | source = file;
109 | }
110 |
111 | // now, we duplicate files from backup to source, if it's java and there api info -> parse and api info
112 |
113 | final File[] files = source.listFiles();
114 | if (files == null
115 | || files.length == 0) {
116 | throw new RuntimeException("Unexpected state of the source directory: it is empty. Try removing it first: " + source.getPath());
117 | }
118 |
119 | log("[Enhance] cleaning the original source folder: `%s`", sdkSources.getPath());
120 |
121 | try {
122 | FileUtils.cleanDirectory(sdkSources);
123 | } catch (IOException e) {
124 | throw new RuntimeException(e);
125 | }
126 |
127 | log("[Enhance] processing source files");
128 |
129 | final EnhanceWriter writer = EnhanceWriter.create(
130 | sdk,
131 | options.sourceFormat(),
132 | store,
133 | apiVersionFormatter
134 | );
135 | writer.write(source, sdkSources);
136 |
137 | final long took = System.currentTimeMillis() - start;
138 |
139 | log("[Enhance] processing took: %s", format(took));
140 | }
141 |
142 | @Nonnull
143 | private static String format(long took) {
144 |
145 | final long second = 1000L;
146 | final long minute = second * 60;
147 |
148 | final long minutes = took / minute;
149 | took -= (minutes * minute);
150 | final long seconds = took / second;
151 |
152 | return String.format("%02d minutes %02d seconds", minutes, seconds);
153 | }
154 | }
155 |
--------------------------------------------------------------------------------
/src/main/java/io/noties/enhance/ApiInfoStoreImpl.java:
--------------------------------------------------------------------------------
1 | package io.noties.enhance;
2 |
3 | import org.w3c.dom.Document;
4 | import org.w3c.dom.Element;
5 | import org.w3c.dom.Node;
6 | import org.w3c.dom.NodeList;
7 |
8 | import javax.annotation.Nonnull;
9 | import javax.annotation.Nullable;
10 | import javax.xml.parsers.DocumentBuilder;
11 | import javax.xml.parsers.DocumentBuilderFactory;
12 | import java.io.File;
13 | import java.util.HashMap;
14 | import java.util.Map;
15 | import java.util.regex.Matcher;
16 | import java.util.regex.Pattern;
17 |
18 | class ApiInfoStoreImpl extends ApiInfoStore {
19 |
20 | private final Map map;
21 |
22 | ApiInfoStoreImpl(@Nonnull File apiVersions) {
23 | this.map = new Parser(apiVersions).parse();
24 | }
25 |
26 | @Nullable
27 | @Override
28 | public ApiInfo type(@Nonnull String type) {
29 | return map.get(type);
30 | }
31 |
32 | @Nullable
33 | @Override
34 | public ApiInfo field(@Nonnull String type, @Nonnull String name) {
35 | final TypeVersion version = map.get(type);
36 | return version != null
37 | ? version.fields.get(name)
38 | : null;
39 | }
40 |
41 | @Nullable
42 | @Override
43 | public ApiInfo method(@Nonnull String type, @Nonnull String signature) {
44 | final TypeVersion version = map.get(type);
45 | return version != null
46 | ? version.methods.get(signature)
47 | : null;
48 | }
49 |
50 | @Nonnull
51 | @Override
52 | public Map info() {
53 | return map;
54 | }
55 |
56 | static class Parser {
57 |
58 | private static final String NAME = "name";
59 | private static final String SINCE = "since";
60 | private static final String DEPRECATED = "deprecated";
61 |
62 | private final File file;
63 |
64 | private Parser(@Nonnull File file) {
65 | this.file = file;
66 | }
67 |
68 | @Nonnull
69 | Map parse() {
70 |
71 | final Map map = new HashMap<>();
72 |
73 | final NodeList list = classes();
74 | Node node;
75 | Element element;
76 | TypeVersion version;
77 |
78 | for (int i = 0, length = list.getLength(); i < length; i++) {
79 |
80 | node = list.item(i);
81 |
82 | if (Node.ELEMENT_NODE == node.getNodeType()) {
83 |
84 | element = (Element) node;
85 |
86 | version = new TypeVersion(
87 | apiVersion(element.getAttribute(SINCE)),
88 | apiVersion(element.getAttribute(DEPRECATED))
89 | );
90 |
91 | fields(version, element);
92 | methods(version, element);
93 |
94 | if (!isEmpty(version)) {
95 | map.put(element.getAttribute(NAME), version);
96 | }
97 | }
98 | }
99 |
100 | return map;
101 | }
102 |
103 | @Nonnull
104 | private NodeList classes() {
105 | try {
106 |
107 | final DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
108 | final Document document = builder.parse(file);
109 | document.getDocumentElement().normalize();
110 | return document.getElementsByTagName("class");
111 | } catch (Throwable t) {
112 | throw new RuntimeException(t);
113 | }
114 | }
115 |
116 | private static void fields(@Nonnull TypeVersion version, @Nonnull Element parent) {
117 |
118 | final NodeList list = parent.getElementsByTagName("field");
119 |
120 | Node node;
121 | Element element;
122 | ApiInfo apiInfo;
123 |
124 | for (int i = 0, length = list.getLength(); i < length; i++) {
125 | node = list.item(i);
126 | if (Node.ELEMENT_NODE == node.getNodeType()) {
127 | element = (Element) node;
128 | apiInfo = apiInfo(element);
129 | if (apiInfo != null) {
130 | version.fields.put(element.getAttribute(NAME), apiInfo);
131 | }
132 | }
133 | }
134 | }
135 |
136 | private static void methods(@Nonnull TypeVersion version, @Nonnull Element parent) {
137 |
138 | final NodeList list = parent.getElementsByTagName("method");
139 |
140 | Node node;
141 | Element element;
142 | ApiInfo apiInfo;
143 |
144 | for (int i = 0, length = list.getLength(); i < length; i++) {
145 | node = list.item(i);
146 | if (Node.ELEMENT_NODE == node.getNodeType()) {
147 | element = (Element) node;
148 | apiInfo = apiInfo(element);
149 | if (apiInfo != null) {
150 | version.methods.put(normalizeMethodSignature(element.getAttribute(NAME)), apiInfo);
151 | }
152 | }
153 | }
154 | }
155 |
156 | private static boolean isEmpty(@Nonnull TypeVersion version) {
157 | return version.since == null
158 | && version.deprecated == null
159 | && version.fields.isEmpty()
160 | && version.methods.isEmpty();
161 | }
162 |
163 | @Nullable
164 | private static ApiInfo apiInfo(@Nonnull Element element) {
165 |
166 | final ApiInfo apiInfo;
167 |
168 | final Integer since = apiVersion(element.getAttribute(SINCE));
169 | final Integer deprecated = apiVersion(element.getAttribute(DEPRECATED));
170 |
171 | if (since == null
172 | && deprecated == null) {
173 | apiInfo = null;
174 | } else {
175 | apiInfo = new ApiInfo(since, deprecated);
176 | }
177 |
178 | return apiInfo;
179 | }
180 |
181 | @Nullable
182 | private static Integer apiVersion(@Nullable String value) {
183 | if (value == null || value.isEmpty()) {
184 | return null;
185 | }
186 |
187 | try {
188 | return Integer.parseInt(value);
189 | } catch (NumberFormatException e) {
190 | //noinspection CallToPrintStackTrace
191 | e.printStackTrace();
192 | }
193 |
194 | return null;
195 | }
196 |
197 | private static final Pattern RE = Pattern.compile("L\\w+[/\\w]+[/$](\\w+);");
198 |
199 | @Nonnull
200 | static String normalizeMethodSignature(@Nonnull String name) {
201 |
202 | // we will cut off all package info from reference types (and possibly parent class)
203 | // LBuilder; instead of Landroid/app/AlertDialog$Builder; so we do not have to resolve types in source code..
204 |
205 | final String out;
206 |
207 | int index = name.indexOf(';');
208 | if (index < 0) {
209 | out = name;
210 | } else {
211 |
212 | final Matcher matcher = RE.matcher(name);
213 | final StringBuilder builder = new StringBuilder();
214 | index = 0;
215 | while (matcher.find()) {
216 | if (matcher.start() > index) {
217 | builder.append(name, index, matcher.start());
218 | }
219 | index = matcher.end();
220 | builder.append('L')
221 | .append(matcher.group(1))
222 | .append(';');
223 | }
224 | if (index < name.length()) {
225 | // the rest
226 | builder.append(name.substring(index));
227 | }
228 |
229 | out = builder.toString();
230 | }
231 |
232 | return out;
233 | }
234 | }
235 | }
236 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | #
4 | # Copyright © 2015-2021 the original 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 POSIX generated by Gradle.
22 | #
23 | # Important for running:
24 | #
25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
26 | # noncompliant, but you have some other compliant shell such as ksh or
27 | # bash, then to run this script, type that shell name before the whole
28 | # command line, like:
29 | #
30 | # ksh Gradle
31 | #
32 | # Busybox and similar reduced shells will NOT work, because this script
33 | # requires all of these POSIX shell features:
34 | # * functions;
35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»;
37 | # * compound commands having a testable exit status, especially «case»;
38 | # * various built-in commands including «command», «set», and «ulimit».
39 | #
40 | # Important for patching:
41 | #
42 | # (2) This script targets any POSIX shell, so it avoids extensions provided
43 | # by Bash, Ksh, etc; in particular arrays are avoided.
44 | #
45 | # The "traditional" practice of packing multiple parameters into a
46 | # space-separated string is a well documented source of bugs and security
47 | # problems, so this is (mostly) avoided, by progressively accumulating
48 | # options in "$@", and eventually passing that to Java.
49 | #
50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
52 | # see the in-line comments for details.
53 | #
54 | # There are tweaks for specific operating systems such as AIX, CygWin,
55 | # Darwin, MinGW, and NonStop.
56 | #
57 | # (3) This script is generated from the Groovy template
58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
59 | # within the Gradle project.
60 | #
61 | # You can find Gradle at https://github.com/gradle/gradle/.
62 | #
63 | ##############################################################################
64 |
65 | # Attempt to set APP_HOME
66 |
67 | # Resolve links: $0 may be a link
68 | app_path=$0
69 |
70 | # Need this for daisy-chained symlinks.
71 | while
72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
73 | [ -h "$app_path" ]
74 | do
75 | ls=$( ls -ld "$app_path" )
76 | link=${ls#*' -> '}
77 | case $link in #(
78 | /*) app_path=$link ;; #(
79 | *) app_path=$APP_HOME$link ;;
80 | esac
81 | done
82 |
83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
84 |
85 | APP_NAME="Gradle"
86 | APP_BASE_NAME=${0##*/}
87 |
88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
90 |
91 | # Use the maximum available, or set MAX_FD != -1 to use that value.
92 | MAX_FD=maximum
93 |
94 | warn () {
95 | echo "$*"
96 | } >&2
97 |
98 | die () {
99 | echo
100 | echo "$*"
101 | echo
102 | exit 1
103 | } >&2
104 |
105 | # OS specific support (must be 'true' or 'false').
106 | cygwin=false
107 | msys=false
108 | darwin=false
109 | nonstop=false
110 | case "$( uname )" in #(
111 | CYGWIN* ) cygwin=true ;; #(
112 | Darwin* ) darwin=true ;; #(
113 | MSYS* | MINGW* ) msys=true ;; #(
114 | NONSTOP* ) nonstop=true ;;
115 | esac
116 |
117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
118 |
119 |
120 | # Determine the Java command to use to start the JVM.
121 | if [ -n "$JAVA_HOME" ] ; then
122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
123 | # IBM's JDK on AIX uses strange locations for the executables
124 | JAVACMD=$JAVA_HOME/jre/sh/java
125 | else
126 | JAVACMD=$JAVA_HOME/bin/java
127 | fi
128 | if [ ! -x "$JAVACMD" ] ; then
129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
130 |
131 | Please set the JAVA_HOME variable in your environment to match the
132 | location of your Java installation."
133 | fi
134 | else
135 | JAVACMD=java
136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
137 |
138 | Please set the JAVA_HOME variable in your environment to match the
139 | location of your Java installation."
140 | fi
141 |
142 | # Increase the maximum file descriptors if we can.
143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
144 | case $MAX_FD in #(
145 | max*)
146 | MAX_FD=$( ulimit -H -n ) ||
147 | warn "Could not query maximum file descriptor limit"
148 | esac
149 | case $MAX_FD in #(
150 | '' | soft) :;; #(
151 | *)
152 | ulimit -n "$MAX_FD" ||
153 | warn "Could not set maximum file descriptor limit to $MAX_FD"
154 | esac
155 | fi
156 |
157 | # Collect all arguments for the java command, stacking in reverse order:
158 | # * args from the command line
159 | # * the main class name
160 | # * -classpath
161 | # * -D...appname settings
162 | # * --module-path (only if needed)
163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
164 |
165 | # For Cygwin or MSYS, switch paths to Windows format before running java
166 | if "$cygwin" || "$msys" ; then
167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
169 |
170 | JAVACMD=$( cygpath --unix "$JAVACMD" )
171 |
172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
173 | for arg do
174 | if
175 | case $arg in #(
176 | -*) false ;; # don't mess with options #(
177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
178 | [ -e "$t" ] ;; #(
179 | *) false ;;
180 | esac
181 | then
182 | arg=$( cygpath --path --ignore --mixed "$arg" )
183 | fi
184 | # Roll the args list around exactly as many times as the number of
185 | # args, so each arg winds up back in the position where it started, but
186 | # possibly modified.
187 | #
188 | # NB: a `for` loop captures its iteration list before it begins, so
189 | # changing the positional parameters here affects neither the number of
190 | # iterations, nor the values presented in `arg`.
191 | shift # remove old arg
192 | set -- "$@" "$arg" # push replacement arg
193 | done
194 | fi
195 |
196 | # Collect all arguments for the java command;
197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
198 | # shell script including quotes and variable substitutions, so put them in
199 | # double quotes to make sure that they get re-expanded; and
200 | # * put everything else in single quotes, so that it's not re-expanded.
201 |
202 | set -- \
203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \
204 | -classpath "$CLASSPATH" \
205 | org.gradle.wrapper.GradleWrapperMain \
206 | "$@"
207 |
208 | # Stop when "xargs" is not available.
209 | if ! command -v xargs >/dev/null 2>&1
210 | then
211 | die "xargs is not available"
212 | fi
213 |
214 | # Use "xargs" to parse quoted args.
215 | #
216 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed.
217 | #
218 | # In Bash we could simply go:
219 | #
220 | # readarray ARGS < <( xargs -n1 <<<"$var" ) &&
221 | # set -- "${ARGS[@]}" "$@"
222 | #
223 | # but POSIX shell has neither arrays nor command substitution, so instead we
224 | # post-process each arg (as a line of input to sed) to backslash-escape any
225 | # character that might be a shell metacharacter, then use eval to reverse
226 | # that process (while maintaining the separation between arguments), and wrap
227 | # the whole thing up as a single "set" statement.
228 | #
229 | # This will of course break if any of these variables contains a newline or
230 | # an unmatched quote.
231 | #
232 |
233 | eval "set -- $(
234 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
235 | xargs -n1 |
236 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
237 | tr '\n' ' '
238 | )" '"$@"'
239 |
240 | exec "$JAVACMD" "$@"
241 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 |
--------------------------------------------------------------------------------
/src/main/java/io/noties/enhance/EnhanceWriterImpl.java:
--------------------------------------------------------------------------------
1 | package io.noties.enhance;
2 |
3 | import com.github.javaparser.JavaParser;
4 | import com.github.javaparser.ParseResult;
5 | import com.github.javaparser.ParserConfiguration;
6 | import com.github.javaparser.ast.CompilationUnit;
7 | import com.github.javaparser.ast.NodeList;
8 | import com.github.javaparser.ast.PackageDeclaration;
9 | import com.github.javaparser.ast.body.*;
10 | import com.github.javaparser.ast.nodeTypes.NodeWithJavadoc;
11 | import com.github.javaparser.ast.visitor.VoidVisitorAdapter;
12 | import com.github.javaparser.javadoc.Javadoc;
13 | import com.github.javaparser.javadoc.description.JavadocDescription;
14 | import com.google.googlejavaformat.java.Formatter;
15 | import com.google.googlejavaformat.java.FormatterException;
16 | import com.google.googlejavaformat.java.JavaFormatterOptions;
17 | import io.noties.enhance.options.SourceFormat;
18 | import org.apache.commons.io.FileUtils;
19 |
20 | import javax.annotation.Nonnull;
21 | import javax.annotation.Nullable;
22 | import java.io.File;
23 | import java.io.FileNotFoundException;
24 | import java.io.IOException;
25 | import java.nio.charset.StandardCharsets;
26 | import java.util.ArrayList;
27 | import java.util.List;
28 |
29 | import static io.noties.enhance.Log.log;
30 |
31 | class EnhanceWriterImpl extends EnhanceWriter {
32 |
33 | private interface Parser {
34 | @Nonnull
35 | CompilationUnit parse(@Nonnull File file);
36 | }
37 |
38 | private interface SourceFormatter {
39 | @Nonnull
40 | String format(@Nonnull String source);
41 | }
42 |
43 | @Nonnull
44 | private final Parser parser;
45 |
46 | @Nullable
47 | private final SourceFormatter sourceFormatter;
48 |
49 | @Nonnull
50 | private final ApiInfoStore apiInfoStore;
51 |
52 | @Nonnull
53 | private final ApiVersionFormatter apiVersionFormatter;
54 |
55 | EnhanceWriterImpl(
56 | int sdk,
57 | @Nonnull SourceFormat format,
58 | @Nonnull ApiInfoStore apiInfoStore,
59 | @Nonnull ApiVersionFormatter apiVersionFormatter
60 | ) {
61 | this.parser = sdk >= Api.SDK_34.sdkInt ? new Parser17() : new Parser11();
62 |
63 | this.sourceFormatter = sourceFormatter(format);
64 | this.apiInfoStore = apiInfoStore;
65 | this.apiVersionFormatter = apiVersionFormatter;
66 | }
67 |
68 | @Override
69 | public void write(@Nonnull File source, @Nonnull File destination) {
70 | write("", source, destination);
71 | }
72 |
73 | // `path` could be used in future if some files would be processed differently
74 | private void write(
75 | @Nonnull String path,
76 | @Nonnull File source,
77 | @Nonnull File destination
78 | ) {
79 | final File[] files = source.listFiles();
80 | //noinspection RedundantLengthCheck
81 | if (files == null
82 | || files.length == 0) {
83 | return;
84 | }
85 |
86 | for (File file : files) {
87 |
88 | if (file.isDirectory()) {
89 |
90 | final File folder = new File(destination, file.getName());
91 | if (!folder.mkdirs()) {
92 | throw new RuntimeException("Cannot create folder: " + folder.getPath());
93 | }
94 |
95 | write(
96 | path + "/" + file.getName(),
97 | file,
98 | folder
99 | );
100 |
101 | } else {
102 |
103 | final String name = file.getName();
104 | final File f = new File(destination, name);
105 |
106 | log("[Enhance] path:'%s' name:'%s'", path, name);
107 |
108 | if (isJavaFileToProcess(name)) {
109 | final String java = processJavaFile(file);
110 | try {
111 | FileUtils.write(f, java, StandardCharsets.UTF_8);
112 | } catch (IOException e) {
113 | throw new RuntimeException(
114 | "Error writing file:'" + name + "' at path:'" + path + "'",
115 | e
116 | );
117 | }
118 | } else {
119 | log("[Enhance] copy file: %s", file.getPath());
120 | try {
121 | FileUtils.copyFile(file, f);
122 | } catch (IOException e) {
123 | throw new RuntimeException(
124 | "Error copying file:'" + name + "' at path:'" + path + "'",
125 | e
126 | );
127 | }
128 | }
129 | }
130 | }
131 | }
132 |
133 | private boolean isJavaFileToProcess(@Nonnull String name) {
134 | // @since 1.0.3 there are also `*.annotated.java` files, ignore them
135 | return name.endsWith(".java") && !name.endsWith(".annotated.java");
136 | }
137 |
138 | @Nonnull
139 | private String processJavaFile(@Nonnull File file) {
140 |
141 | log("[Enhance] processing java source file: %s", file.getPath());
142 |
143 | final CompilationUnit unit = parser.parse(file);
144 |
145 | unit.accept(new ApiInfoVisitor(apiVersionFormatter), apiInfoStore);
146 |
147 | final String out;
148 |
149 | if (sourceFormatter == null) {
150 | out = unit.toString();
151 | } else {
152 | final String source = unit.toString();
153 | try {
154 | out = sourceFormatter.format(source);
155 | } catch (Throwable t) {
156 | try {
157 | final File failedFile = new File(".", ".failed." + file.getName());
158 | FileUtils.write(failedFile, source, "utf-8");
159 | } catch (IOException e) {
160 | // ignored
161 | }
162 | throw t;
163 | }
164 | }
165 |
166 | return out;
167 | }
168 |
169 | private static class ApiInfoVisitor extends VoidVisitorAdapter {
170 |
171 | private final ApiVersionFormatter formatter;
172 |
173 | private String currentPackage;
174 |
175 | ApiInfoVisitor(@Nonnull ApiVersionFormatter formatter) {
176 | this.formatter = formatter;
177 | }
178 |
179 | @Override
180 | public void visit(PackageDeclaration n, ApiInfoStore arg) {
181 | currentPackage = n.getNameAsString().replaceAll("\\.", "/") + "/";
182 | super.visit(n, arg);
183 | }
184 |
185 | @Override
186 | public void visit(EnumDeclaration n, ApiInfoStore arg) {
187 | super.visit(n, arg);
188 |
189 | final String type = typeName(n);
190 |
191 | final NodeList constants = n.getEntries();
192 | if (constants != null) {
193 | for (EnumConstantDeclaration declaration : constants) {
194 | setApiInfo(declaration, arg.field(type, declaration.getNameAsString()));
195 | }
196 | }
197 |
198 | visit(type, n, arg, n.getConstructors());
199 | }
200 |
201 | @Override
202 | public void visit(ClassOrInterfaceDeclaration n, ApiInfoStore api) {
203 | super.visit(n, api);
204 |
205 | final String type = typeName(n);
206 |
207 | visit(type, n, api, n.getConstructors());
208 | }
209 |
210 | private void visit(
211 | @Nonnull String type,
212 | @Nonnull TypeDeclaration> n,
213 | @Nonnull ApiInfoStore api,
214 | @Nullable List constructors
215 | ) {
216 |
217 | final List fields = n.getFields();
218 | if (fields != null) {
219 |
220 | String name;
221 |
222 | for (FieldDeclaration field : fields) {
223 |
224 | name = field.getVariables().get(0).getNameAsString();
225 | setApiInfo(field, api.field(type, name));
226 | }
227 | }
228 |
229 | final List> callableDeclarations;
230 | {
231 | callableDeclarations = new ArrayList<>();
232 | final List methods = n.getMethods();
233 | if (methods != null) {
234 | callableDeclarations.addAll(methods);
235 | }
236 |
237 | if (constructors != null) {
238 | callableDeclarations.addAll(constructors);
239 | }
240 | }
241 |
242 | for (CallableDeclaration> declaration : callableDeclarations) {
243 | setApiInfo(declaration, api.method(type, ByteCodeSignature.create(declaration)));
244 | }
245 |
246 | final ApiInfo info = api.type(type);
247 | if (info != null) {
248 | setApiInfo(n, info);
249 | }
250 | }
251 |
252 | private void setApiInfo(@Nonnull NodeWithJavadoc> node, @Nullable ApiInfo apiInfo) {
253 |
254 | if (apiInfo == null) {
255 | return;
256 | }
257 |
258 | Javadoc javadoc = node.getJavadoc().orElse(null);
259 | if (javadoc == null) {
260 | javadoc = new Javadoc(new JavadocDescription());
261 | }
262 | if (apiInfo.since != null) {
263 | javadoc.addBlockTag("since", formatter.format(apiInfo.since));
264 | }
265 | if (apiInfo.deprecated != null) {
266 | javadoc.addBlockTag("deprecated", formatter.format(apiInfo.deprecated));
267 | }
268 | node.setJavadocComment(javadoc.toComment(" "));
269 | }
270 |
271 | @Nonnull
272 | private String typeName(@Nonnull TypeDeclaration> typeDeclaration) {
273 | final String out;
274 | if (typeDeclaration.isTopLevelType()) {
275 | out = currentPackage + typeDeclaration.getNameAsString();
276 | } else {
277 | final StringBuilder builder = new StringBuilder();
278 | builder.append(typeDeclaration.getNameAsString());
279 | TypeDeclaration> parent = parentTypeDeclaration(typeDeclaration);
280 | while (parent != null) {
281 | builder.insert(0, '$');
282 | builder.insert(0, parent.getNameAsString());
283 | parent = parentTypeDeclaration(parent);
284 | }
285 | builder.insert(0, currentPackage);
286 | out = builder.toString();
287 | }
288 | return out;
289 | }
290 |
291 | @Nullable
292 | private static TypeDeclaration> parentTypeDeclaration(@Nonnull TypeDeclaration> typeDeclaration) {
293 | return (TypeDeclaration>) typeDeclaration.getParentNode()
294 | .filter(node -> node instanceof TypeDeclaration)
295 | .orElse(null);
296 | }
297 | }
298 |
299 | // Unfortunately java-parser printer is a little weird and does not give enough options
300 | // to format the code
301 | // @Nonnull
302 | // private static Printer createDefaultPrinter(int indent) {
303 | // final PrinterConfiguration configuration = new DefaultPrinterConfiguration()
304 | // .addOption(new DefaultConfigurationOption(DefaultPrinterConfiguration.ConfigOption.INDENTATION, new Indentation(Indentation.IndentType.SPACES, indent)))
305 | // .addOption(new DefaultConfigurationOption(DefaultPrinterConfiguration.ConfigOption.ORDER_IMPORTS, Boolean.TRUE))
306 | // .addOption(new DefaultConfigurationOption(DefaultPrinterConfiguration.ConfigOption.SORT_IMPORTS_STRATEGY, new IntelliJImportOrderingStrategy()))
307 | // .addOption(new DefaultConfigurationOption(DefaultPrinterConfiguration.ConfigOption.PRINT_COMMENTS, Boolean.TRUE))
308 | // .addOption(new DefaultConfigurationOption(DefaultPrinterConfiguration.ConfigOption.PRINT_JAVADOC, Boolean.TRUE))
309 | // .addOption(new DefaultConfigurationOption(DefaultPrinterConfiguration.ConfigOption.COLUMN_ALIGN_PARAMETERS, Boolean.FALSE))
310 | // .addOption(new DefaultConfigurationOption(DefaultPrinterConfiguration.ConfigOption.COLUMN_ALIGN_FIRST_METHOD_CHAIN, Boolean.FALSE))
311 | // .addOption(new DefaultConfigurationOption(DefaultPrinterConfiguration.ConfigOption.INDENT_CASE_IN_SWITCH, Boolean.FALSE))
312 | // .addOption(new DefaultConfigurationOption(DefaultPrinterConfiguration.ConfigOption.MAX_ENUM_CONSTANTS_TO_ALIGN_HORIZONTALLY, 1));
313 | // return new DefaultPrettyPrinter(configuration);
314 | // }
315 |
316 | private static class Parser11 implements Parser {
317 |
318 | private final JavaParser javaParser11 = new JavaParser(new ParserConfiguration().setLanguageLevel(ParserConfiguration.LanguageLevel.JAVA_11));
319 |
320 | @Nonnull
321 | @Override
322 | public CompilationUnit parse(@Nonnull File file) {
323 | return parse(javaParser11, file);
324 | }
325 |
326 | @Nonnull
327 | protected static CompilationUnit parse(@Nonnull JavaParser javaParser, @Nonnull File file) {
328 | final CompilationUnit unit;
329 | try {
330 | final ParseResult result = javaParser.parse(file);
331 | if (result.isSuccessful()) {
332 | //noinspection OptionalGetWithoutIsPresent
333 | unit = result.getResult().get();
334 | } else {
335 | throw new RuntimeException(result.toString());
336 | }
337 | } catch (FileNotFoundException e) {
338 | throw new RuntimeException(e);
339 | }
340 | return unit;
341 | }
342 | }
343 |
344 | // Android 34 should have been compiled with Java-17, but some sources
345 | // contain java-17 keywords: `sealed` and `permits` as variable names
346 | private static class Parser17 extends Parser11 {
347 |
348 | private final JavaParser javaParser17 = new JavaParser(new ParserConfiguration().setLanguageLevel(ParserConfiguration.LanguageLevel.JAVA_17));
349 |
350 | @Nonnull
351 | @Override
352 | public CompilationUnit parse(@Nonnull File file) {
353 |
354 | // first try parsing with java-17 and then fallback to java-11
355 | // this is done because, even though android-34 should be compiled with java-17
356 | // there are classes that contain illegal variable names: `sealed` and `permits`
357 | CompilationUnit compilationUnit = null;
358 | try {
359 | compilationUnit = parse(javaParser17, file);
360 | } catch (Throwable t) {
361 | log("[Enhance] Exception parsing with java-17");
362 | //noinspection CallToPrintStackTrace
363 | t.printStackTrace();
364 | }
365 |
366 | if (compilationUnit == null) {
367 | compilationUnit = super.parse(file);
368 | }
369 |
370 | return compilationUnit;
371 | }
372 | }
373 |
374 | @Nullable
375 | private static SourceFormatter sourceFormatter(@Nonnull SourceFormat format) {
376 |
377 | final SourceFormatter sourceFormatter;
378 |
379 | switch (format) {
380 |
381 | case AOSP:
382 | sourceFormatter = new AospSourceFormatter();
383 | break;
384 |
385 | case GOOGLE:
386 | sourceFormatter = new GoogleSourceFormatter();
387 | break;
388 |
389 | default:
390 | sourceFormatter = null;
391 | }
392 |
393 | return sourceFormatter;
394 | }
395 |
396 | private static class AospSourceFormatter implements SourceFormatter {
397 |
398 | private final Formatter formatter;
399 |
400 | AospSourceFormatter() {
401 | final JavaFormatterOptions options = JavaFormatterOptions.builder()
402 | .style(JavaFormatterOptions.Style.AOSP)
403 | .build();
404 | formatter = new Formatter(options);
405 | }
406 |
407 | @Nonnull
408 | @Override
409 | public String format(@Nonnull String source) {
410 | try {
411 | return formatter.formatSource(source);
412 | } catch (FormatterException e) {
413 | throw new RuntimeException(e);
414 | }
415 | }
416 | }
417 |
418 | private static class GoogleSourceFormatter implements SourceFormatter {
419 |
420 | private final Formatter formatter;
421 |
422 | GoogleSourceFormatter() {
423 | final JavaFormatterOptions options = JavaFormatterOptions.builder()
424 | .style(JavaFormatterOptions.Style.GOOGLE)
425 | .build();
426 | formatter = new Formatter(options);
427 | }
428 |
429 | @Nonnull
430 | @Override
431 | public String format(@Nonnull String source) {
432 | try {
433 | return formatter.formatSource(source);
434 | } catch (FormatterException e) {
435 | throw new RuntimeException(e);
436 | }
437 | }
438 | }
439 | }
440 |
--------------------------------------------------------------------------------
/art/logo.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
131 |
--------------------------------------------------------------------------------