1#!/usr/bin/env python
2# Copyright 2015 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6import argparse
7import logging
8import os
9import sys
10
11if __name__ == '__main__':
12  sys.path.append(os.path.abspath(os.path.join(
13      os.path.dirname(__file__), '..', '..', '..')))
14from devil.android import device_blacklist
15from devil.android import device_utils
16from devil.android import fastboot_utils
17from devil.android.tools import script_common
18from devil.constants import exit_codes
19from devil.utils import run_tests_helper
20
21
22def main():
23  parser = argparse.ArgumentParser()
24  parser.add_argument('build_path', help='Path to android build.')
25  parser.add_argument('-d', '--device', dest='devices', action='append',
26                      help='Device(s) to flash.')
27  parser.add_argument('-v', '--verbose', default=0, action='count',
28                      help='Verbose level (multiple times for more)')
29  parser.add_argument('-w', '--wipe', action='store_true',
30                       help='If set, wipes user data')
31  parser.add_argument('--blacklist-file', help='Device blacklist file.')
32  args = parser.parse_args()
33  run_tests_helper.SetLogLevel(args.verbose)
34
35  if args.blacklist_file:
36    blacklist = device_blacklist.Blacklist(args.blacklist_file).Read()
37    if blacklist:
38      logging.critical('Device(s) in blacklist, not flashing devices:')
39      for key in blacklist:
40        logging.critical('  %s', key)
41      return exit_codes.INFRA
42
43  flashed_devices = []
44  failed_devices = []
45
46  def flash(device):
47    fastboot = fastboot_utils.FastbootUtils(device)
48    try:
49      fastboot.FlashDevice(args.build_path, wipe=args.wipe)
50      flashed_devices.append(device)
51    except Exception:  # pylint: disable=broad-except
52      logging.exception('Device %s failed to flash.', str(device))
53      failed_devices.append(device)
54
55  devices = script_common.GetDevices(args.devices, args.blacklist_file)
56  device_utils.DeviceUtils.parallel(devices).pMap(flash)
57
58  if flashed_devices:
59    logging.info('The following devices were flashed:')
60    logging.info('  %s', ' '.join(str(d) for d in flashed_devices))
61  if failed_devices:
62    logging.critical('The following devices failed to flash:')
63    logging.critical('  %s', ' '.join(str(d) for d in failed_devices))
64    return exit_codes.INFRA
65  return 0
66
67if __name__ == '__main__':
68  sys.exit(main())
69