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
5"""A module to keep track of devices across builds."""
6
7import json
8import logging
9import os
10
11logger = logging.getLogger(__name__)
12
13
14def GetPersistentDeviceList(file_name):
15  """Returns a list of devices.
16
17  Args:
18    file_name: the file name containing a list of devices.
19
20  Returns: List of device serial numbers that were on the bot.
21  """
22  if not os.path.isfile(file_name):
23    logger.warning("Device file %s doesn't exist.", file_name)
24    return []
25
26  try:
27    with open(file_name) as f:
28      devices = json.load(f)
29    if not isinstance(devices, list) or not all(isinstance(d, basestring)
30                                                for d in devices):
31      logger.warning('Unrecognized device file format: %s', devices)
32      return []
33    return [d for d in devices if d != '(error)']
34  except ValueError:
35    logger.exception(
36        'Error reading device file %s. Falling back to old format.', file_name)
37
38  # TODO(bpastene) Remove support for old unstructured file format.
39  with open(file_name) as f:
40    return [d for d in f.read().splitlines() if d != '(error)']
41
42
43def WritePersistentDeviceList(file_name, device_list):
44  path = os.path.dirname(file_name)
45  assert isinstance(device_list, list)
46  # If there is a problem with ADB "(error)" can be added to the device list.
47  # These should be removed before saving.
48  device_list = [d for d in device_list if d != '(error)']
49  if not os.path.exists(path):
50    os.makedirs(path)
51  with open(file_name, 'w') as f:
52    json.dump(device_list, f)
53