blob: 43ef09dc95435d02e94900ea006c4a9c2deaf571 [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
9import hashlib
10import os
11import re
12import stat
13import command_executer
14import logger
15import tempfile
16from contextlib import contextmanager
17
18
19def ApplySubs(string, *substitutions):
20 for pattern, replacement in substitutions:
21 string = re.sub(pattern, replacement, string)
22 return string
23
24
Ahmad Sharif5ae8a5c2012-05-18 10:59:51 -070025def UnitToNumber(string, base=1000):
26 unit_dict = {"kilo": base,
27 "mega": base**2,
28 "giga": base**3}
29 string = string.lower()
30 mo = re.search("(\d*)(.+)", string)
31 number = mo.group(1)
32 unit = mo.group(2)
33 for k, v in unit_dict.items():
34 if k.startswith(unit):
35 return float(number) * v
36 raise Exception("Unit: %s not found in byte: %s!" %
37 (unit,
38 string))
39
40
Ahmad Shariffd356fb2012-05-07 12:02:16 -070041def GetFilenameFromString(string):
42 return ApplySubs(string,
43 ("/", "__"),
44 ("\s", "_"),
45 ("=", ""),
46 ("\"", ""))
47
48
49def GetRoot(scr_name):
50 """Break up pathname into (dir+name)."""
51 abs_path = os.path.abspath(scr_name)
52 return (os.path.dirname(abs_path), os.path.basename(abs_path))
53
54
Ahmad Sharif5ae8a5c2012-05-18 10:59:51 -070055def GetChrootPath(chromeos_root):
56 return os.path.join(chromeos_root,
57 "chroot")
58
59
60def GetInsideChrootPath(chromeos_root, file_path):
61 if not file_path.startswith(GetChrootPath(chromeos_root)):
62 raise Exception("File: %s doesn't seem to be in the chroot: %s" %
63 (file_path,
64 chromeos_root))
65 return file_path[len(GetChrootPath(chromeos_root)):]
66
67
68def GetOutsideChrootPath(chromeos_root, file_path):
69 return os.path.join(GetChrootPath(chromeos_root),
70 file_path.lstrip("/"))
71
72
Ahmad Shariffd356fb2012-05-07 12:02:16 -070073def FormatQuotedCommand(command):
74 return ApplySubs(command,
75 ("\"", "\\\""))
76
77
78def FormatCommands(commands):
79 return ApplySubs(str(commands),
80 ("&&", "&&\n"),
81 (";", ";\n"),
82 ("\n+\s*", "\n"))
83
84
85def GetImageDir(chromeos_root, board):
86 return os.path.join(chromeos_root,
87 "src",
88 "build",
89 "images",
90 board)
91
92
93def LabelLatestImage(chromeos_root, board, label):
94 image_dir = GetImageDir(chromeos_root, board)
95 latest_image_dir = os.path.join(image_dir, "latest")
96 latest_image_dir = os.path.realpath(latest_image_dir)
97 latest_image_dir = os.path.basename(latest_image_dir)
98 with WorkingDirectory(image_dir):
99 command = "ln -sf -T %s %s" % (latest_image_dir, label)
100 ce = command_executer.GetCommandExecuter()
101 return ce.RunCommand(command)
102
103
104def DoesLabelExist(chromeos_root, board, label):
105 image_label = os.path.join(GetImageDir(chromeos_root, board),
106 label)
107 return os.path.exists(image_label)
108
109
110def GetBuildPackagesCommand(board, usepkg=False):
111 if usepkg:
112 usepkg_flag = "--usepkg"
113 else:
114 usepkg_flag = "--nousepkg"
115 return ("./build_packages %s --withdev --withtest --withautotest "
116 "--skip_toolchain_update --nowithdebug --board=%s" %
117 (usepkg_flag, board))
118
119
120def GetBuildImageCommand(board):
121 return "./build_image --board=%s test" % board
122
123
124def GetSetupBoardCommand(board, gcc_version=None, binutils_version=None,
125 usepkg=None, force=None):
126 options = []
127
128 if gcc_version:
129 options.append("--gcc_version=%s" % gcc_version)
130
131 if binutils_version:
132 options.append("--binutils_version=%s" % binutils_version)
133
134 if usepkg:
135 options.append("--usepkg")
136 else:
137 options.append("--nousepkg")
138
139 if force:
140 options.append("--force")
141
142 return "./setup_board --board=%s %s" % (board, " ".join(options))
143
144
145def CanonicalizePath(path):
146 path = os.path.expanduser(path)
147 path = os.path.realpath(path)
148 return path
149
150
151def GetCtargetFromBoard(board, chromeos_root):
152 base_board = board.split("_")[0]
153 command = ("source "
154 "../platform/dev/toolchain_utils.sh; get_ctarget_from_board %s" %
155 base_board)
156 ce = command_executer.GetCommandExecuter()
157 ret, out, err = ce.ChrootRunCommand(chromeos_root,
158 command,
159 return_output=True)
160 if ret != 0:
161 raise ValueError("Board %s is invalid!" % board)
162 return out.strip()
163
164
165def GetChromeSrcDir():
166 return "var/cache/distfiles/target/chrome-src/src"
167
168
169def GetEnvStringFromDict(env_dict):
170 return " ".join(["%s=\"%s\"" % var for var in env_dict.items()])
171
172
173def GetAllImages(chromeos_root, board):
174 ce = command_executer.GetCommandExecuter()
175 command = ("find %s/src/build/images/%s -name chromiumos_test_image.bin" %
176 (chromeos_root, board))
177 ret, out, err = ce.RunCommand(command, return_output=True)
178 return out.splitlines()
179
180
181@contextmanager
182def WorkingDirectory(new_dir):
183 old_dir = os.getcwd()
184 if old_dir != new_dir:
185 msg = "cd %s" % new_dir
186 logger.GetLogger().LogCmd(msg)
187 os.chdir(new_dir)
188 yield new_dir
189 if old_dir != new_dir:
190 msg = "cd %s" % old_dir
191 logger.GetLogger().LogCmd(msg)
192 os.chdir(old_dir)