Subversion Repositories DevTools

Rev

Rev 4364 | Rev 4371 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
4350 dpurdie 1
########################################################################
2
# Copyright (c) VIX TECHNOLOGY (AUST) LTD
3
#
4
# Module name   : androidBuilder.pl
5
# Module type   : Makefile system
6
# Compiler(s)   : Perl
7
# Environment(s): jats
8
#
9
# Description   : This program is invoked by the JATS Makefile System
10
#                 to 'build' an Android project from an Eclipse based
11
#                 Android project. It does this by:
12
#                   Creating a build.xml file from the Eclispe files
13
#                   Injecting properties into the build
14
#                   Invoking ANT to perform the build 
15
#
16
#                 This process requires external tool - delivered in packages
17
#                 These are:
18
#                   ant         - Normally more recent than that installed 
19
#                                 on the build machines
20
#                   androidSdk  - From package rather than installed
21
#                                 This provides flexability when a new Sdk
22
#                                 is required
23
#
24
# Usage:        The utility is invoked in a controlled manner from a Jats
25
#               makefile. The call is generated by the Android Toolset
26
#               Arguments:
27
#                -verbose                   - Increase debugging
28
#                -verbose=n                 - Increase debugging
29
#                -f=manifestFile.xml        - project Manifest file
30
#                -i=path                    - Path to the interface directory
31
#                -t=[P|D]"                  - Build Type. Production or Debug
32
#                -pn=PackageName            - Package Name
33
#                -pv=PackageVersion         - Package Version
34
#                -clean                     - Will clean the build
35
#                -populate                  - Test Env and Populate 'libs'
36
#               Aguments that can be provided by the user
37
#                -projectname=ProjectName   - Project Name [optional]
38
#                -target=number             - Project Target
4370 dpurdie 39
#                -Jar=name                  - Name of a Jar to include
40
#                -lname                     - Name of a Jats library to include
41
#                -Lname                     - Name of a 3rd party library to include
4350 dpurdie 42
#
43
#......................................................................#
44
 
45
require 5.008_002;
46
use strict;
47
use warnings;
48
 
4364 dpurdie 49
use Getopt::Long qw(:config pass_through);
4350 dpurdie 50
 
51
use JatsError;
52
use JatsSystem;
53
use FileUtils;
54
use JatsProperties;
55
use JatsVersionUtils;
56
use ReadBuildConfig;
57
use JatsCopy;
4364 dpurdie 58
use ArrayHashUtils;
4350 dpurdie 59
 
60
#
61
#   Globals
62
#   Command line arguments
63
#
64
my $opt_verbose = $ENV{GBE_VERBOSE};
65
my $opt_manifestFile;
66
my $opt_interface;
67
my $opt_gbetype = 'P';
68
my $opt_clean;
69
my $opt_pkgname;
70
my $opt_pkgversion;
71
my $opt_projectname;
72
my $opt_populate;
73
my $opt_target = 1;
4364 dpurdie 74
my @opt_jlibs;
75
my @opt_elibs;
76
my @opt_jars;
4350 dpurdie 77
 
78
#
79
#   Configuration
80
#   Map JATS platforms to Shared library targets
81
#
82
my %SharedLibMap = (
83
    'ANDROIDARM'    => 'armeabi',
84
    'ANDROIDMIPS'   => 'mips',
85
    'ANDROIDX86'    => 'x86',
86
    );
87
 
88
#   Build type in ant format: release or debug
89
my $ant_target;
90
 
91
#-------------------------------------------------------------------------------
92
# Function        : Main Entry Point 
93
#
94
# Description     : Main entry to this program
95
#
96
# Inputs          : @ARGV           - Array of command line arguments
97
#                                     See file header
98
#
99
# Returns         : 0               - No Error
100
#                   1               - Error encountered    
101
#
4354 dpurdie 102
InitFileUtils();
4350 dpurdie 103
ErrorConfig( 'name'    => 'ANDROIDBUILDER',
104
             'verbose' => $opt_verbose);
105
 
