aboutsummaryrefslogtreecommitdiffstats
path: root/anttasks/src/com/android/ant/ApkBuilderTask.java
blob: 8997ad1bea953041faa60181b8a2b91a71c00cf5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.ant;

import com.android.sdklib.build.ApkBuilder;
import com.android.sdklib.build.ApkBuilder.FileEntry;
import com.android.sdklib.build.ApkCreationException;
import com.android.sdklib.build.DuplicateFileException;
import com.android.sdklib.build.SealedApkException;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.types.Path;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

public class ApkBuilderTask extends SingleDependencyTask {

    private final static Pattern PATTERN_JAR_EXT = Pattern.compile("^.+\\.jar$",
            Pattern.CASE_INSENSITIVE);

    private String mOutFolder;
    private String mApkFilepath;
    private String mResourceFile;
    private boolean mVerbose = false;
    private boolean mDebugPackaging = false;
    private boolean mDebugSigning = false;
    private boolean mHasCode = true;

    private Path mDexPath;

    private final ArrayList<Path> mZipList = new ArrayList<Path>();
    private final ArrayList<Path> mSourceList = new ArrayList<Path>();
    private final ArrayList<Path> mJarfolderList = new ArrayList<Path>();
    private final ArrayList<Path> mJarfileList = new ArrayList<Path>();
    private final ArrayList<Path> mNativeList = new ArrayList<Path>();

    private static class SourceFolderInputPath extends InputPath {
        public SourceFolderInputPath(File file) {
            super(file);
        }

        @Override
        public boolean ignores(File file) {
            if (file.isDirectory()) {
                return !ApkBuilder.checkFolderForPackaging(file.getName());
            } else {
                return !ApkBuilder.checkFileForPackaging(file.getName());
            }
        }
    }

    /**
     * Sets the value of the "outfolder" attribute.
     * @param outFolder the value.
     */
    public void setOutfolder(Path outFolder) {
        mOutFolder = TaskHelper.checkSinglePath("outfolder", outFolder);
    }

    /**
     * Sets the full filepath to the apk to generate.
     * @param filepath
     */
    public void setApkfilepath(String filepath) {
        mApkFilepath = filepath;
    }

    /**
     * Sets the resourcefile attribute
     * @param resourceFile
     */
    public void setResourcefile(String resourceFile) {
        mResourceFile = resourceFile;
    }

    /**
     * Sets the value of the "verbose" attribute.
     * @param verbose the value.
     */
    public void setVerbose(boolean verbose) {
        mVerbose = verbose;
    }

    /**
     * Sets the value of the "debug" attribute.
     * @param debug the debug mode value.
     */
    public void setDebug(boolean debug) {
        System.out.println("WARNNG: Using deprecated 'debug' attribute in ApkBuilderTask." +
        "Use 'debugpackaging' and 'debugsigning' instead.");
        mDebugPackaging = debug;
        mDebugSigning = debug;
    }

    /**
     * Sets the value of the "debugpackaging" attribute.
     * @param debug the debug mode value.
     */
    public void setDebugpackaging(boolean debug) {
        mDebugPackaging = debug;
    }

    /**
     * Sets the value of the "debugsigning" attribute.
     * @param debug the debug mode value.
     */
    public void setDebugsigning(boolean debug) {
        mDebugSigning = debug;
    }

    /**
     * Sets the hascode attribute. Default is true.
     * If set to false, then <dex> and <sourcefolder> nodes are ignored and not processed.
     * @param hasCode the value of the attribute.
     */
    public void setHascode(boolean hasCode) {
        mHasCode   = hasCode;
    }

    /**
     * Returns an object representing a nested <var>zip</var> element.
     */
    public Object createZip() {
        Path path = new Path(getProject());
        mZipList.add(path);
        return path;
    }

    /**
     * Returns an object representing a nested <var>dex</var> element.
     * This is similar to a nested <var>file</var> element, except when {@link #mHasCode}
     * is <code>false</code> in which case it's ignored.
     */
    public Object createDex() {
        if (mDexPath == null) {
            return mDexPath = new Path(getProject());
        } else {
            throw new BuildException("Only one <dex> inner element can be provided");
        }
    }

    /**
     * Returns an object representing a nested <var>sourcefolder</var> element.
     */
    public Object createSourcefolder() {
        Path path = new Path(getProject());
        mSourceList.add(path);
        return path;
    }

    /**
     * Returns an object representing a nested <var>jarfolder</var> element.
     */
    public Object createJarfolder() {
        Path path = new Path(getProject());
        mJarfolderList.add(path);
        return path;
    }

    /**
     * Returns an object representing a nested <var>jarfile</var> element.
     */
    public Object createJarfile() {
        Path path = new Path(getProject());
        mJarfileList.add(path);
        return path;
    }

    /**
     * Returns an object representing a nested <var>nativefolder</var> element.
     */
    public Object createNativefolder() {
        Path path = new Path(getProject());
        mNativeList.add(path);
        return path;
    }

