Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Fixed proguard handling of custom gradle files #1401

Merged
merged 5 commits into from
Jul 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## Unreleased

### Fixes

- The SDK now handles proguardfiles sections indicated by both `consumerProguardFiles` and `proguardFiles` ([#1401](https://github.com/getsentry/sentry-unity/pull/1401))
bitsandfoxes marked this conversation as resolved.
Show resolved Hide resolved

### Dependencies

- Bump CLI from v2.19.1 to v2.19.4 ([#1387](https://github.com/getsentry/sentry-unity/pull/1387), [#1388](https://github.com/getsentry/sentry-unity/pull/1388))
Expand Down
34 changes: 31 additions & 3 deletions src/Sentry.Unity.Editor/Android/ProguardSetup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,19 @@ public void RemoveFromGradleProject()
}
else
{
var gradleNew = Regex.Replace(gradle, @"(\s+consumerProguardFiles .*), *'" + RuleFileName + "'", "$1");
var pattern = string.Empty;
if (gradle.Contains("consumerProguardFiles"))
{
_logger.LogDebug("Detected `consumerProguardFiles`. Removing Sentry rules.");
pattern = @"(\s+consumerProguardFiles .*), *'";
}
else if (gradle.Contains("proguardFiles"))
{
_logger.LogDebug("Detected `proguardFiles`. Removing Sentry rules.");
pattern = @"(\s+proguardFiles .*), *'";
}

var gradleNew = Regex.Replace(gradle, pattern + RuleFileName + "'", "$1");
if (gradle.Length == gradleNew.Length)
{
throw new Exception($"Couldn't remove Proguard rule {RuleFileName} from {_gradleScriptPath}.");
Expand Down Expand Up @@ -66,10 +78,26 @@ public void AddToGradleProject()
}
else
{
var gradleNew = Regex.Replace(gradle, @"(\s+consumerProguardFiles [^\r\n]*)", "$1, '" + RuleFileName + "'");
string pattern;
if (gradle.Contains("consumerProguardFiles"))
{
_logger.LogDebug("Detected `consumerProguardFiles`. Adding Sentry rules.");
pattern = @"(\s+consumerProguardFiles [^\r\n]*)";
}
else if (gradle.Contains("proguardFiles"))
{
_logger.LogDebug("Detected `proguardFiles`. Adding Sentry rules.");
pattern = @"(\s+proguardFiles [^\r\n]*)";
}
else
{
throw new Exception($"Failed to find 'proguard rule section' in gradle file at: {_gradleScriptPath} - no `consumerProguardFiles` or `proguardFiles` found.");
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this breaking the build for the user? Should we gracefully degrade instead?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The build doesn't break. The exception bubbles up and we catch and log it as an error.

}

var gradleNew = Regex.Replace(gradle, pattern, "$1, '" + RuleFileName + "'");
if (gradle.Length == gradleNew.Length)
{
throw new Exception($"Couldn't add Proguard rule {RuleFileName} to {_gradleScriptPath} - no `consumerProguardFiles` found.");
throw new Exception($"Couldn't add Proguard rule {RuleFileName} to {_gradleScriptPath}.");
}
File.WriteAllText(_gradleScriptPath, gradleNew);
}
Expand Down
47 changes: 26 additions & 21 deletions test/Sentry.Unity.Editor.Tests/Android/ProguardSetupTests.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using NUnit.Framework;
using Sentry.Unity.Editor.Android;
Expand Down Expand Up @@ -97,33 +98,37 @@ public void AddsRuleToGradleScript(string lineSeparator)
}

[Test]
[TestCase(false)]
[TestCase(true)]
public void RemovesRuleFromGradleScript(bool existsBefore)
[TestCase("AddingProguard/build.gradle_test_1")]
[TestCase("AddingProguard/build.gradle_test_2")]
public void AddsRulesToGradleScript_ContainsConsumerProguardRules_MatchesExpectedOutput(string testCaseFileName)
{
var gradleScript = Path.Combine(_outputPath, "build.gradle");
var assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var testCasePath = Path.Combine(assemblyPath, "TestFiles", "Android", testCaseFileName + ".txt");
var expectedPath = Path.Combine(assemblyPath, "TestFiles", "Android", testCaseFileName + "_expected.txt");

var expectedFinalScript = @"
android {
defaultConfig {
consumerProguardFiles 'proguard-unity.txt', 'proguard-user.txt', 'other-proguard.txt'
}
}
";
var actualOutputPath = Path.Combine(_outputPath, "build.gradle");
File.Copy(testCasePath, actualOutputPath, true);

File.WriteAllText(gradleScript, existsBefore ? @"
android {
defaultConfig {
consumerProguardFiles 'proguard-unity.txt', 'proguard-user.txt', '" + ProguardSetup.RuleFileName + @"', 'other-proguard.txt'
}
}
" : expectedFinalScript);
GetSut().AddToGradleProject();

var sut = GetSut();
StringAssert.AreEqualIgnoringCase(File.ReadAllText(expectedPath), File.ReadAllText(actualOutputPath));
}

sut.RemoveFromGradleProject();
[Test]
[TestCase("AddingProguard/build.gradle_test_1")]
[TestCase("AddingProguard/build.gradle_test_2")]
public void RemovesRuleFromGradleScript(string testCaseFileName)
{
var assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var testCasePath = Path.Combine(assemblyPath, "TestFiles", "Android", testCaseFileName + "_expected.txt");
var expectedPath = Path.Combine(assemblyPath, "TestFiles", "Android", testCaseFileName + ".txt");

var actualOutputPath = Path.Combine(_outputPath, "build.gradle");
File.Copy(testCasePath, actualOutputPath, true);

GetSut().RemoveFromGradleProject();

Assert.AreEqual(File.ReadAllText(gradleScript), expectedFinalScript);
StringAssert.AreEqualIgnoringCase(File.ReadAllText(expectedPath), File.ReadAllText(actualOutputPath));
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
// GENERATED BY UNITY. REMOVE THIS COMMENT TO PREVENT OVERWRITING WHEN EXPORTING AGAIN

apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'


dependencies {
implementation ('io.sentry:sentry-android:6.25.1') { exclude group: 'androidx.core' exclude group: 'androidx.lifecycle' }
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.4.31'
}

android {
compileSdkVersion 30
buildToolsVersion '30.0.2'

compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}

defaultConfig {
minSdkVersion 19
targetSdkVersion 30
ndk {
abiFilters 'arm64-v8a'
}
versionCode 1
versionName '0.1'
consumerProguardFiles 'proguard-unity.txt', 'proguard-user.txt'
}

lintOptions {
abortOnError false
}

aaptOptions {
noCompress = ['.ress', '.resource', '.obb'] + unityStreamingAssets.tokenize(', ')
ignoreAssetsPattern = "!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~"
}

packagingOptions {
doNotStrip '*/arm64-v8a/*.so'
}
}
repositories {
mavenCentral { content { excludeGroupByRegex "io\\.sentry.*" } }
}

def getSdkDir() {
Properties local = new Properties()
local.load(new FileInputStream("${rootDir}/local.properties"))
return local.getProperty('sdk.dir')
}

def BuildIl2Cpp(String workingDir, String targetDirectory, String architecture, String abi, String configuration) {
exec {
commandLine(workingDir + "/src/main/Il2CppOutputProject/IL2CPP/build/deploy/netcoreapp3.1/il2cpp",
"--compile-cpp",
"--avoid-dynamic-library-copy",
"--profiler-report",
"--libil2cpp-static",
"--platform=Android",
"--architecture=" + architecture,
"--configuration=" + configuration,
"--outputpath=" + workingDir + targetDirectory + abi + "/libil2cpp.so",
"--cachedirectory=" + workingDir + "/build/il2cpp_"+ abi + "_" + configuration + "/il2cpp_cache",
"--additional-include-directories=" + workingDir + "/src/main/Il2CppOutputProject/IL2CPP/external/bdwgc/include",
"--additional-include-directories=" + workingDir + "/src/main/Il2CppOutputProject/IL2CPP/libil2cpp/include",
"--tool-chain-path=" + android.ndkDirectory,
"--map-file-parser=" + workingDir + "/src/main/Il2CppOutputProject/IL2CPP/MapFileParser/MapFileParser.exe",
"--generatedcppdir=" + workingDir + "/src/main/Il2CppOutputProject/Source/il2cppOutput",
"--baselib-directory=" + workingDir + "/src/main/jniStaticLibs/" + abi,
"--dotnetprofile=unityaot")
environment "ANDROID_SDK_ROOT", getSdkDir()
}
delete workingDir + targetDirectory + abi + "/libil2cpp.sym.so"
ant.move(file: workingDir + targetDirectory + abi + "/libil2cpp.dbg.so", tofile: workingDir + "/symbols/" + abi + "/libil2cpp.so")
}

android {
task BuildIl2CppTask {
doLast {
BuildIl2Cpp(projectDir.toString().replaceAll('\\\\', '/'), '/src/main/jniLibs/', 'ARM64', 'arm64-v8a', 'Release');
}
}
afterEvaluate {
if (project(':unityLibrary').tasks.findByName('mergeDebugJniLibFolders'))
project(':unityLibrary').mergeDebugJniLibFolders.dependsOn BuildIl2CppTask
if (project(':unityLibrary').tasks.findByName('mergeReleaseJniLibFolders'))
project(':unityLibrary').mergeReleaseJniLibFolders.dependsOn BuildIl2CppTask
}
sourceSets {
main {
jni.srcDirs = ["src/main/Il2CppOutputProject"]
}
}
}



Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
// GENERATED BY UNITY. REMOVE THIS COMMENT TO PREVENT OVERWRITING WHEN EXPORTING AGAIN

apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'


dependencies {
implementation ('io.sentry:sentry-android:6.25.1') { exclude group: 'androidx.core' exclude group: 'androidx.lifecycle' }
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.4.31'
}

android {
compileSdkVersion 30
buildToolsVersion '30.0.2'

compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}

defaultConfig {
minSdkVersion 19
targetSdkVersion 30
ndk {
abiFilters 'arm64-v8a'
}
versionCode 1
versionName '0.1'
consumerProguardFiles 'proguard-unity.txt', 'proguard-user.txt', 'proguard-sentry-unity.pro'
}

lintOptions {
abortOnError false
}

aaptOptions {
noCompress = ['.ress', '.resource', '.obb'] + unityStreamingAssets.tokenize(', ')
ignoreAssetsPattern = "!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~"
}

packagingOptions {
doNotStrip '*/arm64-v8a/*.so'
}
}
repositories {
mavenCentral { content { excludeGroupByRegex "io\\.sentry.*" } }
}

def getSdkDir() {
Properties local = new Properties()
local.load(new FileInputStream("${rootDir}/local.properties"))
return local.getProperty('sdk.dir')
}

def BuildIl2Cpp(String workingDir, String targetDirectory, String architecture, String abi, String configuration) {
exec {
commandLine(workingDir + "/src/main/Il2CppOutputProject/IL2CPP/build/deploy/netcoreapp3.1/il2cpp",
"--compile-cpp",
"--avoid-dynamic-library-copy",
"--profiler-report",
"--libil2cpp-static",
"--platform=Android",
"--architecture=" + architecture,
"--configuration=" + configuration,
"--outputpath=" + workingDir + targetDirectory + abi + "/libil2cpp.so",
"--cachedirectory=" + workingDir + "/build/il2cpp_"+ abi + "_" + configuration + "/il2cpp_cache",
"--additional-include-directories=" + workingDir + "/src/main/Il2CppOutputProject/IL2CPP/external/bdwgc/include",
"--additional-include-directories=" + workingDir + "/src/main/Il2CppOutputProject/IL2CPP/libil2cpp/include",
"--tool-chain-path=" + android.ndkDirectory,
"--map-file-parser=" + workingDir + "/src/main/Il2CppOutputProject/IL2CPP/MapFileParser/MapFileParser.exe",
"--generatedcppdir=" + workingDir + "/src/main/Il2CppOutputProject/Source/il2cppOutput",
"--baselib-directory=" + workingDir + "/src/main/jniStaticLibs/" + abi,
"--dotnetprofile=unityaot")
environment "ANDROID_SDK_ROOT", getSdkDir()
}
delete workingDir + targetDirectory + abi + "/libil2cpp.sym.so"
ant.move(file: workingDir + targetDirectory + abi + "/libil2cpp.dbg.so", tofile: workingDir + "/symbols/" + abi + "/libil2cpp.so")
}

android {
task BuildIl2CppTask {
doLast {
BuildIl2Cpp(projectDir.toString().replaceAll('\\\\', '/'), '/src/main/jniLibs/', 'ARM64', 'arm64-v8a', 'Release');
}
}
afterEvaluate {
if (project(':unityLibrary').tasks.findByName('mergeDebugJniLibFolders'))
project(':unityLibrary').mergeDebugJniLibFolders.dependsOn BuildIl2CppTask
if (project(':unityLibrary').tasks.findByName('mergeReleaseJniLibFolders'))
project(':unityLibrary').mergeReleaseJniLibFolders.dependsOn BuildIl2CppTask
}
sourceSets {
main {
jni.srcDirs = ["src/main/Il2CppOutputProject"]
}
}
}



Loading
Loading