xref: /aosp_15_r20/external/chromium-trace/catapult/devil/devil/android/device_list.py (revision 1fa4b3da657c0e9ad43c0220bacf9731820715a5)
1# Copyright 2014 The Chromium Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4"""A module to keep track of devices across builds."""
5
6import json
7import logging
8import os
9
10import six
11
12logger = logging.getLogger(__name__)
13
14
15def GetPersistentDeviceList(file_name):
16  """Returns a list of devices.
17
18  Args:
19    file_name: the file name containing a list of devices.
20
21  Returns: List of device serial numbers that were on the bot.
22  """
23  if not os.path.isfile(file_name):
24    logger.warning("Device file %s doesn't exist.", file_name)
25    return []
26
27  try:
28    with open(file_name) as f:
29      devices = json.load(f)
30    if not isinstance(devices, list) or not all(
31        isinstance(d, six.string_types) for d in devices):
32      logger.warning('Unrecognized device file format: %s', devices)
33      return []
34    return [d for d in devices if d != '(error)']
35  except ValueError:
36    logger.exception(
37        'Error reading device file %s. Falling back to old format.', file_name)
38
39  # TODO(bpastene) Remove support for old unstructured file format.
40  with open(file_name) as f:
41    return [d for d in f.read().splitlines() if d != '(error)']
42
43
44def WritePersistentDeviceList(file_name, device_list):
45  path = os.path.dirname(file_name)
46  assert isinstance(device_list, list)
47  # If there is a problem with ADB "(error)" can be added to the device list.
48  # These should be removed before saving.
49  device_list = [d for d in device_list if d != '(error)']
50  if not os.path.exists(path):
51    os.makedirs(path)
52  with open(file_name, 'w') as f:
53    json.dump(device_list, f)
54