106
#
107
#   Install local signal handlers to process GetOptions messages
108
#
109
local $SIG{__WARN__} = sub { ReportError('AndroidBuilder.' . "@_"); };
110
local $SIG{__DIE__} = sub { ReportError('AndroidBuilder.' . "@_"); };
111
my $result = GetOptions (
112
                "verbose:+"     => \$opt_verbose,       # flag
113
                "f=s"           => \$opt_manifestFile,  # string
114
                "i=s"           => \$opt_interface,     # Interface directory
115
                "t=s"           => \$opt_gbetype,       # string
116
                "pn=s"          => \$opt_pkgname,       # string
117
                "pv=s"          => \$opt_pkgversion,    # string
118
                "projectname=s" => \$opt_projectname,   # string
119
                "clean"         => \$opt_clean,         # flag
120
                "populate"      => \$opt_populate,      # flag
121
                "target:i"      => \$opt_target,        # Number
4364 dpurdie 122
                "Jar=s"         => \@opt_jars,
4350 dpurdie 123
                );
124
 
125
#
126
#   Restore signal handlers and report parse errors
127
#
4364 dpurdie 128
$SIG{__WARN__} = 'DEFAULT';
129
$SIG{__DIE__} = 'DEFAULT';
4350 dpurdie 130
Error('AndroidBuilder. Invalid call options detected') if (!$result);
4364 dpurdie 131
 
132
#
133
#   Process remaining arguments
134
#   Only --Lname and --lname are valid
135
#
136
foreach my $arg (@ARGV) {
137
    if ($arg =~ m~^[-]{1,2}l(.*)~) {
138
        push @opt_jlibs, $1;
139
    } elsif ($arg =~ m~^[-]{1,2}L(.*)~) {
140
        push @opt_elibs, $1;
141
    } else {
142
        ReportError("Invalid option: $arg");
143
    }
144
}
4350 dpurdie 145
ErrorDoExit();
146
 
147
#
148
#   Sanity Test
149
#
150
ReportError ("Manifest file not specified") unless ( defined $opt_manifestFile); 
151
ReportError ("Manifest file not found: $opt_manifestFile") unless ( -f $opt_manifestFile);
152
 
153
ReportError ("Interface directory not specified") unless ( defined $opt_interface);
154
ReportError ("Interface directory not found: $opt_interface") unless ( -d $opt_interface);
155
 
156
ReportError ("Package Name not specified") unless ( defined $opt_pkgname); 
157
ReportError ("Package Version not specified") unless ( defined $opt_pkgversion); 
158
ErrorDoExit();
159
 
160
#
161
#   Basic setup
162
#
163
$ant_target = $opt_gbetype eq 'P' ? 'release' : 'debug';
164
 
165
#
166
#   If multiple project are built in the same package it may be best to provide
167
#   a project name
168
#
169
$opt_projectname = $opt_pkgname
170
    unless (defined $opt_projectname);
171
 
172
#
173
#   The AndroidManifest.xml file MUST be in the root of the project
174
#   There will be some other files there too
175
#   Calculate the root of the project
176
#
177
my $project_root = StripFileExt($opt_manifestFile);
178
my $project_buildfile = catfile($project_root, 'build.xml');
179
 
180
Message ("Project Root:" . $project_root);
181
Message ("Project Name:" . $opt_projectname);
182
Message ("Project build file:" . $project_buildfile);
4354 dpurdie 183
Verbose ("Interface:" . $opt_interface);
4350 dpurdie 184
 
185
#
186
#   Essential tool
187
#       ant     - setup ANT_HOME for other tools
188
#
189
#
190
ReadBuildConfig( $opt_interface, 'ANDROID', '--NoTest' );
191
my $antTool = getToolInfo('ant', 'JAVA_VERSION');
192
$ENV{ANT_HOME} = catdir($antTool->{PKGBASE}, $antTool->{TOOLROOT});
193
 
194
#
195
#   Setup the required version of Java for the tool
196
#
197
my $javaVersion = $antTool->{JAVA_VERSION};
198
ReportError ("$javaVersion not defined.", "Building ANDROID requires $javaVersion be installed and correctly configured.") 
199
    unless $ENV{$javaVersion};
200
$ENV{JAVA_HOME}=$ENV{$javaVersion};
201
 
