blob: 861ef719bb3e357916436614ef8faeff6638f364 [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',
Henrik Kjellander94a12322015-06-09 14:56:20 +020089 'third_party/android_platform',
kjellander@webrtc.org3bd41562014-09-01 11:06:37 +000090 'third_party/android_tools',
kjellander@webrtc.orgcbe7ca82015-01-06 07:24:27 +000091 'third_party/appurify-python',
kjellander@webrtc.orgb8caf6a2014-09-30 18:05:02 +000092 'third_party/ashmem',
kjellander34a70542015-12-06 10:32:34 -080093 'third_party/catapult',
kjellander53761002015-11-10 10:58:22 -080094 'third_party/icu',
Henrik Kjellandereecbab72015-09-16 19:19:04 +020095 'third_party/ijar',
kjellander@webrtc.orgb8caf6a2014-09-30 18:05:02 +000096 'third_party/jsr-305',
Henrik Kjellander10ba3ee2015-04-29 14:47:53 +020097 'third_party/junit',
kjellander@webrtc.orgb8caf6a2014-09-30 18:05:02 +000098 'third_party/libxml',
Henrik Kjellander10ba3ee2015-04-29 14:47:53 +020099 'third_party/mockito',
kjellander@webrtc.orgb8caf6a2014-09-30 18:05:02 +0000100 'third_party/modp_b64',
kjellander@webrtc.orgcbe7ca82015-01-06 07:24:27 +0000101 'third_party/requests',
Henrik Kjellander10ba3ee2015-04-29 14:47:53 +0200102 'third_party/robolectric',
primianob332e5d2016-01-25 08:13:05 -0800103 'third_party/tcmalloc',
kjellander@webrtc.org3bd41562014-09-01 11:06:37 +0000104 'tools/android',
kjellander@webrtc.orgbfdee692015-02-03 15:23:34 +0000105 'tools/grit',
kjellander34a70542015-12-06 10:32:34 -0800106 'tools/telemetry',
kjellander@webrtc.org3bd41562014-09-01 11:06:37 +0000107 ]
tommide3b0292016-04-22 01:47:02 -0700108else:
109 DIRECTORIES += [
110 'base/third_party/libevent',
111 ]
112
Henrik Kjellanderca843022015-06-09 10:51:22 +0200113if 'ios' in target_os:
114 DIRECTORIES.append('third_party/class-dump')
kjellander@webrtc.org3bd41562014-09-01 11:06:37 +0000115
kjellander@webrtc.org89256622014-08-20 12:10:11 +0000116FILES = {
Henrik Kjellanderd6d27e72015-09-25 22:19:11 +0200117 'tools/isolate_driver.py': None,
kjellander@webrtc.org89256622014-08-20 12:10:11 +0000118 'third_party/BUILD.gn': None,
kjellander@webrtc.org89256622014-08-20 12:10:11 +0000119}
120
kjellander@webrtc.orge94f83a2014-09-18 13:47:23 +0000121ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
kjellander@webrtc.org89256622014-08-20 12:10:11 +0000122CHROMIUM_CHECKOUT = os.path.join('chromium', 'src')
123LINKS_DB = 'links'
124
125# Version management to make future upgrades/downgrades easier to support.
126SCHEMA_VERSION = 1
127
128
129def query_yes_no(question, default=False):
130 """Ask a yes/no question via raw_input() and return their answer.
131
132 Modified from http://stackoverflow.com/a/3041990.
133 """
134 prompt = " [%s/%%s]: "
135 prompt = prompt % ('Y' if default is True else 'y')
136 prompt = prompt % ('N' if default is False else 'n')
137
138 if default is None:
139 default = 'INVALID'
140
141 while True:
142 sys.stdout.write(question + prompt)
143 choice = raw_input().lower()
144 if choice == '' and default != 'INVALID':
145 return default
146
147 if 'yes'.startswith(choice):
148 return True
149 elif 'no'.startswith(choice):
150 return False
151
152 print "Please respond with 'yes' or 'no' (or 'y' or 'n')."
153
154
155# Actions
156class Action(object):
157 def __init__(self, dangerous):
158 self.dangerous = dangerous
159
160 def announce(self, planning):
161 """Log a description of this action.
162
163 Args:
164 planning - True iff we're in the planning stage, False if we're in the
165 doit stage.
166 """
167 pass
168
169 def doit(self, links_db):
170 """Execute the action, recording what we did to links_db, if necessary."""
171 pass
172
173
174class Remove(Action):
175 def __init__(self, path, dangerous):
176 super(Remove, self).__init__(dangerous)
177 self._priority = 0
178 self._path = path
179
180 def announce(self, planning):
181 log = logging.warn
182 filesystem_type = 'file'
183 if not self.dangerous:
184 log = logging.info
185 filesystem_type = 'link'
186 if planning:
187 log('Planning to remove %s: %s', filesystem_type, self._path)
188 else:
189 log('Removing %s: %s', filesystem_type, self._path)
190
Henrik Kjellander57e5fd22015-05-25 12:55:39 +0200191 def doit(self, _):
kjellander@webrtc.org89256622014-08-20 12:10:11 +0000192 os.remove(self._path)
193
194
195class Rmtree(Action):
196 def __init__(self, path):
197 super(Rmtree, self).__init__(dangerous=True)
198 self._priority = 0
199 self._path = path
200
201 def announce(self, planning):
202 if planning:
203 logging.warn('Planning to remove directory: %s', self._path)
204 else:
205 logging.warn('Removing directory: %s', self._path)
206
Henrik Kjellander57e5fd22015-05-25 12:55:39 +0200207 def doit(self, _):
kjellander@webrtc.org89256622014-08-20 12:10:11 +0000208 if sys.platform.startswith('win'):
209 # shutil.rmtree() doesn't work on Windows if any of the directories are
210 # read-only, which svn repositories are.
211 subprocess.check_call(['rd', '/q', '/s', self._path], shell=True)
212 else:
213 shutil.rmtree(self._path)
214
215
216class Makedirs(Action):
217 def __init__(self, path):
218 super(Makedirs, self).__init__(dangerous=False)
219 self._priority = 1
220 self._path = path
221
Henrik Kjellander57e5fd22015-05-25 12:55:39 +0200222 def doit(self, _):
kjellander@webrtc.org89256622014-08-20 12:10:11 +0000223 try:
224 os.makedirs(self._path)
225 except OSError as e:
226 if e.errno != errno.EEXIST:
227 raise
228
229
230class Symlink(Action):
231 def __init__(self, source_path, link_path):
232 super(Symlink, self).__init__(dangerous=False)
233 self._priority = 2
234 self._source_path = source_path
235 self._link_path = link_path
236
237 def announce(self, planning):
238 if planning:
239 logging.info(
240 'Planning to create link from %s to %s', self._link_path,
241 self._source_path)
242 else:
243 logging.debug(
244 'Linking from %s to %s', self._link_path, self._source_path)
245
246 def doit(self, links_db):
247 # Files not in the root directory need relative path calculation.
248 # On Windows, use absolute paths instead since NTFS doesn't seem to support
249 # relative paths for symlinks.
250 if sys.platform.startswith('win'):
251 source_path = os.path.abspath(self._source_path)
252 else:
253 if os.path.dirname(self._link_path) != self._link_path:
254 source_path = os.path.relpath(self._source_path,
255 os.path.dirname(self._link_path))
256
257 os.symlink(source_path, os.path.abspath(self._link_path))
258 links_db[self._source_path] = self._link_path
259
260
261class LinkError(IOError):
262 """Failed to create a link."""
263 pass
264
265
kjellander844dd2a2016-04-05 00:13:58 -0700266# Use junctions instead of symlinks on the Windows platform.
kjellander@webrtc.org89256622014-08-20 12:10:11 +0000267if sys.platform.startswith('win'):
268 def symlink(source_path, link_path):
kjellander844dd2a2016-04-05 00:13:58 -0700269 if os.path.isdir(source_path):
270 subprocess.check_call(['cmd.exe', '/c', 'mklink', '/J', link_path,
271 source_path])
272 else:
273 # Don't create symlinks to files on Windows, just copy the file instead
274 # (there's no way to create a link without administrator's privileges).
275 shutil.copy(source_path, link_path)
kjellander@webrtc.org89256622014-08-20 12:10:11 +0000276 os.symlink = symlink
277
278
Henrik Kjellander57e5fd22015-05-25 12:55:39 +0200279class WebRTCLinkSetup(object):
kjellander@webrtc.org89256622014-08-20 12:10:11 +0000280 def __init__(self, links_db, force=False, dry_run=False, prompt=False):
281 self._force = force
282 self._dry_run = dry_run
283 self._prompt = prompt
284 self._links_db = links_db
285
286 def CreateLinks(self, on_bot):
287 logging.debug('CreateLinks')
288 # First, make a plan of action
289 actions = []
290
291 for source_path, link_path in FILES.iteritems():
292 actions += self._ActionForPath(
293 source_path, link_path, check_fn=os.path.isfile, check_msg='files')
294 for source_dir in DIRECTORIES:
295 actions += self._ActionForPath(
296 source_dir, None, check_fn=os.path.isdir,
297 check_msg='directories')
298
kjellander@webrtc.orge94f83a2014-09-18 13:47:23 +0000299 if not on_bot and self._force:
300 # When making the manual switch from legacy SVN checkouts to the new
301 # Git-based Chromium DEPS, the .gclient_entries file that contains cached
302 # URLs for all DEPS entries must be removed to avoid future sync problems.
303 entries_file = os.path.join(os.path.dirname(ROOT_DIR), '.gclient_entries')
304 if os.path.exists(entries_file):
305 actions.append(Remove(entries_file, dangerous=True))
306
kjellander@webrtc.org89256622014-08-20 12:10:11 +0000307 actions.sort()
308
309 if self._dry_run:
310 for action in actions:
311 action.announce(planning=True)
312 logging.info('Not doing anything because dry-run was specified.')
313 sys.exit(0)
314
315 if any(a.dangerous for a in actions):
316 logging.warn('Dangerous actions:')
317 for action in (a for a in actions if a.dangerous):
318 action.announce(planning=True)
319 print
320
321 if not self._force:
322 logging.error(textwrap.dedent("""\
323 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
324 A C T I O N R E Q I R E D
325 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
326
kjellander844dd2a2016-04-05 00:13:58 -0700327 Setting up the checkout requires creating symlinks to directories in the
328 Chromium checkout inside chromium/src.
329 To avoid disrupting developers, we've chosen to not delete directories
330 forcibly, in case you have some work in progress in one of them :)
kjellander@webrtc.org89256622014-08-20 12:10:11 +0000331
332 ACTION REQUIRED:
333 Before running `gclient sync|runhooks` again, you must run:
334 %s%s --force
335
336 Which will replace all directories which now must be symlinks, after
337 prompting with a summary of the work-to-be-done.
kjellander844dd2a2016-04-05 00:13:58 -0700338 """), 'python ' if sys.platform.startswith('win') else '', __file__)
kjellander@webrtc.org89256622014-08-20 12:10:11 +0000339 sys.exit(1)
340 elif self._prompt:
341 if not query_yes_no('Would you like to perform the above plan?'):
342 sys.exit(1)
343
344 for action in actions:
345 action.announce(planning=False)
346 action.doit(self._links_db)
347
348 if not on_bot and self._force:
349 logging.info('Completed!\n\nNow run `gclient sync|runhooks` again to '
350 'let the remaining hooks (that probably were interrupted) '
351 'execute.')
352
353 def CleanupLinks(self):
354 logging.debug('CleanupLinks')
355 for source, link_path in self._links_db.iteritems():
356 if source == 'SCHEMA_VERSION':
357 continue
358 if os.path.islink(link_path) or sys.platform.startswith('win'):
359 # os.path.islink() always returns false on Windows
360 # See http://bugs.python.org/issue13143.
361 logging.debug('Removing link to %s at %s', source, link_path)
362 if not self._dry_run:
363 if os.path.exists(link_path):
364 if sys.platform.startswith('win') and os.path.isdir(link_path):
Henrik Kjellanderc444de62015-04-29 11:27:22 +0200365 subprocess.check_call(['rmdir', '/q', '/s', link_path],
366 shell=True)
kjellander@webrtc.org89256622014-08-20 12:10:11 +0000367 else:
368 os.remove(link_path)
369 del self._links_db[source]
370
371 @staticmethod
372 def _ActionForPath(source_path, link_path=None, check_fn=None,
373 check_msg=None):
374 """Create zero or more Actions to link to a file or directory.
375
kjellander844dd2a2016-04-05 00:13:58 -0700376 This will be a symlink on POSIX platforms. On Windows it will result in:
377 * a junction for directories
378 * a copied file for single files.
kjellander@webrtc.org89256622014-08-20 12:10:11 +0000379
380 Args:
381 source_path: Path relative to the Chromium checkout root.
382 For readability, the path may contain slashes, which will
383 automatically be converted to the right path delimiter on Windows.
384 link_path: The location for the link to create. If omitted it will be the
385 same path as source_path.
386 check_fn: A function returning true if the type of filesystem object is
387 correct for the attempted call. Otherwise an error message with
388 check_msg will be printed.
389 check_msg: String used to inform the user of an invalid attempt to create
390 a file.
391 Returns:
392 A list of Action objects.
393 """
394 def fix_separators(path):
395 if sys.platform.startswith('win'):
396 return path.replace(os.altsep, os.sep)
397 else:
398 return path
399
400 assert check_fn
401 assert check_msg
402 link_path = link_path or source_path
403 link_path = fix_separators(link_path)
404
405 source_path = fix_separators(source_path)
406 source_path = os.path.join(CHROMIUM_CHECKOUT, source_path)
407 if os.path.exists(source_path) and not check_fn:
kjellander844dd2a2016-04-05 00:13:58 -0700408 raise LinkError('Can only to link to %s: tried to link to: %s' %
409 (check_msg, source_path))
kjellander@webrtc.org89256622014-08-20 12:10:11 +0000410
411 if not os.path.exists(source_path):
412 logging.debug('Silently ignoring missing source: %s. This is to avoid '
413 'errors on platform-specific dependencies.', source_path)
414 return []
415
416 actions = []
417
418 if os.path.exists(link_path) or os.path.islink(link_path):
419 if os.path.islink(link_path):
420 actions.append(Remove(link_path, dangerous=False))
421 elif os.path.isfile(link_path):
422 actions.append(Remove(link_path, dangerous=True))
423 elif os.path.isdir(link_path):
424 actions.append(Rmtree(link_path))
425 else:
426 raise LinkError('Don\'t know how to plan: %s' % link_path)
427
428 # Create parent directories to the target link if needed.
429 target_parent_dirs = os.path.dirname(link_path)
430 if (target_parent_dirs and
431 target_parent_dirs != link_path and
432 not os.path.exists(target_parent_dirs)):
433 actions.append(Makedirs(target_parent_dirs))
434
435 actions.append(Symlink(source_path, link_path))
436
437 return actions
438
439def _initialize_database(filename):
440 links_database = shelve.open(filename)
441
442 # Wipe the database if this version of the script ends up looking at a
443 # newer (future) version of the links db, just to be sure.
444 version = links_database.get('SCHEMA_VERSION')
445 if version and version != SCHEMA_VERSION:
446 logging.info('Found database with schema version %s while this script only '
447 'supports %s. Wiping previous database contents.', version,
448 SCHEMA_VERSION)
449 links_database.clear()
450 links_database['SCHEMA_VERSION'] = SCHEMA_VERSION
451 return links_database
452
453
454def main():
455 on_bot = os.environ.get('CHROME_HEADLESS') == '1'
456
457 parser = optparse.OptionParser()
458 parser.add_option('-d', '--dry-run', action='store_true', default=False,
459 help='Print what would be done, but don\'t perform any '
460 'operations. This will automatically set logging to '
461 'verbose.')
462 parser.add_option('-c', '--clean-only', action='store_true', default=False,
463 help='Only clean previously created links, don\'t create '
464 'new ones. This will automatically set logging to '
465 'verbose.')
466 parser.add_option('-f', '--force', action='store_true', default=on_bot,
467 help='Force link creation. CAUTION: This deletes existing '
468 'folders and files in the locations where links are '
469 'about to be created.')
470 parser.add_option('-n', '--no-prompt', action='store_false', dest='prompt',
471 default=(not on_bot),
472 help='Prompt if we\'re planning to do a dangerous action')
473 parser.add_option('-v', '--verbose', action='store_const',
474 const=logging.DEBUG, default=logging.INFO,
475 help='Print verbose output for debugging.')
476 options, _ = parser.parse_args()
477
478 if options.dry_run or options.force or options.clean_only:
479 options.verbose = logging.DEBUG
480 logging.basicConfig(format='%(message)s', level=options.verbose)
481
482 # Work from the root directory of the checkout.
483 script_dir = os.path.dirname(os.path.abspath(__file__))
484 os.chdir(script_dir)
485
486 if sys.platform.startswith('win'):
487 def is_admin():
488 try:
489 return os.getuid() == 0
490 except AttributeError:
491 return ctypes.windll.shell32.IsUserAnAdmin() != 0
kjellander844dd2a2016-04-05 00:13:58 -0700492 if is_admin():
493 logging.warning('WARNING: On Windows, you no longer need run as '
494 'administrator. Please run with user account privileges.')
kjellander@webrtc.org89256622014-08-20 12:10:11 +0000495
496 if not os.path.exists(CHROMIUM_CHECKOUT):
497 logging.error('Cannot find a Chromium checkout at %s. Did you run "gclient '
498 'sync" before running this script?', CHROMIUM_CHECKOUT)
499 return 2
500
501 links_database = _initialize_database(LINKS_DB)
502 try:
503 symlink_creator = WebRTCLinkSetup(links_database, options.force,
504 options.dry_run, options.prompt)
505 symlink_creator.CleanupLinks()
506 if not options.clean_only:
507 symlink_creator.CreateLinks(on_bot)
508 except LinkError as e:
509 print >> sys.stderr, e.message
510 return 3
511 finally:
512 links_database.close()
513 return 0
514
515
516if __name__ == '__main__':
517 sys.exit(main())