aboutsummaryrefslogtreecommitdiffstats
path: root/anttasks/src/com/android/ant/MultiApkExportTask.java
blob: 151b81b41aa81c0d58c2186a49ac47f8d4fbe9cf (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
/*
 * Copyright (C) 2010 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.internal.export.ApkData;
import com.android.sdklib.internal.export.MultiApkExportHelper;
import com.android.sdklib.internal.export.MultiApkExportHelper.ExportException;
import com.android.sdklib.internal.export.MultiApkExportHelper.Target;
import com.android.sdklib.io.FileWrapper;
import com.android.sdklib.io.IAbstractFile;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.taskdefs.Input;
import org.apache.tools.ant.taskdefs.Property;
import org.apache.tools.ant.taskdefs.SubAnt;
import org.apache.tools.ant.types.FileSet;
import org.xml.sax.InputSource;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashSet;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

/**
 * Multiple APK export task.
 * This task is meant to replace {@link SetupTask} as the main setup/export task, importing
 * the rules and generating the export for all projects.
 */
public class MultiApkExportTask extends Task {

    private Target mTarget;

    public void setTarget(String target) {
        mTarget = Target.getTarget(target);
    }

    @Override
    public void execute() throws BuildException {
        Project antProject = getProject();

        if (mTarget == null) {
            throw new BuildException("'target' attribute not set.");
        }

        // get the SDK location
        File sdk = TaskHelper.getSdkLocation(antProject);

        // display SDK Tools revision
        int toolsRevison = TaskHelper.getToolsRevision(sdk);
        if (toolsRevison != -1) {
            System.out.println("Android SDK Tools Revision " + toolsRevison);
        }

        String appPackage = getValidatedProperty(antProject, "package");
        System.out.println("Multi APK export for: " + appPackage);
        String version = getValidatedProperty(antProject, "version");
        int versionCode;
        try {
            versionCode = Integer.parseInt(version);
        } catch (NumberFormatException e) {
            throw new BuildException("version value is not a valid integer.", e);
        }
        System.out.println("versionCode: " + version);

        // checks whether the projects can be signed.
        boolean canSign = false;
        String keyStore = null, keyAlias = null;
        if (mTarget == Target.RELEASE) {
            String value = antProject.getProperty("key.store");
            keyStore = value != null && value.length() > 0 ? value : null;
            value = antProject.getProperty("key.alias");
            keyAlias = value != null && value.length() > 0 ? value : null;
            canSign = keyStore != null && keyAlias != null;
        }

        // get the list of projects
        String projects = getValidatedProperty(antProject, "projects");

        // look to see if there's an export log from a previous export
        IAbstractFile log = getBuildLog(appPackage, versionCode);

        MultiApkExportHelper helper = new MultiApkExportHelper(appPackage, versionCode, mTarget);
        try {
            ApkData[] apks = helper.getProjects(projects, log);

            // some temp var used by the project loop
            HashSet<String> compiledProject = new HashSet<String>();
            XPathFactory xPathFactory = XPathFactory.newInstance();

            File exportProjectOutput = new File(getValidatedProperty(antProject, "out.absolute.dir"));

            // if there's no error, and we can sign, prompt for the passwords.
            String keyStorePassword = null;
            String keyAliasPassword = null;
            if (canSign) {
                System.out.println("Found signing keystore and key alias. Need passwords.");

                Input input = new Input();
                input.setProject(antProject);
                input.setAddproperty("key.store.password");
                input.setMessage(String.format("Please enter keystore password (store: %1$s):",
                        keyStore));
                input.execute();

                input = new Input();
                input.setProject(antProject);
                input.setAddproperty("key.alias.password");
                input.setMessage(String.format("Please enter password for alias '%1$s':",
                        keyAlias));
                input.execute();

                // and now read the property so that they can be set into the sub ant task.
                keyStorePassword = getValidatedProperty(antProject, "key.store.password");
                keyAliasPassword = getValidatedProperty(antProject, "key.alias.password");
            }

            for (ApkData apk : apks) {
                // this output is prepended by "[android-export] " (17 chars), so we put 61 stars
                System.out.println("\n*************************************************************");
                System.out.println("Exporting project: " + apk.getRelativePath());

                SubAnt subAnt = new SubAnt();
                subAnt.setTarget(mTarget.getTarget());
                subAnt.setProject(antProject);

                File subProjectFolder = new File(antProject.getBaseDir(), apk.getRelativePath());

                FileSet fileSet = new FileSet();
                fileSet.setProject(antProject);
                fileSet.setDir(subProjectFolder);
                fileSet.setIncludes("build.xml");
                subAnt.addFileset(fileSet);

    //            subAnt.setVerbose(true);

                if (mTarget == Target.RELEASE) {
                    // only do the compilation part if it's the first time we export
                    // this project.
                    // (projects can be export multiple time if some properties are set up to
                    // generate more than one APK (for instance ABI split).
                    if (compiledProject.contains(apk.getRelativePath()) == false) {
                        compiledProject.add(apk.getRelativePath());
                    } else {
                        addProp(subAnt, "do.not.compile", "true");
                    }

                    // set the version code, and filtering
                    int compositeVersionCode = apk.getCompositeVersionCode(versionCode);
                    addProp(subAnt, "version.code", Integer.toString(compositeVersionCode));
                    System.out.println("Composite versionCode: " + compositeVersionCode);
                    String abi = apk.getAbi();
                    if (abi != null) {
                        addProp(subAnt, "filter.abi", abi);
                        System.out.println("ABI Filter: " + abi);
                    }

                    // end of the output by this task. Everything that follows will be output
                    // by the subant.
                    System.out.println("Calling to project's Ant file...");
                    System.out.println("----------\n");

                    // set the output file names/paths. Keep all the temporary files in the project
                    // folder, and only put the final file (which is different depending on whether
                    // the file can be signed) locally.

                    // read the base name from the build.xml file.
                    String name = null;
                    try {
                        File buildFile = new File(subProjectFolder, "build.xml");
                        XPath xPath = xPathFactory.newXPath();
                        name = xPath.evaluate("/project/@name",
                                new InputSource(new FileInputStream(buildFile)));
                    } catch (XPathExpressionException e) {
                        throw new BuildException("Failed to read build.xml", e);
                    } catch (FileNotFoundException e) {
                        throw new BuildException("build.xml is missing.", e);
                    }

                    // override the resource pack file.
                    addProp(subAnt, "resource.package.file.name",
                            name + "-" + apk.getBuildInfo() + ".ap_");

                    if (canSign) {
                        // set the properties for the password.
                        addProp(subAnt, "key.store", keyStore);
                        addProp(subAnt, "key.alias", keyAlias);
                        addProp(subAnt, "key.store.password", keyStorePassword);
                        addProp(subAnt, "key.alias.password", keyAliasPassword);

                        // temporary file only get a filename change (still stored in the project
                        // bin folder).
                        addProp(subAnt, "out.unsigned.file.name",
                                name + "-" + apk.getBuildInfo() + "-unsigned.apk");
                        addProp(subAnt, "out.unaligned.file",
                                name + "-" + apk.getBuildInfo() + "-unaligned.apk");

                        // final file is stored locally.
                        apk.setOutputName(name + "-" + compositeVersionCode + "-release.apk");
                        addProp(subAnt, "out.release.file", new File(exportProjectOutput,
                                apk.getOutputName()).getAbsolutePath());

                    } else {
                        // put some empty prop. This is to override possible ones defined in the
                        // project. The reason is that if there's more than one project, we don't
                        // want some to signed and some not to be (and we don't want each project
                        // to prompt for password.)
                        addProp(subAnt, "key.store", "");
                        addProp(subAnt, "key.alias", "");
                        // final file is the unsigned version. It gets stored locally.
                        apk.setOutputName(name + "-" + compositeVersionCode + "-unsigned.apk");
                        addProp(subAnt, "out.unsigned.file", new File(exportProjectOutput,
                                apk.getOutputName()).getAbsolutePath());
                    }
                }

                subAnt.execute();
            }

            if (mTarget == Target.RELEASE) {
                helper.makeBuildLog(log, apks);
            }
        } catch (ExportException e) {
            // we only want to have Ant display the message, not the stack trace, since
            // we use Exceptions to report errors, so we build the BuildException only
            // with the message and not the cause exception.
            throw new BuildException(e.getMessage());
        }
    }

    /**
     * Gets, validates and returns a project property.
     * The property must exist and be non empty.
     * @param antProject the project
     * @param name the name of the property to return.
     * @return the property value always (cannot be null).
     * @throws BuildException if the property is missing or not valid.
     */
    private String getValidatedProperty(Project antProject, String name) {
        String value = antProject.getProperty(name);
        if (value == null || value.length() == 0) {
            throw new BuildException(String.format("Property '%1$s' is not set or empty.", name));
        }

        return value;
    }


    /**
     * Adds a property to a {@link SubAnt} task.
     * @param task the task.
     * @param name the name of the property.
     * @param value the value of the property.
     */
    private void addProp(SubAnt task, String name, String value) {
        Property prop = new Property();
        prop.setName(name);
        prop.setValue(value);
        task.addProperty(prop);
    }

    /**
     * Returns the {@link File} for the build log.
     * @param appPackage
     * @param versionCode
     * @return A new non-null {@link IAbstractFile} mapping to the build log.
     */
    private IAbstractFile getBuildLog(String appPackage, int versionCode) {
        return new FileWrapper(appPackage + "." + versionCode + ".log");
    }
}