202
#
203
#   Essential tool
204
#       androidSdk  - setup path to the android executable
205
#
206
my $androidSdk = getToolInfo('androidSdk');
207
my $androidPkg = catdir($androidSdk->{PKGBASE}, $androidSdk->{TOOLROOT} );
208
my $ANDROID = catdir($androidPkg,'sdk', 'tools', 'android' );
209
ReportError("Tool Package 'androidSdk' does not provide program 'android'")
210
    unless -f ($ANDROID);
211
ErrorDoExit();
212
 
213
#
214
#   Clean out any build artifacts
215
#
216
if ($opt_clean)
217
{
218
    #
219
    #   Invoke ANT on the build script - if present
220
    #
221
    Message ("Clean the existing build");
222
    JatsCmd('ant', '-buildfile', $project_buildfile, 'clean')
223
        if (-f $project_buildfile);
224
    deleteGeneratedFiles();
225
    exit 0;
226
}
227
 
228
#
229
#   Delete files that we will create and inject
230
#       Not sure about project.properties
231
#       It appears that it can be written - and info will be lost
232
#
233
deleteGeneratedFiles();
234
 
235
#
236
#   Populate the Android Project 'libs' directory
237
#
238
injectDependencies();
239
 
240
#
241
#   Create the project files
242
#       The android tool does not appear to provide an non-zero exit code on error
243
#       Detect error via the non-creation of the expected output file
244
#
245
System($ANDROID, $opt_verbose ? '--verbose' : '--silent',
246
                 'update', 'project', 
247
                 '--path', $project_root, 
248
                 '--subprojects', 
249
                 '--target', $opt_target, 
250
                 '--name', $opt_projectname );
251
unless ( -f catfile($project_root, 'build.xml'))
252
{
253
    Error("Cannot update android project: $opt_projectname");
254
}
255
 
256
#
257
#   The provided AndroidManifest.xml file contains 
258
#       android:versionCode and android:versionName
259
#   These prevent the ones in ant.properties from being reflected in the output
260
#   Rewrite the AndroidManifest.xml file with corrected versions
261
#
262
updateManifest();
263
 
264
#
265
#   If we are only populating the build then we have done all we need to do
266
#
267
if ($opt_populate)
268
{
269
    Verbose ("Populate complete");
270
    exit 0;
271
}
272
 
273
#
274
#   Build the Android project through the ANT package
275
#       ANT_HOME    - has been set up
276
#       JAVA_HOME   - has been set up
277
#
278
Message ("Build the android project: $opt_projectname");
279
my $rv = JatsCmd('ant', '-buildfile', $project_buildfile, $ant_target);
280
Error("Cannot build android project: $opt_projectname") if $rv;
281
exit(0);
282
 
