types.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. import errno
  2. import re
  3. import os
  4. class OEList(list):
  5. """OpenEmbedded 'list' type
  6. Acts as an ordinary list, but is constructed from a string value and a
  7. separator (optional), and re-joins itself when converted to a string with
  8. str(). Set the variable type flag to 'list' to use this type, and the
  9. 'separator' flag may be specified (defaulting to whitespace)."""
  10. name = "list"
  11. def __init__(self, value, separator = None):
  12. if value is not None:
  13. list.__init__(self, value.split(separator))
  14. else:
  15. list.__init__(self)
  16. if separator is None:
  17. self.separator = " "
  18. else:
  19. self.separator = separator
  20. def __str__(self):
  21. return self.separator.join(self)
  22. def choice(value, choices):
  23. """OpenEmbedded 'choice' type
  24. Acts as a multiple choice for the user. To use this, set the variable
  25. type flag to 'choice', and set the 'choices' flag to a space separated
  26. list of valid values."""
  27. if not isinstance(value, str):
  28. raise TypeError("choice accepts a string, not '%s'" % type(value))
  29. value = value.lower()
  30. choices = choices.lower()
  31. if value not in choices.split():
  32. raise ValueError("Invalid choice '%s'. Valid choices: %s" %
  33. (value, choices))
  34. return value
  35. class NoMatch(object):
  36. """Stub python regex pattern object which never matches anything"""
  37. def findall(self, string, flags=0):
  38. return None
  39. def finditer(self, string, flags=0):
  40. return None
  41. def match(self, flags=0):
  42. return None
  43. def search(self, string, flags=0):
  44. return None
  45. def split(self, string, maxsplit=0):
  46. return None
  47. def sub(pattern, repl, string, count=0):
  48. return None
  49. def subn(pattern, repl, string, count=0):
  50. return None
  51. NoMatch = NoMatch()
  52. def regex(value, regexflags=None):
  53. """OpenEmbedded 'regex' type
  54. Acts as a regular expression, returning the pre-compiled regular
  55. expression pattern object. To use this type, set the variable type flag
  56. to 'regex', and optionally, set the 'regexflags' type to a space separated
  57. list of the flags to control the regular expression matching (e.g.
  58. FOO[regexflags] += 'ignorecase'). See the python documentation on the
  59. 're' module for a list of valid flags."""
  60. flagval = 0
  61. if regexflags:
  62. for flag in regexflags.split():
  63. flag = flag.upper()
  64. try:
  65. flagval |= getattr(re, flag)
  66. except AttributeError:
  67. raise ValueError("Invalid regex flag '%s'" % flag)
  68. if not value:
  69. # Let's ensure that the default behavior for an undefined or empty
  70. # variable is to match nothing. If the user explicitly wants to match
  71. # anything, they can match '.*' instead.
  72. return NoMatch
  73. try:
  74. return re.compile(value, flagval)
  75. except re.error as exc:
  76. raise ValueError("Invalid regex value '%s': %s" %
  77. (value, exc.args[0]))
  78. def boolean(value):
  79. """OpenEmbedded 'boolean' type
  80. Valid values for true: 'yes', 'y', 'true', 't', '1'
  81. Valid values for false: 'no', 'n', 'false', 'f', '0', None
  82. """
  83. if value is None:
  84. return False
  85. if isinstance(value, bool):
  86. return value
  87. if not isinstance(value, str):
  88. raise TypeError("boolean accepts a string, not '%s'" % type(value))
  89. value = value.lower()
  90. if value in ('yes', 'y', 'true', 't', '1'):
  91. return True
  92. elif value in ('no', 'n', 'false', 'f', '0'):
  93. return False
  94. raise ValueError("Invalid boolean value '%s'" % value)
  95. def integer(value, numberbase=10):
  96. """OpenEmbedded 'integer' type
  97. Defaults to base 10, but this can be specified using the optional
  98. 'numberbase' flag."""
  99. return int(value, int(numberbase))
  100. _float = float
  101. def float(value, fromhex='false'):
  102. """OpenEmbedded floating point type
  103. To use this type, set the type flag to 'float', and optionally set the
  104. 'fromhex' flag to a true value (obeying the same rules as for the
  105. 'boolean' type) if the value is in base 16 rather than base 10."""
  106. if boolean(fromhex):
  107. return _float.fromhex(value)
  108. else:
  109. return _float(value)
  110. def path(value, relativeto='', normalize='true', mustexist='false'):
  111. value = os.path.join(relativeto, value)
  112. if boolean(normalize):
  113. value = os.path.normpath(value)
  114. if boolean(mustexist):
  115. try:
  116. open(value, 'r')
  117. except IOError as exc:
  118. if exc.errno == errno.ENOENT:
  119. raise ValueError("{0}: {1}".format(value, os.strerror(errno.ENOENT)))
  120. return value
  121. def is_x86(arch):
  122. """
  123. Check whether arch is x86 or x86_64
  124. """
  125. if arch.startswith('x86_') or re.match('i.*86', arch):
  126. return True
  127. else:
  128. return False
  129. def qemu_use_kvm(kvm, target_arch):
  130. """
  131. Enable kvm if target_arch == build_arch or both of them are x86 archs.
  132. """
  133. use_kvm = False
  134. if kvm and boolean(kvm):
  135. build_arch = os.uname()[4]
  136. if is_x86(build_arch) and is_x86(target_arch):
  137. use_kvm = True
  138. elif build_arch == target_arch:
  139. use_kvm = True
  140. return use_kvm