Skip to content

Commit c076375

Browse files
vtrifonovvmutafov
authored andcommitted
suppress deprecation warnings in generated code (#1395)
* suppress deprecation warnings in generated code * Fixed some warnings * added an option to check for warnings and fail
1 parent 938fe31 commit c076375

File tree

15 files changed

+159
-22
lines changed

15 files changed

+159
-22
lines changed

test-app/app/build.gradle

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -411,6 +411,13 @@ task addDependenciesFromAppResourcesLibraries {
411411
}
412412
}
413413

414+
if (failOnCompilationWarningsEnabled()) {
415+
tasks.withType(JavaCompile) {
416+
options.compilerArgs << '-Xlint:all' << "-Werror"
417+
options.deprecation = true
418+
}
419+
}
420+
414421
tasks.whenTaskAdded({ org.gradle.api.DefaultTask currentTask ->
415422
if (currentTask =~ /generate.+BuildConfig/) {
416423
currentTask.finalizedBy(extractAllJars)
@@ -445,7 +452,15 @@ task runSbg(type: JavaExec) {
445452

446453
workingDir "$BUILD_TOOLS_PATH"
447454
main "-jar"
448-
args "static-binding-generator.jar"
455+
456+
def paramz = new ArrayList<String>()
457+
paramz.add("static-binding-generator.jar")
458+
459+
if (failOnCompilationWarningsEnabled()) {
460+
paramz.add("-show-deprecation-warnings")
461+
}
462+
463+
args paramz
449464

450465
doFirst {
451466
new File("$OUTPUT_JAVA_DIR/com/tns/gen").deleteDir()
@@ -459,6 +474,10 @@ task ensureMetadataOutDir {
459474
}
460475
}
461476

477+
def failOnCompilationWarningsEnabled() {
478+
return project.hasProperty("failOnCompilationWarnings") && (failOnCompilationWarnings || failOnCompilationWarnings.toBoolean())
479+
}
480+
462481
def explodeAar(File compileDependency, File outputDir) {
463482
logger.info("explodeAar: Extracting ${compileDependency.path} -> ${outputDir.path}")
464483

test-app/app/src/debug/java/com/tns/ErrorReport.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -318,6 +318,7 @@ private class Pager extends FragmentStatePagerAdapter {
318318

319319
int tabCount;
320320

321+
@SuppressWarnings("deprecation")
321322
public Pager(FragmentManager fm, int tabCount) {
322323
super(fm);
323324
this.tabCount = tabCount;

test-app/app/src/debug/java/com/tns/NativeScriptSyncService.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ public class NativeScriptSyncService {
4040

4141
public NativeScriptSyncService(Runtime runtime, Logger logger, Context context) {
4242
this.runtime = runtime;
43-
this.logger = logger;
43+
NativeScriptSyncService.logger = logger;
4444
this.context = context;
4545

4646
syncPath = SYNC_ROOT_SOURCE_DIR + context.getPackageName() + SYNC_SOURCE_DIR;

test-app/app/src/debug/java/com/tns/NativeScriptSyncServiceSocketImpl.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ public class NativeScriptSyncServiceSocketImpl {
2525

2626
public NativeScriptSyncServiceSocketImpl(Runtime runtime, Logger logger, Context context) {
2727
this.runtime = runtime;
28-
this.logger = logger;
28+
NativeScriptSyncServiceSocketImpl.logger = logger;
2929
this.context = context;
3030
DEVICE_APP_DIR = this.context.getFilesDir().getAbsolutePath() + "/app";
3131
}

test-app/app/src/main/java/com/tns/DefaultExtractPolicy.java

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@
1515
import android.content.pm.PackageManager;
1616
import android.content.pm.PackageManager.NameNotFoundException;
1717

18+
import androidx.core.content.pm.PackageInfoCompat;
19+
1820
import com.tns.Logger;
1921
import com.tns.ExtractPolicy;
2022
import com.tns.FileExtractor;
@@ -67,9 +69,9 @@ public String getAssetsThumb(Context context) {
6769
private String generateAssetsThumb(Context context) {
6870
try {
6971
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
70-
int code = packageInfo.versionCode;
72+
long code = PackageInfoCompat.getLongVersionCode(packageInfo);
7173
long updateTime = packageInfo.lastUpdateTime;
72-
return String.valueOf(updateTime) + "-" + String.valueOf(code);
74+
return updateTime + "-" + code;
7375
} catch (NameNotFoundException e) {
7476
logger.write("Error while getting current assets thumb");
7577
e.printStackTrace();

test-app/app/src/main/java/com/tns/RuntimeHelper.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,10 +34,10 @@ private static boolean hasErrorIntent(Context context) {
3434
// empty file just to check if there was a raised uncaught error by
3535
// ErrorReport
3636
if (Util.isDebuggableApp(context)) {
37-
String fileName = "";
37+
String fileName;
3838

3939
try {
40-
Class ErrReport = Class.forName("com.tns.ErrorReport");
40+
Class<?> ErrReport = Class.forName("com.tns.ErrorReport");
4141
Field field = ErrReport.getDeclaredField("ERROR_FILE_NAME");
4242
fileName = (String) field.get(null);
4343
} catch (Exception e) {
@@ -310,10 +310,10 @@ public static void initLiveSync(Runtime runtime, Logger logger, Context context)
310310
// runtime needs to be initialized before the NativeScriptSyncService is enabled because it uses runtime.runScript(...)
311311
try {
312312
@SuppressWarnings("unchecked")
313-
Class NativeScriptSyncService = Class.forName("com.tns.NativeScriptSyncServiceSocketImpl");
313+
Class<?> NativeScriptSyncService = Class.forName("com.tns.NativeScriptSyncServiceSocketImpl");
314314

315315
@SuppressWarnings("unchecked")
316-
Constructor cons = NativeScriptSyncService.getConstructor(new Class[]{Runtime.class, Logger.class, Context.class});
316+
Constructor<?> cons = NativeScriptSyncService.getConstructor(new Class<?>[]{Runtime.class, Logger.class, Context.class});
317317
Object syncService = cons.newInstance(runtime, logger, context);
318318

319319
@SuppressWarnings("unchecked")

test-app/app/src/main/java/com/tns/Util.java

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,15 +11,17 @@
1111
import android.content.pm.PackageManager.NameNotFoundException;
1212
import android.os.Bundle;
1313

14+
import androidx.core.content.pm.PackageInfoCompat;
15+
1416
public final class Util {
1517
private Util() {
1618
}
1719

1820
public static String getDexThumb(Context context) throws NameNotFoundException {
1921
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
20-
int code = packageInfo.versionCode;
22+
long code = PackageInfoCompat.getLongVersionCode(packageInfo);
2123
long updateTime = packageInfo.lastUpdateTime;
22-
return String.valueOf(updateTime) + "-" + String.valueOf(code);
24+
return updateTime + "-" + code;
2325
}
2426

2527
public static boolean isDebuggableApp(Context context) {

test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/Generator.java

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -78,13 +78,13 @@ public class Generator {
7878
private Set<String> nonPublicNestedClasses;
7979

8080
public Generator(File outputDir, List<DataRow> libs) throws IOException {
81-
this(outputDir, libs, false, false);
81+
this(outputDir, libs, false);
8282
}
8383

84-
public Generator(File outputDir, List<DataRow> libs, boolean suppressCallJSMethodExceptions, boolean throwOnError) throws IOException {
84+
public Generator(File outputDir, List<DataRow> libs, boolean suppressCallJSMethodExceptions) throws IOException {
8585
this.outputDir = outputDir;
8686
this.libs = libs;
87-
this.fileSystemHelper = new FileSystemHelperImpl(throwOnError);
87+
this.fileSystemHelper = new FileSystemHelperImpl(InputParameters.getCurrent().getThrowOnError());
8888
ClassesCollection classesCollection = readClasses(libs);
8989
this.classes = classesCollection.getRegularClasses();
9090
this.nonPublicNestedClasses = classesCollection.getNonPublicNestedClasses();
@@ -443,16 +443,19 @@ private void writeMethodsToWriter(Writer writer, GenericHierarchyView genericHie
443443
for (ReifiedJavaMethod abstractMethod : inheritedMethodsView.getNonImplementedMethods()) {
444444
writer.writeln();
445445
writer.writeln();
446-
methodsWriter.writeMethod(abstractMethod);
446+
methodsWriter.writeMethod(abstractMethod, false);
447447
}
448448

449-
for (ReifiedJavaMethod overridableMethod : inheritedMethodsView.getOverridableImplementedMethods()) {
449+
List<ReifiedJavaMethod> overridableImplementedMethods = inheritedMethodsView.getOverridableImplementedMethods();
450+
451+
for (ReifiedJavaMethod overridableMethod : overridableImplementedMethods) {
450452
for (String userImplementedMethodName : userImplementedMethods) {
451453
if (overridableMethod.getName().equals(userImplementedMethodName)) {
452454
if (areAllArgumentsAndReturnTypePublic(overridableMethod)) {
453455
writer.writeln();
454456
writer.writeln();
455-
methodsWriter.writeMethod(overridableMethod);
457+
boolean isUserImplemented = !overridableMethod.isDeprecated() || !hasNonDeprecatedImplementation(overridableMethod, overridableImplementedMethods);
458+
methodsWriter.writeMethod(overridableMethod, isUserImplemented);
456459
}
457460
}
458461
}
@@ -471,6 +474,22 @@ private void writeMethodsToWriter(Writer writer, GenericHierarchyView genericHie
471474
methodsWriter.writeInternalRuntimeEqualsMethod();
472475
}
473476

477+
/**
478+
* Checks whether in the list of implemented methods there's another method with the same name which is not deprecated.
479+
* In that case we'll consider that method as user implemented, but not the current one
480+
*
481+
* @private
482+
* @param {ReifiedJavaMethod} currentMethod The method to check.
483+
* @param {List<ReifiedJavaMethod>} allOverridableMethods The list will all the overridable methods to check in.
484+
* @returns {boolean} Returns true or false.
485+
*/
486+
private boolean hasNonDeprecatedImplementation(ReifiedJavaMethod currentMethod, List<ReifiedJavaMethod> allOverridableMethods) {
487+
return allOverridableMethods.stream().anyMatch(method ->
488+
method != currentMethod
489+
&& method.getName().equals(currentMethod.getName())
490+
&& !method.isDeprecated());
491+
}
492+
474493
private boolean hasOverriddenOnCreateMethod(List<String> overriddenMethods) {
475494
return overriddenMethods.contains("onCreate");
476495
}
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package org.nativescript.staticbindinggenerator;
2+
3+
public class InputParameters {
4+
5+
// if the flag is passed the deprecation warnings will not be suppressed
6+
private static final String SHOW_DEPRECATION_WARNINGS = "-show-deprecation-warnings";
7+
// if the flag is passed the generation will exit on error
8+
private static final String THROW_ON_ERROR = "-throw-on-error";
9+
10+
private static InputParameters current = new InputParameters();
11+
12+
private boolean showDeprecationWarnings;
13+
private boolean throwOnError;
14+
15+
public InputParameters() {
16+
this.showDeprecationWarnings = false;
17+
this.throwOnError = false;
18+
}
19+
20+
public void setShowDeprecationWarnings(boolean value) {
21+
this.showDeprecationWarnings = value;
22+
}
23+
24+
public boolean getSuppressDeprecationWarnings() {
25+
return !showDeprecationWarnings;
26+
}
27+
28+
public void setThrowOnError(boolean value) {
29+
this.throwOnError = value;
30+
}
31+
32+
public boolean getThrowOnError() {
33+
return throwOnError;
34+
}
35+
36+
public static void parseCommand(String[] args) {
37+
InputParameters inputParameters = new InputParameters();
38+
39+
if (args != null) {
40+
for (int i = 0; i < args.length; i++) {
41+
String commandArg = args[i];
42+
43+
if (commandArg.equals(SHOW_DEPRECATION_WARNINGS)) {
44+
inputParameters.setShowDeprecationWarnings(true);
45+
}
46+
47+
if (commandArg.equals(THROW_ON_ERROR)) {
48+
inputParameters.setThrowOnError(true);
49+
}
50+
}
51+
}
52+
53+
InputParameters.current = inputParameters;
54+
}
55+
56+
public static InputParameters getCurrent() {
57+
return InputParameters.current;
58+
}
59+
}

test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/Main.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,8 @@ public class Main {
3333
}
3434

3535
public static void main(String[] args) throws IOException, ClassNotFoundException {
36+
InputParameters.parseCommand(args);
37+
3638
validateInput();
3739

3840
getWorkerExcludeFile();
@@ -44,7 +46,7 @@ public static void main(String[] args) throws IOException, ClassNotFoundExceptio
4446

4547
// generate java bindings
4648
String inputBindingFilename = Paths.get(System.getProperty("user.dir"), SBG_BINDINGS_NAME).toString();
47-
Generator generator = new Generator(outputDir, rows, isSuppressCallJSMethodExceptionsEnabled(), false);
49+
Generator generator = new Generator(outputDir, rows, isSuppressCallJSMethodExceptionsEnabled());
4850
generator.writeBindings(inputBindingFilename);
4951
}
5052

0 commit comments

Comments
 (0)