blob: b2af8fedcc4174bc5e016c517b3c76b39be6f45c [file] [log] [blame]
Ahmad Sharif4467f002012-12-20 12:09:49 -08001#!/usr/bin/python
Yunlian Jiangb0a02f42013-08-22 09:55:54 -07002
Rahul Chaudhry8ac4ec02014-11-01 09:31:15 -07003# Copyright 2013 The Chromium OS Authors. All rights reserved.
Yunlian Jiangb0a02f42013-08-22 09:55:54 -07004# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
Ahmad Shariffd356fb2012-05-07 12:02:16 -07006
7"""Utilities for toolchain build."""
8
9__author__ = "asharif@google.com (Ahmad Sharif)"
10
Ahmad Shariff395c262012-10-09 17:48:09 -070011from contextlib import contextmanager
Ahmad Shariffd356fb2012-05-07 12:02:16 -070012import os
13import re
Ahmad Sharif4467f002012-12-20 12:09:49 -080014import shutil
15import sys
16import time
Han Shencc34c222014-01-03 11:39:39 -080017import traceback
Ahmad Sharif4467f002012-12-20 12:09:49 -080018
Ahmad Shariffd356fb2012-05-07 12:02:16 -070019import command_executer
20import logger
Ahmad Shariff395c262012-10-09 17:48:09 -070021
22
Rahul Chaudhry8ac4ec02014-11-01 09:31:15 -070023CHROMEOS_SCRIPTS_DIR = "~/trunk/src/scripts"
24TOOLCHAIN_UTILS_PATH = "~/trunk/src/platform/dev/toolchain_utils.sh"
25
26
Ahmad Shariff395c262012-10-09 17:48:09 -070027def GetChromeOSVersionFromLSBVersion(lsb_version):
Ahmad Sharif4467f002012-12-20 12:09:49 -080028 """Get Chromeos version from Lsb version."""
Ahmad Shariff395c262012-10-09 17:48:09 -070029 ce = command_executer.GetCommandExecuter()
Luis Lozano6aebeb12013-09-03 01:55:02 -070030 command = ("git ls-remote "
Luis Lozano6aae4c92013-09-10 00:00:27 -070031 "https://chromium.googlesource.com/chromiumos/manifest.git")
Ahmad Shariff395c262012-10-09 17:48:09 -070032 ret, out, _ = ce.RunCommand(command, return_output=True,
33 print_to_console=False)
34 assert ret == 0, "Command %s failed" % command
35 lower = []
36 for line in out.splitlines():
Ahmad Sharif4467f002012-12-20 12:09:49 -080037 mo = re.search(r"refs/heads/release-R(\d+)-(\d+)\.B", line)
Ahmad Shariff395c262012-10-09 17:48:09 -070038 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"
Ahmad Shariffd356fb2012-05-07 12:02:16 -070049
50
51def ApplySubs(string, *substitutions):
52 for pattern, replacement in substitutions:
53 string = re.sub(pattern, replacement, string)
54 return string
55
56
Ahmad Sharif4467f002012-12-20 12:09:49 -080057def UnitToNumber(unit_num, base=1000):
58 """Convert a number with unit to float."""
Ahmad Sharif5ae8a5c2012-05-18 10:59:51 -070059 unit_dict = {"kilo": base,
60 "mega": base**2,
61 "giga": base**3}
Ahmad Sharif4467f002012-12-20 12:09:49 -080062 unit_num = unit_num.lower()
63 mo = re.search(r"(\d*)(.+)?", unit_num)
Ahmad Sharif5ae8a5c2012-05-18 10:59:51 -070064 number = mo.group(1)
65 unit = mo.group(2)
Ahmad Shariff395c262012-10-09 17:48:09 -070066 if not unit:
67 return float(number)
Ahmad Sharif5ae8a5c2012-05-18 10:59:51 -070068 for k, v in unit_dict.items():
69 if k.startswith(unit):
70 return float(number) * v
71 raise Exception("Unit: %s not found in byte: %s!" %
72 (unit,
Ahmad Sharif4467f002012-12-20 12:09:49 -080073 unit_num))
Ahmad Sharif5ae8a5c2012-05-18 10:59:51 -070074
75
Ahmad Shariffd356fb2012-05-07 12:02:16 -070076def GetFilenameFromString(string):
77 return ApplySubs(string,
Ahmad Sharif4467f002012-12-20 12:09:49 -080078 (r"/", "__"),
79 (r"\s", "_"),
80 (r"[\^\$=\"\\\?]", ""),
81 )
Ahmad Shariffd356fb2012-05-07 12:02:16 -070082
83
84def GetRoot(scr_name):
85 """Break up pathname into (dir+name)."""
86 abs_path = os.path.abspath(scr_name)
87 return (os.path.dirname(abs_path), os.path.basename(abs_path))
88
89
Ahmad Sharif4467f002012-12-20 12:09:49 -080090def GetChromeOSKeyFile(chromeos_root):
91 return os.path.join(chromeos_root,
92 "src",
93 "scripts",
94 "mod_for_test_scripts",
95 "ssh_keys",
96 "testing_rsa")
97
98
Ahmad Sharif5ae8a5c2012-05-18 10:59:51 -070099def GetChrootPath(chromeos_root):
100 return os.path.join(chromeos_root,
101 "chroot")
102
103
104def GetInsideChrootPath(chromeos_root, file_path):
105 if not file_path.startswith(GetChrootPath(chromeos_root)):
106 raise Exception("File: %s doesn't seem to be in the chroot: %s" %
107 (file_path,
108 chromeos_root))
109 return file_path[len(GetChrootPath(chromeos_root)):]
110
111
112def GetOutsideChrootPath(chromeos_root, file_path):
113 return os.path.join(GetChrootPath(chromeos_root),
114 file_path.lstrip("/"))
115
116
Ahmad Shariffd356fb2012-05-07 12:02:16 -0700117def FormatQuotedCommand(command):
118 return ApplySubs(command,
119 ("\"", "\\\""))
120
121
122def FormatCommands(commands):
123 return ApplySubs(str(commands),
124 ("&&", "&&\n"),
125 (";", ";\n"),
Ahmad Sharif4467f002012-12-20 12:09:49 -0800126 (r"\n+\s*", "\n"))
Ahmad Shariffd356fb2012-05-07 12:02:16 -0700127
128
129def GetImageDir(chromeos_root, board):
130 return os.path.join(chromeos_root,
131 "src",
132 "build",
133 "images",
134 board)
135
136
cmtice56fb7162014-06-18 11:32:15 -0700137def LabelLatestImage(chromeos_root, board, label, vanilla_path=None):
Ahmad Shariffd356fb2012-05-07 12:02:16 -0700138 image_dir = GetImageDir(chromeos_root, board)
139 latest_image_dir = os.path.join(image_dir, "latest")
140 latest_image_dir = os.path.realpath(latest_image_dir)
141 latest_image_dir = os.path.basename(latest_image_dir)
cmtice56fb7162014-06-18 11:32:15 -0700142 retval = 0
Ahmad Shariffd356fb2012-05-07 12:02:16 -0700143 with WorkingDirectory(image_dir):
144 command = "ln -sf -T %s %s" % (latest_image_dir, label)
145 ce = command_executer.GetCommandExecuter()
cmtice56fb7162014-06-18 11:32:15 -0700146 retval = ce.RunCommand(command)
147 if retval:
148 return retval
149 if vanilla_path:
150 command = "ln -sf -T %s %s" % (vanilla_path, "vanilla")
151 retval2 = ce.RunCommand(command)
152 return retval2
153 return retval
Ahmad Shariffd356fb2012-05-07 12:02:16 -0700154
155
156def DoesLabelExist(chromeos_root, board, label):
157 image_label = os.path.join(GetImageDir(chromeos_root, board),
158 label)
159 return os.path.exists(image_label)
160
161
Luis Lozanof81680c2013-03-15 14:44:13 -0700162def GetBuildPackagesCommand(board, usepkg=False, debug=False):
Ahmad Shariffd356fb2012-05-07 12:02:16 -0700163 if usepkg:
164 usepkg_flag = "--usepkg"
165 else:
166 usepkg_flag = "--nousepkg"
Luis Lozanof81680c2013-03-15 14:44:13 -0700167 if debug:
Han Shene4b6f222013-11-22 10:02:38 -0800168 withdebug_flag = "--withdebug"
Luis Lozanof81680c2013-03-15 14:44:13 -0700169 else:
Han Shene4b6f222013-11-22 10:02:38 -0800170 withdebug_flag = "--nowithdebug"
Rahul Chaudhry8ac4ec02014-11-01 09:31:15 -0700171 return ("%s/build_packages %s --withdev --withtest --withautotest "
Yunlian Jiangb0a02f42013-08-22 09:55:54 -0700172 "--skip_toolchain_update %s --board=%s "
173 "--accept_licenses=@CHROMEOS" %
Rahul Chaudhry8ac4ec02014-11-01 09:31:15 -0700174 (CHROMEOS_SCRIPTS_DIR, usepkg_flag, withdebug_flag, board))
Ahmad Shariffd356fb2012-05-07 12:02:16 -0700175
176
Luis Lozanof81680c2013-03-15 14:44:13 -0700177def GetBuildImageCommand(board, dev=False):
178 dev_args = ""
179 if dev:
180 dev_args = "--noenable_rootfs_verification --disk_layout=2gb-rootfs"
Rahul Chaudhry8ac4ec02014-11-01 09:31:15 -0700181 return ("%s/build_image --board=%s %s test" %
182 (CHROMEOS_SCRIPTS_DIR, board, dev_args))
Ahmad Shariffd356fb2012-05-07 12:02:16 -0700183
Han Shene4b6f222013-11-22 10:02:38 -0800184
Ahmad Shariffd356fb2012-05-07 12:02:16 -0700185def GetSetupBoardCommand(board, gcc_version=None, binutils_version=None,
186 usepkg=None, force=None):
Ahmad Sharif4467f002012-12-20 12:09:49 -0800187 """Get setup_board command."""
Ahmad Shariffd356fb2012-05-07 12:02:16 -0700188 options = []
189
190 if gcc_version:
191 options.append("--gcc_version=%s" % gcc_version)
192
193 if binutils_version:
194 options.append("--binutils_version=%s" % binutils_version)
195
196 if usepkg:
197 options.append("--usepkg")
198 else:
199 options.append("--nousepkg")
200
201 if force:
202 options.append("--force")
203
Yunlian Jiangb0a02f42013-08-22 09:55:54 -0700204 options.append("--accept_licenses=@CHROMEOS")
205
Rahul Chaudhry8ac4ec02014-11-01 09:31:15 -0700206 return ("%s/setup_board --board=%s %s" %
207 (CHROMEOS_SCRIPTS_DIR, board, " ".join(options)))
Ahmad Shariffd356fb2012-05-07 12:02:16 -0700208
209
210def CanonicalizePath(path):
211 path = os.path.expanduser(path)
212 path = os.path.realpath(path)
213 return path
214
215
216def GetCtargetFromBoard(board, chromeos_root):
Ahmad Sharif4467f002012-12-20 12:09:49 -0800217 """Get Ctarget from board."""
Ahmad Shariffd356fb2012-05-07 12:02:16 -0700218 base_board = board.split("_")[0]
Rahul Chaudhry8ac4ec02014-11-01 09:31:15 -0700219 command = ("source %s; get_ctarget_from_board %s" %
220 (TOOLCHAIN_UTILS_PATH, base_board))
Ahmad Shariffd356fb2012-05-07 12:02:16 -0700221 ce = command_executer.GetCommandExecuter()
Ahmad Shariff395c262012-10-09 17:48:09 -0700222 ret, out, _ = ce.ChrootRunCommand(chromeos_root,
223 command,
224 return_output=True)
Ahmad Shariffd356fb2012-05-07 12:02:16 -0700225 if ret != 0:
226 raise ValueError("Board %s is invalid!" % board)
Ahmad Shariff395c262012-10-09 17:48:09 -0700227 # Remove ANSI escape sequences.
228 out = StripANSIEscapeSequences(out)
Ahmad Shariffd356fb2012-05-07 12:02:16 -0700229 return out.strip()
230
231
Rahul Chaudhry215c12f2014-11-04 15:18:47 -0800232def GetArchFromBoard(board, chromeos_root):
233 """Get Arch from board."""
234 base_board = board.split("_")[0]
235 command = ("source %s; get_board_arch %s" %
236 (TOOLCHAIN_UTILS_PATH, base_board))
237 ce = command_executer.GetCommandExecuter()
238 ret, out, _ = ce.ChrootRunCommand(chromeos_root,
239 command,
240 return_output=True)
241 if ret != 0:
242 raise ValueError("Board %s is invalid!" % board)
243 # Remove ANSI escape sequences.
244 out = StripANSIEscapeSequences(out)
245 return out.strip()
246
247
248def GetGccLibsDestForBoard(board, chromeos_root):
249 """Get gcc libs destination from board."""
250 arch = GetArchFromBoard(board, chromeos_root)
251 if arch == "x86":
252 return "/build/%s/usr/lib/gcc/" % board
253 if arch == "amd64":
254 return "/build/%s/usr/lib64/gcc/" % board
255 if arch == "arm":
256 return "/build/%s/usr/lib/gcc/" % board
257 raise ValueError("Arch %s is invalid!" % arch)
258
259
Ahmad Shariff395c262012-10-09 17:48:09 -0700260def StripANSIEscapeSequences(string):
Ahmad Sharif4467f002012-12-20 12:09:49 -0800261 string = re.sub(r"\x1b\[[0-9]*[a-zA-Z]", "", string)
Ahmad Shariff395c262012-10-09 17:48:09 -0700262 return string
263
264
Ahmad Shariffd356fb2012-05-07 12:02:16 -0700265def GetChromeSrcDir():
266 return "var/cache/distfiles/target/chrome-src/src"
267
268
269def GetEnvStringFromDict(env_dict):
270 return " ".join(["%s=\"%s\"" % var for var in env_dict.items()])
271
272
Ahmad Shariff395c262012-10-09 17:48:09 -0700273def MergeEnvStringWithDict(env_string, env_dict, prepend=True):
Ahmad Sharif4467f002012-12-20 12:09:49 -0800274 """Merge env string with dict."""
Ahmad Shariff395c262012-10-09 17:48:09 -0700275 if not env_string.strip():
276 return GetEnvStringFromDict(env_dict)
277 override_env_list = []
278 ce = command_executer.GetCommandExecuter()
279 for k, v in env_dict.items():
280 v = v.strip("\"'")
281 if prepend:
282 new_env = "%s=\"%s $%s\"" % (k, v, k)
283 else:
284 new_env = "%s=\"$%s %s\"" % (k, k, v)
285 command = "; ".join([env_string, new_env, "echo $%s" % k])
286 ret, out, _ = ce.RunCommand(command, return_output=True)
287 override_env_list.append("%s=%r" % (k, out.strip()))
288 ret = env_string + " " + " ".join(override_env_list)
289 return ret.strip()
290
291
Ahmad Shariffd356fb2012-05-07 12:02:16 -0700292def GetAllImages(chromeos_root, board):
293 ce = command_executer.GetCommandExecuter()
294 command = ("find %s/src/build/images/%s -name chromiumos_test_image.bin" %
295 (chromeos_root, board))
Ahmad Shariff395c262012-10-09 17:48:09 -0700296 ret, out, _ = ce.RunCommand(command, return_output=True)
297 assert ret == 0, "Could not run command: %s" % command
Ahmad Shariffd356fb2012-05-07 12:02:16 -0700298 return out.splitlines()
299
300
Ahmad Sharif4467f002012-12-20 12:09:49 -0800301def IsFloat(text):
302 if text is None:
303 return False
304 try:
305 float(text)
306 return True
307 except ValueError:
308 return False
309
Han Shene4b6f222013-11-22 10:02:38 -0800310
Ahmad Sharif4467f002012-12-20 12:09:49 -0800311def RemoveChromeBrowserObjectFiles(chromeos_root, board):
Han Shene4b6f222013-11-22 10:02:38 -0800312 """Remove any object files from all the posible locations."""
Ahmad Sharif4467f002012-12-20 12:09:49 -0800313 out_dir = os.path.join(
314 GetChrootPath(chromeos_root),
315 "var/cache/chromeos-chrome/chrome-src/src/out_%s" % board)
316 if os.path.exists(out_dir):
317 shutil.rmtree(out_dir)
318 logger.GetLogger().LogCmd("rm -rf %s" % out_dir)
319 out_dir = os.path.join(
320 GetChrootPath(chromeos_root),
321 "var/cache/chromeos-chrome/chrome-src-internal/src/out_%s" % board)
322 if os.path.exists(out_dir):
323 shutil.rmtree(out_dir)
324 logger.GetLogger().LogCmd("rm -rf %s" % out_dir)
325
Han Shene4b6f222013-11-22 10:02:38 -0800326
Ahmad Shariffd356fb2012-05-07 12:02:16 -0700327@contextmanager
328def WorkingDirectory(new_dir):
Ahmad Sharif4467f002012-12-20 12:09:49 -0800329 """Get the working directory."""
Ahmad Shariffd356fb2012-05-07 12:02:16 -0700330 old_dir = os.getcwd()
331 if old_dir != new_dir:
332 msg = "cd %s" % new_dir
333 logger.GetLogger().LogCmd(msg)
334 os.chdir(new_dir)
335 yield new_dir
336 if old_dir != new_dir:
337 msg = "cd %s" % old_dir
338 logger.GetLogger().LogCmd(msg)
339 os.chdir(old_dir)
Han Shen91445322013-03-20 13:43:31 -0700340
Han Shene4b6f222013-11-22 10:02:38 -0800341
Han Shen91445322013-03-20 13:43:31 -0700342def HasGitStagedChanges(git_dir):
343 """Return True if git repository has staged changes."""
Han Shene4b6f222013-11-22 10:02:38 -0800344 command = "cd {0} && git diff --quiet --cached --exit-code HEAD".format(
345 git_dir)
Han Shen91445322013-03-20 13:43:31 -0700346 return command_executer.GetCommandExecuter().RunCommand(
Han Shene4b6f222013-11-22 10:02:38 -0800347 command, print_to_console=False)
348
Han Shen91445322013-03-20 13:43:31 -0700349
350def HasGitUnstagedChanges(git_dir):
351 """Return True if git repository has un-staged changes."""
Han Shene4b6f222013-11-22 10:02:38 -0800352 command = "cd {0} && git diff --quiet --exit-code HEAD".format(git_dir)
Han Shen91445322013-03-20 13:43:31 -0700353 return command_executer.GetCommandExecuter().RunCommand(
Han Shene4b6f222013-11-22 10:02:38 -0800354 command, print_to_console=False)
355
Han Shen91445322013-03-20 13:43:31 -0700356
357def HasGitUntrackedChanges(git_dir):
358 """Return True if git repository has un-tracked changes."""
Han Shene4b6f222013-11-22 10:02:38 -0800359 command = ("cd {0} && test -z "
360 "$(git ls-files --exclude-standard --others)").format(git_dir)
Han Shen91445322013-03-20 13:43:31 -0700361 return command_executer.GetCommandExecuter().RunCommand(
Han Shene4b6f222013-11-22 10:02:38 -0800362 command, print_to_console=False)
363
Han Shen91445322013-03-20 13:43:31 -0700364
Han Shen819f8622014-04-08 16:57:38 -0700365def GitGetCommitHash(git_dir, commit_symbolic_name):
366 """Return githash for the symbolic git commit.
367
368 For example, commit_symbolic_name could be
369 "cros/gcc.gnu.org/branches/gcc/gcc-4_8-mobile, this function returns the git
370 hash for this symbolic name.
371
372 Args:
373 git_dir: a git working tree.
374 commit_symbolic_name: a symbolic name for a particular git commit.
375 Returns:
376 The git hash for the symbolic name or None if fails.
377 """
378
379 command = ('cd {0} && git log -n 1 --pretty="format:%H" {1}').format(
380 git_dir, commit_symbolic_name)
381 rv, out, _ = command_executer.GetCommandExecuter().RunCommand(
382 command, return_output=True, print_to_console=False)
383 if rv == 0:
384 return out.strip()
385 return None
386
387
Han Shen91445322013-03-20 13:43:31 -0700388def IsGitTreeClean(git_dir):
Han Shene4b6f222013-11-22 10:02:38 -0800389 """Test if git tree has no local changes.
390
391 Args:
392 git_dir: git tree directory.
393 Returns:
394 True if git dir is clean.
395 """
Han Shen91445322013-03-20 13:43:31 -0700396 if HasGitStagedChanges(git_dir):
397 logger.GetLogger().LogWarning("Git tree has staged changes.")
398 return False
399 if HasGitUnstagedChanges(git_dir):
400 logger.GetLogger().LogWarning("Git tree has unstaged changes.")
401 return False
402 if HasGitUntrackedChanges(git_dir):
403 logger.GetLogger().LogWarning("Git tree has un-tracked changes.")
404 return False
405 return True
406
Han Shene4b6f222013-11-22 10:02:38 -0800407
Han Shen91445322013-03-20 13:43:31 -0700408def GetGitChangesAsList(git_dir, path=None, staged=False):
Han Shene4b6f222013-11-22 10:02:38 -0800409 """Get changed files as a list.
410
411 Args:
412 git_dir: git tree directory.
413 path: a relative path that is part of the tree directory, could be null.
414 staged: whether to include staged files as well.
415 Returns:
416 A list containing all the changed files.
417 """
418 command = "cd {0} && git diff --name-only".format(git_dir)
Han Shen91445322013-03-20 13:43:31 -0700419 if staged:
Han Shene4b6f222013-11-22 10:02:38 -0800420 command += " --cached"
Han Shen91445322013-03-20 13:43:31 -0700421 if path:
Han Shene4b6f222013-11-22 10:02:38 -0800422 command += " -- " + path
Luis Lozano6aebeb12013-09-03 01:55:02 -0700423 _, out, _ = command_executer.GetCommandExecuter().RunCommand(
Han Shene4b6f222013-11-22 10:02:38 -0800424 command, return_output=True, print_to_console=False)
Han Shen91445322013-03-20 13:43:31 -0700425 rv = []
426 for line in out.splitlines():
427 rv.append(line)
428 return rv
Han Shene4b6f222013-11-22 10:02:38 -0800429
430
431def IsChromeOsTree(chromeos_root):
432 return (os.path.isdir(os.path.join(
433 chromeos_root, "src/third_party/chromiumos-overlay")) and
434 os.path.isdir(os.path.join(
435 chromeos_root, "manifest")))
436
437
438def DeleteChromeOsTree(chromeos_root, dry_run=False):
439 """Delete a ChromeOs tree *safely*.
440
441 Args:
442 chromeos_root: dir of the tree, could be a relative one (but be careful)
443 dry_run: only prints out the command if True
444
445 Returns:
446 True if everything is ok.
447 """
448 if not IsChromeOsTree(chromeos_root):
449 logger.GetLogger().LogWarning(
450 '"{0}" does not seem to be a valid chromeos tree, do nothing.'.format(
451 chromeos_root))
452 return False
453 cmd0 = "cd {0} && cros_sdk --delete".format(chromeos_root)
454 if dry_run:
455 print cmd0
456 else:
457 if command_executer.GetCommandExecuter().RunCommand(
458 cmd0, return_output=False, print_to_console=True) != 0:
459 return False
460
461 cmd1 = ('export CHROMEOSDIRNAME="$(dirname $(cd {0} && pwd))" && '
462 'export CHROMEOSBASENAME="$(basename $(cd {0} && pwd))" && '
463 'cd $CHROMEOSDIRNAME && sudo rm -fr $CHROMEOSBASENAME').format(
464 chromeos_root)
465 if dry_run:
466 print cmd1
467 return True
468
469 return command_executer.GetCommandExecuter().RunCommand(
470 cmd1, return_output=False, print_to_console=True) == 0
Han Shencc34c222014-01-03 11:39:39 -0800471
472
473def ApplyGerritPatches(chromeos_root,
474 gerrit_patch_string, branch='cros/master'):
475 """Apply gerrit patches on a chromeos tree.
476
477 Args:
478 chromeos_root: chromeos tree path
479 gerrit_patch_string: a patch string just like the one gives to cbuildbot,
480 'id1 id2 *id3 ... idn'. A prefix of '* means this is an internal patch.
481 branch: the tree based on which to apply the patches.
482 Returns:
483 True if success.
484 """
485
486 ### First of all, we need chromite libs
487 sys.path.append(os.path.join(chromeos_root, 'chromite'))
488 from lib import git
489 from lib import gerrit
490 manifest = git.ManifestCheckout(chromeos_root)
491 patch_list = gerrit_patch_string.split(' ')
492 ### This takes time, print log information.
493 logger.GetLogger().LogOutput('Retrieving patch information from server ...')
494 patch_info_list = gerrit.GetGerritPatchInfo(patch_list)
495 for pi in patch_info_list:
496 project_checkout = manifest.FindCheckout(pi.project, strict=False)
497 if not project_checkout:
498 logger.GetLogger().LogError(
499 'Failed to find patch project "{project}" in manifest.'.format(
500 project=pi.project))
501 return False
502
503 pi_str = '{project}:{ref}'.format(project=pi.project, ref=pi.ref)
504 try:
505 project_git_path = project_checkout.GetPath(absolute=True)
506 logger.GetLogger().LogOutput('Applying patch "{0}" in "{1}" ...'.format(
507 pi_str, project_git_path))
508 pi.Apply(project_git_path, branch, trivial=False)
509 except Exception:
510 traceback.print_exc(file=sys.stdout)
511 logger.GetLogger().LogError('Failed to apply patch "{0}"'.format(pi_str))
512 return False
513 return True
cmtice5c09fc22015-04-22 09:25:53 -0700514
515
516def BooleanPrompt(prompt='Do you want to continue?', default=True,
517 true_value='yes', false_value='no', prolog=None):
518 """Helper function for processing boolean choice prompts.
519
520 Args:
521 prompt: The question to present to the user.
522 default: Boolean to return if the user just presses enter.
523 true_value: The text to display that represents a True returned.
524 false_value: The text to display that represents a False returned.
525 prolog: The text to display before prompt.
526
527 Returns:
528 True or False.
529 """
530 true_value, false_value = true_value.lower(), false_value.lower()
531 true_text, false_text = true_value, false_value
532 if true_value == false_value:
533 raise ValueError('true_value and false_value must differ: got %r'
534 % true_value)
535
536 if default:
537 true_text = true_text[0].upper() + true_text[1:]
538 else:
539 false_text = false_text[0].upper() + false_text[1:]
540
541 prompt = ('\n%s (%s/%s)? ' % (prompt, true_text, false_text))
542
543 if prolog:
544 prompt = ('\n%s\n%s' % (prolog, prompt))
545
546 while True:
547 try:
548 response = raw_input(prompt).lower()
549 except EOFError:
550 # If the user hits CTRL+D, or stdin is disabled, use the default.
551 print()
552 response = None
553 except KeyboardInterrupt:
554 # If the user hits CTRL+C, just exit the process.
555 print()
556 Die('CTRL+C detected; exiting')
557
558 if not response:
559 return default
560 if true_value.startswith(response):
561 if not false_value.startswith(response):
562 return True
563 # common prefix between the two...
564 elif false_value.startswith(response):
565 return False