1# -*- coding: utf-8 -*- 2# Copyright 2013 The Chromium OS Authors. All rights reserved. 3# Use of this source code is governed by a BSD-style license that can be 4# found in the LICENSE file. 5 6"""Utilities for toolchain build.""" 7 8from __future__ import division 9from __future__ import print_function 10 11__author__ = 'asharif@google.com (Ahmad Sharif)' 12 13from contextlib import contextmanager 14import os 15import re 16import shutil 17import sys 18 19from cros_utils import command_executer 20from cros_utils import logger 21 22CHROMEOS_SCRIPTS_DIR = '/mnt/host/source/src/scripts' 23TOOLCHAIN_UTILS_PATH = ('/mnt/host/source/src/third_party/toolchain-utils/' 24 'cros_utils/toolchain_utils.sh') 25 26 27def GetChromeOSVersionFromLSBVersion(lsb_version): 28 """Get Chromeos version from Lsb version.""" 29 ce = command_executer.GetCommandExecuter() 30 command = ('git ls-remote ' 31 'https://chromium.googlesource.com/chromiumos/manifest.git ' 32 'refs/heads/release-R*') 33 ret, out, _ = ce.RunCommandWOutput(command, print_to_console=False) 34 assert ret == 0, 'Command %s failed' % command 35 lower = [] 36 for line in out.splitlines(): 37 mo = re.search(r'refs/heads/release-R(\d+)-(\d+)\.B', line) 38 if mo: 39 revision = int(mo.group(1)) 40 build = int(mo.group(2)) 41 lsb_build = int(lsb_version.split('.')[0]) 42 if lsb_build > build: 43 lower.append(revision) 44 lower = sorted(lower) 45 if lower: 46 return 'R%d-%s' % (lower[-1] + 1, lsb_version) 47 else: 48 return 'Unknown' 49 50 51def ApplySubs(string, *substitutions): 52 for pattern, replacement in substitutions: 53 string = re.sub(pattern, replacement, string) 54 return string 55 56 57def UnitToNumber(unit_num, base=1000): 58 """Convert a number with unit to float.""" 59 unit_dict = {'kilo': base, 'mega': base**2, 'giga': base**3} 60 unit_num = unit_num.lower() 61 mo = re.search(r'(\d*)(.+)?', unit_num) 62 number = mo.group(1) 63 unit = mo.group(2) 64 if not unit: 65 return float(number) 66 for k, v in unit_dict.items(): 67 if k.startswith(unit): 68 return float(number) * v 69 raise RuntimeError('Unit: %s not found in byte: %s!' % (unit, unit_num)) 70 71 72def GetFilenameFromString(string): 73 return ApplySubs( 74 string, 75 (r'/', '__'), 76 (r'\s', '_'), 77 (r'[\\$="?^]', ''), 78 ) 79 80 81def GetRoot(scr_name): 82 """Break up pathname into (dir+name).""" 83 abs_path = os.path.abspath(scr_name) 84 return (os.path.dirname(abs_path), os.path.basename(abs_path)) 85 86 87def GetChromeOSKeyFile(chromeos_root): 88 return os.path.join(chromeos_root, 'src', 'scripts', 'mod_for_test_scripts', 89 'ssh_keys', 'testing_rsa') 90 91 92def GetChrootPath(chromeos_root): 93 return os.path.join(chromeos_root, 'chroot') 94 95 96def GetInsideChrootPath(chromeos_root, file_path): 97 if not file_path.startswith(GetChrootPath(chromeos_root)): 98 raise RuntimeError("File: %s doesn't seem to be in the chroot: %s" % 99 (file_path, chromeos_root)) 100 return file_path[len(GetChrootPath(chromeos_root)):] 101 102 103def GetOutsideChrootPath(chromeos_root, file_path): 104 return os.path.join(GetChrootPath(chromeos_root), file_path.lstrip('/')) 105 106 107def FormatQuotedCommand(command): 108 return ApplySubs(command, ('"', r'\"')) 109 110 111def FormatCommands(commands): 112 return ApplySubs(str(commands), ('&&', '&&\n'), (';', ';\n'), 113 (r'\n+\s*', '\n')) 114 115 116def GetImageDir(chromeos_root, board): 117 return os.path.join(chromeos_root, 'src', 'build', 'images', board) 118 119 120def LabelLatestImage(chromeos_root, board, label, vanilla_path=None): 121 image_dir = GetImageDir(chromeos_root, board) 122 latest_image_dir = os.path.join(image_dir, 'latest') 123 latest_image_dir = os.path.realpath(latest_image_dir) 124 latest_image_dir = os.path.basename(latest_image_dir) 125 retval = 0 126 with WorkingDirectory(image_dir): 127 command = 'ln -sf -T %s %s' % (latest_image_dir, label) 128 ce = command_executer.GetCommandExecuter() 129 retval = ce.RunCommand(command) 130 if retval: 131 return retval 132 if vanilla_path: 133 command = 'ln -sf -T %s %s' % (vanilla_path, 'vanilla') 134 retval2 = ce.RunCommand(command) 135 return retval2 136 return retval 137 138 139def DoesLabelExist(chromeos_root, board, label): 140 image_label = os.path.join(GetImageDir(chromeos_root, board), label) 141 return os.path.exists(image_label) 142 143 144def GetBuildPackagesCommand(board, usepkg=False, debug=False): 145 if usepkg: 146 usepkg_flag = '--usepkg' 147 else: 148 usepkg_flag = '--nousepkg' 149 if debug: 150 withdebug_flag = '--withdebug' 151 else: 152 withdebug_flag = '--nowithdebug' 153 return ('%s/build_packages %s --withdev --withtest --withautotest ' 154 '--skip_toolchain_update %s --board=%s ' 155 '--accept_licenses=@CHROMEOS' % 156 (CHROMEOS_SCRIPTS_DIR, usepkg_flag, withdebug_flag, board)) 157 158 159def GetBuildImageCommand(board, dev=False): 160 dev_args = '' 161 if dev: 162 dev_args = '--noenable_rootfs_verification --disk_layout=2gb-rootfs' 163 return ('%s/build_image --board=%s %s test' % 164 (CHROMEOS_SCRIPTS_DIR, board, dev_args)) 165 166 167def GetSetupBoardCommand(board, usepkg=None, force=None): 168 """Get setup_board command.""" 169 options = [] 170 171 if usepkg: 172 options.append('--usepkg') 173 else: 174 options.append('--nousepkg') 175 176 if force: 177 options.append('--force') 178 179 options.append('--accept-licenses=@CHROMEOS') 180 181 return 'setup_board --board=%s %s' % (board, ' '.join(options)) 182 183 184def CanonicalizePath(path): 185 path = os.path.expanduser(path) 186 path = os.path.realpath(path) 187 return path 188 189 190def GetCtargetFromBoard(board, chromeos_root): 191 """Get Ctarget from board.""" 192 base_board = board.split('_')[0] 193 command = ('source %s; get_ctarget_from_board %s' % 194 (TOOLCHAIN_UTILS_PATH, base_board)) 195 ce = command_executer.GetCommandExecuter() 196 ret, out, _ = ce.ChrootRunCommandWOutput(chromeos_root, command) 197 if ret != 0: 198 raise ValueError('Board %s is invalid!' % board) 199 # Remove ANSI escape sequences. 200 out = StripANSIEscapeSequences(out) 201 return out.strip() 202 203 204def GetArchFromBoard(board, chromeos_root): 205 """Get Arch from board.""" 206 base_board = board.split('_')[0] 207 command = ('source %s; get_board_arch %s' % 208 (TOOLCHAIN_UTILS_PATH, base_board)) 209 ce = command_executer.GetCommandExecuter() 210 ret, out, _ = ce.ChrootRunCommandWOutput(chromeos_root, command) 211 if ret != 0: 212 raise ValueError('Board %s is invalid!' % board) 213 # Remove ANSI escape sequences. 214 out = StripANSIEscapeSequences(out) 215 return out.strip() 216 217 218def GetGccLibsDestForBoard(board, chromeos_root): 219 """Get gcc libs destination from board.""" 220 arch = GetArchFromBoard(board, chromeos_root) 221 if arch == 'x86': 222 return '/build/%s/usr/lib/gcc/' % board 223 if arch == 'amd64': 224 return '/build/%s/usr/lib64/gcc/' % board 225 if arch == 'arm': 226 return '/build/%s/usr/lib/gcc/' % board 227 if arch == 'arm64': 228 return '/build/%s/usr/lib/gcc/' % board 229 raise ValueError('Arch %s is invalid!' % arch) 230 231 232def StripANSIEscapeSequences(string): 233 string = re.sub(r'\x1b\[[0-9]*[a-zA-Z]', '', string) 234 return string 235 236 237def GetChromeSrcDir(): 238 return 'var/cache/distfiles/target/chrome-src/src' 239 240 241def GetEnvStringFromDict(env_dict): 242 return ' '.join(['%s="%s"' % var for var in env_dict.items()]) 243 244 245def MergeEnvStringWithDict(env_string, env_dict, prepend=True): 246 """Merge env string with dict.""" 247 if not env_string.strip(): 248 return GetEnvStringFromDict(env_dict) 249 override_env_list = [] 250 ce = command_executer.GetCommandExecuter() 251 for k, v in env_dict.items(): 252 v = v.strip('"\'') 253 if prepend: 254 new_env = '%s="%s $%s"' % (k, v, k) 255 else: 256 new_env = '%s="$%s %s"' % (k, k, v) 257 command = '; '.join([env_string, new_env, 'echo $%s' % k]) 258 ret, out, _ = ce.RunCommandWOutput(command) 259 override_env_list.append('%s=%r' % (k, out.strip())) 260 ret = env_string + ' ' + ' '.join(override_env_list) 261 return ret.strip() 262 263 264def GetAllImages(chromeos_root, board): 265 ce = command_executer.GetCommandExecuter() 266 command = ('find %s/src/build/images/%s -name chromiumos_test_image.bin' % 267 (chromeos_root, board)) 268 ret, out, _ = ce.RunCommandWOutput(command) 269 assert ret == 0, 'Could not run command: %s' % command 270 return out.splitlines() 271 272 273def IsFloat(text): 274 if text is None: 275 return False 276 try: 277 float(text) 278 return True 279 except ValueError: 280 return False 281 282 283def RemoveChromeBrowserObjectFiles(chromeos_root, board): 284 """Remove any object files from all the posible locations.""" 285 out_dir = os.path.join( 286 GetChrootPath(chromeos_root), 287 'var/cache/chromeos-chrome/chrome-src/src/out_%s' % board) 288 if os.path.exists(out_dir): 289 shutil.rmtree(out_dir) 290 logger.GetLogger().LogCmd('rm -rf %s' % out_dir) 291 out_dir = os.path.join( 292 GetChrootPath(chromeos_root), 293 'var/cache/chromeos-chrome/chrome-src-internal/src/out_%s' % board) 294 if os.path.exists(out_dir): 295 shutil.rmtree(out_dir) 296 logger.GetLogger().LogCmd('rm -rf %s' % out_dir) 297 298 299@contextmanager 300def WorkingDirectory(new_dir): 301 """Get the working directory.""" 302 old_dir = os.getcwd() 303 if old_dir != new_dir: 304 msg = 'cd %s' % new_dir 305 logger.GetLogger().LogCmd(msg) 306 os.chdir(new_dir) 307 yield new_dir 308 if old_dir != new_dir: 309 msg = 'cd %s' % old_dir 310 logger.GetLogger().LogCmd(msg) 311 os.chdir(old_dir) 312 313 314def HasGitStagedChanges(git_dir): 315 """Return True if git repository has staged changes.""" 316 command = f'cd {git_dir} && git diff --quiet --cached --exit-code HEAD' 317 return command_executer.GetCommandExecuter().RunCommand( 318 command, print_to_console=False) 319 320 321def HasGitUnstagedChanges(git_dir): 322 """Return True if git repository has un-staged changes.""" 323 command = f'cd {git_dir} && git diff --quiet --exit-code HEAD' 324 return command_executer.GetCommandExecuter().RunCommand( 325 command, print_to_console=False) 326 327 328def HasGitUntrackedChanges(git_dir): 329 """Return True if git repository has un-tracked changes.""" 330 command = (f'cd {git_dir} && test -z ' 331 '$(git ls-files --exclude-standard --others)') 332 return command_executer.GetCommandExecuter().RunCommand( 333 command, print_to_console=False) 334 335 336def GitGetCommitHash(git_dir, commit_symbolic_name): 337 """Return githash for the symbolic git commit. 338 339 For example, commit_symbolic_name could be 340 "cros/gcc.gnu.org/branches/gcc/gcc-4_8-mobile, this function returns the git 341 hash for this symbolic name. 342 343 Args: 344 git_dir: a git working tree. 345 commit_symbolic_name: a symbolic name for a particular git commit. 346 347 Returns: 348 The git hash for the symbolic name or None if fails. 349 """ 350 351 command = (f'cd {git_dir} && git log -n 1' 352 f' --pretty="format:%H" {commit_symbolic_name}') 353 rv, out, _ = command_executer.GetCommandExecuter().RunCommandWOutput( 354 command, print_to_console=False) 355 if rv == 0: 356 return out.strip() 357 return None 358 359 360def IsGitTreeClean(git_dir): 361 """Test if git tree has no local changes. 362 363 Args: 364 git_dir: git tree directory. 365 366 Returns: 367 True if git dir is clean. 368 """ 369 if HasGitStagedChanges(git_dir): 370 logger.GetLogger().LogWarning('Git tree has staged changes.') 371 return False 372 if HasGitUnstagedChanges(git_dir): 373 logger.GetLogger().LogWarning('Git tree has unstaged changes.') 374 return False 375 if HasGitUntrackedChanges(git_dir): 376 logger.GetLogger().LogWarning('Git tree has un-tracked changes.') 377 return False 378 return True 379 380 381def GetGitChangesAsList(git_dir, path=None, staged=False): 382 """Get changed files as a list. 383 384 Args: 385 git_dir: git tree directory. 386 path: a relative path that is part of the tree directory, could be null. 387 staged: whether to include staged files as well. 388 389 Returns: 390 A list containing all the changed files. 391 """ 392 command = f'cd {git_dir} && git diff --name-only' 393 if staged: 394 command += ' --cached' 395 if path: 396 command += ' -- ' + path 397 _, out, _ = command_executer.GetCommandExecuter().RunCommandWOutput( 398 command, print_to_console=False) 399 rv = [] 400 for line in out.splitlines(): 401 rv.append(line) 402 return rv 403 404 405def IsChromeOsTree(chromeos_root): 406 return (os.path.isdir( 407 os.path.join(chromeos_root, 'src/third_party/chromiumos-overlay')) 408 and os.path.isdir(os.path.join(chromeos_root, 'manifest'))) 409 410 411def DeleteChromeOsTree(chromeos_root, dry_run=False): 412 """Delete a ChromeOs tree *safely*. 413 414 Args: 415 chromeos_root: dir of the tree, could be a relative one (but be careful) 416 dry_run: only prints out the command if True 417 418 Returns: 419 True if everything is ok. 420 """ 421 if not IsChromeOsTree(chromeos_root): 422 logger.GetLogger().LogWarning(f'"{chromeos_root}" does not seem to be a' 423 ' valid chromeos tree, do nothing.') 424 return False 425 cmd0 = f'cd {chromeos_root} && cros_sdk --delete' 426 if dry_run: 427 print(cmd0) 428 else: 429 if command_executer.GetCommandExecuter().RunCommand( 430 cmd0, print_to_console=True) != 0: 431 return False 432 433 cmd1 = ( 434 f'export CHROMEOSDIRNAME="$(dirname $(cd {chromeos_root} && pwd))" && ' 435 f'export CHROMEOSBASENAME="$(basename $(cd {chromeos_root} && pwd))" && ' 436 'cd $CHROMEOSDIRNAME && sudo rm -fr $CHROMEOSBASENAME') 437 if dry_run: 438 print(cmd1) 439 return True 440 441 return command_executer.GetCommandExecuter().RunCommand( 442 cmd1, print_to_console=True) == 0 443 444 445def BooleanPrompt(prompt='Do you want to continue?', 446 default=True, 447 true_value='yes', 448 false_value='no', 449 prolog=None): 450 """Helper function for processing boolean choice prompts. 451 452 Args: 453 prompt: The question to present to the user. 454 default: Boolean to return if the user just presses enter. 455 true_value: The text to display that represents a True returned. 456 false_value: The text to display that represents a False returned. 457 prolog: The text to display before prompt. 458 459 Returns: 460 True or False. 461 """ 462 true_value, false_value = true_value.lower(), false_value.lower() 463 true_text, false_text = true_value, false_value 464 if true_value == false_value: 465 raise ValueError('true_value and false_value must differ: got %r' % 466 true_value) 467 468 if default: 469 true_text = true_text[0].upper() + true_text[1:] 470 else: 471 false_text = false_text[0].upper() + false_text[1:] 472 473 prompt = ('\n%s (%s/%s)? ' % (prompt, true_text, false_text)) 474 475 if prolog: 476 prompt = ('\n%s\n%s' % (prolog, prompt)) 477 478 while True: 479 try: 480 # pylint: disable=input-builtin, bad-builtin 481 response = input(prompt).lower() 482 except EOFError: 483 # If the user hits CTRL+D, or stdin is disabled, use the default. 484 print() 485 response = None 486 except KeyboardInterrupt: 487 # If the user hits CTRL+C, just exit the process. 488 print() 489 print('CTRL+C detected; exiting') 490 sys.exit() 491 492 if not response: 493 return default 494 if true_value.startswith(response): 495 if not false_value.startswith(response): 496 return True 497 # common prefix between the two... 498 elif false_value.startswith(response): 499 return False 500 501 502# pylint: disable=unused-argument 503def rgb2short(r, g, b): 504 """Converts RGB values to xterm-256 color.""" 505 506 redcolor = [255, 124, 160, 196, 9] 507 greencolor = [255, 118, 82, 46, 10] 508 509 if g == 0: 510 return redcolor[r // 52] 511 if r == 0: 512 return greencolor[g // 52] 513 return 4 514