Skip to content

Commit 535370d

Browse files
committed
Keep the compression of each entries in the resources.ap_ which generated by the base aapt, refer to wequick#215 wequick#172 wequick#220
1 parent a1dc49e commit 535370d

4 files changed

Lines changed: 176 additions & 30 deletions

File tree

‎Android/DevSample/buildSrc/src/main/groovy/net/wequick/gradle/AppPlugin.groovy‎

Lines changed: 37 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -23,15 +23,18 @@ import com.android.build.gradle.internal.transforms.ProGuardTransform
2323
import com.android.build.gradle.tasks.MergeManifests
2424
import com.android.build.gradle.tasks.MergeSourceSetFolders
2525
import com.android.build.gradle.tasks.ProcessAndroidResources
26+
import com.android.sdklib.BuildToolInfo
2627
import groovy.io.FileType
2728
import net.wequick.gradle.aapt.Aapt
2829
import net.wequick.gradle.aapt.SymbolParser
2930
import net.wequick.gradle.transform.StripAarTransform
3031
import net.wequick.gradle.util.JNIUtils
32+
import net.wequick.gradle.util.ZipUtils
3133
import org.gradle.api.Project
3234
import org.gradle.api.Task
3335
import org.gradle.api.artifacts.DependencySet
3436
import org.gradle.api.artifacts.ResolvedDependency
37+
import org.gradle.api.file.FileTree
3538
import org.gradle.api.internal.artifacts.dependencies.DefaultProjectDependency
3639
import org.gradle.api.tasks.compile.JavaCompile
3740

