blob: a6a460744e3c93e162800aa3f4f16168b2246082 [file] [log] [blame]
Kuang-che Wu875c89a2020-01-08 14:30:55 +08001#!/usr/bin/env python3
Kuang-che Wu41e8b592018-09-25 17:01:30 +08002# -*- coding: utf-8 -*-
3# Copyright 2018 The Chromium OS Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6"""Helper script to prepare source trees for ChromeOS bisection.
7
8Typical usage:
9
10 Initial setup:
11 $ %(prog)s init --chromeos
12 $ %(prog)s init --chrome
13 $ %(prog)s init --android=pi-arc-dev
14
15 Sync code if necessary:
16 $ %(prog)s sync
17
18 Create source trees for bisection
19 $ %(prog)s new --session=12345
20
21 After bisection finished, delete trees
22 $ %(prog)s delete --session=12345
23"""
24from __future__ import print_function
25import argparse
26import csv
Zheng-Jie Changcd424c12020-01-10 14:32:08 +080027import glob
Kuang-che Wu41e8b592018-09-25 17:01:30 +080028import logging
29import os
Kuang-che Wu22f207e2019-02-23 12:53:53 +080030import subprocess
Kuang-che Wu67be74b2018-10-15 14:17:26 +080031import time
Kuang-che Wu7d0c7592019-09-16 09:59:28 +080032import xml.etree.ElementTree
Kuang-che Wu41e8b592018-09-25 17:01:30 +080033
Kuang-che Wud3a4e842019-12-11 12:15:23 +080034import six
Kuang-che Wua7ddf9b2019-11-25 18:59:57 +080035from six.moves import urllib
36
Kuang-che Wu41e8b592018-09-25 17:01:30 +080037from bisect_kit import common
38from bisect_kit import configure
39from bisect_kit import gclient_util
40from bisect_kit import git_util
Kuang-che Wudc714412018-10-17 16:06:39 +080041from bisect_kit import locking
Kuang-che Wu41e8b592018-09-25 17:01:30 +080042from bisect_kit import repo_util
43from bisect_kit import util
44
45DEFAULT_MIRROR_BASE = os.path.expanduser('~/git-mirrors')
46DEFAULT_WORK_BASE = os.path.expanduser('~/bisect-workdir')
47CHECKOUT_TEMPLATE_NAME = 'template'
48
49logger = logging.getLogger(__name__)
50
51
52class DefaultProjectPathFactory(object):
53 """Factory for chromeos/chrome/android source tree paths."""
54
55 def __init__(self, mirror_base, work_base, session):
56 self.mirror_base = mirror_base
57 self.work_base = work_base
58 self.session = session
59
60 def get_chromeos_mirror(self):
61 return os.path.join(self.mirror_base, 'chromeos')
62
63 def get_chromeos_tree(self):
64 return os.path.join(self.work_base, self.session, 'chromeos')
65
66 def get_android_mirror(self, branch):
67 return os.path.join(self.mirror_base, 'android.%s' % branch)
68
69 def get_android_tree(self, branch):
70 return os.path.join(self.work_base, self.session, 'android.%s' % branch)
71
72 def get_chrome_cache(self):
73 return os.path.join(self.mirror_base, 'chrome')
74
75 def get_chrome_tree(self):
76 return os.path.join(self.work_base, self.session, 'chrome')
77
78
79def subvolume_or_makedirs(opts, path):
80 if os.path.exists(path):
81 return
82
83 path = os.path.abspath(path)
84 if opts.btrfs:
85 dirname, basename = os.path.split(path)
86 if not os.path.exists(dirname):
87 os.makedirs(dirname)
88 util.check_call('btrfs', 'subvolume', 'create', basename, cwd=dirname)
89 else:
90 os.makedirs(path)
91
92
93def is_btrfs_subvolume(path):
94 if util.check_output('stat', '-f', '--format=%T', path).strip() != 'btrfs':
95 return False
96 return util.check_output('stat', '--format=%i', path).strip() == '256'
97
98
99def snapshot_or_copytree(src, dst):
100 assert os.path.isdir(src), '%s does not exist' % src
101 assert os.path.isdir(os.path.dirname(dst))
102
103 # Make sure dst do not exist, otherwise it becomes "dst/name" (one extra
104 # depth) instead of "dst".
105 assert not os.path.exists(dst)
106
107 if is_btrfs_subvolume(src):
108 util.check_call('btrfs', 'subvolume', 'snapshot', src, dst)
109 else:
110 # -a for recursion and preserve all attributes.
111 util.check_call('cp', '-a', src, dst)
112
113
Kuang-che Wubfa64482018-10-16 11:49:49 +0800114def collect_removed_manifest_repos(repo_dir, last_sync_time, only_branch=None):
Kuang-che Wu67be74b2018-10-15 14:17:26 +0800115 manifest_dir = os.path.join(repo_dir, '.repo', 'manifests')
Kuang-che Wu67be74b2018-10-15 14:17:26 +0800116 manifest_path = 'default.xml'
117 manifest_full_path = os.path.join(manifest_dir, manifest_path)
118 # hack for chromeos symlink
119 if os.path.islink(manifest_full_path):
120 manifest_path = os.readlink(manifest_full_path)
121
122 parser = repo_util.ManifestParser(manifest_dir)
123 latest = None
124 removed = {}
125 for _, git_rev in reversed(
126 parser.enumerate_manifest_commits(last_sync_time, None, manifest_path)):
Kuang-che Wu7d0c7592019-09-16 09:59:28 +0800127 try:
128 root = parser.parse_xml_recursive(git_rev, manifest_path)
129 except xml.etree.ElementTree.ParseError:
130 logger.warning('%s %s@%s syntax error, skip', manifest_dir, manifest_path,
131 git_rev[:12])
132 continue
Kuang-che Wubfa64482018-10-16 11:49:49 +0800133 if (only_branch and root.find('default') is not None and
134 root.find('default').get('revision') != only_branch):
135 break
Kuang-che Wu67be74b2018-10-15 14:17:26 +0800136 entries = parser.process_parsed_result(root)
137 if latest is None:
138 assert entries is not None
139 latest = entries
140 continue
141
142 for path, path_spec in entries.items():
143 if path in latest:
144 continue
145 if path in removed:
146 continue
147 removed[path] = path_spec
148
149 return removed
150
151
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800152def setup_chromeos_repos(opts, path_factory):
153 chromeos_mirror = path_factory.get_chromeos_mirror()
154 chromeos_tree = path_factory.get_chromeos_tree()
155 subvolume_or_makedirs(opts, chromeos_mirror)
156 subvolume_or_makedirs(opts, chromeos_tree)
157
158 manifest_url = (
159 'https://chrome-internal.googlesource.com/chromeos/manifest-internal')
160 repo_url = 'https://chromium.googlesource.com/external/repo.git'
161
162 if os.path.exists(os.path.join(chromeos_mirror, '.repo', 'manifests')):
163 logger.warning(
164 '%s has already been initialized, assume it is setup properly',
165 chromeos_mirror)
166 else:
167 logger.info('repo init for chromeos mirror')
168 repo_util.init(
169 chromeos_mirror,
170 manifest_url=manifest_url,
171 repo_url=repo_url,
172 mirror=True)
173
174 local_manifest_dir = os.path.join(chromeos_mirror, '.repo',
175 'local_manifests')
176 os.mkdir(local_manifest_dir)
177 with open(os.path.join(local_manifest_dir, 'manifest-versions.xml'),
178 'w') as f:
Kuang-che Wuae6824b2019-08-27 22:20:01 +0800179 f.write("""<?xml version="1.0" encoding="UTF-8"?>
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800180 <manifest>
181 <project name="chromeos/manifest-versions" remote="cros-internal" />
182 </manifest>
Kuang-che Wuae6824b2019-08-27 22:20:01 +0800183 """)
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800184
185 logger.info('repo init for chromeos tree')
186 repo_util.init(
187 chromeos_tree,
188 manifest_url=manifest_url,
189 repo_url=repo_url,
190 reference=chromeos_mirror)
191
Kuang-che Wudc714412018-10-17 16:06:39 +0800192 with locking.lock_file(
193 os.path.join(chromeos_mirror, locking.LOCK_FILE_FOR_MIRROR_SYNC)):
194 logger.info('repo sync for chromeos mirror (this takes hours; be patient)')
195 repo_util.sync(chromeos_mirror)
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800196
197 logger.info('repo sync for chromeos tree')
198 repo_util.sync(chromeos_tree)
199
200
Kuang-che Wu67be74b2018-10-15 14:17:26 +0800201def read_last_sync_time(repo_dir):
202 timestamp_path = os.path.join(repo_dir, 'last_sync_time')
203 if os.path.exists(timestamp_path):
204 with open(timestamp_path) as f:
205 return int(f.read())
206 else:
207 # 4 months should be enough for most bisect cases.
208 return int(time.time()) - 86400 * 120
209
210
211def write_sync_time(repo_dir, sync_time):
212 timestamp_path = os.path.join(repo_dir, 'last_sync_time')
213 with open(timestamp_path, 'w') as f:
214 f.write('%d\n' % sync_time)
215
216
217def write_extra_manifest_to_mirror(repo_dir, removed):
218 local_manifest_dir = os.path.join(repo_dir, '.repo', 'local_manifests')
219 if not os.path.exists(local_manifest_dir):
220 os.mkdir(local_manifest_dir)
221 with open(os.path.join(local_manifest_dir, 'deleted-repos.xml'), 'w') as f:
Kuang-che Wuae6824b2019-08-27 22:20:01 +0800222 f.write("""<?xml version="1.0" encoding="UTF-8"?>\n<manifest>\n""")
Kuang-che Wu67be74b2018-10-15 14:17:26 +0800223 remotes = {}
224 for path_spec in removed.values():
Kuang-che Wua7ddf9b2019-11-25 18:59:57 +0800225 scheme, netloc, remote_path = urllib.parse.urlsplit(
226 path_spec.repo_url)[:3]
Kuang-che Wu67be74b2018-10-15 14:17:26 +0800227 assert remote_path[0] == '/'
228 remote_path = remote_path[1:]
229 if (scheme, netloc) not in remotes:
230 remote_name = 'remote_for_deleted_repo_%s' % (scheme + netloc)
231 remotes[scheme, netloc] = remote_name
Kuang-che Wuae6824b2019-08-27 22:20:01 +0800232 f.write(""" <remote name="%s" fetch="%s" />\n""" %
Kuang-che Wu67be74b2018-10-15 14:17:26 +0800233 (remote_name, '%s://%s' % (scheme, netloc)))
Kuang-che Wubfa64482018-10-16 11:49:49 +0800234 f.write(
Kuang-che Wuae6824b2019-08-27 22:20:01 +0800235 """ <project name="%s" path="%s" remote="%s" revision="%s" />\n""" %
Kuang-che Wubfa64482018-10-16 11:49:49 +0800236 (remote_path, path_spec.path, remotes[scheme, netloc], path_spec.at))
Kuang-che Wuae6824b2019-08-27 22:20:01 +0800237 f.write("""</manifest>\n""")
Kuang-che Wu67be74b2018-10-15 14:17:26 +0800238
239
Kuang-che Wubfa64482018-10-16 11:49:49 +0800240def generate_extra_manifest_for_deleted_repo(repo_dir, only_branch=None):
241 last_sync_time = read_last_sync_time(repo_dir)
242 removed = collect_removed_manifest_repos(
243 repo_dir, last_sync_time, only_branch=only_branch)
244 write_extra_manifest_to_mirror(repo_dir, removed)
245 logger.info('since last sync, %d repo got removed', len(removed))
Kuang-che Wub76b7f62019-09-16 10:06:18 +0800246 return len(removed)
Kuang-che Wubfa64482018-10-16 11:49:49 +0800247
248
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800249def sync_chromeos_code(opts, path_factory):
250 del opts # unused
251
Kuang-che Wu67be74b2018-10-15 14:17:26 +0800252 start_sync_time = int(time.time())
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800253 chromeos_mirror = path_factory.get_chromeos_mirror()
Kuang-che Wu67be74b2018-10-15 14:17:26 +0800254
Kuang-che Wu67be74b2018-10-15 14:17:26 +0800255 logger.info('repo sync for chromeos mirror')
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800256 repo_util.sync(chromeos_mirror)
Kuang-che Wub76b7f62019-09-16 10:06:18 +0800257 # If there are repos deleted after last sync, generate custom manifest and
258 # sync again for those repos. So we can mirror commits just before the repo
259 # deletion.
260 if generate_extra_manifest_for_deleted_repo(chromeos_mirror) != 0:
261 logger.info('repo sync again')
262 repo_util.sync(chromeos_mirror)
Kuang-che Wu67be74b2018-10-15 14:17:26 +0800263 write_sync_time(chromeos_mirror, start_sync_time)
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800264
265 logger.info('repo sync for chromeos tree')
266 chromeos_tree = path_factory.get_chromeos_tree()
267 repo_util.sync(chromeos_tree)
268
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800269
270def query_chrome_latest_branch():
Kuang-che Wud3a4e842019-12-11 12:15:23 +0800271 result = 0
Kuang-che Wua7ddf9b2019-11-25 18:59:57 +0800272 r = urllib.request.urlopen('https://omahaproxy.appspot.com/all')
Kuang-che Wud3a4e842019-12-11 12:15:23 +0800273 # TODO(kcwu): use io.TextIOWrapper after migrated to python3
274 content = r.read().decode('utf8')
275 for row in csv.DictReader(six.StringIO(content)):
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800276 if row['true_branch'].isdigit():
277 result = max(result, int(row['true_branch']))
278 return result
279
280
281def setup_chrome_repos(opts, path_factory):
282 chrome_cache = path_factory.get_chrome_cache()
283 subvolume_or_makedirs(opts, chrome_cache)
284 chrome_tree = path_factory.get_chrome_tree()
285 subvolume_or_makedirs(opts, chrome_tree)
286
287 latest_branch = query_chrome_latest_branch()
288 logger.info('latest chrome branch is %d', latest_branch)
289 assert latest_branch
Kuang-che Wuae6824b2019-08-27 22:20:01 +0800290 spec = """
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800291solutions = [
292 { "name" : "buildspec",
293 "url" : "https://chrome-internal.googlesource.com/a/chrome/tools/buildspec.git",
294 "deps_file" : "branches/%d/DEPS",
295 "custom_deps" : {
296 },
297 "custom_vars": {'checkout_src_internal': True},
298 },
299]
300target_os = ['chromeos']
301cache_dir = %r
Kuang-che Wuae6824b2019-08-27 22:20:01 +0800302""" % (latest_branch, chrome_cache)
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800303
Kuang-che Wudc714412018-10-17 16:06:39 +0800304 with locking.lock_file(
305 os.path.join(chrome_cache, locking.LOCK_FILE_FOR_MIRROR_SYNC)):
306 logger.info('gclient config for chrome')
307 gclient_util.config(chrome_tree, spec=spec)
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800308
Kuang-che Wudc714412018-10-17 16:06:39 +0800309 is_first_sync = not os.listdir(chrome_cache)
310 if is_first_sync:
311 logger.info('gclient sync for chrome (this takes hours; be patient)')
312 else:
313 logger.info('gclient sync for chrome')
314 gclient_util.sync(
315 chrome_tree, with_branch_heads=True, with_tags=True, ignore_locks=True)
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800316
Kuang-che Wudc714412018-10-17 16:06:39 +0800317 # It's possible that some repos are removed from latest branch and thus
318 # their commit history is not fetched in recent gclient sync. So we call
319 # 'git fetch' for all existing git mirrors.
320 # TODO(kcwu): only sync repos not in DEPS files of latest branch
321 logger.info('additional sync for chrome mirror')
322 for git_repo_name in os.listdir(chrome_cache):
323 # another gclient is running or leftover of previous run; skip
324 if git_repo_name.startswith('_cache_tmp'):
325 continue
326 git_repo = os.path.join(chrome_cache, git_repo_name)
Kuang-che Wu08366542019-01-12 12:37:49 +0800327 if not git_util.is_git_bare_dir(git_repo):
Kuang-che Wudc714412018-10-17 16:06:39 +0800328 continue
Kuang-che Wu2b1286b2019-05-20 20:37:26 +0800329 git_util.fetch(git_repo)
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800330
Kuang-che Wu1e49f512018-12-06 15:27:42 +0800331 # Some repos were removed from the DEPS and won't be synced here. They will
332 # be synced during DEPS file processing because the necessary information
333 # requires full DEPS parsing. (crbug.com/902238)
334
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800335
336def sync_chrome_code(opts, path_factory):
337 # The sync step is identical to the initial gclient config step.
338 setup_chrome_repos(opts, path_factory)
339
340
341def setup_android_repos(opts, path_factory, branch):
342 android_mirror = path_factory.get_android_mirror(branch)
343 android_tree = path_factory.get_android_tree(branch)
344 subvolume_or_makedirs(opts, android_mirror)
345 subvolume_or_makedirs(opts, android_tree)
346
347 manifest_url = ('persistent-https://googleplex-android.git.corp.google.com'
348 '/platform/manifest')
349 repo_url = 'https://gerrit.googlesource.com/git-repo'
350
351 if os.path.exists(os.path.join(android_mirror, '.repo', 'manifests')):
352 logger.warning(
353 '%s has already been initialized, assume it is setup properly',
354 android_mirror)
355 else:
356 logger.info('repo init for android mirror branch=%s', branch)
357 repo_util.init(
358 android_mirror,
359 manifest_url=manifest_url,
360 repo_url=repo_url,
361 manifest_branch=branch,
362 mirror=True)
363
364 logger.info('repo init for android tree branch=%s', branch)
365 repo_util.init(
366 android_tree,
367 manifest_url=manifest_url,
368 repo_url=repo_url,
369 manifest_branch=branch,
370 reference=android_mirror)
371
372 logger.info('repo sync for android mirror (this takes hours; be patient)')
373 repo_util.sync(android_mirror, current_branch=True)
374
375 logger.info('repo sync for android tree branch=%s', branch)
376 repo_util.sync(android_tree, current_branch=True)
377
378
379def sync_android_code(opts, path_factory, branch):
380 del opts # unused
Kuang-che Wu67be74b2018-10-15 14:17:26 +0800381 start_sync_time = int(time.time())
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800382 android_mirror = path_factory.get_android_mirror(branch)
383 android_tree = path_factory.get_android_tree(branch)
384
Kuang-che Wudc714412018-10-17 16:06:39 +0800385 with locking.lock_file(
386 os.path.join(android_mirror, locking.LOCK_FILE_FOR_MIRROR_SYNC)):
387 logger.info('repo sync for android mirror branch=%s', branch)
Kuang-che Wub76b7f62019-09-16 10:06:18 +0800388 repo_util.sync(android_mirror, current_branch=True)
Kuang-che Wudc714412018-10-17 16:06:39 +0800389 # Android usually big jump between milestone releases and add/delete lots of
390 # repos when switch releases. Because it's infeasible to bisect between such
391 # big jump, the deleted repo is useless. In order to save disk, do not sync
392 # repos deleted in other branches.
Kuang-che Wub76b7f62019-09-16 10:06:18 +0800393 if generate_extra_manifest_for_deleted_repo(
394 android_mirror, only_branch=branch) != 0:
395 logger.info('repo sync again')
396 repo_util.sync(android_mirror, current_branch=True)
Kuang-che Wudc714412018-10-17 16:06:39 +0800397 write_sync_time(android_mirror, start_sync_time)
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800398
399 logger.info('repo sync for android tree branch=%s', branch)
400 repo_util.sync(android_tree, current_branch=True)
401
402
403def cmd_init(opts):
404 path_factory = DefaultProjectPathFactory(opts.mirror_base, opts.work_base,
405 CHECKOUT_TEMPLATE_NAME)
406
407 if opts.chromeos:
408 setup_chromeos_repos(opts, path_factory)
409 if opts.chrome:
410 setup_chrome_repos(opts, path_factory)
411 for branch in opts.android:
412 setup_android_repos(opts, path_factory, branch)
413
414
415def enumerate_android_branches_available(base):
416 branches = []
417 for name in os.listdir(base):
418 if name.startswith('android.'):
419 branches.append(name.partition('.')[2])
420 return branches
421
422
Kuang-che Wu22f207e2019-02-23 12:53:53 +0800423def do_sync(opts):
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800424 path_factory = DefaultProjectPathFactory(opts.mirror_base, opts.work_base,
425 CHECKOUT_TEMPLATE_NAME)
426
427 sync_all = False
428 if not opts.chromeos and not opts.chrome and not opts.android:
429 logger.info('sync trees for all')
430 sync_all = True
431
432 if sync_all or opts.chromeos:
433 sync_chromeos_code(opts, path_factory)
434 if sync_all or opts.chrome:
435 sync_chrome_code(opts, path_factory)
436
437 if sync_all:
438 android_branches = enumerate_android_branches_available(opts.mirror_base)
439 else:
440 android_branches = opts.android
441 for branch in android_branches:
442 sync_android_code(opts, path_factory, branch)
443
444
Kuang-che Wu22f207e2019-02-23 12:53:53 +0800445def cmd_sync(opts):
446 try:
447 do_sync(opts)
448 except subprocess.CalledProcessError:
449 # Sync may fail due to network or server issues.
450 logger.exception('do_sync failed, will retry one minute later')
451 time.sleep(60)
452 do_sync(opts)
453
454
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800455def cmd_new(opts):
456 work_dir = os.path.join(opts.work_base, opts.session)
457 if not os.path.exists(work_dir):
458 os.makedirs(work_dir)
459
460 template_factory = DefaultProjectPathFactory(opts.mirror_base, opts.work_base,
461 CHECKOUT_TEMPLATE_NAME)
462 path_factory = DefaultProjectPathFactory(opts.mirror_base, opts.work_base,
463 opts.session)
464
465 prepare_all = False
466 if not opts.chromeos and not opts.chrome and not opts.android:
467 logger.info('prepare trees for all')
468 prepare_all = True
469
470 chromeos_template = template_factory.get_chromeos_tree()
471 if (prepare_all and os.path.exists(chromeos_template)) or opts.chromeos:
472 logger.info('prepare tree for chromeos, %s',
473 path_factory.get_chromeos_tree())
474 snapshot_or_copytree(chromeos_template, path_factory.get_chromeos_tree())
475
476 chrome_template = template_factory.get_chrome_tree()
477 if (prepare_all and os.path.exists(chrome_template)) or opts.chrome:
478 logger.info('prepare tree for chrome, %s', path_factory.get_chrome_tree())
479 snapshot_or_copytree(chrome_template, path_factory.get_chrome_tree())
480
481 if prepare_all:
482 android_branches = enumerate_android_branches_available(opts.mirror_base)
483 else:
484 android_branches = opts.android
485 for branch in android_branches:
486 logger.info('prepare tree for android branch=%s, %s', branch,
487 path_factory.get_android_tree(branch))
488 snapshot_or_copytree(
489 template_factory.get_android_tree(branch),
490 path_factory.get_android_tree(branch))
491
492
493def delete_tree(path):
494 if is_btrfs_subvolume(path):
Kuang-che Wu9d3ccde2019-01-03 17:06:09 +0800495 # btrfs should be mounted with 'user_subvol_rm_allowed' option and thus
496 # normal user permission is enough.
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800497 util.check_call('btrfs', 'subvolume', 'delete', path)
498 else:
Kuang-che Wu9d3ccde2019-01-03 17:06:09 +0800499 util.check_call('sudo', 'rm', '-rf', path)
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800500
501
502def cmd_list(opts):
503 print('%-20s %s' % ('Session', 'Path'))
504 for name in os.listdir(opts.work_base):
505 if name == CHECKOUT_TEMPLATE_NAME:
506 continue
507 path = os.path.join(opts.work_base, name)
508 print('%-20s %s' % (name, path))
509
510
511def cmd_delete(opts):
512 assert opts.session
513 path_factory = DefaultProjectPathFactory(opts.mirror_base, opts.work_base,
514 opts.session)
515
516 chromeos_tree = path_factory.get_chromeos_tree()
517 if os.path.exists(chromeos_tree):
518 if os.path.exists(os.path.join(chromeos_tree, 'chromite')):
519 # ignore error
520 util.call('cros_sdk', '--unmount', cwd=chromeos_tree)
521 delete_tree(chromeos_tree)
522
523 chrome_tree = path_factory.get_chrome_tree()
524 if os.path.exists(chrome_tree):
525 delete_tree(chrome_tree)
526
527 android_branches = enumerate_android_branches_available(opts.mirror_base)
528 for branch in android_branches:
529 android_tree = path_factory.get_android_tree(branch)
530 if os.path.exists(android_tree):
531 delete_tree(android_tree)
532
533 os.rmdir(os.path.join(opts.work_base, opts.session))
534
Zheng-Jie Changcd424c12020-01-10 14:32:08 +0800535 # remove caches
536 chromeos_root = os.getenv('DEFAULT_CHROMEOS_ROOT')
537 if chromeos_root:
538 path = os.path.join(chromeos_root, 'devserver/static')
539 if os.path.exists(path):
540 logger.info('remove cache: %s', path)
541 util.call('cros', 'clean', '--flash', cwd=path)
542
543 for path in glob.glob(os.path.join(chromeos_root, 'chroot/tmp/*')):
544 logger.info('remove cache: %s', path)
545 delete_tree(path)
546
547 for path in glob.glob(
548 os.path.join(path_factory.get_chrome_cache(), '_cache_*')):
549 logger.info('remove cache: %s', path)
550 delete_tree(path)
551
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800552
553def create_parser():
554 parser = argparse.ArgumentParser(
555 formatter_class=argparse.RawDescriptionHelpFormatter, description=__doc__)
556 parser.add_argument(
557 '--mirror_base',
558 metavar='MIRROR_BASE',
559 default=configure.get('MIRROR_BASE', DEFAULT_MIRROR_BASE),
560 help='Directory for mirrors (default: %(default)s)')
561 parser.add_argument(
562 '--work_base',
563 metavar='WORK_BASE',
564 default=configure.get('WORK_BASE', DEFAULT_WORK_BASE),
565 help='Directory for bisection working directories (default: %(default)s)')
566 common.add_common_arguments(parser)
567 subparsers = parser.add_subparsers(
568 dest='command', title='commands', metavar='<command>')
569
570 parser_init = subparsers.add_parser(
571 'init', help='Mirror source trees and create template checkout')
572 parser_init.add_argument(
573 '--chrome', action='store_true', help='init chrome mirror and tree')
574 parser_init.add_argument(
575 '--chromeos', action='store_true', help='init chromeos mirror and tree')
576 parser_init.add_argument(
577 '--android',
578 metavar='BRANCH',
579 action='append',
580 default=[],
581 help='init android mirror and tree of BRANCH')
582 parser_init.add_argument(
583 '--btrfs',
584 action='store_true',
585 help='create btrfs subvolume for source tree')
586 parser_init.set_defaults(func=cmd_init)
587
588 parser_sync = subparsers.add_parser(
589 'sync',
590 help='Sync source trees',
591 description='Sync all if no projects are specified '
592 '(--chrome, --chromeos, or --android)')
593 parser_sync.add_argument(
594 '--chrome', action='store_true', help='sync chrome mirror and tree')
595 parser_sync.add_argument(
596 '--chromeos', action='store_true', help='sync chromeos mirror and tree')
597 parser_sync.add_argument(
598 '--android',
599 metavar='BRANCH',
600 action='append',
601 default=[],
602 help='sync android mirror and tree of BRANCH')
603 parser_sync.set_defaults(func=cmd_sync)
604
605 parser_new = subparsers.add_parser(
606 'new',
607 help='Create new source checkout for bisect',
608 description='Create for all if no projects are specified '
609 '(--chrome, --chromeos, or --android)')
610 parser_new.add_argument('--session', required=True)
611 parser_new.add_argument(
612 '--chrome', action='store_true', help='create chrome checkout')
613 parser_new.add_argument(
614 '--chromeos', action='store_true', help='create chromeos checkout')
615 parser_new.add_argument(
616 '--android',
617 metavar='BRANCH',
618 action='append',
619 default=[],
620 help='create android checkout of BRANCH')
621 parser_new.set_defaults(func=cmd_new)
622
623 parser_list = subparsers.add_parser(
624 'list', help='List existing sessions with source checkout')
625 parser_list.set_defaults(func=cmd_list)
626
627 parser_delete = subparsers.add_parser('delete', help='Delete source checkout')
628 parser_delete.add_argument('--session', required=True)
629 parser_delete.set_defaults(func=cmd_delete)
630
631 return parser
632
633
634def main():
635 common.init()
636 parser = create_parser()
637 opts = parser.parse_args()
638 common.config_logging(opts)
639
Kuang-che Wud3a4e842019-12-11 12:15:23 +0800640 # It's optional by default since python3.
641 if not opts.command:
642 parser.error('command is missing')
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800643 opts.func(opts)
644
645
646if __name__ == '__main__':
647 main()