blob: 29b5b6a0aafa93ff4db730e43f02b269b8dcca88 [file] [log] [blame]
kjellander@webrtc.org89256622014-08-20 12:10:11 +00001#!/usr/bin/env python
2# Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
3#
4# Use of this source code is governed by a BSD-style license
5# that can be found in the LICENSE file in the root of the source
6# tree. An additional intellectual property rights grant can be found
7# in the file PATENTS. All contributing project authors may
8# be found in the AUTHORS file in the root of the source tree.
9
10"""Setup links to a Chromium checkout for WebRTC.
11
12WebRTC standalone shares a lot of dependencies and build tools with Chromium.
13To do this, many of the paths of a Chromium checkout is emulated by creating
14symlinks to files and directories. This script handles the setup of symlinks to
15achieve this.
kjellander@webrtc.org89256622014-08-20 12:10:11 +000016"""
17
18
19import ctypes
20import errno
21import logging
22import optparse
23import os
24import shelve
25import shutil
26import subprocess
27import sys
28import textwrap
29
30
31DIRECTORIES = [
32 'build',
33 'buildtools',
kjellandere26e7872016-03-04 14:39:28 -080034 'mojo', # TODO(kjellander): Remove, see webrtc:5629.
kjellander@webrtc.org89256622014-08-20 12:10:11 +000035 'testing',
metzmanf89a5712016-07-25 02:14:09 -070036 'third_party/afl',
kjellander@webrtc.org89256622014-08-20 12:10:11 +000037 'third_party/binutils',
38 'third_party/boringssl',
39 'third_party/colorama',
40 'third_party/drmemory',
41 'third_party/expat',
hbosa9a1d2a2016-01-11 10:19:02 -080042 'third_party/ffmpeg',
kjellander@webrtc.org4e4fe4f2014-10-01 08:03:19 +000043 'third_party/instrumented_libraries',
kjellander@webrtc.org89256622014-08-20 12:10:11 +000044 'third_party/jsoncpp',
Henrik Kjellander26ab91b2015-11-26 10:26:32 +010045 'third_party/libc++-static',
kjellander@webrtc.org2addf3f2016-04-04 08:33:12 +020046 'third_party/libFuzzer',
kjellander@webrtc.org89256622014-08-20 12:10:11 +000047 'third_party/libjpeg',
48 'third_party/libjpeg_turbo',
49 'third_party/libsrtp',
kjellandere26e7872016-03-04 14:39:28 -080050 'third_party/libvpx',
kjellander@webrtc.org89256622014-08-20 12:10:11 +000051 'third_party/libyuv',
52 'third_party/llvm-build',
Patrik Höglundc92c23d2015-08-31 11:30:14 +020053 'third_party/lss',
kjellander@webrtc.org89256622014-08-20 12:10:11 +000054 'third_party/nss',
tkchin@webrtc.org3a63a3c2015-01-06 07:21:34 +000055 'third_party/ocmock',
hbosa9a1d2a2016-01-11 10:19:02 -080056 'third_party/openh264',
kjellander@webrtc.org89256622014-08-20 12:10:11 +000057 'third_party/openmax_dl',
58 'third_party/opus',
Patrik Höglundc92c23d2015-08-31 11:30:14 +020059 'third_party/proguard',
kjellander@webrtc.org89256622014-08-20 12:10:11 +000060 'third_party/protobuf',
61 'third_party/sqlite',
62 'third_party/syzygy',
63 'third_party/usrsctp',
64 'third_party/yasm',
kjellander@webrtc.org3bd41562014-09-01 11:06:37 +000065 'third_party/zlib',
kjellander752f36f2016-03-22 16:56:01 -070066 'third_party/WebKit', # TODO(kjellander): Remove, see webrtc:5629.
kjellander@webrtc.org89256622014-08-20 12:10:11 +000067 'tools/clang',
68 'tools/generate_library_loader',
hbos5602f652016-01-15 01:38:34 -080069 'tools/generate_stubs',
kjellander@webrtc.org89256622014-08-20 12:10:11 +000070 'tools/gn',
71 'tools/gyp',
kjellandere532aec2016-04-17 20:08:20 -070072 'tools/luci-go',
kjellander17849fc2016-02-24 00:04:44 -080073 'tools/mb',
kjellander@webrtc.org89256622014-08-20 12:10:11 +000074 'tools/memory',
75 'tools/protoc_wrapper',
76 'tools/python',
77 'tools/swarming_client',
78 'tools/valgrind',
Andrew MacDonald65de7d22015-05-19 11:37:34 -070079 'tools/vim',
kjellander@webrtc.org89256622014-08-20 12:10:11 +000080 'tools/win',
Henrik Kjellander9589e2a2015-10-22 06:48:21 +020081 'tools/xdisplaycheck',
kjellander@webrtc.org89256622014-08-20 12:10:11 +000082]
83
kjellander@webrtc.org3bd41562014-09-01 11:06:37 +000084from sync_chromium import get_target_os_list
Henrik Kjellanderca843022015-06-09 10:51:22 +020085target_os = get_target_os_list()
86if 'android' in target_os:
kjellander@webrtc.org3bd41562014-09-01 11:06:37 +000087 DIRECTORIES += [
88 'base',
ehmaldonado9f73f7a2016-07-28 01:20:22 -070089 'third_party/accessibility_test_framework',
Henrik Kjellander94a12322015-06-09 14:56:20 +020090 'third_party/android_platform',
kjellander@webrtc.org3bd41562014-09-01 11:06:37 +000091 'third_party/android_tools',
ehmaldonado9f73f7a2016-07-28 01:20:22 -070092 'third_party/apache_velocity',
kjellander@webrtc.orgcbe7ca82015-01-06 07:24:27 +000093 'third_party/appurify-python',
kjellander@webrtc.orgb8caf6a2014-09-30 18:05:02 +000094 'third_party/ashmem',
ehmaldonado9f73f7a2016-07-28 01:20:22 -070095 'third_party/bouncycastle',
kjellander34a70542015-12-06 10:32:34 -080096 'third_party/catapult',
ehmaldonado9f73f7a2016-07-28 01:20:22 -070097 'third_party/guava',
98 'third_party/hamcrest',
kjellander53761002015-11-10 10:58:22 -080099 'third_party/icu',
ehmaldonado9f73f7a2016-07-28 01:20:22 -0700100 'third_party/icu4j',
Henrik Kjellandereecbab72015-09-16 19:19:04 +0200101 'third_party/ijar',
ehmaldonado9f73f7a2016-07-28 01:20:22 -0700102 'third_party/intellij',
kjellander@webrtc.orgb8caf6a2014-09-30 18:05:02 +0000103 'third_party/jsr-305',
Henrik Kjellander10ba3ee2015-04-29 14:47:53 +0200104 'third_party/junit',
kjellander@webrtc.orgb8caf6a2014-09-30 18:05:02 +0000105 'third_party/libxml',
Henrik Kjellander10ba3ee2015-04-29 14:47:53 +0200106 'third_party/mockito',
kjellander@webrtc.orgb8caf6a2014-09-30 18:05:02 +0000107 'third_party/modp_b64',
ehmaldonado9f73f7a2016-07-28 01:20:22 -0700108 'third_party/ow2_asm',
kjellander@webrtc.orgcbe7ca82015-01-06 07:24:27 +0000109 'third_party/requests',
Henrik Kjellander10ba3ee2015-04-29 14:47:53 +0200110 'third_party/robolectric',
ehmaldonado9f73f7a2016-07-28 01:20:22 -0700111 'third_party/sqlite4java',
primianob332e5d2016-01-25 08:13:05 -0800112 'third_party/tcmalloc',
kjellander@webrtc.org3bd41562014-09-01 11:06:37 +0000113 'tools/android',
kjellander@webrtc.orgbfdee692015-02-03 15:23:34 +0000114 'tools/grit',
kjellander34a70542015-12-06 10:32:34 -0800115 'tools/telemetry',
kjellander@webrtc.org3bd41562014-09-01 11:06:37 +0000116 ]
tommide3b0292016-04-22 01:47:02 -0700117else:
118 DIRECTORIES += [
119 'base/third_party/libevent',
120 ]
121
Henrik Kjellanderca843022015-06-09 10:51:22 +0200122if 'ios' in target_os:
123 DIRECTORIES.append('third_party/class-dump')
kjellander@webrtc.org3bd41562014-09-01 11:06:37 +0000124
kjellander@webrtc.org89256622014-08-20 12:10:11 +0000125FILES = {
Henrik Kjellanderd6d27e72015-09-25 22:19:11 +0200126 'tools/isolate_driver.py': None,
kjellander@webrtc.org89256622014-08-20 12:10:11 +0000127 'third_party/BUILD.gn': None,
kjellander@webrtc.org89256622014-08-20 12:10:11 +0000128}
129
kjellander@webrtc.orge94f83a2014-09-18 13:47:23 +0000130ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
kjellander@webrtc.org89256622014-08-20 12:10:11 +0000131CHROMIUM_CHECKOUT = os.path.join('chromium', 'src')
132LINKS_DB = 'links'
133
134# Version management to make future upgrades/downgrades easier to support.
135SCHEMA_VERSION = 1
136
137
138def query_yes_no(question, default=False):
139 """Ask a yes/no question via raw_input() and return their answer.
140
141 Modified from http://stackoverflow.com/a/3041990.
142 """
143 prompt = " [%s/%%s]: "
144 prompt = prompt % ('Y' if default is True else 'y')
145 prompt = prompt % ('N' if default is False else 'n')
146
147 if default is None:
148 default = 'INVALID'
149
150 while True:
151 sys.stdout.write(question + prompt)
152 choice = raw_input().lower()
153 if choice == '' and default != 'INVALID':
154 return default
155
156 if 'yes'.startswith(choice):
157 return True
158 elif 'no'.startswith(choice):
159 return False
160
161 print "Please respond with 'yes' or 'no' (or 'y' or 'n')."
162
163
164# Actions
165class Action(object):
166 def __init__(self, dangerous):
167 self.dangerous = dangerous
168
169 def announce(self, planning):
170 """Log a description of this action.
171
172 Args:
173 planning - True iff we're in the planning stage, False if we're in the
174 doit stage.
175 """
176 pass
177
178 def doit(self, links_db):
179 """Execute the action, recording what we did to links_db, if necessary."""
180 pass
181
182
183class Remove(Action):
184 def __init__(self, path, dangerous):
185 super(Remove, self).__init__(dangerous)
186 self._priority = 0
187 self._path = path
188
189 def announce(self, planning):
190 log = logging.warn
191 filesystem_type = 'file'
192 if not self.dangerous:
193 log = logging.info
194 filesystem_type = 'link'
195 if planning:
196 log('Planning to remove %s: %s', filesystem_type, self._path)
197 else:
198 log('Removing %s: %s', filesystem_type, self._path)
199
Henrik Kjellander57e5fd22015-05-25 12:55:39 +0200200 def doit(self, _):
kjellander@webrtc.org89256622014-08-20 12:10:11 +0000201 os.remove(self._path)
202
203
204class Rmtree(Action):
205 def __init__(self, path):
206 super(Rmtree, self).__init__(dangerous=True)
207 self._priority = 0
208 self._path = path
209
210 def announce(self, planning):
211 if planning:
212 logging.warn('Planning to remove directory: %s', self._path)
213 else:
214 logging.warn('Removing directory: %s', self._path)
215
Henrik Kjellander57e5fd22015-05-25 12:55:39 +0200216 def doit(self, _):
kjellander@webrtc.org89256622014-08-20 12:10:11 +0000217 if sys.platform.startswith('win'):
218 # shutil.rmtree() doesn't work on Windows if any of the directories are
219 # read-only, which svn repositories are.
220 subprocess.check_call(['rd', '/q', '/s', self._path], shell=True)
221 else:
222 shutil.rmtree(self._path)
223
224
225class Makedirs(Action):
226 def __init__(self, path):
227 super(Makedirs, self).__init__(dangerous=False)
228 self._priority = 1
229 self._path = path
230
Henrik Kjellander57e5fd22015-05-25 12:55:39 +0200231 def doit(self, _):
kjellander@webrtc.org89256622014-08-20 12:10:11 +0000232 try:
233 os.makedirs(self._path)
234 except OSError as e:
235 if e.errno != errno.EEXIST:
236 raise
237
238
239class Symlink(Action):
240 def __init__(self, source_path, link_path):
241 super(Symlink, self).__init__(dangerous=False)
242 self._priority = 2
243 self._source_path = source_path
244 self._link_path = link_path
245
246 def announce(self, planning):
247 if planning:
248 logging.info(
249 'Planning to create link from %s to %s', self._link_path,
250 self._source_path)
251 else:
252 logging.debug(
253 'Linking from %s to %s', self._link_path, self._source_path)
254
255 def doit(self, links_db):
256 # Files not in the root directory need relative path calculation.
257 # On Windows, use absolute paths instead since NTFS doesn't seem to support
258 # relative paths for symlinks.
259 if sys.platform.startswith('win'):
260 source_path = os.path.abspath(self._source_path)
261 else:
262 if os.path.dirname(self._link_path) != self._link_path:
263 source_path = os.path.relpath(self._source_path,
264 os.path.dirname(self._link_path))
265
266 os.symlink(source_path, os.path.abspath(self._link_path))
267 links_db[self._source_path] = self._link_path
268
269
270class LinkError(IOError):
271 """Failed to create a link."""
272 pass
273
274
kjellander844dd2a2016-04-05 00:13:58 -0700275# Use junctions instead of symlinks on the Windows platform.
kjellander@webrtc.org89256622014-08-20 12:10:11 +0000276if sys.platform.startswith('win'):
277 def symlink(source_path, link_path):
kjellander844dd2a2016-04-05 00:13:58 -0700278 if os.path.isdir(source_path):
279 subprocess.check_call(['cmd.exe', '/c', 'mklink', '/J', link_path,
280 source_path])
281 else:
282 # Don't create symlinks to files on Windows, just copy the file instead
283 # (there's no way to create a link without administrator's privileges).
284 shutil.copy(source_path, link_path)
kjellander@webrtc.org89256622014-08-20 12:10:11 +0000285 os.symlink = symlink
286
287
Henrik Kjellander57e5fd22015-05-25 12:55:39 +0200288class WebRTCLinkSetup(object):
kjellander@webrtc.org89256622014-08-20 12:10:11 +0000289 def __init__(self, links_db, force=False, dry_run=False, prompt=False):
290 self._force = force
291 self._dry_run = dry_run
292 self._prompt = prompt
293 self._links_db = links_db
294
295 def CreateLinks(self, on_bot):
296 logging.debug('CreateLinks')
297 # First, make a plan of action
298 actions = []
299
300 for source_path, link_path in FILES.iteritems():
301 actions += self._ActionForPath(
302 source_path, link_path, check_fn=os.path.isfile, check_msg='files')
303 for source_dir in DIRECTORIES:
304 actions += self._ActionForPath(
305 source_dir, None, check_fn=os.path.isdir,
306 check_msg='directories')
307
kjellander@webrtc.orge94f83a2014-09-18 13:47:23 +0000308 if not on_bot and self._force:
309 # When making the manual switch from legacy SVN checkouts to the new
310 # Git-based Chromium DEPS, the .gclient_entries file that contains cached
311 # URLs for all DEPS entries must be removed to avoid future sync problems.
312 entries_file = os.path.join(os.path.dirname(ROOT_DIR), '.gclient_entries')
313 if os.path.exists(entries_file):
314 actions.append(Remove(entries_file, dangerous=True))
315
kjellander@webrtc.org89256622014-08-20 12:10:11 +0000316 actions.sort()
317
318 if self._dry_run:
319 for action in actions:
320 action.announce(planning=True)
321 logging.info('Not doing anything because dry-run was specified.')
322 sys.exit(0)
323
324 if any(a.dangerous for a in actions):
325 logging.warn('Dangerous actions:')
326 for action in (a for a in actions if a.dangerous):
327 action.announce(planning=True)
328 print
329
330 if not self._force:
331 logging.error(textwrap.dedent("""\
332 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
333 A C T I O N R E Q I R E D
334 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
335
kjellander844dd2a2016-04-05 00:13:58 -0700336 Setting up the checkout requires creating symlinks to directories in the
337 Chromium checkout inside chromium/src.
338 To avoid disrupting developers, we've chosen to not delete directories
339 forcibly, in case you have some work in progress in one of them :)
kjellander@webrtc.org89256622014-08-20 12:10:11 +0000340
341 ACTION REQUIRED:
342 Before running `gclient sync|runhooks` again, you must run:
343 %s%s --force
344
345 Which will replace all directories which now must be symlinks, after
346 prompting with a summary of the work-to-be-done.
kjellander844dd2a2016-04-05 00:13:58 -0700347 """), 'python ' if sys.platform.startswith('win') else '', __file__)
kjellander@webrtc.org89256622014-08-20 12:10:11 +0000348 sys.exit(1)
349 elif self._prompt:
350 if not query_yes_no('Would you like to perform the above plan?'):
351 sys.exit(1)
352
353 for action in actions:
354 action.announce(planning=False)
355 action.doit(self._links_db)
356
357 if not on_bot and self._force:
358 logging.info('Completed!\n\nNow run `gclient sync|runhooks` again to '
359 'let the remaining hooks (that probably were interrupted) '
360 'execute.')
361
362 def CleanupLinks(self):
363 logging.debug('CleanupLinks')
364 for source, link_path in self._links_db.iteritems():
365 if source == 'SCHEMA_VERSION':
366 continue
367 if os.path.islink(link_path) or sys.platform.startswith('win'):
368 # os.path.islink() always returns false on Windows
369 # See http://bugs.python.org/issue13143.
370 logging.debug('Removing link to %s at %s', source, link_path)
371 if not self._dry_run:
372 if os.path.exists(link_path):
373 if sys.platform.startswith('win') and os.path.isdir(link_path):
Henrik Kjellanderc444de62015-04-29 11:27:22 +0200374 subprocess.check_call(['rmdir', '/q', '/s', link_path],
375 shell=True)
kjellander@webrtc.org89256622014-08-20 12:10:11 +0000376 else:
377 os.remove(link_path)
378 del self._links_db[source]
379
380 @staticmethod
381 def _ActionForPath(source_path, link_path=None, check_fn=None,
382 check_msg=None):
383 """Create zero or more Actions to link to a file or directory.
384
kjellander844dd2a2016-04-05 00:13:58 -0700385 This will be a symlink on POSIX platforms. On Windows it will result in:
386 * a junction for directories
387 * a copied file for single files.
kjellander@webrtc.org89256622014-08-20 12:10:11 +0000388
389 Args:
390 source_path: Path relative to the Chromium checkout root.
391 For readability, the path may contain slashes, which will
392 automatically be converted to the right path delimiter on Windows.
393 link_path: The location for the link to create. If omitted it will be the
394 same path as source_path.
395 check_fn: A function returning true if the type of filesystem object is
396 correct for the attempted call. Otherwise an error message with
397 check_msg will be printed.
398 check_msg: String used to inform the user of an invalid attempt to create
399 a file.
400 Returns:
401 A list of Action objects.
402 """
403 def fix_separators(path):
404 if sys.platform.startswith('win'):
405 return path.replace(os.altsep, os.sep)
406 else:
407 return path
408
409 assert check_fn
410 assert check_msg
411 link_path = link_path or source_path
412 link_path = fix_separators(link_path)
413
414 source_path = fix_separators(source_path)
415 source_path = os.path.join(CHROMIUM_CHECKOUT, source_path)
416 if os.path.exists(source_path) and not check_fn:
kjellander844dd2a2016-04-05 00:13:58 -0700417 raise LinkError('Can only to link to %s: tried to link to: %s' %
418 (check_msg, source_path))
kjellander@webrtc.org89256622014-08-20 12:10:11 +0000419
420 if not os.path.exists(source_path):
421 logging.debug('Silently ignoring missing source: %s. This is to avoid '
422 'errors on platform-specific dependencies.', source_path)
423 return []
424
425 actions = []
426
427 if os.path.exists(link_path) or os.path.islink(link_path):
428 if os.path.islink(link_path):
429 actions.append(Remove(link_path, dangerous=False))
430 elif os.path.isfile(link_path):
431 actions.append(Remove(link_path, dangerous=True))
432 elif os.path.isdir(link_path):
433 actions.append(Rmtree(link_path))
434 else:
435 raise LinkError('Don\'t know how to plan: %s' % link_path)
436
437 # Create parent directories to the target link if needed.
438 target_parent_dirs = os.path.dirname(link_path)
439 if (target_parent_dirs and
440 target_parent_dirs != link_path and
441 not os.path.exists(target_parent_dirs)):
442 actions.append(Makedirs(target_parent_dirs))
443
444 actions.append(Symlink(source_path, link_path))
445
446 return actions
447
448def _initialize_database(filename):
449 links_database = shelve.open(filename)
450
451 # Wipe the database if this version of the script ends up looking at a
452 # newer (future) version of the links db, just to be sure.
453 version = links_database.get('SCHEMA_VERSION')
454 if version and version != SCHEMA_VERSION:
455 logging.info('Found database with schema version %s while this script only '
456 'supports %s. Wiping previous database contents.', version,
457 SCHEMA_VERSION)
458 links_database.clear()
459 links_database['SCHEMA_VERSION'] = SCHEMA_VERSION
460 return links_database
461
462
463def main():
464 on_bot = os.environ.get('CHROME_HEADLESS') == '1'
465
466 parser = optparse.OptionParser()
467 parser.add_option('-d', '--dry-run', action='store_true', default=False,
468 help='Print what would be done, but don\'t perform any '
469 'operations. This will automatically set logging to '
470 'verbose.')
471 parser.add_option('-c', '--clean-only', action='store_true', default=False,
472 help='Only clean previously created links, don\'t create '
473 'new ones. This will automatically set logging to '
474 'verbose.')
475 parser.add_option('-f', '--force', action='store_true', default=on_bot,
476 help='Force link creation. CAUTION: This deletes existing '
477 'folders and files in the locations where links are '
478 'about to be created.')
479 parser.add_option('-n', '--no-prompt', action='store_false', dest='prompt',
480 default=(not on_bot),
481 help='Prompt if we\'re planning to do a dangerous action')
482 parser.add_option('-v', '--verbose', action='store_const',
483 const=logging.DEBUG, default=logging.INFO,
484 help='Print verbose output for debugging.')
485 options, _ = parser.parse_args()
486
487 if options.dry_run or options.force or options.clean_only:
488 options.verbose = logging.DEBUG
489 logging.basicConfig(format='%(message)s', level=options.verbose)
490
491 # Work from the root directory of the checkout.
492 script_dir = os.path.dirname(os.path.abspath(__file__))
493 os.chdir(script_dir)
494
495 if sys.platform.startswith('win'):
496 def is_admin():
497 try:
498 return os.getuid() == 0
499 except AttributeError:
500 return ctypes.windll.shell32.IsUserAnAdmin() != 0
kjellander844dd2a2016-04-05 00:13:58 -0700501 if is_admin():
502 logging.warning('WARNING: On Windows, you no longer need run as '
503 'administrator. Please run with user account privileges.')
kjellander@webrtc.org89256622014-08-20 12:10:11 +0000504
505 if not os.path.exists(CHROMIUM_CHECKOUT):
506 logging.error('Cannot find a Chromium checkout at %s. Did you run "gclient '
507 'sync" before running this script?', CHROMIUM_CHECKOUT)
508 return 2
509
510 links_database = _initialize_database(LINKS_DB)
511 try:
512 symlink_creator = WebRTCLinkSetup(links_database, options.force,
513 options.dry_run, options.prompt)
514 symlink_creator.CleanupLinks()
515 if not options.clean_only:
516 symlink_creator.CreateLinks(on_bot)
517 except LinkError as e:
518 print >> sys.stderr, e.message
519 return 3
520 finally:
521 links_database.close()
522 return 0
523
524
525if __name__ == '__main__':
526 sys.exit(main())