aboutsummaryrefslogtreecommitdiff
path: root/src/vogar/Vogar.java
blob: 7fba4aa32f66cce8f7d07e6bdab9ec9b2cf69ff9 (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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
/*
 * 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 vogar;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.LinkedHashSet;

import vogar.android.AdbChrootTarget;
import vogar.android.AdbTarget;
import vogar.android.AndroidSdk;
import vogar.android.DeviceFileCache;
import vogar.android.DeviceFilesystem;
import vogar.commands.Mkdir;
import vogar.commands.Rm;
import vogar.util.Strings;

/**
 * Command line interface for running benchmarks and tests on dalvik.
 */
public final class Vogar {
    static final int LARGE_TIMEOUT_MULTIPLIER = 20;
    public static final int NUM_PROCESSORS = Runtime.getRuntime().availableProcessors();

    private final List<File> actionFiles = new ArrayList<File>();
    private final List<String> actionClassesAndPackages = new ArrayList<String>();
    final List<String> targetArgs = new ArrayList<String>();
    private final OptionParser optionParser = new OptionParser(this);
    private File configFile = Vogar.dotFile(".vogarconfig");
    private String[] configArgs;
    public final static Console console = new Console.StreamingConsole();

    public static File dotFile (String name) {
        return new File(System.getProperty("user.home", "."), name);
    }

    private static boolean maybeAnsiTerminal() {
        if (System.console() == null) {
            return false;
        }
        String terminal = System.getenv("TERM");
        return terminal == null || !terminal.contains("dumb");
    }

    private static boolean maybeColorTerminal() {
        if (!maybeAnsiTerminal()) {
            return false;
        }
        String terminal = System.getenv("TERM");
        return terminal != null && terminal.contains("color");
    }

    @Option(names = { "--expectations" })
    Set<File> expectationFiles = new LinkedHashSet<File>();
    {
        expectationFiles.addAll(AndroidSdk.defaultExpectations());
    }

    @Option(names = { "--mode" })
    ModeId modeId = ModeId.DEVICE;

    @Option(names = { "--variant" })
    Variant variant = Variant.DEFAULT;

    @Option(names = { "--ssh" })
    private String sshHost;

    @Option(names = { "--chroot" })
    private String chrootDir;

    @Option(names = { "--timeout" })
    int timeoutSeconds = 60; // default is one minute;

    @Option(names = { "--first-monitor-port" })
    int firstMonitorPort = -1;

    @Option(names = { "--clean-before" })
    boolean cleanBefore = true;

    @Option(names = { "--clean-after" })
    boolean cleanAfter = true;

    @Option(names = { "--clean" })
    private boolean clean = true;

    @Option(names = { "--xml-reports-directory" })
    File xmlReportsDirectory;

    @Option(names = { "--indent" })
    private String indent = "  ";

    @Option(names = { "--verbose" })
    private boolean verbose;

    @Option(names = { "--stream" })
    boolean stream = true;

    @Option(names = { "--color" })
    private boolean color = maybeColorTerminal();

    @Option(names = { "--pass-color" })
    private int passColor = 32; // green

    @Option(names = { "--skip-color" })
    private int skipColor = 33; // yellow

    @Option(names = { "--fail-color" })
    private int failColor = 31; // red

    @Option(names = { "--warn-color" })
    private int warnColor = 35; // purple

    @Option(names = { "--ansi" })
    private boolean ansi = maybeAnsiTerminal();

    @Option(names = { "--debug" })
    Integer debugPort;

    @Option(names = { "--debug-app" })
    boolean debugApp;

    @Option(names = { "--device-dir" })
    private File deviceDir;

    @Option(names = { "--vm-arg" })
    List<String> vmArgs = new ArrayList<String>();

    @Option(names = { "--vm-command" })
    String vmCommand;

    @Option(names = { "--dalvik-cache" })
    String dalvikCache = "dalvik-cache";

    @Option(names = { "--java-home" })
    File javaHome;

    @Option(names = { "--javac-arg" })
    List<String> javacArgs = new ArrayList<String>();

    @Option(names = { "--multidex" })
    boolean multidex = true;

    @Option(names = { "--use-bootclasspath" })
    boolean useBootClasspath = false;

    @Option(names = { "--build-classpath" })
    List<File> buildClasspath = new ArrayList<File>();

    @Option(names = { "--classpath", "-cp" })
    List<File> classpath = new ArrayList<File>();

    @Option(names = { "--resource-classpath" })
    List<File> resourceClasspath = new ArrayList<File>();

    @Option(names = { "--sourcepath" })
    List<File> sourcepath = new ArrayList<File>();
    {
        sourcepath.addAll(AndroidSdk.defaultSourcePath());
    }

    @Option(names = { "--jar-search-dir" })
    List<File> jarSearchDirs = Lists.newArrayList();

    @Option(names = { "--vogar-dir" })
    File vogarDir = Vogar.dotFile(".vogar");

    @Option(names = { "--record-results" })
    boolean recordResults = false;

    @Option(names = { "--results-dir" })
    File resultsDir = null;

    @Option(names = { "--suggest-classpaths" })
    boolean suggestClasspaths = false;

    @Option(names = { "--invoke-with" })
    String invokeWith = null;

    @Option(names = { "--benchmark" })
    boolean benchmark = false;

    @Option(names = { "--open-bugs-command" })
    String openBugsCommand;

    @Option(names = { "--test-only" })
    boolean testOnly = false;

    @Option(names = { "--toolchain" })
    Toolchain toolchain = null;

    @Option(names = { "--language" })
    Language language = Language.CUR;

    @Option(names = { "--check-jni" })
    boolean checkJni = true;

    @Option(names = {"--runner-type"})
    RunnerType runnerType;

    @Option(names = {"--sdk-version"})
    Integer sdkVersion = 28;

    @Option(names = {"--serial-dexing"})
    boolean serialDexing = false;

    @Option(names = {"--verbose-dex-stats"})
    boolean verboseDexStats = false;

    @VisibleForTesting public Vogar() {}

    private void printUsage() {
        // have to reset fields so that "Default is: FOO" lines are accurate
        optionParser.reset();

        System.out.println("Usage: Vogar [options]... <actions>... [-- target args]...");
        System.out.println();
        System.out.println("  <actions>: .java files, directories, or class names.");
        System.out.println("      These should be JUnit tests, TestNG tests, jtreg tests, Caliper benchmarks");
        System.out.println("      or executable Java classes.");
        System.out.println();
        System.out.println("      When passing in a JUnit or TestNG test class, it may have \"#method_name\"");
        System.out.println("      appended to it, to specify a single test method.");
        System.out.println();
        System.out.println("  [target args]: arguments passed to the target process. This is only useful when");
        System.out.println("      the target process is a Caliper benchmark or main method.");
        System.out.println();
        System.out.println("GENERAL OPTIONS");
        System.out.println();
        System.out.println("  --mode <ACTIVITY|APP_PROCESS|DEVICE|HOST|JVM>: specify which environment to run in.");
        System.out.println("      ACTIVITY: runs in an Android application on a device or emulator");
        System.out.println("      APP_PROCESS: runs in an app_process runtime on a device or emulator");
        System.out.println("      DEVICE: runs in an ART runtime on a device or emulator");
        System.out.println("      HOST: runs in an ART runtime on the local desktop built with any lunch combo.");
        System.out.println("      JVM: runs in a Java VM on the local desktop");
        System.out.println("      Default is: " + modeId);
        System.out.println();
        System.out.println("  --variant <DEFAULT|X32|X64>: specify which dalvikvm (or other) variant to execute with");
        System.out.println("      Used with --mode <HOST|DEVICE> only, not applicable for all devices.");
        System.out.println("      DEFAULT: default (or N/A), X32: 32-bit, X64: 64-bit");
        System.out.println("      Default is: " + variant);
        System.out.println();
        System.out.println("  --toolchain <D8|JAVAC>: Which toolchain to use.");
        System.out.println("      Default depends on --mode value (currently "
                + modeId.defaultToolchain() + " for --mode=" + modeId + ")");
        System.out.println();
        System.out.println("  --language <J17|JN|JO|CUR>: Which language level to use.");
        System.out.println("      Default is: " + language);
        System.out.println();
        System.out.println("  --ssh <host:port>: target a remote machine via SSH.");
        System.out.println();
        System.out.println("  --chroot <dir>: target a chroot dir on device");
        System.out.println("      Only works with --mode device.");
        System.out.println();
        System.out.println("  --clean: synonym for --clean-before and --clean-after (default).");
        System.out.println("      Disable with --no-clean if you want no files removed.");
        System.out.println();
        System.out.println("  --stream: stream output as it is emitted.");
        System.out.println();
        System.out.println("  --benchmark: for use with dalvikvm, this dexes all files together,");
        System.out.println("      and is mandatory for running Caliper benchmarks, and a good idea");
        System.out.println("      for other performance sensitive code.");
        System.out.println("      If you specify this without specifying --runner-type then it");
        System.out.println("      assumes --runner-type="
                + RunnerType.CALIPER.name().toLowerCase());
        System.out.println();
        System.out.println("  --invoke-with: provide a command to invoke the VM with. Examples:");
        System.out.println("      --mode host --invoke-with \"valgrind --leak-check=full\"");
        System.out.println("      --mode device --invoke-with \"strace -f -o/sdcard/strace.txt\"");
        System.out.println();
        System.out.println("  --timeout <seconds>: maximum execution time of each action before the");
        System.out.println("      runner aborts it. Specifying zero seconds or using --debug will");
        System.out.println("      disable the execution timeout. Tests tagged with 'large' will time");
        System.out.println("      out in " + LARGE_TIMEOUT_MULTIPLIER + "x this timeout.");
        System.out.println("      Default is: " + timeoutSeconds);
        System.out.println();
        System.out.println("  --xml-reports-directory <path>: directory to emit JUnit-style");
        System.out.println("      XML test results.");
        System.out.println();
        System.out.println("  --classpath <jar file>: add the .jar to both build and execute classpaths.");
        System.out.println();
        System.out.println("  --use-bootclasspath: use the classpath as search path for bootstrap classes.");
        System.out.println();
        System.out.println("  --build-classpath <element>: add the directory or .jar to the build");
        System.out.println("      classpath. Such classes are available as build dependencies, but");
        System.out.println("      not at runtime.");
        System.out.println();
        System.out.println("  --sourcepath <directory>: add the directory to the build sourcepath.");
        System.out.println();
        System.out.println("  --vogar-dir <directory>: directory in which to find Vogar");
        System.out.println("      configuration information, caches, saved and results");
        System.out.println("      unless they've been put explicitly elsewhere.");
        System.out.println("      Default is: " + vogarDir);
        System.out.println();
        System.out.println("  --record-results: record test results for future comparison.");
        System.out.println();
        System.out.println("  --results-dir <directory>: read and write (if --record-results used)");
        System.out.println("      results from and to this directory.");
        System.out.println();
        System.out.println("  --runner-type <default|caliper|main|junit|testng>: specify which runner to use.");
        System.out.println("      default: runs JUnit tests, TestNG tests and main() classes");
        System.out.println("      caliper: runs Caliper benchmarks only");
        System.out.println("      main: runs main() classes only");
        System.out.println("      junit: runs JUnit tests only");
        System.out.println("      testng: runs TestNG tests only");
        System.out.println("      Default is determined by --benchmark and --testonly, if they are");
        System.out.println("      not specified then defaults to: default");
        System.out.println();
        System.out.println("  --test-only: only run JUnit tests.");
        System.out.println("      Default is: " + testOnly);
        System.out.println("      DEPRECATED: Use --runner-type="
                + RunnerType.JUNIT.name().toLowerCase());
        System.out.println();
        System.out.println("  --verbose: turn on persistent verbose output.");
        System.out.println();
        System.out.println("  --serial-dexing: disallow Vogar spawn multiple simultaneous dex tasks");
        System.out.println("      Enabling this is useful when there is a memory constraint;");
        System.out.println("      and each dex task could easily consume around 1.5G of memory.");
        System.out.println("      Default is: " + serialDexing);
        System.out.println();
        System.out.println("  --verbose-dex-stats: print verbose stats of used resources by dex tasks");
        System.out.println("      Enabling this wraps each dex task in '/usr/bin/time -v' call");
        System.out.println("      and adds its output to the stdout log. Useful to get a sense of");
        System.out.println("      resource usage such as RSS memory, CPU usage and wall-clock time.");
        System.out.println("      Default is: " + verboseDexStats);
        System.out.println();
        System.out.println("  --check-jni: enable CheckJNI mode.");
        System.out.println("      See http://developer.android.com/training/articles/perf-jni.html.");
        System.out.println("      Default is: " + checkJni + ", but disabled for --benchmark.");
        System.out.println("");
        System.out.println("TARGET OPTIONS");
        System.out.println();
        System.out.println("  --debug <port>: enable Java debugging on the specified port.");
        System.out.println("      This port must be free both on the device and on the local");
        System.out.println("      system. Disables the timeout specified by --timeout-seconds.");
        System.out.println();
        System.out.println("  --debug-app: enable debugging while running in an activity.");
        System.out.println("      This will require the use of DDMS to connect to the activity");
        System.out.println("      on the device, and expose the debugger on an appropriate port.");
        System.out.println();
        System.out.println("  --device-dir <directory>: use the specified directory for");
        System.out.println("      on-device temporary files and code.");
        System.out.println();
        System.out.println("  --vm-arg <argument>: include the specified argument when spawning a");
        System.out.println("      virtual machine. Examples: -Xint:fast, -ea, -Xmx16M");
        System.out.println();
        System.out.println("  --vm-command <argument>: override default vm executable name.");
        System.out.println("      Default is 'java' for the JVM and a version of dalvikvm for the host and target.");
        System.out.println();
        System.out.println("  --java-home <java_home>: execute the actions on the local workstation");
        System.out.println("      using the specified java home directory. This does not impact");
        System.out.println("      which javac gets used. When unset, java is used from the PATH.");
        System.out.println();
        System.out.println("EXOTIC OPTIONS");
        System.out.println();
        System.out.println("  --suggest-classpaths: build an index of jar files under the");
        System.out.println("      directories given by --jar-search-dir arguments. If Vogar then ");
        System.out.println("      fails due to missing classes or packages, it will use the index to");
        System.out.println("      diagnose the problem and suggest a fix.");
        System.out.println();
        System.out.println("      Currently only looks for jars called exactly \"classes.jar\".");
        System.out.println();
        System.out.println("  --jar-search-dir <directory>: a directory that should be searched for");
        System.out.println("      jar files to add to the class file index for use with");
        System.out.println("      --suggest-classpaths.");
        System.out.println();
        System.out.println("  --clean-before: remove working directories before building and");
        System.out.println("      running (default). Disable with --no-clean-before if you are");
        System.out.println("      using interactively with your own temporary input files.");
        System.out.println();
        System.out.println("  --clean-after: remove temporary files after running (default).");
        System.out.println("      Disable with --no-clean-after and use with --verbose if");
        System.out.println("      you'd like to manually re-run commands afterwards.");
        System.out.println();
        System.out.println("  --color: format output in technicolor.");
        System.out.println();
        System.out.println("  --pass-color: ANSI color code to use for passes.");
        System.out.println("      Default: 32 (green)");
        System.out.println();
        System.out.println("  --skip-color: ANSI color code to use for skips.");
        System.out.println("      Default: 33 (yellow)");
        System.out.println();
        System.out.println("  --warn-color: ANSI color code to use for warnings.");
        System.out.println("      Default: 35 (purple)");
        System.out.println();
        System.out.println("  --fail-color: ANSI color code to use for failures.");
        System.out.println("      Default: 31 (red)");
        System.out.println();
        System.out.println("  --ansi: use ANSI escape sequences to remove intermediate output.");
        System.out.println();
        System.out.println("  --expectations <file>: include the specified file when looking for");
        System.out.println("      action expectations. The file should include qualified action names");
        System.out.println("      and the corresponding expected output.");
        System.out.println("      Default is: " + expectationFiles);
        System.out.println();
        System.out.println("  --indent: amount to indent action result output. Can be set to ''");
        System.out.println("      (aka empty string) to simplify output parsing.");
        System.out.println("      Default is: '" + indent + "'");
        System.out.println();
        System.out.println("  --javac-arg <argument>: include the specified argument when invoking");
        System.out.println("      javac. Examples: --javac-arg -Xmaxerrs --javac-arg 1");
        System.out.println();
        System.out.println("  --multidex: whether to use native multidex support");
        System.out.println("      Disable with --no-multidex.");
        System.out.println("      Default is: " + multidex);
        System.out.println();
        System.out.println("  --sdk-version <argument>: min and target sdk version.");
        System.out.println("      Used in the app manifest for ACTIVITY mode");
        System.out.println("      to prevent warning popups about old applications");
        System.out.println("      Default is: " + sdkVersion);
        System.out.println();
        System.out.println("  --dalvik-cache <argument>: override default dalvik-cache location.");
        System.out.println("      Default is: " + dalvikCache);
        System.out.println();
        System.out.println("  --first-monitor-port <port>: the port on the host (and possibly target)");
        System.out.println("      used to traffic control messages between vogar and forked processes.");
        System.out.println("      Use this to avoid port conflicts when running multiple vogar instances");
        System.out.println("      concurrently. Vogar will use up to N ports starting with this one,");
        System.out.println("      where N is the number of processors on the host (" + NUM_PROCESSORS + "). ");
        System.out.println();
        System.out.println("  --open-bugs-command <command>: a command that will take bug IDs as parameters");
        System.out.println("      and return those bugs that are still open. For example, if bugs 123 and");
        System.out.println("      789 are both open, the command should echo those values:");
        System.out.println("         $ ~/bin/bug-command 123 456 789");
        System.out.println("         123");
        System.out.println("         789");
        System.out.println();
        System.out.println("CONFIG FILE");
        System.out.println();
        System.out.println("  User-defined default arguments can be specified in ~/.vogarconfig. See");
        System.out.println("  .vogarconfig.example for an example.");
        System.out.println();
    }

    @VisibleForTesting
    public boolean parseArgs(String[] args) {
        // extract arguments from config file
        configArgs = OptionParser.readFile(configFile);

        // config file args are added first so that in a conflict, the currently supplied
        // arguments win.
        List<String> actionsAndTargetArgs = optionParser.parse(configArgs);
        if (!actionsAndTargetArgs.isEmpty()) {
            throw new RuntimeException(
                    "actions or targets given in .vogarconfig: " + actionsAndTargetArgs);
        }

        try {
            actionsAndTargetArgs.addAll(optionParser.parse(args));
        } catch (RuntimeException e) {
            System.out.println(e.getMessage());
            return false;
        }

        //
        // Semantic error validation
        //

        if (javaHome != null && !new File(javaHome, "/bin/java").exists()) {
            System.out.println("Invalid java home: " + javaHome);
            return false;
        }

        // check vm option consistency
        if (!modeId.acceptsVmArgs() && !vmArgs.isEmpty()) {
            System.out.println("VM args " + vmArgs + " should not be specified for mode " + modeId);
            return false;
        }

        // Check variant / mode compatibility.
        if (!modeId.supportsVariant(variant)) {
            System.out.println("Variant " + variant + " not supported for mode " + modeId);
            return false;
        }

        if (toolchain == null) {
            toolchain = modeId.defaultToolchain();
            System.out.println("Defaulting --toolchain to " + toolchain);
        } else if (!modeId.supportsToolchain(toolchain)) {
            System.out.println("Toolchain " + toolchain + " not supported for mode " + modeId);
            return false;
        }

        if (chrootDir != null && !modeId.supportsChroot()) {
            System.out.println("Chroot-based execution not supported for mode " + modeId);
            return false;
        }

        if (xmlReportsDirectory != null && !xmlReportsDirectory.isDirectory()) {
            System.out.println("Invalid XML reports directory: " + xmlReportsDirectory);
            return false;
        }

        if (!clean) {
            cleanBefore = false;
            cleanAfter = false;
        }

        //
        // Post-processing arguments
        //

        if (vmCommand == null) {
            vmCommand = modeId.defaultVmCommand(variant);
        }

        // disable timeout when benchmarking or debugging
        if (benchmark || debugPort != null) {
            timeoutSeconds = 0;
        }

        if (firstMonitorPort == -1) {
            firstMonitorPort = modeId.isLocal() ? 8788 : 8787;
        }

        // separate the actions and the target args
        int index = 0;
        for (; index < actionsAndTargetArgs.size(); index++) {
            String arg = actionsAndTargetArgs.get(index);
            if (arg.equals("--")) {
                index++;
                break;
            }

            File file = new File(arg);
            if (file.exists()) {
                if (arg.endsWith(".java") || file.isDirectory()) {
                    actionFiles.add(file.getAbsoluteFile());
                } else {
                    System.out.println("Expected a .jar file, .java file, directory, "
                            + "package name or classname, but was: " + arg);
                    return false;
                }
            } else {
                actionClassesAndPackages.add(arg);
            }
        }

        targetArgs.addAll(actionsAndTargetArgs.subList(index, actionsAndTargetArgs.size()));

        if (actionFiles.isEmpty() && actionClassesAndPackages.isEmpty()) {
            System.out.println("No actions provided.");
            return false;
        }

        if (!modeId.acceptsVmArgs() && !targetArgs.isEmpty()) {
            System.out.println("Target args " + targetArgs + " should not be specified for mode " + modeId);
            return false;
        }

        if (modeId == ModeId.ACTIVITY && debugPort != null) {
            System.out.println("Activity debugging requires the use of --debug-app and DDMS.");
            return false;
        }

        if (debugApp && modeId != ModeId.ACTIVITY) {
            System.out.println("--debug-app can only be used in combination with --mode activity.");
            return false;
        }

        // When using --benchmark,
        // caliper will spawn each benchmark as a new process (default dalvikvm).
        //
        // When using also --mode app_process, we want that new process to be app_process.
        //
        // Pass --vm app_process to it so that it knows not to use dalvikvm.
        if ("app_process".equals(vmCommand) && benchmark) {
          targetArgs.add("--vm");
          targetArgs.add("app_process");
        }

        return true;
    }

    /**
     * The type of the target.
     */
    private enum TargetType {
        ADB(AdbTarget.defaultDeviceDir()),
        ADB_CHROOT(AdbChrootTarget.defaultDeviceDir()),
        LOCAL(LocalTarget.defaultDeviceDir()),
        SSH(SshTarget.defaultDeviceDir());

        /**
         * The default device dir.
         */
        private final File defaultDeviceDir;

        TargetType(File defaultDeviceDir) {
            this.defaultDeviceDir = defaultDeviceDir;
        }

        public File defaultDeviceDir() {
            return defaultDeviceDir;
        }
    }

    private boolean run() throws IOException {
        // Create a new Console for use by Run.
        Console console = this.stream
                ? new Console.StreamingConsole()
                : new Console.MultiplexingConsole();
        console.setUseColor(color, passColor, skipColor, failColor, warnColor);
        console.setAnsi(ansi);
        console.setIndent(indent);
        console.setVerbose(verbose);

        Mkdir mkdir = new Mkdir(console);
        Rm rm = new Rm(console);

        // Select the target type, this is needed in order to calculate the runnerDir, which is in
        // turn needed for creating the AdbTarget below.
        TargetType targetType;
        if (sshHost != null) {
            targetType = TargetType.SSH;
        } else if (modeId.isLocal()) {
            targetType = TargetType.LOCAL;
        } else if (chrootDir != null) {
            targetType = TargetType.ADB_CHROOT;
        } else {
            targetType = TargetType.ADB;
        }

        File runnerDir = deviceDir != null
                ? new File(deviceDir, "run")
                : new File(targetType.defaultDeviceDir(), "run");

        // Create the target.
        Target target;
        switch (targetType) {
            case ADB: {
                    ImmutableList<String> targetProcessPrefix = ImmutableList.of("adb", "shell");
                    DeviceFilesystem deviceFilesystem =
                            new DeviceFilesystem(console, targetProcessPrefix);
                    DeviceFileCache deviceFileCache =
                            new DeviceFileCache(console, runnerDir, deviceFilesystem);
                    target = new AdbTarget(console, deviceFilesystem, deviceFileCache);
                }
                break;
            case ADB_CHROOT: {
                    ImmutableList<String> targetProcessPrefix = ImmutableList.of("adb", "shell");
                    DeviceFilesystem deviceFilesystem =
                            new DeviceFilesystem(console, targetProcessPrefix);
                    // Directory `runnerDir` is relative to the chroot; `runnerDirInRoot` is its
                    // counterpart relative to the device's filesystem "absolute" root.
                    File runnerDirInRoot = new File(chrootDir + "/" + runnerDir.getPath());
                    DeviceFileCache deviceFileCache =
                            new DeviceFileCache(console, runnerDirInRoot, deviceFilesystem);
                    target =
                        new AdbChrootTarget(console, deviceFilesystem, deviceFileCache, chrootDir);
                }
                break;
            case SSH:
                target = new SshTarget(console, sshHost);
                break;
            case LOCAL:
                target = new LocalTarget(console, mkdir, rm);
                break;
            default:
                throw new IllegalStateException("Unknown target type: " + targetType);
        }

        AndroidSdk androidSdk = null;
        if (modeId.requiresAndroidSdk()) {
            androidSdk = AndroidSdk.createAndroidSdk(console, mkdir, modeId, language,
                    !actionFiles.isEmpty(), serialDexing, verboseDexStats);
        }

        if (runnerType == null) {
            if (benchmark) {
                if (testOnly) {
                    throw new IllegalStateException(
                            "--benchmark and --testOnly are mutually exclusive and deprecated,"
                                    + " use --runner-type");
                }
                if (modeId == ModeId.ACTIVITY) {
                    throw new IllegalStateException(
                            "--benchmark and --mode activity are mutually exclusive");
                }
                runnerType = RunnerType.CALIPER;
            } else if (testOnly) {
                runnerType = RunnerType.JUNIT;
            } else {
                runnerType = RunnerType.DEFAULT;
            }
        } else {
            if (testOnly) {
                throw new IllegalStateException(
                        "--runnerType and --testOnly are mutually exclusive");
            }

            if (runnerType.supportsCaliper()) {
                if (modeId == ModeId.ACTIVITY) {
                    throw new IllegalStateException(
                            "--runnerType caliper and --mode activity are mutually exclusive");
                }

                // Assume --benchmark
                benchmark = true;
            }
        }

        Run run = new Run(this, toolchain, console, mkdir, androidSdk, rm,
                target, runnerDir);
        if (configArgs.length > 0) {
            run.console.verbose("loaded arguments from .vogarconfig: " +
                                Strings.join(" ", (Object)configArgs));
        }
        return run.driver.buildAndRun(actionFiles, actionClassesAndPackages);
    }

    public static void main(String[] args) throws IOException {
        Vogar vogar = new Vogar();
        if (!vogar.parseArgs(args)) {
            vogar.printUsage();
            System.exit(1);
        }
        boolean allSuccess = vogar.run();
        System.exit(allSuccess ? 0 : 1);
    }
}