    @Override
    public void execute() throws BuildException {

        File outputFile;
        if (mApkFilepath != null) {
            outputFile = new File(mApkFilepath);
        } else {
            throw new BuildException("missing attribute 'apkFilepath'");
        }

        if (mResourceFile == null) {
            throw new BuildException("missing attribute 'resourcefile'");
        }

        if (mOutFolder == null) {
            throw new BuildException("missing attribute 'outfolder'");
        }

        // check dexPath is only one file.
        File dexFile = null;
        if (mHasCode) {
            String[] dexFiles = mDexPath.list();
            if (dexFiles.length != 1) {
                throw new BuildException(String.format(
                        "Expected one dex file but path value resolve to %d files.",
                        dexFiles.length));
            }
            dexFile = new File(dexFiles[0]);
        }

        try {
            // build list of input files/folders to compute dependencies
            // add the content of the zip files.
            List<InputPath> inputPaths = new ArrayList<InputPath>();

            // resource file
            InputPath resourceInputPath = new InputPath(new File(mOutFolder, mResourceFile));
            inputPaths.add(resourceInputPath);

            // dex file
            if (dexFile != null) {
                inputPaths.add(new InputPath(dexFile));
            }

            // zip input files
            List<File> zipFiles = new ArrayList<File>();
            for (Path pathList : mZipList) {
                for (String path : pathList.list()) {
                    File f =  new File(path);
                    zipFiles.add(f);
                    inputPaths.add(new InputPath(f));
                }
            }

            // now go through the list of source folders used to add non java files.
            List<File> sourceFolderList = new ArrayList<File>();
            if (mHasCode) {
                for (Path pathList : mSourceList) {
                    for (String path : pathList.list()) {
                        File f =  new File(path);
                        sourceFolderList.add(f);
                        // because this is a source folder but we only care about non
                        // java files.
                        inputPaths.add(new SourceFolderInputPath(f));
                    }
                }
            }

            // now go through the list of jar folders.
            List<File> jarFileList = new ArrayList<File>();
            for (Path pathList : mJarfolderList) {
                for (String path : pathList.list()) {
                    // it's ok if top level folders are missing
                    File folder = new File(path);
                    if (folder.isDirectory()) {
                        String[] filenames = folder.list(new FilenameFilter() {
                            @Override
                            public boolean accept(File dir, String name) {
                                return PATTERN_JAR_EXT.matcher(name).matches();
                            }
                        });

                        for (String filename : filenames) {
                            File f = new File(folder, filename);
                            jarFileList.add(f);
                            inputPaths.add(new InputPath(f));
                        }
                    }
                }
            }

            // now go through the list of jar files.
            for (Path pathList : mJarfileList) {
                for (String path : pathList.list()) {
                    File f = new File(path);
                    jarFileList.add(f);
                    inputPaths.add(new InputPath(f));
                }
            }

            // now the native lib folder.
            List<FileEntry> nativeFileList = new ArrayList<FileEntry>();
            for (Path pathList : mNativeList) {
                for (String path : pathList.list()) {
                    // it's ok if top level folders are missing
                    File folder = new File(path);
                    if (folder.isDirectory()) {
                        List<FileEntry> entries = ApkBuilder.getNativeFiles(folder,
                                mDebugPackaging);
                        // add the list to the list of native files and then create an input
                        // path for each file
                        nativeFileList.addAll(entries);

                        for (FileEntry entry : entries) {
                            inputPaths.add(new InputPath(entry.mFile));
                        }
                    }
                }
            }

            // Finally figure out the path to the dependency file.
            String depFile = outputFile.getAbsolutePath() + ".d";

            // check dependencies
            if (initDependencies(depFile, inputPaths) && dependenciesHaveChanged() == false) {
                System.out.println(
                        "No changes. No need to create apk.");
                return;
            }

            if (mDebugSigning) {
                System.out.println(String.format(
                        "Creating %s and signing it with a debug key...", outputFile.getName()));
            } else {
                System.out.println(String.format(
                        "Creating %s for release...", outputFile.getName()));
            }

            ApkBuilder apkBuilder = new ApkBuilder(
                    outputFile,
                    resourceInputPath.getFile(),
                    dexFile,
                    mDebugSigning ? ApkBuilder.getDebugKeystore() : null,
                    mVerbose ? System.out : null);
            apkBuilder.setDebugMode(mDebugPackaging);


            // add the content of the zip files.
            for (File f : zipFiles) {
                if (mVerbose) {
                    System.out.println("Zip Input: " + f.getAbsolutePath());
                }
                apkBuilder.addZipFile(f);
            }

            // now go through the list of file to directly add the to the list.
            for (File f : sourceFolderList) {
                if (mVerbose) {
                    System.out.println("Source Folder Input: " + f.getAbsolutePath());
                }
                apkBuilder.addSourceFolder(f);
            }

            // now go through the list of jar files.
            for (File f : jarFileList) {
                if (mVerbose) {
                    System.out.println("Jar Input: " + f.getAbsolutePath());
                }
                apkBuilder.addResourcesFromJar(f);
            }

            // and finally the native files
            apkBuilder.addNativeLibraries(nativeFileList);

            // close the archive
            apkBuilder.sealApk();

            // and generate the dependency file
            generateDependencyFile(depFile, inputPaths, outputFile.getAbsolutePath());
        } catch (DuplicateFileException e) {
            System.err.println(String.format(
                    "Found duplicate file for APK: %1$s\nOrigin 1: %2$s\nOrigin 2: %3$s",
                    e.getArchivePath(), e.getFile1(), e.getFile2()));
            throw new BuildException(e);
        } catch (ApkCreationException e) {
            throw new BuildException(e);
        } catch (SealedApkException e) {
            throw new BuildException(e);
        } catch (IllegalArgumentException e) {
            throw new BuildException(e);
        }
    }

    @Override
    protected String getExecTaskName() {
        return "apkbuilder";
    }
}