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