@@ -941,10 +944,16 @@ class AppPlugin extends BundlePlugin {
941944
aaptTask.doLast { ProcessAndroidResources it ->
942945
// Unpack resources.ap_
943946
File apFile = it.packageOutputFile
947+
FileTree apFiles = project.zipTree(apFile)
944948
File unzipApDir = new File(apFile.parentFile, 'ap_unzip')
949+
unzipApDir.delete()
945950
project.copy {
946-
from project.zipTree(apFile)
951+
from apFiles
947952
into unzipApDir
953+
954+
include 'AndroidManifest.xml'
955+
include 'resources.arsc'
956+
include 'res/**/*'
948957
}
949958

950959
// Modify assets
@@ -955,13 +964,15 @@ class AppPlugin extends BundlePlugin {
955964
File rJavaFile = new File(sourceOutputDir, "${small.packagePath}/R.java")
956965
def rev = android.buildToolsRevision
957966
int noResourcesFlag = 0
967+
def filteredResources = new HashSet()
968+
def updatedResources = new HashSet()
958969
Aapt aapt = new Aapt(unzipApDir, rJavaFile, symbolFile, rev)
959970
if (small.retainedTypes != null && small.retainedTypes.size() > 0) {
960-
aapt.filterResources(small.retainedTypes)
971+
aapt.filterResources(small.retainedTypes, filteredResources)
961972
Log.success "[${project.name}] split library res files..."
962973

963974
aapt.filterPackage(small.retainedTypes, small.packageId, small.idMaps,
964-
small.retainedStyleables)
975+
small.retainedStyleables, updatedResources)
965976

966977
Log.success "[${project.name}] slice asset package and reset package id..."
967978

@@ -997,11 +1008,11 @@ class AppPlugin extends BundlePlugin {
9971008
Log.success "[${project.name}] split library R.java files..."
9981009
} else {
9991010
noResourcesFlag = 1
1000-
if (aapt.deleteResourcesDir()) {
1011+
if (aapt.deleteResourcesDir(filteredResources)) {
10011012
Log.success "[${project.name}] remove resources dir..."
10021013
}
10031014

1004-
if (aapt.deletePackage()) {
1015+
if (aapt.deletePackage(filteredResources)) {
10051016
Log.success "[${project.name}] remove resources.arsc..."
10061017
}
10071018

@@ -1012,16 +1023,33 @@ class AppPlugin extends BundlePlugin {
10121023

10131024
int abiFlag = getABIFlag()
10141025
int flags = (abiFlag << 1) | noResourcesFlag
1015-
if (aapt.writeSmallFlags(flags)) {
1026+
if (aapt.writeSmallFlags(flags, updatedResources)) {
10161027
Log.success "[${project.name}] add flags: ${Integer.toBinaryString(flags)}..."
10171028
}
10181029

1019-
// Repack resources.ap_
1020-
apFile.delete()
1021-
project.ant.zip(baseDir: unzipApDir, destFile: apFile)
1030+
String aaptExe = small.aapt.buildTools.getPath(BuildToolInfo.PathId.AAPT)
1031+
1032+
// Delete filtered entries.
1033+
// Cause there is no `aapt update' command supported, so for the updated resources
1034+
// we also delete first and run `aapt add' later.
1035+
filteredResources.addAll(updatedResources)
1036+
ZipUtils.with(apFile).deleteAll(filteredResources)
1037+
1038+
// Re-add updated entries.
1039+
// $ aapt add resources.ap_ file1 file2 ...
1040+
project.exec {
1041+
executable aaptExe
1042+
workingDir unzipApDir
1043+
args 'add', apFile.path
1044+
args updatedResources
1045+
1046+
// store the output instead of printing to the console
1047+
standardOutput = new ByteArrayOutputStream()
1048+
}
10221049
}
10231050
}
10241051

1052+
10251053
/**
10261054
* Hook javac task to split libraries' R.class
10271055
*/

‎Android/DevSample/buildSrc/src/main/groovy/net/wequick/gradle/AssetPlugin.groovy‎

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
package net.wequick.gradle
1717

1818
import com.android.build.gradle.api.BaseVariant
19+
import com.android.sdklib.BuildToolInfo
1920
import net.wequick.gradle.aapt.Aapt
2021
import org.gradle.api.Project
2122
import org.gradle.api.tasks.Copy
@@ -73,13 +74,7 @@ class AssetPlugin extends BundlePlugin {
7374
// Generate AndroidManifest.xml
7475
Aapt aapt = new Aapt(destDir, null, null, android.buildToolsRevision)
7576
def aaptTask = project.processReleaseResources
76-
def aaptExe
77-
aaptTask.buildTools.mPaths.each { k, v ->
78-
if ((String) k == 'AAPT') { // k.class = `com.android.sdklib.BuildToolInfo$PathId'
79-
aaptExe = v
80-
return
81-
}
82-
}
77+
def aaptExe = aaptTask.buildTools.getPath(BuildToolInfo.PathId.AAPT)
8378
def cf = android.defaultConfig
8479
def baseAsset = new File(android.getSdkDirectory(),
8580
"platforms/android-${cf.targetSdkVersion.getApiLevel()}/android.jar")

‎Android/DevSample/buildSrc/src/main/groovy/net/wequick/gradle/aapt/Aapt.groovy‎

Lines changed: 36 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ import org.gradle.api.Project
2424
public class Aapt {
2525

2626
public static final int ID_DELETED = -1
27+
public static final String FILE_ARSC = 'resources.arsc'
28+
public static final String FILE_MANIFEST = 'AndroidManifest.xml'
2729

2830
private File mAssetDir
2931
private File mJavaFile
@@ -43,23 +45,29 @@ public class Aapt {
4345
* @param pp new package id
4446
* @param idMaps
4547
*/
46-
void filterPackage(List retainedTypes, int pp, Map idMaps, List retainedStyleables) {
47-
File arscFile = new File(mAssetDir, 'resources.arsc')
48+
void filterPackage(List retainedTypes, int pp, Map idMaps, List retainedStyleables,
49+
Set outUpdatedResources) {
50+
File arscFile = new File(mAssetDir, FILE_ARSC)
4851
def arscEditor = new ArscEditor(arscFile, mToolsRevision)
4952

5053
// Filter R.txt
5154
if (mSymbolFile != null) filterRtext(mSymbolFile, retainedTypes, retainedStyleables)
5255
// Filter resources.arsc
5356
arscEditor.slice(pp, idMaps, retainedTypes)
57+
outUpdatedResources.add(FILE_ARSC)
5458

55-
resetAllXmlPackageId(mAssetDir, pp, idMaps)
59+
resetAllXmlPackageId(mAssetDir, pp, idMaps, outUpdatedResources)
5660
}
5761

58-
def writeSmallFlags(int flags) {
62+
def writeSmallFlags(int flags, Set outUpdatedResources) {
5963
if (flags == 0) return false
6064

61-
def e = new AXmlEditor(new File(mAssetDir, 'AndroidManifest.xml'))
62-
return e.setSmallFlags(flags)
65+
def e = new AXmlEditor(new File(mAssetDir, FILE_MANIFEST))
66+
if (e.setSmallFlags(flags)) {
67+
outUpdatedResources.add(FILE_MANIFEST)
68+
return true
69+
}
70+
return false
6371
}
6472

6573
/**
@@ -69,20 +77,21 @@ public class Aapt {
6977
* @param idMaps
7078
*/
7179
void resetPackage(int pp, String ppStr, Map idMaps) {
72-
File arscFile = new File(mAssetDir, 'resources.arsc')
80+
File arscFile = new File(mAssetDir, FILE_ARSC)
7381
def arscEditor = new ArscEditor(arscFile, null)
7482

7583
// Modify R.java
7684
resetRjava(mJavaFile, ppStr)
7785
// Modify resources.arsc
7886
arscEditor.reset(pp, idMaps)
7987

80-
resetAllXmlPackageId(mAssetDir, pp, idMaps)
88+
resetAllXmlPackageId(mAssetDir, pp, idMaps, null)
8189
}
8290

83-
boolean deletePackage() {
84-
File arscFile = new File(mAssetDir, 'resources.arsc')
91+
boolean deletePackage(Set outFilteredResources) {
92+
File arscFile = new File(mAssetDir, FILE_ARSC)
8593
if (arscFile.exists()) {
94+
outFilteredResources.add(FILE_ARSC)
8695
return arscFile.delete()
8796
}
8897
return false
@@ -101,7 +110,7 @@ public class Aapt {
101110

102111
void manifest(Project project, Map options) {
103112
// Create source file
104-
File tempManifest = new File(mAssetDir, 'AndroidManifest.xml')
113+
File tempManifest = new File(mAssetDir, FILE_MANIFEST)
105114
tempManifest.write("""<manifest xmlns:android="http://schemas.android.com/apk/res/android"
106115
package="${options.packageName}"
107116
android:versionName="${options.versionName}"
@@ -126,12 +135,15 @@ public class Aapt {
126135
* Filter resources with specific types
127136
* @param retainedTypes
128137
*/
129-
void filterResources(List retainedTypes) {
138+
void filterResources(List retainedTypes, Set outFilteredResources) {
130139
def resDir = new File(mAssetDir, 'res')
131140
resDir.listFiles().each { typeDir ->
132141
def type = retainedTypes.find { typeDir.name.startsWith(it.name) }
133142
if (type == null) {
134143
// Split whole type
144+
typeDir.listFiles().each {
145+
outFilteredResources.add("res/$typeDir.name/$it.name" as String)
146+
}
135147
typeDir.deleteDir()
136148
return
137149
}
@@ -141,6 +153,7 @@ public class Aapt {
141153
def entry = type.entries.find { entryFile.name.startsWith("${it.name}.") }
142154
if (entry == null) {
143155
// Split specify entry
156+
outFilteredResources.add("res/$typeDir.name/$entryFile.name" as String)
144157
entryFile.delete()
145158
retainedEntryCount--
146159
}
@@ -152,20 +165,29 @@ public class Aapt {
152165
}
153166
}
154167

155-
boolean deleteResourcesDir() {
168+
boolean deleteResourcesDir(Set outFilters) {
156169
def resDir = new File(mAssetDir, 'res')
157170
if (resDir.exists()) {
171+
resDir.listFiles().each { dir ->
172+
dir.listFiles().each { file ->
173+
outFilters.add("res/$dir.name/$file.name" as String)
174+
}
175+
}
158176
return resDir.deleteDir()
159177
}
160178
return false
161179
}
162180

163181
/** Reset package id for *.xml */
164-
private void resetAllXmlPackageId(File dir, int pp, Map idMaps) {
182+
private static void resetAllXmlPackageId(File dir, int pp, Map idMaps, Set outUpdatedResources) {
183+
int len = dir.canonicalPath.length() + 1 // bypass '/'
165184
dir.eachFileRecurse(FileType.FILES) { file ->
166185
if (file.name.endsWith('.xml')) {
167186
def editor = new AXmlEditor(file)
168187
editor.setPackageId(pp, idMaps)
188+
if (outUpdatedResources != null) {
189+
outUpdatedResources.add(file.canonicalPath.substring(len))
190+
}
169191
}
170192
}
171193
}
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
/*
2+
* Copyright 2015-present wequick.net
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"); you may
5+
* not use this file except in compliance with the License. You may obtain
6+
* a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12+
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13+
* License for the specific language governing permissions and limitations
14+
* under the License.
15+
*/
16+
package net.wequick.gradle.util
17+
18+
import java.util.zip.ZipEntry
19+
import java.util.zip.ZipFile
20+
import java.util.zip.ZipOutputStream
21+
22+
/**
23+
* Class to operate on zip file
24+
*/
25+
public final class ZipUtils {
26+
27+
private static final int BUFFER_SIZE = 1024
28+
29+
private byte[] buffer = new byte[BUFFER_SIZE]
30+
31+
private File file
32+
33+
public static ZipUtils with(File file) {
34+
ZipUtils zu = new ZipUtils()
35+
zu.file = file
36+
return zu
37+
}
38+
39+
/**
40+
* Delete zip entries from a zip file (Copy entries excludes the deletes)
41+
* @param file the zip file
42+
* @param deletes the entries to delete
43+
*/
44+
public ZipUtils deleteAll(Set<String> deletes) {
45+
ZipFile zf = new ZipFile(file)
46+
File temp = new File(file.parentFile, 'temp.zip')
47+
ZipOutputStream os = new ZipOutputStream(new FileOutputStream(temp))
48+
49+
def entries = zf.entries()
50+
while (entries.hasMoreElements()) {
51+
ZipEntry ze = entries.nextElement()
52+
if (!deletes.contains(ze.name)) {
53+
writeEntry(zf, os, ze)
54+
}
55+
}
56+
zf.close()
57+
os.flush()
58+
os.close()
59+
60+
temp.renameTo(file)
61+
return this
62+
}
63+
64+
private void writeEntry(ZipFile zf, ZipOutputStream os, ZipEntry ze)
65+
throws IOException
66+
{
67+
ZipEntry ze2 = new ZipEntry(ze.getName());
68+
ze2.setMethod(ze.getMethod());
69+
ze2.setTime(ze.getTime());
70+
ze2.setComment(ze.getComment());
71+
ze2.setExtra(ze.getExtra());
72+
if (ze.getMethod() == ZipEntry.STORED) {
73+
ze2.setSize(ze.getSize());
74+
ze2.setCrc(ze.getCrc());
75+
}
76+
os.putNextEntry(ze2);
77+
writeBytes(zf, ze, os);
78+
}
79+
80+
/**
81+
* Writes all the bytes for a given entry to the specified output stream.
82+
*/
83+
private synchronized void writeBytes(ZipFile zf, ZipEntry ze, ZipOutputStream os) throws IOException {
84+
int n;
85+
86+
InputStream is = null;
87+
try {
88+
is = zf.getInputStream(ze);
89+
long left = ze.getSize();
90+
91+
while((left > 0) && (n = is.read(buffer, 0, buffer.length)) != -1) {
92+
os.write(buffer, 0, n);
93+
left -= n;
94+
}
95+
} finally {
96+
if (is != null) {
97+
is.close();
98+
}
99+
}
100+
}
101+
}

0 commit comments

Comments
 (0)