283
#-------------------------------------------------------------------------------
284
# Function        : updateManifest 
285
#
286
# Description     : Calculate Version information
287
#                   Rewrite the Projects Manifest file and local properties files
288
#
289
# Inputs          : None 
290
#
291
# Returns         : Nothing
292
#
293
sub updateManifest
294
{
295
    #
296
    #   Generate Package Versioning information   
297
    #       Need a text string and a number
298
    #       Generate the 'number' from the version number
299
    #
300
    my $version_text;
301
    my $version_num;
302
 
303
    $version_text = $opt_pkgversion;
304
    my ($major, $minor, $patch, $build )= SplitVersion($opt_pkgversion);
305
    foreach my $item ($major, $minor, $patch, $build)
306
    {
307
        Error("Package version has invalid form. It contains non-numeric parts", $item)
308
            unless ( $item =~ m~^\d+$~);
309
    }
310
    $version_num = ($major << 24) + ($minor << 16) + ($patch << 8) + $build;
311
 
312
    Message ("Project Version Txt:" . $version_text);
313
    Message ("Project Version Num:" . $version_num);
314
 
315
    #
316
    #   Rewrite the Manifest File 
317
    #       Delete the Versioning information
318
    #       It will be picked up from the ant.properties file
319
    #       Store it in the interface directory
320
    #
321
    my $jats_androidManifestFile = catfile($opt_interface, $opt_projectname . '_'.'AndroidManifest.xml');
322
    Message ("Rewrite Manifest: " . $jats_androidManifestFile);
323
 
324
    open (AM, '<', $opt_manifestFile) or Error("Cannot open $opt_manifestFile: $!");
325
    open (JAM, '>', $jats_androidManifestFile) or Error ("Cannot create $jats_androidManifestFile: $!");
326
    while (<AM>)
327
    {
328
        s~(android:versionCode=").*(")~$1$version_num$2~;
329
        s~(android:versionName=").*(")~$1$version_text$2~;
330
        print JAM $_
331
    }
332
    close AM;
333
    close JAM;
334
 
335
    #
336
    #   Create the ant.properties file
337
    #   It needs to be in the same directory as the build.xml
338
    #
339
    my $antProperies = catfile($project_root,'ant.properties');
340
    Message ("Create Properties file: " . $antProperies);
341
 
342
    my $data = JatsProperties::New();
343
 
344
    #$data->setProperty('source.dir'        , 'src');
345
 
346
    #   Appears to work best when left as default
347
    #$data->setProperty('out.dir'           , 'bin');
348
 
349
    #   Don't write these to the properties file as it will
350
    #   create warning messages. The data is in the Manifest File
351
    #
352
    #$data->setProperty('version.code'      , $version_num);
353
    #$data->setProperty('version.name'      , $version_text);
354
 
4354 dpurdie 355
    $data->setProperty('manifest.file'      , FullPath($jats_androidManifestFile));
4350 dpurdie 356
    $data->setProperty('verbose'            , $opt_verbose ? 'true' : 'false');
357
 
358
    #   May be of interest
359
    #<property name="jar.libs.dir" value="libs" />
360
    #<property name="jar.libs.absolute.dir" location="${jar.libs.dir}" />
361
    #<property name="native.libs.absolute.dir" location="libs" />
362
    #
363
    #<property name="out.dir" value="bin" />
364
    #<property name="out.absolute.dir" location="${out.dir}" />
365
    #<property name="out.classes.absolute.dir" location="${out.dir}/classes" />
366
    #<property name="out.res.absolute.dir" location="${out.dir}/res" />
367
    #<property name="out.rs.obj.absolute.dir" location="${out.dir}/rsObj" />
368
    #<property name="out.rs.libs.absolute.dir" location="${out.dir}/rsLibs" />
369
    #<property name="out.aidl.absolute.dir" location="${out.dir}/aidl" />
370
    #<property name="out.dexed.absolute.dir" location="${out.dir}/dexedLibs" />
371
    #<property name="out.manifest.abs.file" location="${out.dir}/AndroidManifest.xml" />
372
 
373
    #
374
    #   Insert key information
375
    #   Only used in the 'release' build
376
    #   At the moment the signing step MUST be done outside of the build system
377
    #
378
    #$data->setProperty('key.store'               , 'vix-pcc.keystore');
379
    #$data->setProperty('key.alias'               , 'pcc');
380
    #$data->setProperty('key.store.password'      , 'VixPassword');
381
    #$data->setProperty('key.alias.password'      , 'VixPassword');
382
 
383
    $data->store( $antProperies );
384
}
385
 
