Ahmad Sharif | 4467f00 | 2012-12-20 12:09:49 -0800 | [diff] [blame] | 1 | #!/usr/bin/python |
Yunlian Jiang | b0a02f4 | 2013-08-22 09:55:54 -0700 | [diff] [blame] | 2 | |
Rahul Chaudhry | 8ac4ec0 | 2014-11-01 09:31:15 -0700 | [diff] [blame] | 3 | # Copyright 2013 The Chromium OS Authors. All rights reserved. |
Yunlian Jiang | b0a02f4 | 2013-08-22 09:55:54 -0700 | [diff] [blame] | 4 | # Use of this source code is governed by a BSD-style license that can be |
| 5 | # found in the LICENSE file. |
Ahmad Sharif | fd356fb | 2012-05-07 12:02:16 -0700 | [diff] [blame] | 6 | |
| 7 | """Utilities for toolchain build.""" |
| 8 | |
| 9 | __author__ = "asharif@google.com (Ahmad Sharif)" |
| 10 | |
Ahmad Sharif | f395c26 | 2012-10-09 17:48:09 -0700 | [diff] [blame] | 11 | from contextlib import contextmanager |
Ahmad Sharif | fd356fb | 2012-05-07 12:02:16 -0700 | [diff] [blame] | 12 | import os |
| 13 | import re |
Ahmad Sharif | 4467f00 | 2012-12-20 12:09:49 -0800 | [diff] [blame] | 14 | import shutil |
| 15 | import sys |
| 16 | import time |
Han Shen | cc34c22 | 2014-01-03 11:39:39 -0800 | [diff] [blame] | 17 | import traceback |
Ahmad Sharif | 4467f00 | 2012-12-20 12:09:49 -0800 | [diff] [blame] | 18 | |
Ahmad Sharif | fd356fb | 2012-05-07 12:02:16 -0700 | [diff] [blame] | 19 | import command_executer |
| 20 | import logger |
Ahmad Sharif | f395c26 | 2012-10-09 17:48:09 -0700 | [diff] [blame] | 21 | |
| 22 | |
Rahul Chaudhry | 8ac4ec0 | 2014-11-01 09:31:15 -0700 | [diff] [blame] | 23 | CHROMEOS_SCRIPTS_DIR = "~/trunk/src/scripts" |
| 24 | TOOLCHAIN_UTILS_PATH = "~/trunk/src/platform/dev/toolchain_utils.sh" |
| 25 | |
| 26 | |
Ahmad Sharif | f395c26 | 2012-10-09 17:48:09 -0700 | [diff] [blame] | 27 | def GetChromeOSVersionFromLSBVersion(lsb_version): |
Ahmad Sharif | 4467f00 | 2012-12-20 12:09:49 -0800 | [diff] [blame] | 28 | """Get Chromeos version from Lsb version.""" |
Ahmad Sharif | f395c26 | 2012-10-09 17:48:09 -0700 | [diff] [blame] | 29 | ce = command_executer.GetCommandExecuter() |
Luis Lozano | 6aebeb1 | 2013-09-03 01:55:02 -0700 | [diff] [blame] | 30 | command = ("git ls-remote " |
Luis Lozano | 6aae4c9 | 2013-09-10 00:00:27 -0700 | [diff] [blame] | 31 | "https://chromium.googlesource.com/chromiumos/manifest.git") |
Ahmad Sharif | f395c26 | 2012-10-09 17:48:09 -0700 | [diff] [blame] | 32 | 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 Sharif | 4467f00 | 2012-12-20 12:09:49 -0800 | [diff] [blame] | 37 | mo = re.search(r"refs/heads/release-R(\d+)-(\d+)\.B", line) |
Ahmad Sharif | f395c26 | 2012-10-09 17:48:09 -0700 | [diff] [blame] | 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" |
Ahmad Sharif | fd356fb | 2012-05-07 12:02:16 -0700 | [diff] [blame] | 49 | |
| 50 | |
| 51 | def ApplySubs(string, *substitutions): |
| 52 | for pattern, replacement in substitutions: |
| 53 | string = re.sub(pattern, replacement, string) |
| 54 | return string |
| 55 | |
| 56 | |
Ahmad Sharif | 4467f00 | 2012-12-20 12:09:49 -0800 | [diff] [blame] | 57 | def UnitToNumber(unit_num, base=1000): |
| 58 | """Convert a number with unit to float.""" |
Ahmad Sharif | 5ae8a5c | 2012-05-18 10:59:51 -0700 | [diff] [blame] | 59 | unit_dict = {"kilo": base, |
| 60 | "mega": base**2, |
| 61 | "giga": base**3} |
Ahmad Sharif | 4467f00 | 2012-12-20 12:09:49 -0800 | [diff] [blame] | 62 | unit_num = unit_num.lower() |
| 63 | mo = re.search(r"(\d*)(.+)?", unit_num) |
Ahmad Sharif | 5ae8a5c | 2012-05-18 10:59:51 -0700 | [diff] [blame] | 64 | number = mo.group(1) |
| 65 | unit = mo.group(2) |
Ahmad Sharif | f395c26 | 2012-10-09 17:48:09 -0700 | [diff] [blame] | 66 | if not unit: |
| 67 | return float(number) |
Ahmad Sharif | 5ae8a5c | 2012-05-18 10:59:51 -0700 | [diff] [blame] | 68 | 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 Sharif | 4467f00 | 2012-12-20 12:09:49 -0800 | [diff] [blame] | 73 | unit_num)) |
Ahmad Sharif | 5ae8a5c | 2012-05-18 10:59:51 -0700 | [diff] [blame] | 74 | |
| 75 | |
Ahmad Sharif | fd356fb | 2012-05-07 12:02:16 -0700 | [diff] [blame] | 76 | def GetFilenameFromString(string): |
| 77 | return ApplySubs(string, |
Ahmad Sharif | 4467f00 | 2012-12-20 12:09:49 -0800 | [diff] [blame] | 78 | (r"/", "__"), |
| 79 | (r"\s", "_"), |
| 80 | (r"[\^\$=\"\\\?]", ""), |
| 81 | ) |
Ahmad Sharif | fd356fb | 2012-05-07 12:02:16 -0700 | [diff] [blame] | 82 | |
| 83 | |
| 84 | def 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 Sharif | 4467f00 | 2012-12-20 12:09:49 -0800 | [diff] [blame] | 90 | def 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 Sharif | 5ae8a5c | 2012-05-18 10:59:51 -0700 | [diff] [blame] | 99 | def GetChrootPath(chromeos_root): |
| 100 | return os.path.join(chromeos_root, |
| 101 | "chroot") |
| 102 | |
| 103 | |
| 104 | def 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 | |
| 112 | def GetOutsideChrootPath(chromeos_root, file_path): |
| 113 | return os.path.join(GetChrootPath(chromeos_root), |
| 114 | file_path.lstrip("/")) |
| 115 | |
| 116 | |
Ahmad Sharif | fd356fb | 2012-05-07 12:02:16 -0700 | [diff] [blame] | 117 | def FormatQuotedCommand(command): |
| 118 | return ApplySubs(command, |
| 119 | ("\"", "\\\"")) |
| 120 | |
| 121 | |
| 122 | def FormatCommands(commands): |
| 123 | return ApplySubs(str(commands), |
| 124 | ("&&", "&&\n"), |
| 125 | (";", ";\n"), |
Ahmad Sharif | 4467f00 | 2012-12-20 12:09:49 -0800 | [diff] [blame] | 126 | (r"\n+\s*", "\n")) |
Ahmad Sharif | fd356fb | 2012-05-07 12:02:16 -0700 | [diff] [blame] | 127 | |
| 128 | |
| 129 | def GetImageDir(chromeos_root, board): |
| 130 | return os.path.join(chromeos_root, |
| 131 | "src", |
| 132 | "build", |
| 133 | "images", |
| 134 | board) |
| 135 | |
| 136 | |
cmtice | 56fb716 | 2014-06-18 11:32:15 -0700 | [diff] [blame] | 137 | def LabelLatestImage(chromeos_root, board, label, vanilla_path=None): |
Ahmad Sharif | fd356fb | 2012-05-07 12:02:16 -0700 | [diff] [blame] | 138 | 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) |
cmtice | 56fb716 | 2014-06-18 11:32:15 -0700 | [diff] [blame] | 142 | retval = 0 |
Ahmad Sharif | fd356fb | 2012-05-07 12:02:16 -0700 | [diff] [blame] | 143 | with WorkingDirectory(image_dir): |
| 144 | command = "ln -sf -T %s %s" % (latest_image_dir, label) |
| 145 | ce = command_executer.GetCommandExecuter() |
cmtice | 56fb716 | 2014-06-18 11:32:15 -0700 | [diff] [blame] | 146 | 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 Sharif | fd356fb | 2012-05-07 12:02:16 -0700 | [diff] [blame] | 154 | |
| 155 | |
| 156 | def 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 Lozano | f81680c | 2013-03-15 14:44:13 -0700 | [diff] [blame] | 162 | def GetBuildPackagesCommand(board, usepkg=False, debug=False): |
Ahmad Sharif | fd356fb | 2012-05-07 12:02:16 -0700 | [diff] [blame] | 163 | if usepkg: |
| 164 | usepkg_flag = "--usepkg" |
| 165 | else: |
| 166 | usepkg_flag = "--nousepkg" |
Luis Lozano | f81680c | 2013-03-15 14:44:13 -0700 | [diff] [blame] | 167 | if debug: |
Han Shen | e4b6f22 | 2013-11-22 10:02:38 -0800 | [diff] [blame] | 168 | withdebug_flag = "--withdebug" |
Luis Lozano | f81680c | 2013-03-15 14:44:13 -0700 | [diff] [blame] | 169 | else: |
Han Shen | e4b6f22 | 2013-11-22 10:02:38 -0800 | [diff] [blame] | 170 | withdebug_flag = "--nowithdebug" |
Rahul Chaudhry | 8ac4ec0 | 2014-11-01 09:31:15 -0700 | [diff] [blame] | 171 | return ("%s/build_packages %s --withdev --withtest --withautotest " |
Yunlian Jiang | b0a02f4 | 2013-08-22 09:55:54 -0700 | [diff] [blame] | 172 | "--skip_toolchain_update %s --board=%s " |
| 173 | "--accept_licenses=@CHROMEOS" % |
Rahul Chaudhry | 8ac4ec0 | 2014-11-01 09:31:15 -0700 | [diff] [blame] | 174 | (CHROMEOS_SCRIPTS_DIR, usepkg_flag, withdebug_flag, board)) |
Ahmad Sharif | fd356fb | 2012-05-07 12:02:16 -0700 | [diff] [blame] | 175 | |
| 176 | |
Luis Lozano | f81680c | 2013-03-15 14:44:13 -0700 | [diff] [blame] | 177 | def GetBuildImageCommand(board, dev=False): |
| 178 | dev_args = "" |
| 179 | if dev: |
| 180 | dev_args = "--noenable_rootfs_verification --disk_layout=2gb-rootfs" |
Rahul Chaudhry | 8ac4ec0 | 2014-11-01 09:31:15 -0700 | [diff] [blame] | 181 | return ("%s/build_image --board=%s %s test" % |
| 182 | (CHROMEOS_SCRIPTS_DIR, board, dev_args)) |
Ahmad Sharif | fd356fb | 2012-05-07 12:02:16 -0700 | [diff] [blame] | 183 | |
Han Shen | e4b6f22 | 2013-11-22 10:02:38 -0800 | [diff] [blame] | 184 | |
Ahmad Sharif | fd356fb | 2012-05-07 12:02:16 -0700 | [diff] [blame] | 185 | def GetSetupBoardCommand(board, gcc_version=None, binutils_version=None, |
| 186 | usepkg=None, force=None): |
Ahmad Sharif | 4467f00 | 2012-12-20 12:09:49 -0800 | [diff] [blame] | 187 | """Get setup_board command.""" |
Ahmad Sharif | fd356fb | 2012-05-07 12:02:16 -0700 | [diff] [blame] | 188 | 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 Jiang | b0a02f4 | 2013-08-22 09:55:54 -0700 | [diff] [blame] | 204 | options.append("--accept_licenses=@CHROMEOS") |
| 205 | |
Rahul Chaudhry | 8ac4ec0 | 2014-11-01 09:31:15 -0700 | [diff] [blame] | 206 | return ("%s/setup_board --board=%s %s" % |
| 207 | (CHROMEOS_SCRIPTS_DIR, board, " ".join(options))) |
Ahmad Sharif | fd356fb | 2012-05-07 12:02:16 -0700 | [diff] [blame] | 208 | |
| 209 | |
| 210 | def CanonicalizePath(path): |
| 211 | path = os.path.expanduser(path) |
| 212 | path = os.path.realpath(path) |
| 213 | return path |
| 214 | |
| 215 | |
| 216 | def GetCtargetFromBoard(board, chromeos_root): |
Ahmad Sharif | 4467f00 | 2012-12-20 12:09:49 -0800 | [diff] [blame] | 217 | """Get Ctarget from board.""" |
Ahmad Sharif | fd356fb | 2012-05-07 12:02:16 -0700 | [diff] [blame] | 218 | base_board = board.split("_")[0] |
Rahul Chaudhry | 8ac4ec0 | 2014-11-01 09:31:15 -0700 | [diff] [blame] | 219 | command = ("source %s; get_ctarget_from_board %s" % |
| 220 | (TOOLCHAIN_UTILS_PATH, base_board)) |
Ahmad Sharif | fd356fb | 2012-05-07 12:02:16 -0700 | [diff] [blame] | 221 | ce = command_executer.GetCommandExecuter() |
Ahmad Sharif | f395c26 | 2012-10-09 17:48:09 -0700 | [diff] [blame] | 222 | ret, out, _ = ce.ChrootRunCommand(chromeos_root, |
| 223 | command, |
| 224 | return_output=True) |
Ahmad Sharif | fd356fb | 2012-05-07 12:02:16 -0700 | [diff] [blame] | 225 | if ret != 0: |
| 226 | raise ValueError("Board %s is invalid!" % board) |
Ahmad Sharif | f395c26 | 2012-10-09 17:48:09 -0700 | [diff] [blame] | 227 | # Remove ANSI escape sequences. |
| 228 | out = StripANSIEscapeSequences(out) |
Ahmad Sharif | fd356fb | 2012-05-07 12:02:16 -0700 | [diff] [blame] | 229 | return out.strip() |
| 230 | |
| 231 | |
Rahul Chaudhry | 215c12f | 2014-11-04 15:18:47 -0800 | [diff] [blame] | 232 | def 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 | |
| 248 | def 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 Sharif | f395c26 | 2012-10-09 17:48:09 -0700 | [diff] [blame] | 260 | def StripANSIEscapeSequences(string): |
Ahmad Sharif | 4467f00 | 2012-12-20 12:09:49 -0800 | [diff] [blame] | 261 | string = re.sub(r"\x1b\[[0-9]*[a-zA-Z]", "", string) |
Ahmad Sharif | f395c26 | 2012-10-09 17:48:09 -0700 | [diff] [blame] | 262 | return string |
| 263 | |
| 264 | |
Ahmad Sharif | fd356fb | 2012-05-07 12:02:16 -0700 | [diff] [blame] | 265 | def GetChromeSrcDir(): |
| 266 | return "var/cache/distfiles/target/chrome-src/src" |
| 267 | |
| 268 | |
| 269 | def GetEnvStringFromDict(env_dict): |
| 270 | return " ".join(["%s=\"%s\"" % var for var in env_dict.items()]) |
| 271 | |
| 272 | |
Ahmad Sharif | f395c26 | 2012-10-09 17:48:09 -0700 | [diff] [blame] | 273 | def MergeEnvStringWithDict(env_string, env_dict, prepend=True): |
Ahmad Sharif | 4467f00 | 2012-12-20 12:09:49 -0800 | [diff] [blame] | 274 | """Merge env string with dict.""" |
Ahmad Sharif | f395c26 | 2012-10-09 17:48:09 -0700 | [diff] [blame] | 275 | 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 Sharif | fd356fb | 2012-05-07 12:02:16 -0700 | [diff] [blame] | 292 | def 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 Sharif | f395c26 | 2012-10-09 17:48:09 -0700 | [diff] [blame] | 296 | ret, out, _ = ce.RunCommand(command, return_output=True) |
| 297 | assert ret == 0, "Could not run command: %s" % command |
Ahmad Sharif | fd356fb | 2012-05-07 12:02:16 -0700 | [diff] [blame] | 298 | return out.splitlines() |
| 299 | |
| 300 | |
Ahmad Sharif | 4467f00 | 2012-12-20 12:09:49 -0800 | [diff] [blame] | 301 | def 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 Shen | e4b6f22 | 2013-11-22 10:02:38 -0800 | [diff] [blame] | 310 | |
Ahmad Sharif | 4467f00 | 2012-12-20 12:09:49 -0800 | [diff] [blame] | 311 | def RemoveChromeBrowserObjectFiles(chromeos_root, board): |
Han Shen | e4b6f22 | 2013-11-22 10:02:38 -0800 | [diff] [blame] | 312 | """Remove any object files from all the posible locations.""" |
Ahmad Sharif | 4467f00 | 2012-12-20 12:09:49 -0800 | [diff] [blame] | 313 | 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 Shen | e4b6f22 | 2013-11-22 10:02:38 -0800 | [diff] [blame] | 326 | |
Ahmad Sharif | fd356fb | 2012-05-07 12:02:16 -0700 | [diff] [blame] | 327 | @contextmanager |
| 328 | def WorkingDirectory(new_dir): |
Ahmad Sharif | 4467f00 | 2012-12-20 12:09:49 -0800 | [diff] [blame] | 329 | """Get the working directory.""" |
Ahmad Sharif | fd356fb | 2012-05-07 12:02:16 -0700 | [diff] [blame] | 330 | 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 Shen | 9144532 | 2013-03-20 13:43:31 -0700 | [diff] [blame] | 340 | |
Han Shen | e4b6f22 | 2013-11-22 10:02:38 -0800 | [diff] [blame] | 341 | |
Han Shen | 9144532 | 2013-03-20 13:43:31 -0700 | [diff] [blame] | 342 | def HasGitStagedChanges(git_dir): |
| 343 | """Return True if git repository has staged changes.""" |
Han Shen | e4b6f22 | 2013-11-22 10:02:38 -0800 | [diff] [blame] | 344 | command = "cd {0} && git diff --quiet --cached --exit-code HEAD".format( |
| 345 | git_dir) |
Han Shen | 9144532 | 2013-03-20 13:43:31 -0700 | [diff] [blame] | 346 | return command_executer.GetCommandExecuter().RunCommand( |
Han Shen | e4b6f22 | 2013-11-22 10:02:38 -0800 | [diff] [blame] | 347 | command, print_to_console=False) |
| 348 | |
Han Shen | 9144532 | 2013-03-20 13:43:31 -0700 | [diff] [blame] | 349 | |
| 350 | def HasGitUnstagedChanges(git_dir): |
| 351 | """Return True if git repository has un-staged changes.""" |
Han Shen | e4b6f22 | 2013-11-22 10:02:38 -0800 | [diff] [blame] | 352 | command = "cd {0} && git diff --quiet --exit-code HEAD".format(git_dir) |
Han Shen | 9144532 | 2013-03-20 13:43:31 -0700 | [diff] [blame] | 353 | return command_executer.GetCommandExecuter().RunCommand( |
Han Shen | e4b6f22 | 2013-11-22 10:02:38 -0800 | [diff] [blame] | 354 | command, print_to_console=False) |
| 355 | |
Han Shen | 9144532 | 2013-03-20 13:43:31 -0700 | [diff] [blame] | 356 | |
| 357 | def HasGitUntrackedChanges(git_dir): |
| 358 | """Return True if git repository has un-tracked changes.""" |
Han Shen | e4b6f22 | 2013-11-22 10:02:38 -0800 | [diff] [blame] | 359 | command = ("cd {0} && test -z " |
| 360 | "$(git ls-files --exclude-standard --others)").format(git_dir) |
Han Shen | 9144532 | 2013-03-20 13:43:31 -0700 | [diff] [blame] | 361 | return command_executer.GetCommandExecuter().RunCommand( |
Han Shen | e4b6f22 | 2013-11-22 10:02:38 -0800 | [diff] [blame] | 362 | command, print_to_console=False) |
| 363 | |
Han Shen | 9144532 | 2013-03-20 13:43:31 -0700 | [diff] [blame] | 364 | |
Han Shen | 819f862 | 2014-04-08 16:57:38 -0700 | [diff] [blame] | 365 | def 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 Shen | 9144532 | 2013-03-20 13:43:31 -0700 | [diff] [blame] | 388 | def IsGitTreeClean(git_dir): |
Han Shen | e4b6f22 | 2013-11-22 10:02:38 -0800 | [diff] [blame] | 389 | """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 Shen | 9144532 | 2013-03-20 13:43:31 -0700 | [diff] [blame] | 396 | 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 Shen | e4b6f22 | 2013-11-22 10:02:38 -0800 | [diff] [blame] | 407 | |
Han Shen | 9144532 | 2013-03-20 13:43:31 -0700 | [diff] [blame] | 408 | def GetGitChangesAsList(git_dir, path=None, staged=False): |
Han Shen | e4b6f22 | 2013-11-22 10:02:38 -0800 | [diff] [blame] | 409 | """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 Shen | 9144532 | 2013-03-20 13:43:31 -0700 | [diff] [blame] | 419 | if staged: |
Han Shen | e4b6f22 | 2013-11-22 10:02:38 -0800 | [diff] [blame] | 420 | command += " --cached" |
Han Shen | 9144532 | 2013-03-20 13:43:31 -0700 | [diff] [blame] | 421 | if path: |
Han Shen | e4b6f22 | 2013-11-22 10:02:38 -0800 | [diff] [blame] | 422 | command += " -- " + path |
Luis Lozano | 6aebeb1 | 2013-09-03 01:55:02 -0700 | [diff] [blame] | 423 | _, out, _ = command_executer.GetCommandExecuter().RunCommand( |
Han Shen | e4b6f22 | 2013-11-22 10:02:38 -0800 | [diff] [blame] | 424 | command, return_output=True, print_to_console=False) |
Han Shen | 9144532 | 2013-03-20 13:43:31 -0700 | [diff] [blame] | 425 | rv = [] |
| 426 | for line in out.splitlines(): |
| 427 | rv.append(line) |
| 428 | return rv |
Han Shen | e4b6f22 | 2013-11-22 10:02:38 -0800 | [diff] [blame] | 429 | |
| 430 | |
| 431 | def 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 | |
| 438 | def 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 Shen | cc34c22 | 2014-01-03 11:39:39 -0800 | [diff] [blame] | 471 | |
| 472 | |
| 473 | def 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 |
cmtice | 5c09fc2 | 2015-04-22 09:25:53 -0700 | [diff] [blame] | 514 | |
| 515 | |
| 516 | def 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 |