blob: 868d90a1188d82b5b5cfe7b4b51b5d7080efe43b [file] [log] [blame]
Joe Onorato0578cbc2016-10-19 17:03:06 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain 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,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "aapt.h"
18#include "adb.h"
19#include "make.h"
20#include "print.h"
21#include "util.h"
22
23#include <sstream>
24#include <string>
25#include <vector>
26
27#include <stdio.h>
28#include <stdlib.h>
29#include <string.h>
30#include <unistd.h>
31
32#include <google/protobuf/stubs/common.h>
33
34using namespace std;
35
36/**
37 * An entry from the command line for something that will be built, installed,
38 * and/or tested.
39 */
40struct Target {
41 bool build;
42 bool install;
43 bool test;
44 string pattern;
45 string name;
46 vector<string> actions;
47 Module module;
48
49 int testActionCount;
50
51 int testPassCount;
52 int testFailCount;
53 bool actionsWithNoTests;
54
55 Target(bool b, bool i, bool t, const string& p);
56};
57
58Target::Target(bool b, bool i, bool t, const string& p)
59 :build(b),
60 install(i),
61 test(t),
62 pattern(p),
63 testActionCount(0),
64 testPassCount(0),
65 testFailCount(0),
66 actionsWithNoTests(false)
67{
68}
69
70/**
71 * Command line options.
72 */
73struct Options {
74 // For help
75 bool runHelp;
76
77 // For tab completion
78 bool runTab;
79 string tabPattern;
80
81 // For build/install/test
Joe Onorato6592c3c2016-11-12 16:34:25 -080082 bool noRestart;
Joe Onorato0578cbc2016-10-19 17:03:06 -070083 bool reboot;
84 vector<Target*> targets;
85
86 Options();
87 ~Options();
88};
89
90Options::Options()
91 :runHelp(false),
92 runTab(false),
Joe Onorato6592c3c2016-11-12 16:34:25 -080093 noRestart(false),
Joe Onorato0578cbc2016-10-19 17:03:06 -070094 reboot(false),
95 targets()
96{
97}
98
99Options::~Options()
100{
101}
102
103struct InstallApk
104{
105 TrackedFile file;
106 bool alwaysInstall;
107 bool installed;
108
109 InstallApk();
110 InstallApk(const InstallApk& that);
111 InstallApk(const string& filename, bool always);
112 ~InstallApk() {};
113};
114
115InstallApk::InstallApk()
116{
117}
118
119InstallApk::InstallApk(const InstallApk& that)
120 :file(that.file),
121 alwaysInstall(that.alwaysInstall),
122 installed(that.installed)
123{
124}
125
126InstallApk::InstallApk(const string& filename, bool always)
127 :file(filename),
128 alwaysInstall(always),
129 installed(false)
130{
131}
132
133
134/**
135 * Record for an test that is going to be launched.
136 */
137struct TestAction {
138 TestAction();
139
140 // The package name from the apk
141 string packageName;
142
143 // The test runner class
144 string runner;
145
146 // The test class, or none if all tests should be run
147 string className;
148
149 // The original target that requested this action
150 Target* target;
151
152 // The number of tests that passed
153 int passCount;
154
155 // The number of tests that failed
156 int failCount;
157};
158
159TestAction::TestAction()
160 :passCount(0),
161 failCount(0)
162{
163}
164
165/**
166 * Record for an activity that is going to be launched.
167 */
168struct ActivityAction {
169 // The package name from the apk
170 string packageName;
171
172 // The test class, or none if all tests should be run
173 string className;
174};
175
176/**
177 * Callback class for the am instrument command.
178 */
179class TestResults: public InstrumentationCallbacks
180{
181public:
182 virtual void OnTestStatus(TestStatus& status);
183 virtual void OnSessionStatus(SessionStatus& status);
184
185 /**
186 * Set the TestAction that the tests are for.
187 * It will be updated with statistics as the tests run.
188 */
189 void SetCurrentAction(TestAction* action);
190
191private:
192 TestAction* m_currentAction;
193};
194
195void
196TestResults::OnTestStatus(TestStatus& status)
197{
198 bool found;
199// printf("OnTestStatus\n");
200// status.PrintDebugString();
201 int32_t resultCode = status.has_results() ? status.result_code() : 0;
202
203 if (!status.has_results()) {
204 return;
205 }
206 const ResultsBundle &results = status.results();
207
208 int32_t currentTestNum = get_bundle_int(results, &found, "current", NULL);
209 if (!found) {
210 currentTestNum = -1;
211 }
212
213 int32_t testCount = get_bundle_int(results, &found, "numtests", NULL);
214 if (!found) {
215 testCount = -1;
216 }
217
218 string className = get_bundle_string(results, &found, "class", NULL);
219 if (!found) {
220 return;
221 }
222
223 string testName = get_bundle_string(results, &found, "test", NULL);
224 if (!found) {
225 return;
226 }
227
228 if (resultCode == 0) {
229 // test passed
230 m_currentAction->passCount++;
231 m_currentAction->target->testPassCount++;
232 } else if (resultCode == 1) {
233 // test starting
234 ostringstream line;
235 line << "Running";
236 if (currentTestNum > 0) {
237 line << ": " << currentTestNum;
238 if (testCount > 0) {
239 line << " of " << testCount;
240 }
241 }
242 line << ": " << m_currentAction->target->name << ':' << className << "\\#" << testName;
243 print_one_line("%s", line.str().c_str());
244 } else if (resultCode == -2) {
245 // test failed
246 m_currentAction->failCount++;
247 m_currentAction->target->testFailCount++;
248 printf("%s\n%sFailed: %s:%s\\#%s%s\n", g_escapeClearLine, g_escapeRedBold,
249 m_currentAction->target->name.c_str(), className.c_str(),
250 testName.c_str(), g_escapeEndColor);
251
252 string stack = get_bundle_string(results, &found, "stack", NULL);
253 if (found) {
254 printf("%s\n", stack.c_str());
255 }
256 }
257}
258
259void
260TestResults::OnSessionStatus(SessionStatus& /*status*/)
261{
262 //status.PrintDebugString();
263}
264
265void
266TestResults::SetCurrentAction(TestAction* action)
267{
268 m_currentAction = action;
269}
270
271/**
272 * Prints the usage statement / help text.
273 */
274static void
275print_usage(FILE* out) {
276 fprintf(out, "usage: bit OPTIONS PATTERN\n");
277 fprintf(out, "\n");
278 fprintf(out, " Build, sync and test android code.\n");
279 fprintf(out, "\n");
280 fprintf(out, " The -b -i and -t options allow you to specify which phases\n");
281 fprintf(out, " you want to run. If none of those options are given, then\n");
282 fprintf(out, " all phases are run. If any of these options are provided\n");
283 fprintf(out, " then only the listed phases are run.\n");
284 fprintf(out, "\n");
285 fprintf(out, " OPTIONS\n");
286 fprintf(out, " -b Run a build\n");
287 fprintf(out, " -i Install the targets\n");
288 fprintf(out, " -t Run the tests\n");
289 fprintf(out, "\n");
Joe Onorato6592c3c2016-11-12 16:34:25 -0800290 fprintf(out, " -n Don't reboot or restart\n");
Joe Onorato0578cbc2016-10-19 17:03:06 -0700291 fprintf(out, " -r If the runtime needs to be restarted, do a full reboot\n");
292 fprintf(out, " instead\n");
293 fprintf(out, "\n");
294 fprintf(out, " PATTERN\n");
295 fprintf(out, " One or more targets to build, install and test. The target\n");
296 fprintf(out, " names are the names that appear in the LOCAL_MODULE or\n");
297 fprintf(out, " LOCAL_PACKAGE_NAME variables in Android.mk or Android.bp files.\n");
298 fprintf(out, "\n");
299 fprintf(out, " Building and installing\n");
300 fprintf(out, " -----------------------\n");
301 fprintf(out, " The modules specified will be built and then installed. If the\n");
302 fprintf(out, " files are on the system partition, they will be synced and the\n");
303 fprintf(out, " attached device rebooted. If they are APKs that aren't on the\n");
304 fprintf(out, " system partition they are installed with adb install.\n");
305 fprintf(out, "\n");
306 fprintf(out, " For example:\n");
307 fprintf(out, " bit framework\n");
308 fprintf(out, " Builds framework.jar, syncs the system partition and reboots.\n");
309 fprintf(out, "\n");
310 fprintf(out, " bit SystemUI\n");
311 fprintf(out, " Builds SystemUI.apk, syncs the system partition and reboots.\n");
312 fprintf(out, "\n");
313 fprintf(out, " bit CtsProtoTestCases\n");
314 fprintf(out, " Builds this CTS apk, adb installs it, but does not run any\n");
315 fprintf(out, " tests.\n");
316 fprintf(out, "\n");
317 fprintf(out, " Running Unit Tests\n");
318 fprintf(out, " ------------------\n");
319 fprintf(out, " To run a unit test, list the test class names and optionally the\n");
320 fprintf(out, " test method after the module.\n");
321 fprintf(out, "\n");
322 fprintf(out, " For example:\n");
323 fprintf(out, " bit CtsProtoTestCases:*\n");
324 fprintf(out, " Builds this CTS apk, adb installs it, and runs all the tests\n");
325 fprintf(out, " contained in that apk.\n");
326 fprintf(out, "\n");
327 fprintf(out, " bit framework CtsProtoTestCases:*\n");
328 fprintf(out, " Builds the framework and the apk, syncs and reboots, then\n");
329 fprintf(out, " adb installs CtsProtoTestCases.apk, and runs all tests \n");
330 fprintf(out, " contained in that apk.\n");
331 fprintf(out, "\n");
332 fprintf(out, " bit CtsProtoTestCases:.ProtoOutputStreamBoolTest\n");
333 fprintf(out, " bit CtsProtoTestCases:android.util.proto.cts.ProtoOutputStreamBoolTest\n");
334 fprintf(out, " Builds and installs CtsProtoTestCases.apk, and runs all the\n");
335 fprintf(out, " tests in the ProtoOutputStreamBoolTest class.\n");
336 fprintf(out, "\n");
337 fprintf(out, " bit CtsProtoTestCases:.ProtoOutputStreamBoolTest\\#testWrite\n");
338 fprintf(out, " Builds and installs CtsProtoTestCases.apk, and runs the testWrite\n");
339 fprintf(out, " test method on that class.\n");
340 fprintf(out, "\n");
341 fprintf(out, " bit CtsProtoTestCases:.ProtoOutputStreamBoolTest\\#testWrite,.ProtoOutputStreamBoolTest\\#testRepeated\n");
342 fprintf(out, " Builds and installs CtsProtoTestCases.apk, and runs the testWrite\n");
343 fprintf(out, " and testRepeated test methods on that class.\n");
344 fprintf(out, "\n");
345 fprintf(out, " Launching an Activity\n");
346 fprintf(out, " ---------------------\n");
347 fprintf(out, " To launch an activity, specify the activity class name after\n");
348 fprintf(out, " the module name.\n");
349 fprintf(out, "\n");
350 fprintf(out, " For example:\n");
351 fprintf(out, " bit StatusBarTest:NotificationBuilderTest\n");
352 fprintf(out, " bit StatusBarTest:.NotificationBuilderTest\n");
353 fprintf(out, " bit StatusBarTest:com.android.statusbartest.NotificationBuilderTest\n");
354 fprintf(out, " Builds and installs StatusBarTest.apk, launches the\n");
355 fprintf(out, " com.android.statusbartest/.NotificationBuilderTest activity.\n");
356 fprintf(out, "\n");
357 fprintf(out, "\n");
358 fprintf(out, "usage: bit --tab ...\n");
359 fprintf(out, "\n");
360 fprintf(out, " Lists the targets in a format for tab completion. To get tab\n");
361 fprintf(out, " completion, add this to your bash environment:\n");
362 fprintf(out, "\n");
363 fprintf(out, " complete -C \"bit --tab\" bit\n");
364 fprintf(out, "\n");
365 fprintf(out, " Sourcing android's build/envsetup.sh will do this for you\n");
366 fprintf(out, " automatically.\n");
367 fprintf(out, "\n");
368 fprintf(out, "\n");
369 fprintf(out, "usage: bit --help\n");
370 fprintf(out, "usage: bit -h\n");
371 fprintf(out, "\n");
372 fprintf(out, " Print this help message\n");
373 fprintf(out, "\n");
374}
375
376
377/**
378 * Sets the appropriate flag* variables. If there is a problem with the
379 * commandline arguments, prints the help message and exits with an error.
380 */
381static void
382parse_args(Options* options, int argc, const char** argv)
383{
384 // Help
385 if (argc == 2 && (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0)) {
386 options->runHelp = true;
387 return;
388 }
389
390 // Tab
391 if (argc >= 4 && strcmp(argv[1], "--tab") == 0) {
392 options->runTab = true;
393 options->tabPattern = argv[3];
394 return;
395 }
396
397 // Normal usage
398 bool anyPhases = false;
399 bool gotPattern = false;
400 bool flagBuild = false;
401 bool flagInstall = false;
402 bool flagTest = false;
403 for (int i=1; i < argc; i++) {
404 string arg(argv[i]);
405 if (arg[0] == '-') {
406 for (size_t j=1; j<arg.size(); j++) {
407 switch (arg[j]) {
408 case '-':
409 break;
410 case 'b':
411 if (gotPattern) {
412 gotPattern = false;
413 flagInstall = false;
414 flagTest = false;
415 }
416 flagBuild = true;
417 anyPhases = true;
418 break;
419 case 'i':
420 if (gotPattern) {
421 gotPattern = false;
422 flagBuild = false;
423 flagTest = false;
424 }
425 flagInstall = true;
426 anyPhases = true;
427 break;
428 case 't':
429 if (gotPattern) {
430 gotPattern = false;
431 flagBuild = false;
432 flagInstall = false;
433 }
434 flagTest = true;
435 anyPhases = true;
436 break;
Joe Onorato6592c3c2016-11-12 16:34:25 -0800437 case 'n':
438 options->noRestart = true;
439 break;
Joe Onorato0578cbc2016-10-19 17:03:06 -0700440 case 'r':
441 options->reboot = true;
442 break;
443 default:
444 fprintf(stderr, "Unrecognized option '%c'\n", arg[j]);
445 print_usage(stderr);
446 exit(1);
447 break;
448 }
449 }
450 } else {
451 Target* target = new Target(flagBuild || !anyPhases, flagInstall || !anyPhases,
452 flagTest || !anyPhases, arg);
453 size_t colonPos = arg.find(':');
454 if (colonPos == 0) {
455 fprintf(stderr, "Test / activity supplied without a module to build: %s\n",
456 arg.c_str());
457 print_usage(stderr);
458 exit(1);
459 } else if (colonPos == string::npos) {
460 target->name = arg;
461 } else {
462 target->name.assign(arg, 0, colonPos);
463 size_t beginPos = colonPos+1;
464 size_t commaPos;
465 while (true) {
466 commaPos = arg.find(',', beginPos);
467 if (commaPos == string::npos) {
468 if (beginPos != arg.size()) {
469 target->actions.push_back(string(arg, beginPos, commaPos));
470 }
471 break;
472 } else {
473 if (commaPos != beginPos) {
474 target->actions.push_back(string(arg, beginPos, commaPos-beginPos));
475 }
476 beginPos = commaPos+1;
477 }
478 }
479 }
480 options->targets.push_back(target);
481 gotPattern = true;
482 }
483 }
484 // If no pattern was supplied, give an error
485 if (options->targets.size() == 0) {
486 fprintf(stderr, "No PATTERN supplied.\n\n");
487 print_usage(stderr);
488 exit(1);
489 }
490}
491
492/**
493 * Get an environment variable.
494 * Exits with an error if it is unset or the empty string.
495 */
496static string
497get_required_env(const char* name, bool quiet)
498{
499 const char* value = getenv(name);
500 if (value == NULL || value[0] == '\0') {
501 if (!quiet) {
502 fprintf(stderr, "%s not set. Did you source build/envsetup.sh,"
503 " run lunch and do a build?\n", name);
504 }
505 exit(1);
506 }
507 return string(value);
508}
509
510/**
511 * Get the out directory.
512 *
513 * This duplicates the logic in build/make/core/envsetup.mk (which hasn't changed since 2011)
514 * so that we don't have to wait for get_build_var make invocation.
515 */
516string
517get_out_dir()
518{
519 const char* out_dir = getenv("OUT_DIR");
520 if (out_dir == NULL || out_dir[0] == '\0') {
521 const char* common_base = getenv("OUT_DIR_COMMON_BASE");
522 if (common_base == NULL || common_base[0] == '\0') {
523 // We don't prefix with buildTop because we cd there and it
524 // makes all the filenames long when being pretty printed.
525 return "out";
526 } else {
Joe Onorato8a5bb632016-10-21 14:31:42 -0700527 char pwd[PATH_MAX];
528 if (getcwd(pwd, PATH_MAX) == NULL) {
529 fprintf(stderr, "Your pwd is too long.\n");
530 exit(1);
531 }
Joe Onorato0578cbc2016-10-19 17:03:06 -0700532 const char* slash = strrchr(pwd, '/');
533 if (slash == NULL) {
534 slash = "";
535 }
536 string result(common_base);
537 result += slash;
Joe Onorato0578cbc2016-10-19 17:03:06 -0700538 return result;
539 }
540 }
541 return string(out_dir);
542}
543
544/**
545 * Check that a system property on the device matches the expected value.
546 * Exits with an error if they don't.
547 */
548static void
549check_device_property(const string& property, const string& expected)
550{
551 int err;
552 string deviceValue = get_system_property(property, &err);
553 check_error(err);
554 if (deviceValue != expected) {
555 print_error("There is a mismatch between the build you just did and the device you");
556 print_error("are trying to sync it to in the %s system property", property.c_str());
557 print_error(" build: %s", expected.c_str());
558 print_error(" device: %s", deviceValue.c_str());
559 exit(1);
560 }
561}
562
563/**
564 * Run the build, install, and test actions.
565 */
566void
Joe Onorato6592c3c2016-11-12 16:34:25 -0800567run_phases(vector<Target*> targets, const Options& options)
Joe Onorato0578cbc2016-10-19 17:03:06 -0700568{
569 int err = 0;
570
571 //
572 // Initialization
573 //
574
575 print_status("Initializing");
576
577 const string buildTop = get_required_env("ANDROID_BUILD_TOP", false);
578 const string buildProduct = get_required_env("TARGET_PRODUCT", false);
579 const string buildVariant = get_required_env("TARGET_BUILD_VARIANT", false);
580 const string buildType = get_required_env("TARGET_BUILD_TYPE", false);
581 const string buildDevice = get_build_var(buildTop, "TARGET_DEVICE", false);
582 const string buildId = get_build_var(buildTop, "BUILD_ID", false);
583 const string buildOut = get_out_dir();
584
585 // TODO: print_command("cd", buildTop.c_str());
586 chdir(buildTop.c_str());
587
588 // Get the modules for the targets
589 map<string,Module> modules;
590 read_modules(buildOut, buildDevice, &modules, false);
591 for (size_t i=0; i<targets.size(); i++) {
592 Target* target = targets[i];
593 map<string,Module>::iterator mod = modules.find(target->name);
594 if (mod != modules.end()) {
595 target->module = mod->second;
596 } else {
597 print_error("Error: Could not find module: %s", target->name.c_str());
598 err = 1;
599 }
600 }
601 if (err != 0) {
602 exit(1);
603 }
604
605 // Choose the goals
606 vector<string> goals;
607 for (size_t i=0; i<targets.size(); i++) {
608 Target* target = targets[i];
609 if (target->build) {
610 goals.push_back(target->name);
611 }
612 }
613
614 // Figure out whether we need to sync the system and which apks to install
615 string systemPath = buildOut + "/target/product/" + buildDevice + "/system/";
616 string dataPath = buildOut + "/target/product/" + buildDevice + "/data/";
617 bool syncSystem = false;
618 bool alwaysSyncSystem = false;
619 vector<InstallApk> installApks;
620 for (size_t i=0; i<targets.size(); i++) {
621 Target* target = targets[i];
622 if (target->install) {
623 for (size_t j=0; j<target->module.installed.size(); j++) {
624 const string& file = target->module.installed[j];
625 // System partition
626 if (starts_with(file, systemPath)) {
627 syncSystem = true;
628 if (!target->build) {
629 // If a system partition target didn't get built then
630 // it won't change we will always need to do adb sync
631 alwaysSyncSystem = true;
632 }
633 continue;
634 }
635 // Apk in the data partition
636 if (starts_with(file, dataPath) && ends_with(file, ".apk")) {
637 // Always install it if we didn't build it because otherwise
638 // it will never have changed.
639 installApks.push_back(InstallApk(file, !target->build));
640 continue;
641 }
642 }
643 }
644 }
645 map<string,FileInfo> systemFilesBefore;
646 if (syncSystem && !alwaysSyncSystem) {
647 get_directory_contents(systemPath, &systemFilesBefore);
648 }
649
650 //
651 // Build
652 //
653
654 // Run the build
655 if (goals.size() > 0) {
656 print_status("Building");
657 err = build_goals(goals);
658 check_error(err);
659 }
660
661 //
662 // Install
663 //
664
665 // Sync the system partition and reboot
666 bool skipSync = false;
667 if (syncSystem) {
668 print_status("Syncing /system");
669
670 if (!alwaysSyncSystem) {
671 // If nothing changed and we weren't forced to sync, skip the reboot for speed.
672 map<string,FileInfo> systemFilesAfter;
673 get_directory_contents(systemPath, &systemFilesAfter);
674 skipSync = !directory_contents_differ(systemFilesBefore, systemFilesAfter);
675 }
676 if (skipSync) {
677 printf("Skipping sync because no files changed.\n");
678 } else {
679 // Do some sanity checks
680 check_device_property("ro.build.product", buildProduct);
681 check_device_property("ro.build.type", buildVariant);
682 check_device_property("ro.build.id", buildId);
683
684 // Stop & Sync
Joe Onorato6592c3c2016-11-12 16:34:25 -0800685 if (!options.noRestart) {
686 err = run_adb("shell", "stop", NULL);
687 check_error(err);
688 }
Joe Onorato0578cbc2016-10-19 17:03:06 -0700689 err = run_adb("remount", NULL);
690 check_error(err);
691 err = run_adb("sync", "system", NULL);
692 check_error(err);
693
Joe Onorato6592c3c2016-11-12 16:34:25 -0800694 if (!options.noRestart) {
695 if (options.reboot) {
696 print_status("Rebooting");
Joe Onorato0578cbc2016-10-19 17:03:06 -0700697
Joe Onorato6592c3c2016-11-12 16:34:25 -0800698 err = run_adb("reboot", NULL);
699 check_error(err);
700 err = run_adb("wait-for-device", NULL);
701 check_error(err);
702 } else {
703 print_status("Restarting the runtime");
Joe Onorato0578cbc2016-10-19 17:03:06 -0700704
Joe Onorato6592c3c2016-11-12 16:34:25 -0800705 err = run_adb("shell", "setprop", "sys.boot_completed", "0", NULL);
706 check_error(err);
707 err = run_adb("shell", "start", NULL);
708 check_error(err);
Joe Onorato0578cbc2016-10-19 17:03:06 -0700709 }
Joe Onorato6592c3c2016-11-12 16:34:25 -0800710
711 while (true) {
712 string completed = get_system_property("sys.boot_completed", &err);
713 check_error(err);
714 if (completed == "1") {
715 break;
716 }
717 sleep(2);
718 }
719 sleep(1);
720 err = run_adb("shell", "wm", "dismiss-keyguard", NULL);
721 check_error(err);
Joe Onorato0578cbc2016-10-19 17:03:06 -0700722 }
Joe Onorato0578cbc2016-10-19 17:03:06 -0700723 }
724 }
725
726 // Install APKs
727 if (installApks.size() > 0) {
728 print_status("Installing APKs");
729 for (size_t i=0; i<installApks.size(); i++) {
730 InstallApk& apk = installApks[i];
731 if (!apk.file.fileInfo.exists || apk.file.HasChanged()) {
732 // It didn't exist before or it changed, so int needs install
733 err = run_adb("install", "-r", apk.file.filename.c_str(), NULL);
734 check_error(err);
735 apk.installed = true;
736 } else {
737 printf("APK didn't change. Skipping install of %s\n", apk.file.filename.c_str());
738 }
739 }
740 }
741
742 //
743 // Actions
744 //
745
746 // Inspect the apks, and figure out what is an activity and what needs a test runner
747 bool printedInspecting = false;
748 vector<TestAction> testActions;
749 vector<ActivityAction> activityActions;
750 for (size_t i=0; i<targets.size(); i++) {
751 Target* target = targets[i];
752 if (target->test) {
753 for (size_t j=0; j<target->module.installed.size(); j++) {
754 string filename = target->module.installed[j];
755
756 if (!ends_with(filename, ".apk")) {
757 continue;
758 }
759
760 if (!printedInspecting) {
761 printedInspecting = true;
762 print_status("Inspecting APKs");
763 }
764
765 Apk apk;
766 err = inspect_apk(&apk, filename);
767 check_error(err);
768
769 for (size_t k=0; k<target->actions.size(); k++) {
770 string actionString = target->actions[k];
771 if (actionString == "*") {
772 if (apk.runner.length() == 0) {
773 print_error("Error: Test requested for apk that doesn't"
774 " have an <instrumentation> tag: %s\n",
775 target->module.name.c_str());
776 exit(1);
777 }
778 TestAction action;
779 action.packageName = apk.package;
780 action.runner = apk.runner;
781 action.target = target;
782 testActions.push_back(action);
783 target->testActionCount++;
784 } else if (apk.HasActivity(actionString)) {
785 ActivityAction action;
786 action.packageName = apk.package;
787 action.className = full_class_name(apk.package, actionString);
788 activityActions.push_back(action);
789 } else {
790 if (apk.runner.length() == 0) {
791 print_error("Error: Test requested for apk that doesn't"
792 " have an <instrumentation> tag: %s\n",
793 target->module.name.c_str());
794 exit(1);
795 }
796 TestAction action;
797 action.packageName = apk.package;
798 action.runner = apk.runner;
799 action.className = full_class_name(apk.package, actionString);
800 action.target = target;
801 testActions.push_back(action);
802 target->testActionCount++;
803 }
804 }
805 }
806 }
807 }
808
809 // Run the instrumentation tests
810 TestResults testResults;
811 if (testActions.size() > 0) {
812 print_status("Running tests");
813 for (size_t i=0; i<testActions.size(); i++) {
814 TestAction& action = testActions[i];
815 testResults.SetCurrentAction(&action);
816 err = run_instrumentation_test(action.packageName, action.runner, action.className,
817 &testResults);
818 check_error(err);
819 if (action.passCount == 0 && action.failCount == 0) {
820 action.target->actionsWithNoTests = true;
821 }
822 int total = action.passCount + action.failCount;
823 printf("%sRan %d test%s for %s. ", g_escapeClearLine,
824 total, total > 1 ? "s" : "", action.target->name.c_str());
825 if (action.passCount == 0 && action.failCount == 0) {
826 printf("%s%d passed, %d failed%s\n", g_escapeYellowBold, action.passCount,
827 action.failCount, g_escapeEndColor);
828 } else if (action.failCount > 0) {
829 printf("%d passed, %s%d failed%s\n", action.passCount, g_escapeRedBold,
830 action.failCount, g_escapeEndColor);
831 } else {
832 printf("%s%d passed%s, %d failed\n", g_escapeGreenBold, action.passCount,
833 g_escapeEndColor, action.failCount);
834 }
835 }
836 }
837
838 // Launch the activity
839 if (activityActions.size() > 0) {
840 print_status("Starting activity");
841
842 if (activityActions.size() > 1) {
843 print_warning("Multiple activities specified. Will only start the first one:");
844 for (size_t i=0; i<activityActions.size(); i++) {
845 ActivityAction& action = activityActions[i];
846 print_warning(" %s",
847 pretty_component_name(action.packageName, action.className).c_str());
848 }
849 }
850
851 const ActivityAction& action = activityActions[0];
852 string componentName = action.packageName + "/" + action.className;
853 err = run_adb("shell", "am", "start", componentName.c_str(), NULL);
854 check_error(err);
855 }
856
857 //
858 // Print summary
859 //
860
861 printf("\n%s--------------------------------------------%s\n", g_escapeBold, g_escapeEndColor);
862
863 // Build
864 if (goals.size() > 0) {
865 printf("%sBuilt:%s\n", g_escapeBold, g_escapeEndColor);
866 for (size_t i=0; i<goals.size(); i++) {
867 printf(" %s\n", goals[i].c_str());
868 }
869 }
870
871 // Install
872 if (syncSystem) {
873 if (skipSync) {
874 printf("%sSkipped syncing /system partition%s\n", g_escapeBold, g_escapeEndColor);
875 } else {
876 printf("%sSynced /system partition%s\n", g_escapeBold, g_escapeEndColor);
877 }
878 }
879 if (installApks.size() > 0) {
880 bool printedTitle = false;
881 for (size_t i=0; i<installApks.size(); i++) {
882 const InstallApk& apk = installApks[i];
883 if (apk.installed) {
884 if (!printedTitle) {
885 printf("%sInstalled:%s\n", g_escapeBold, g_escapeEndColor);
886 printedTitle = true;
887 }
888 printf(" %s\n", apk.file.filename.c_str());
889 }
890 }
891 printedTitle = false;
892 for (size_t i=0; i<installApks.size(); i++) {
893 const InstallApk& apk = installApks[i];
894 if (!apk.installed) {
895 if (!printedTitle) {
896 printf("%sSkipped install:%s\n", g_escapeBold, g_escapeEndColor);
897 printedTitle = true;
898 }
899 printf(" %s\n", apk.file.filename.c_str());
900 }
901 }
902 }
903
904 // Tests
905 if (testActions.size() > 0) {
906 printf("%sRan tests:%s\n", g_escapeBold, g_escapeEndColor);
907 size_t maxNameLength = 0;
908 for (size_t i=0; i<targets.size(); i++) {
909 Target* target = targets[i];
910 if (target->test) {
911 size_t len = target->name.length();
912 if (len > maxNameLength) {
913 maxNameLength = len;
914 }
915 }
916 }
917 string padding(maxNameLength, ' ');
918 for (size_t i=0; i<targets.size(); i++) {
919 Target* target = targets[i];
920 if (target->testActionCount > 0) {
921 printf(" %s%s", target->name.c_str(), padding.c_str() + target->name.length());
922 if (target->actionsWithNoTests) {
923 printf(" %s%d passed, %d failed%s\n", g_escapeYellowBold,
924 target->testPassCount, target->testFailCount, g_escapeEndColor);
925 } else if (target->testFailCount > 0) {
926 printf(" %d passed, %s%d failed%s\n", target->testPassCount,
927 g_escapeRedBold, target->testFailCount, g_escapeEndColor);
928 } else {
929 printf(" %s%d passed%s, %d failed\n", g_escapeGreenBold,
930 target->testPassCount, g_escapeEndColor, target->testFailCount);
931 }
932 }
933 }
934 }
935 if (activityActions.size() > 1) {
936 printf("%sStarted Activity:%s\n", g_escapeBold, g_escapeEndColor);
937 const ActivityAction& action = activityActions[0];
938 printf(" %s\n", pretty_component_name(action.packageName, action.className).c_str());
939 }
940
941 printf("%s--------------------------------------------%s\n", g_escapeBold, g_escapeEndColor);
942}
943
944/**
945 * Implement tab completion of the target names from the all modules file.
946 */
947void
948run_tab_completion(const string& word)
949{
950 const string buildTop = get_required_env("ANDROID_BUILD_TOP", true);
951 const string buildProduct = get_required_env("TARGET_PRODUCT", false);
952 const string buildOut = get_out_dir();
953
954 chdir(buildTop.c_str());
955
956 string buildDevice = sniff_device_name(buildOut, buildProduct);
957
958 map<string,Module> modules;
959 read_modules(buildOut, buildDevice, &modules, true);
960
961 for (map<string,Module>::const_iterator it = modules.begin(); it != modules.end(); it++) {
962 if (starts_with(it->first, word)) {
963 printf("%s\n", it->first.c_str());
964 }
965 }
966}
967
968/**
969 * Main entry point.
970 */
971int
972main(int argc, const char** argv)
973{
974 GOOGLE_PROTOBUF_VERIFY_VERSION;
975 init_print();
976
977 Options options;
978 parse_args(&options, argc, argv);
979
980 if (options.runHelp) {
981 // Help
982 print_usage(stdout);
983 exit(0);
984 } else if (options.runTab) {
985 run_tab_completion(options.tabPattern);
986 exit(0);
987 } else {
988 // Normal run
Joe Onorato6592c3c2016-11-12 16:34:25 -0800989 run_phases(options.targets, options);
Joe Onorato0578cbc2016-10-19 17:03:06 -0700990 }
991
992 return 0;
993}
994