386
#-------------------------------------------------------------------------------
387
# Function        : injectDependencies 
388
#
389
# Description     : Populate the 'libs' directory
390
#                       
391
#                   Inject dependencies
392
#                   The android build will make use of files in the 'libs' directory
393
#                   There are two types of files that can be placed in that directory
394
#                   These appear to be:
395
#                       1) .jar files
396
#                       2) Shared libraries provided by NDK components
397
#                   
398
#                   Assume that the user is doing the right thing and not manually placing
399
#                   external dependencies in the 'libs' directory
400
#                   
401
#                   Clean out all files and repopulate - depending on the build type
402
#                   It may be different for debug and production builds
403
#
404
# Inputs          : 
405
#
406
# Returns         : 
407
#
408
sub injectDependencies
409
{
4364 dpurdie 410
    my @jlist;
411
    my @liblist;
412
 
413
    #
414
    #   Only if we need to do something
415
    #
416
    return unless (@opt_jars || @opt_elibs || @opt_jlibs);
417
 
418
    #
419
    #   Create search entries suitable for the CopyDir
420
    #   We will delete entries as the files are copied
421
    #
422
    foreach my $item ( @opt_jars) {
423
        UniquePush \@jlist, $item . '.jar';
424
    }
425
 
426
    foreach my $item ( @opt_elibs) {
427
        UniquePush \@liblist, 'lib' . $item . '.so';
428
    }
429
 
430
    foreach my $item ( @opt_jlibs) {
431
        UniquePush \@liblist, 'lib' . $item . $opt_gbetype . '.so';
432
    }
433
 
434
 
435
    #
436
    #   Where does it go
437
    #
4350 dpurdie 438
    my $androidLibs = catdir($project_root, 'libs');
439
    Verbose ("Android libs: $androidLibs");
440
 
441
    my @pkg_paths = getPackagePaths("--Interface=$opt_interface");
442
    foreach my $pkg ( @pkg_paths)
443
    {
444
        #
445
        #   Copy in all JAR files found in dependent packages
446
        #
447
        my $jarDir = catdir($pkg,'jar'); 
4364 dpurdie 448
        if (-d $jarDir && @jlist)
4350 dpurdie 449
        {
450
            Verbose("Jar Dir Found found", $jarDir);
451
            Message ("Copy in: $jarDir");
452
            CopyDir ( $jarDir, $androidLibs,
4364 dpurdie 453
                        'Match' => \@jlist,
4350 dpurdie 454
                        'Log' => $opt_verbose + 1,
455
                        'SymlinkFiles' => 1,
4364 dpurdie 456
                        'Examine' => sub 
457
                            {
458
                                my ($opt) = @_;
459
                                ArrayDelete \@jlist, $opt->{file};
460
                            },
4350 dpurdie 461
                        );
462
        }
463
 
464
        #
465
        #   Build up the Shared Library structure as used by JNI
466
        #   Note: Only support current JATS format
467
        #   Copy in .so files and in to process massage the pathname so that
468
        #   it confirms to that expected by the Android Project
469
        #
470
        my $libDir = catdir($pkg,'lib');
4364 dpurdie 471
        if (-d $libDir && @liblist)
4350 dpurdie 472
        {
473
            Verbose("Lib Dir Found found", $libDir);
474
            Message ("Copy in: $libDir");
475
            CopyDir ( $libDir, $androidLibs,
4364 dpurdie 476
                        'Match' => \@liblist,
4350 dpurdie 477
                        'Log' => $opt_verbose + 1,
478
                        'SymlinkFiles' => 1,
479
                        'Examine' => sub 
480
                            { 
481
                                my ($opt) = @_;
482
                                foreach my $platform ( keys %SharedLibMap ) {
483
                                    my $replace = $SharedLibMap{$platform};
484
                                    if ($opt->{'target'} =~ s~/$platform/~/$replace/~)
485
                                    {
4364 dpurdie 486
                                        ArrayDelete \@liblist, $opt->{file};
4350 dpurdie 487
                                        return 1;
488
                                    }
489
                                }
490
                                return 0;
491
                            },
492
                        );
493
        }
494
    }
4364 dpurdie 495
 
496
    #
497
    #   Report files that could not be located. They were deleted from the lists
498
    #   as they were processed
499
    #       These are Warnings in populate Mode
500
    #       and errors at build time
501
    #
502
    if (@jlist || @liblist)
503
    {
504
        my $fn = $opt_populate ? \&Warning : \&Error; 
505
        &$fn("External dependencies not found:", @jlist, @liblist);
506
    }
4350 dpurdie 507
}
508
 
509
#-------------------------------------------------------------------------------
510
# Function        : deleteGeneratedFiles 
511
#
512
# Description     : Delete files that we generate
513
#
514
# Inputs          : 
515
#
516
# Returns         : 
517
#
518
sub deleteGeneratedFiles
519
{
520
    #
521
    #   Delete files that we will create
522
    #       Not sure about project.properties
523
    #       It appears that it can be written - and info will be lost
524
    #
525
    my @deleteList = qw(local.properties build.xml proguard-project.txt);
526
    foreach my $file (@deleteList)
527
    {
528
        Verbose ("Deleting $project_root/$file");
529
        unlink catfile($project_root, $file);
530
    }
531
 
532
    #
533
    #   Clean out the 'libs' directory
534
    #       Assume that its populated with 'external' dependencies
535
    #       Leave the directory - it may have been checked into version control
536
    #
537
    my $androidLibs = catdir($project_root, 'libs');
4364 dpurdie 538
    foreach my $item (glob(catdir($androidLibs, '*'))) {
539
        RmDirTree($item);
540
    }
4350 dpurdie 541
}
542
 
543