blob: cb9acbfae45114f56f8d1e8954d02c416652dcc1 [file] [log] [blame]
Ahmad Shariffd356fb2012-05-07 12:02:16 -07001#!/usr/bin/python2.6
2#
3# Copyright 2010 Google Inc. All Rights Reserved.
4
5"""Utilities for toolchain build."""
6
7__author__ = "asharif@google.com (Ahmad Sharif)"
8
Ahmad Shariff395c262012-10-09 17:48:09 -07009from contextlib import contextmanager
Ahmad Shariffd356fb2012-05-07 12:02:16 -070010import os
11import re
Ahmad Shariff395c262012-10-09 17:48:09 -070012
Ahmad Shariffd356fb2012-05-07 12:02:16 -070013import command_executer
14import logger
Ahmad Shariff395c262012-10-09 17:48:09 -070015
16
17def GetChromeOSVersionFromLSBVersion(lsb_version):
18 ce = command_executer.GetCommandExecuter()
19 command = "git ls-remote http://git.chromium.org/chromiumos/manifest.git"
20 ret, out, _ = ce.RunCommand(command, return_output=True,
21 print_to_console=False)
22 assert ret == 0, "Command %s failed" % command
23 lower = []
24 for line in out.splitlines():
25 mo = re.search("refs/heads/release-R(\d+)-(\d+)\.B", line)
26 if mo:
27 revision = int(mo.group(1))
28 build = int(mo.group(2))
29 lsb_build = int(lsb_version.split(".")[0])
30 if lsb_build > build:
31 lower.append(revision)
32 lower = sorted(lower)
33 if lower:
34 return "R%d-%s" % (lower[-1] + 1, lsb_version)
35 else:
36 return "Unknown"
Ahmad Shariffd356fb2012-05-07 12:02:16 -070037
38
39def ApplySubs(string, *substitutions):
40 for pattern, replacement in substitutions:
41 string = re.sub(pattern, replacement, string)
42 return string
43
44
Ahmad Sharif5ae8a5c2012-05-18 10:59:51 -070045def UnitToNumber(string, base=1000):
46 unit_dict = {"kilo": base,
47 "mega": base**2,
48 "giga": base**3}
49 string = string.lower()
Ahmad Shariff395c262012-10-09 17:48:09 -070050 mo = re.search("(\d*)(.+)?", string)
Ahmad Sharif5ae8a5c2012-05-18 10:59:51 -070051 number = mo.group(1)
52 unit = mo.group(2)
Ahmad Shariff395c262012-10-09 17:48:09 -070053 if not unit:
54 return float(number)
Ahmad Sharif5ae8a5c2012-05-18 10:59:51 -070055 for k, v in unit_dict.items():
56 if k.startswith(unit):
57 return float(number) * v
58 raise Exception("Unit: %s not found in byte: %s!" %
59 (unit,
60 string))
61
62
Ahmad Shariffd356fb2012-05-07 12:02:16 -070063def GetFilenameFromString(string):
64 return ApplySubs(string,
65 ("/", "__"),
66 ("\s", "_"),
Ahmad Shariff395c262012-10-09 17:48:09 -070067 ("[\^\$=\"\\\?]", ""),
68 )
Ahmad Shariffd356fb2012-05-07 12:02:16 -070069
70
71def GetRoot(scr_name):
72 """Break up pathname into (dir+name)."""
73 abs_path = os.path.abspath(scr_name)
74 return (os.path.dirname(abs_path), os.path.basename(abs_path))
75
76
Ahmad Sharif5ae8a5c2012-05-18 10:59:51 -070077def GetChrootPath(chromeos_root):
78 return os.path.join(chromeos_root,
79 "chroot")
80
81
82def GetInsideChrootPath(chromeos_root, file_path):
83 if not file_path.startswith(GetChrootPath(chromeos_root)):
84 raise Exception("File: %s doesn't seem to be in the chroot: %s" %
85 (file_path,
86 chromeos_root))
87 return file_path[len(GetChrootPath(chromeos_root)):]
88
89
90def GetOutsideChrootPath(chromeos_root, file_path):
91 return os.path.join(GetChrootPath(chromeos_root),
92 file_path.lstrip("/"))
93
94
Ahmad Shariffd356fb2012-05-07 12:02:16 -070095def FormatQuotedCommand(command):
96 return ApplySubs(command,
97 ("\"", "\\\""))
98
99
100def FormatCommands(commands):
101 return ApplySubs(str(commands),
102 ("&&", "&&\n"),
103 (";", ";\n"),
104 ("\n+\s*", "\n"))
105
106
107def GetImageDir(chromeos_root, board):
108 return os.path.join(chromeos_root,
109 "src",
110 "build",
111 "images",
112 board)
113
114
115def LabelLatestImage(chromeos_root, board, label):
116 image_dir = GetImageDir(chromeos_root, board)
117 latest_image_dir = os.path.join(image_dir, "latest")
118 latest_image_dir = os.path.realpath(latest_image_dir)
119 latest_image_dir = os.path.basename(latest_image_dir)
120 with WorkingDirectory(image_dir):
121 command = "ln -sf -T %s %s" % (latest_image_dir, label)
122 ce = command_executer.GetCommandExecuter()
123 return ce.RunCommand(command)
124
125
126def DoesLabelExist(chromeos_root, board, label):
127 image_label = os.path.join(GetImageDir(chromeos_root, board),
128 label)
129 return os.path.exists(image_label)
130
131
132def GetBuildPackagesCommand(board, usepkg=False):
133 if usepkg:
134 usepkg_flag = "--usepkg"
135 else:
136 usepkg_flag = "--nousepkg"
137 return ("./build_packages %s --withdev --withtest --withautotest "
138 "--skip_toolchain_update --nowithdebug --board=%s" %
139 (usepkg_flag, board))
140
141
142def GetBuildImageCommand(board):
143 return "./build_image --board=%s test" % board
144
145
146def GetSetupBoardCommand(board, gcc_version=None, binutils_version=None,
147 usepkg=None, force=None):
148 options = []
149
150 if gcc_version:
151 options.append("--gcc_version=%s" % gcc_version)
152
153 if binutils_version:
154 options.append("--binutils_version=%s" % binutils_version)
155
156 if usepkg:
157 options.append("--usepkg")
158 else:
159 options.append("--nousepkg")
160
161 if force:
162 options.append("--force")
163
164 return "./setup_board --board=%s %s" % (board, " ".join(options))
165
166
167def CanonicalizePath(path):
168 path = os.path.expanduser(path)
169 path = os.path.realpath(path)
170 return path
171
172
173def GetCtargetFromBoard(board, chromeos_root):
174 base_board = board.split("_")[0]
175 command = ("source "
176 "../platform/dev/toolchain_utils.sh; get_ctarget_from_board %s" %
177 base_board)
178 ce = command_executer.GetCommandExecuter()
Ahmad Shariff395c262012-10-09 17:48:09 -0700179 ret, out, _ = ce.ChrootRunCommand(chromeos_root,
180 command,
181 return_output=True)
Ahmad Shariffd356fb2012-05-07 12:02:16 -0700182 if ret != 0:
183 raise ValueError("Board %s is invalid!" % board)
Ahmad Shariff395c262012-10-09 17:48:09 -0700184 # Remove ANSI escape sequences.
185 out = StripANSIEscapeSequences(out)
Ahmad Shariffd356fb2012-05-07 12:02:16 -0700186 return out.strip()
187
188
Ahmad Shariff395c262012-10-09 17:48:09 -0700189def StripANSIEscapeSequences(string):
190 string = re.sub("\x1b\[[0-9]*[a-zA-Z]", "", string)
191 return string
192
193
Ahmad Shariffd356fb2012-05-07 12:02:16 -0700194def GetChromeSrcDir():
195 return "var/cache/distfiles/target/chrome-src/src"
196
197
198def GetEnvStringFromDict(env_dict):
199 return " ".join(["%s=\"%s\"" % var for var in env_dict.items()])
200
201
Ahmad Shariff395c262012-10-09 17:48:09 -0700202def MergeEnvStringWithDict(env_string, env_dict, prepend=True):
203 if not env_string.strip():
204 return GetEnvStringFromDict(env_dict)
205 override_env_list = []
206 ce = command_executer.GetCommandExecuter()
207 for k, v in env_dict.items():
208 v = v.strip("\"'")
209 if prepend:
210 new_env = "%s=\"%s $%s\"" % (k, v, k)
211 else:
212 new_env = "%s=\"$%s %s\"" % (k, k, v)
213 command = "; ".join([env_string, new_env, "echo $%s" % k])
214 ret, out, _ = ce.RunCommand(command, return_output=True)
215 override_env_list.append("%s=%r" % (k, out.strip()))
216 ret = env_string + " " + " ".join(override_env_list)
217 return ret.strip()
218
219
Ahmad Shariffd356fb2012-05-07 12:02:16 -0700220def GetAllImages(chromeos_root, board):
221 ce = command_executer.GetCommandExecuter()
222 command = ("find %s/src/build/images/%s -name chromiumos_test_image.bin" %
223 (chromeos_root, board))
Ahmad Shariff395c262012-10-09 17:48:09 -0700224 ret, out, _ = ce.RunCommand(command, return_output=True)
225 assert ret == 0, "Could not run command: %s" % command
Ahmad Shariffd356fb2012-05-07 12:02:16 -0700226 return out.splitlines()
227
228
229@contextmanager
230def WorkingDirectory(new_dir):
231 old_dir = os.getcwd()
232 if old_dir != new_dir:
233 msg = "cd %s" % new_dir
234 logger.GetLogger().LogCmd(msg)
235 os.chdir(new_dir)
236 yield new_dir
237 if old_dir != new_dir:
238 msg = "cd %s" % old_dir
239 logger.GetLogger().LogCmd(msg)
240 os.chdir(old_dir)