1# Copyright 2011 Google Inc. All Rights Reserved. 2"""Module to get the settings from experiment file.""" 3 4from __future__ import print_function 5 6from cros_utils import logger 7from cros_utils import misc 8from download_images import ImageDownloader 9 10 11class Settings(object): 12 """Class representing settings (a set of fields) from an experiment file.""" 13 14 def __init__(self, name, settings_type): 15 self.name = name 16 self.settings_type = settings_type 17 self.fields = {} 18 self.parent = None 19 20 def SetParentSettings(self, settings): 21 """Set the parent settings which these settings can inherit from.""" 22 self.parent = settings 23 24 def AddField(self, field): 25 name = field.name 26 if name in self.fields: 27 raise SyntaxError('Field %s defined previously.' % name) 28 self.fields[name] = field 29 30 def SetField(self, name, value, append=False): 31 if name not in self.fields: 32 raise SyntaxError("'%s' is not a valid field in '%s' settings" % 33 (name, self.settings_type)) 34 if append: 35 self.fields[name].Append(value) 36 else: 37 self.fields[name].Set(value) 38 39 def GetField(self, name): 40 """Get the value of a field with a given name.""" 41 if name not in self.fields: 42 raise SyntaxError("Field '%s' not a valid field in '%s' settings." % 43 (name, self.name)) 44 field = self.fields[name] 45 if not field.assigned and field.required: 46 raise SyntaxError("Required field '%s' not defined in '%s' settings." % 47 (name, self.name)) 48 return self.fields[name].Get() 49 50 def Inherit(self): 51 """Inherit any unset values from the parent settings.""" 52 for name in self.fields: 53 if (not self.fields[name].assigned and self.parent and 54 name in self.parent.fields and self.parent.fields[name].assigned): 55 self.fields[name].Set(self.parent.GetField(name), parse=False) 56 57 def Override(self, settings): 58 """Override settings with settings from a different object.""" 59 for name in settings.fields: 60 if name in self.fields and settings.fields[name].assigned: 61 self.fields[name].Set(settings.GetField(name), parse=False) 62 63 def Validate(self): 64 """Check that all required fields have been set.""" 65 for name in self.fields: 66 if not self.fields[name].assigned and self.fields[name].required: 67 raise SyntaxError('Field %s is invalid.' % name) 68 69 def GetXbuddyPath(self, path_str, autotest_path, board, chromeos_root, 70 log_level): 71 prefix = 'remote' 72 l = logger.GetLogger() 73 if (path_str.find('trybot') < 0 and path_str.find('toolchain') < 0 and 74 path_str.find(board) < 0): 75 xbuddy_path = '%s/%s/%s' % (prefix, board, path_str) 76 else: 77 xbuddy_path = '%s/%s' % (prefix, path_str) 78 image_downloader = ImageDownloader(l, log_level) 79 image_and_autotest_path = image_downloader.Run( 80 misc.CanonicalizePath(chromeos_root), xbuddy_path, autotest_path) 81 return image_and_autotest_path 82