blob: d5807d10d777ac5ff27456e70cefe7f03e5a1963 [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 Wu999893c2020-04-13 22:06:22 +080028import io
Kuang-che Wu41e8b592018-09-25 17:01:30 +080029import logging
30import os
Kuang-che Wu22f207e2019-02-23 12:53:53 +080031import subprocess
Kuang-che Wu67be74b2018-10-15 14:17:26 +080032import time
Kuang-che Wu7d0c7592019-09-16 09:59:28 +080033import xml.etree.ElementTree
Kuang-che Wu999893c2020-04-13 22:06:22 +080034import urllib.parse
35import urllib.request
Kuang-che Wua7ddf9b2019-11-25 18:59:57 +080036
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
Kuang-che Wu23192ad2020-03-11 18:12:46 +080052class DefaultProjectPathFactory:
Kuang-che Wu41e8b592018-09-25 17:01:30 +080053 """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 Wua7f29352020-03-02 17:07:53 +0800263
264 # Work around for b/149883148: 'repo' tool does not fetch all branches in
265 # mirror mode.
266 chromiumos_overlay_mirror = os.path.join(
267 chromeos_mirror, 'chromiumos/overlays/chromiumos-overlay.git')
268 git_util.fetch(chromiumos_overlay_mirror, 'cros')
269
Kuang-che Wu67be74b2018-10-15 14:17:26 +0800270 write_sync_time(chromeos_mirror, start_sync_time)
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800271
272 logger.info('repo sync for chromeos tree')
273 chromeos_tree = path_factory.get_chromeos_tree()
274 repo_util.sync(chromeos_tree)
275
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800276
277def query_chrome_latest_branch():
Kuang-che Wud3a4e842019-12-11 12:15:23 +0800278 result = 0
Kuang-che Wua7ddf9b2019-11-25 18:59:57 +0800279 r = urllib.request.urlopen('https://omahaproxy.appspot.com/all')
Kuang-che Wu6bf6ac32020-04-15 01:14:32 +0800280 for row in csv.DictReader(io.TextIOWrapper(r, encoding='utf-8')):
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800281 if row['true_branch'].isdigit():
282 result = max(result, int(row['true_branch']))
283 return result
284
285
286def setup_chrome_repos(opts, path_factory):
287 chrome_cache = path_factory.get_chrome_cache()
288 subvolume_or_makedirs(opts, chrome_cache)
289 chrome_tree = path_factory.get_chrome_tree()
290 subvolume_or_makedirs(opts, chrome_tree)
291
292 latest_branch = query_chrome_latest_branch()
293 logger.info('latest chrome branch is %d', latest_branch)
294 assert latest_branch
Kuang-che Wuae6824b2019-08-27 22:20:01 +0800295 spec = """
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800296solutions = [
297 { "name" : "buildspec",
298 "url" : "https://chrome-internal.googlesource.com/a/chrome/tools/buildspec.git",
299 "deps_file" : "branches/%d/DEPS",
300 "custom_deps" : {
301 },
302 "custom_vars": {'checkout_src_internal': True},
303 },
304]
305target_os = ['chromeos']
306cache_dir = %r
Kuang-che Wuae6824b2019-08-27 22:20:01 +0800307""" % (latest_branch, chrome_cache)
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800308
Kuang-che Wudc714412018-10-17 16:06:39 +0800309 with locking.lock_file(
310 os.path.join(chrome_cache, locking.LOCK_FILE_FOR_MIRROR_SYNC)):
311 logger.info('gclient config for chrome')
312 gclient_util.config(chrome_tree, spec=spec)
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800313
Kuang-che Wudc714412018-10-17 16:06:39 +0800314 is_first_sync = not os.listdir(chrome_cache)
315 if is_first_sync:
316 logger.info('gclient sync for chrome (this takes hours; be patient)')
317 else:
318 logger.info('gclient sync for chrome')
Kuang-che Wu6ee24b52020-11-02 11:33:49 +0800319 gclient_util.sync(chrome_tree, with_branch_heads=True, with_tags=True)
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800320
Kuang-che Wudc714412018-10-17 16:06:39 +0800321 # It's possible that some repos are removed from latest branch and thus
322 # their commit history is not fetched in recent gclient sync. So we call
323 # 'git fetch' for all existing git mirrors.
324 # TODO(kcwu): only sync repos not in DEPS files of latest branch
325 logger.info('additional sync for chrome mirror')
326 for git_repo_name in os.listdir(chrome_cache):
327 # another gclient is running or leftover of previous run; skip
328 if git_repo_name.startswith('_cache_tmp'):
329 continue
330 git_repo = os.path.join(chrome_cache, git_repo_name)
Kuang-che Wu08366542019-01-12 12:37:49 +0800331 if not git_util.is_git_bare_dir(git_repo):
Kuang-che Wudc714412018-10-17 16:06:39 +0800332 continue
Kuang-che Wu2b1286b2019-05-20 20:37:26 +0800333 git_util.fetch(git_repo)
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800334
Kuang-che Wu1e49f512018-12-06 15:27:42 +0800335 # Some repos were removed from the DEPS and won't be synced here. They will
336 # be synced during DEPS file processing because the necessary information
337 # requires full DEPS parsing. (crbug.com/902238)
338
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800339
340def sync_chrome_code(opts, path_factory):
341 # The sync step is identical to the initial gclient config step.
342 setup_chrome_repos(opts, path_factory)
343
344
345def setup_android_repos(opts, path_factory, branch):
346 android_mirror = path_factory.get_android_mirror(branch)
347 android_tree = path_factory.get_android_tree(branch)
348 subvolume_or_makedirs(opts, android_mirror)
349 subvolume_or_makedirs(opts, android_tree)
350
351 manifest_url = ('persistent-https://googleplex-android.git.corp.google.com'
352 '/platform/manifest')
353 repo_url = 'https://gerrit.googlesource.com/git-repo'
354
355 if os.path.exists(os.path.join(android_mirror, '.repo', 'manifests')):
356 logger.warning(
357 '%s has already been initialized, assume it is setup properly',
358 android_mirror)
359 else:
360 logger.info('repo init for android mirror branch=%s', branch)
361 repo_util.init(
362 android_mirror,
363 manifest_url=manifest_url,
364 repo_url=repo_url,
365 manifest_branch=branch,
366 mirror=True)
367
368 logger.info('repo init for android tree branch=%s', branch)
369 repo_util.init(
370 android_tree,
371 manifest_url=manifest_url,
372 repo_url=repo_url,
373 manifest_branch=branch,
374 reference=android_mirror)
375
376 logger.info('repo sync for android mirror (this takes hours; be patient)')
377 repo_util.sync(android_mirror, current_branch=True)
378
379 logger.info('repo sync for android tree branch=%s', branch)
380 repo_util.sync(android_tree, current_branch=True)
381
382
383def sync_android_code(opts, path_factory, branch):
384 del opts # unused
Kuang-che Wu67be74b2018-10-15 14:17:26 +0800385 start_sync_time = int(time.time())
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800386 android_mirror = path_factory.get_android_mirror(branch)
387 android_tree = path_factory.get_android_tree(branch)
388
Kuang-che Wudc714412018-10-17 16:06:39 +0800389 with locking.lock_file(
390 os.path.join(android_mirror, locking.LOCK_FILE_FOR_MIRROR_SYNC)):
391 logger.info('repo sync for android mirror branch=%s', branch)
Kuang-che Wub76b7f62019-09-16 10:06:18 +0800392 repo_util.sync(android_mirror, current_branch=True)
Kuang-che Wudc714412018-10-17 16:06:39 +0800393 # Android usually big jump between milestone releases and add/delete lots of
394 # repos when switch releases. Because it's infeasible to bisect between such
395 # big jump, the deleted repo is useless. In order to save disk, do not sync
396 # repos deleted in other branches.
Kuang-che Wub76b7f62019-09-16 10:06:18 +0800397 if generate_extra_manifest_for_deleted_repo(
398 android_mirror, only_branch=branch) != 0:
399 logger.info('repo sync again')
400 repo_util.sync(android_mirror, current_branch=True)
Kuang-che Wudc714412018-10-17 16:06:39 +0800401 write_sync_time(android_mirror, start_sync_time)
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800402
403 logger.info('repo sync for android tree branch=%s', branch)
404 repo_util.sync(android_tree, current_branch=True)
405
406
407def cmd_init(opts):
408 path_factory = DefaultProjectPathFactory(opts.mirror_base, opts.work_base,
409 CHECKOUT_TEMPLATE_NAME)
410
411 if opts.chromeos:
412 setup_chromeos_repos(opts, path_factory)
413 if opts.chrome:
414 setup_chrome_repos(opts, path_factory)
415 for branch in opts.android:
416 setup_android_repos(opts, path_factory, branch)
417
418
419def enumerate_android_branches_available(base):
420 branches = []
421 for name in os.listdir(base):
422 if name.startswith('android.'):
423 branches.append(name.partition('.')[2])
424 return branches
425
426
Kuang-che Wu22f207e2019-02-23 12:53:53 +0800427def do_sync(opts):
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800428 path_factory = DefaultProjectPathFactory(opts.mirror_base, opts.work_base,
429 CHECKOUT_TEMPLATE_NAME)
430
431 sync_all = False
432 if not opts.chromeos and not opts.chrome and not opts.android:
433 logger.info('sync trees for all')
434 sync_all = True
435
436 if sync_all or opts.chromeos:
437 sync_chromeos_code(opts, path_factory)
438 if sync_all or opts.chrome:
439 sync_chrome_code(opts, path_factory)
440
441 if sync_all:
442 android_branches = enumerate_android_branches_available(opts.mirror_base)
443 else:
444 android_branches = opts.android
445 for branch in android_branches:
446 sync_android_code(opts, path_factory, branch)
447
448
Kuang-che Wu22f207e2019-02-23 12:53:53 +0800449def cmd_sync(opts):
450 try:
451 do_sync(opts)
452 except subprocess.CalledProcessError:
453 # Sync may fail due to network or server issues.
454 logger.exception('do_sync failed, will retry one minute later')
455 time.sleep(60)
456 do_sync(opts)
457
458
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800459def cmd_new(opts):
460 work_dir = os.path.join(opts.work_base, opts.session)
461 if not os.path.exists(work_dir):
462 os.makedirs(work_dir)
463
464 template_factory = DefaultProjectPathFactory(opts.mirror_base, opts.work_base,
465 CHECKOUT_TEMPLATE_NAME)
466 path_factory = DefaultProjectPathFactory(opts.mirror_base, opts.work_base,
467 opts.session)
468
469 prepare_all = False
470 if not opts.chromeos and not opts.chrome and not opts.android:
471 logger.info('prepare trees for all')
472 prepare_all = True
473
474 chromeos_template = template_factory.get_chromeos_tree()
475 if (prepare_all and os.path.exists(chromeos_template)) or opts.chromeos:
476 logger.info('prepare tree for chromeos, %s',
477 path_factory.get_chromeos_tree())
478 snapshot_or_copytree(chromeos_template, path_factory.get_chromeos_tree())
479
480 chrome_template = template_factory.get_chrome_tree()
481 if (prepare_all and os.path.exists(chrome_template)) or opts.chrome:
482 logger.info('prepare tree for chrome, %s', path_factory.get_chrome_tree())
483 snapshot_or_copytree(chrome_template, path_factory.get_chrome_tree())
484
485 if prepare_all:
486 android_branches = enumerate_android_branches_available(opts.mirror_base)
487 else:
488 android_branches = opts.android
489 for branch in android_branches:
490 logger.info('prepare tree for android branch=%s, %s', branch,
491 path_factory.get_android_tree(branch))
492 snapshot_or_copytree(
493 template_factory.get_android_tree(branch),
494 path_factory.get_android_tree(branch))
495
496
497def delete_tree(path):
498 if is_btrfs_subvolume(path):
Kuang-che Wu9d3ccde2019-01-03 17:06:09 +0800499 # btrfs should be mounted with 'user_subvol_rm_allowed' option and thus
500 # normal user permission is enough.
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800501 util.check_call('btrfs', 'subvolume', 'delete', path)
502 else:
Kuang-che Wu9d3ccde2019-01-03 17:06:09 +0800503 util.check_call('sudo', 'rm', '-rf', path)
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800504
505
506def cmd_list(opts):
507 print('%-20s %s' % ('Session', 'Path'))
508 for name in os.listdir(opts.work_base):
509 if name == CHECKOUT_TEMPLATE_NAME:
510 continue
511 path = os.path.join(opts.work_base, name)
512 print('%-20s %s' % (name, path))
513
514
515def cmd_delete(opts):
516 assert opts.session
517 path_factory = DefaultProjectPathFactory(opts.mirror_base, opts.work_base,
518 opts.session)
519
520 chromeos_tree = path_factory.get_chromeos_tree()
521 if os.path.exists(chromeos_tree):
522 if os.path.exists(os.path.join(chromeos_tree, 'chromite')):
523 # ignore error
524 util.call('cros_sdk', '--unmount', cwd=chromeos_tree)
525 delete_tree(chromeos_tree)
526
527 chrome_tree = path_factory.get_chrome_tree()
528 if os.path.exists(chrome_tree):
529 delete_tree(chrome_tree)
530
531 android_branches = enumerate_android_branches_available(opts.mirror_base)
532 for branch in android_branches:
533 android_tree = path_factory.get_android_tree(branch)
534 if os.path.exists(android_tree):
535 delete_tree(android_tree)
536
537 os.rmdir(os.path.join(opts.work_base, opts.session))
538
Zheng-Jie Changcd424c12020-01-10 14:32:08 +0800539 # remove caches
540 chromeos_root = os.getenv('DEFAULT_CHROMEOS_ROOT')
541 if chromeos_root:
542 path = os.path.join(chromeos_root, 'devserver/static')
543 if os.path.exists(path):
Kuang-che Wud2747442020-07-01 16:50:24 +0800544 logger.debug('remove cache (cros flash): %s', path)
Zheng-Jie Changcd424c12020-01-10 14:32:08 +0800545 util.call('cros', 'clean', '--flash', cwd=path)
546
547 for path in glob.glob(os.path.join(chromeos_root, 'chroot/tmp/*')):
Kuang-che Wud2747442020-07-01 16:50:24 +0800548 logger.debug('remove cache (chroot/tmp): %s', path)
Zheng-Jie Changcd424c12020-01-10 14:32:08 +0800549 delete_tree(path)
550
Zheng-Jie Changd164da42020-03-12 10:33:23 +0800551 for path in glob.glob(os.path.join(chromeos_root, 'tmp/*')):
Kuang-che Wud2747442020-07-01 16:50:24 +0800552 logger.debug('remove cache (chromeos root tmp): %s', path)
Zheng-Jie Changd164da42020-03-12 10:33:23 +0800553 delete_tree(path)
554
Zheng-Jie Changcd424c12020-01-10 14:32:08 +0800555 for path in glob.glob(
556 os.path.join(path_factory.get_chrome_cache(), '_cache_*')):
Kuang-che Wud2747442020-07-01 16:50:24 +0800557 logger.debug('remove cache (chrome gclient cache): %s', path)
Zheng-Jie Changcd424c12020-01-10 14:32:08 +0800558 delete_tree(path)
559
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800560
561def create_parser():
562 parser = argparse.ArgumentParser(
563 formatter_class=argparse.RawDescriptionHelpFormatter, description=__doc__)
564 parser.add_argument(
565 '--mirror_base',
566 metavar='MIRROR_BASE',
567 default=configure.get('MIRROR_BASE', DEFAULT_MIRROR_BASE),
568 help='Directory for mirrors (default: %(default)s)')
569 parser.add_argument(
570 '--work_base',
571 metavar='WORK_BASE',
572 default=configure.get('WORK_BASE', DEFAULT_WORK_BASE),
573 help='Directory for bisection working directories (default: %(default)s)')
574 common.add_common_arguments(parser)
575 subparsers = parser.add_subparsers(
576 dest='command', title='commands', metavar='<command>')
577
578 parser_init = subparsers.add_parser(
579 'init', help='Mirror source trees and create template checkout')
580 parser_init.add_argument(
581 '--chrome', action='store_true', help='init chrome mirror and tree')
582 parser_init.add_argument(
583 '--chromeos', action='store_true', help='init chromeos mirror and tree')
584 parser_init.add_argument(
585 '--android',
586 metavar='BRANCH',
587 action='append',
588 default=[],
589 help='init android mirror and tree of BRANCH')
590 parser_init.add_argument(
591 '--btrfs',
592 action='store_true',
593 help='create btrfs subvolume for source tree')
594 parser_init.set_defaults(func=cmd_init)
595
596 parser_sync = subparsers.add_parser(
597 'sync',
598 help='Sync source trees',
599 description='Sync all if no projects are specified '
600 '(--chrome, --chromeos, or --android)')
601 parser_sync.add_argument(
602 '--chrome', action='store_true', help='sync chrome mirror and tree')
603 parser_sync.add_argument(
604 '--chromeos', action='store_true', help='sync chromeos mirror and tree')
605 parser_sync.add_argument(
606 '--android',
607 metavar='BRANCH',
608 action='append',
609 default=[],
610 help='sync android mirror and tree of BRANCH')
611 parser_sync.set_defaults(func=cmd_sync)
612
613 parser_new = subparsers.add_parser(
614 'new',
615 help='Create new source checkout for bisect',
616 description='Create for all if no projects are specified '
617 '(--chrome, --chromeos, or --android)')
618 parser_new.add_argument('--session', required=True)
619 parser_new.add_argument(
620 '--chrome', action='store_true', help='create chrome checkout')
621 parser_new.add_argument(
622 '--chromeos', action='store_true', help='create chromeos checkout')
623 parser_new.add_argument(
624 '--android',
625 metavar='BRANCH',
626 action='append',
627 default=[],
628 help='create android checkout of BRANCH')
629 parser_new.set_defaults(func=cmd_new)
630
631 parser_list = subparsers.add_parser(
632 'list', help='List existing sessions with source checkout')
633 parser_list.set_defaults(func=cmd_list)
634
635 parser_delete = subparsers.add_parser('delete', help='Delete source checkout')
636 parser_delete.add_argument('--session', required=True)
637 parser_delete.set_defaults(func=cmd_delete)
638
639 return parser
640
641
642def main():
643 common.init()
644 parser = create_parser()
645 opts = parser.parse_args()
646 common.config_logging(opts)
647
Kuang-che Wud3a4e842019-12-11 12:15:23 +0800648 # It's optional by default since python3.
649 if not opts.command:
650 parser.error('command is missing')
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800651 opts.func(opts)
652
653
654if __name__ == '__main__':
655 main()