blob: b19f044af5a3c2040a2186a8962a5744f4c372a1 [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
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 Wud3a4e842019-12-11 12:15:23 +0800280 # TODO(kcwu): use io.TextIOWrapper after migrated to python3
281 content = r.read().decode('utf8')
282 for row in csv.DictReader(six.StringIO(content)):
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800283 if row['true_branch'].isdigit():
284 result = max(result, int(row['true_branch']))
285 return result
286
287
288def setup_chrome_repos(opts, path_factory):
289 chrome_cache = path_factory.get_chrome_cache()
290 subvolume_or_makedirs(opts, chrome_cache)
291 chrome_tree = path_factory.get_chrome_tree()
292 subvolume_or_makedirs(opts, chrome_tree)
293
294 latest_branch = query_chrome_latest_branch()
295 logger.info('latest chrome branch is %d', latest_branch)
296 assert latest_branch
Kuang-che Wuae6824b2019-08-27 22:20:01 +0800297 spec = """
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800298solutions = [
299 { "name" : "buildspec",
300 "url" : "https://chrome-internal.googlesource.com/a/chrome/tools/buildspec.git",
301 "deps_file" : "branches/%d/DEPS",
302 "custom_deps" : {
303 },
304 "custom_vars": {'checkout_src_internal': True},
305 },
306]
307target_os = ['chromeos']
308cache_dir = %r
Kuang-che Wuae6824b2019-08-27 22:20:01 +0800309""" % (latest_branch, chrome_cache)
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800310
Kuang-che Wudc714412018-10-17 16:06:39 +0800311 with locking.lock_file(
312 os.path.join(chrome_cache, locking.LOCK_FILE_FOR_MIRROR_SYNC)):
313 logger.info('gclient config for chrome')
314 gclient_util.config(chrome_tree, spec=spec)
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800315
Kuang-che Wudc714412018-10-17 16:06:39 +0800316 is_first_sync = not os.listdir(chrome_cache)
317 if is_first_sync:
318 logger.info('gclient sync for chrome (this takes hours; be patient)')
319 else:
320 logger.info('gclient sync for chrome')
321 gclient_util.sync(
322 chrome_tree, with_branch_heads=True, with_tags=True, ignore_locks=True)
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800323
Kuang-che Wudc714412018-10-17 16:06:39 +0800324 # It's possible that some repos are removed from latest branch and thus
325 # their commit history is not fetched in recent gclient sync. So we call
326 # 'git fetch' for all existing git mirrors.
327 # TODO(kcwu): only sync repos not in DEPS files of latest branch
328 logger.info('additional sync for chrome mirror')
329 for git_repo_name in os.listdir(chrome_cache):
330 # another gclient is running or leftover of previous run; skip
331 if git_repo_name.startswith('_cache_tmp'):
332 continue
333 git_repo = os.path.join(chrome_cache, git_repo_name)
Kuang-che Wu08366542019-01-12 12:37:49 +0800334 if not git_util.is_git_bare_dir(git_repo):
Kuang-che Wudc714412018-10-17 16:06:39 +0800335 continue
Kuang-che Wu2b1286b2019-05-20 20:37:26 +0800336 git_util.fetch(git_repo)
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800337
Kuang-che Wu1e49f512018-12-06 15:27:42 +0800338 # Some repos were removed from the DEPS and won't be synced here. They will
339 # be synced during DEPS file processing because the necessary information
340 # requires full DEPS parsing. (crbug.com/902238)
341
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800342
343def sync_chrome_code(opts, path_factory):
344 # The sync step is identical to the initial gclient config step.
345 setup_chrome_repos(opts, path_factory)
346
347
348def setup_android_repos(opts, path_factory, branch):
349 android_mirror = path_factory.get_android_mirror(branch)
350 android_tree = path_factory.get_android_tree(branch)
351 subvolume_or_makedirs(opts, android_mirror)
352 subvolume_or_makedirs(opts, android_tree)
353
354 manifest_url = ('persistent-https://googleplex-android.git.corp.google.com'
355 '/platform/manifest')
356 repo_url = 'https://gerrit.googlesource.com/git-repo'
357
358 if os.path.exists(os.path.join(android_mirror, '.repo', 'manifests')):
359 logger.warning(
360 '%s has already been initialized, assume it is setup properly',
361 android_mirror)
362 else:
363 logger.info('repo init for android mirror branch=%s', branch)
364 repo_util.init(
365 android_mirror,
366 manifest_url=manifest_url,
367 repo_url=repo_url,
368 manifest_branch=branch,
369 mirror=True)
370
371 logger.info('repo init for android tree branch=%s', branch)
372 repo_util.init(
373 android_tree,
374 manifest_url=manifest_url,
375 repo_url=repo_url,
376 manifest_branch=branch,
377 reference=android_mirror)
378
379 logger.info('repo sync for android mirror (this takes hours; be patient)')
380 repo_util.sync(android_mirror, current_branch=True)
381
382 logger.info('repo sync for android tree branch=%s', branch)
383 repo_util.sync(android_tree, current_branch=True)
384
385
386def sync_android_code(opts, path_factory, branch):
387 del opts # unused
Kuang-che Wu67be74b2018-10-15 14:17:26 +0800388 start_sync_time = int(time.time())
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800389 android_mirror = path_factory.get_android_mirror(branch)
390 android_tree = path_factory.get_android_tree(branch)
391
Kuang-che Wudc714412018-10-17 16:06:39 +0800392 with locking.lock_file(
393 os.path.join(android_mirror, locking.LOCK_FILE_FOR_MIRROR_SYNC)):
394 logger.info('repo sync for android mirror branch=%s', branch)
Kuang-che Wub76b7f62019-09-16 10:06:18 +0800395 repo_util.sync(android_mirror, current_branch=True)
Kuang-che Wudc714412018-10-17 16:06:39 +0800396 # Android usually big jump between milestone releases and add/delete lots of
397 # repos when switch releases. Because it's infeasible to bisect between such
398 # big jump, the deleted repo is useless. In order to save disk, do not sync
399 # repos deleted in other branches.
Kuang-che Wub76b7f62019-09-16 10:06:18 +0800400 if generate_extra_manifest_for_deleted_repo(
401 android_mirror, only_branch=branch) != 0:
402 logger.info('repo sync again')
403 repo_util.sync(android_mirror, current_branch=True)
Kuang-che Wudc714412018-10-17 16:06:39 +0800404 write_sync_time(android_mirror, start_sync_time)
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800405
406 logger.info('repo sync for android tree branch=%s', branch)
407 repo_util.sync(android_tree, current_branch=True)
408
409
410def cmd_init(opts):
411 path_factory = DefaultProjectPathFactory(opts.mirror_base, opts.work_base,
412 CHECKOUT_TEMPLATE_NAME)
413
414 if opts.chromeos:
415 setup_chromeos_repos(opts, path_factory)
416 if opts.chrome:
417 setup_chrome_repos(opts, path_factory)
418 for branch in opts.android:
419 setup_android_repos(opts, path_factory, branch)
420
421
422def enumerate_android_branches_available(base):
423 branches = []
424 for name in os.listdir(base):
425 if name.startswith('android.'):
426 branches.append(name.partition('.')[2])
427 return branches
428
429
Kuang-che Wu22f207e2019-02-23 12:53:53 +0800430def do_sync(opts):
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800431 path_factory = DefaultProjectPathFactory(opts.mirror_base, opts.work_base,
432 CHECKOUT_TEMPLATE_NAME)
433
434 sync_all = False
435 if not opts.chromeos and not opts.chrome and not opts.android:
436 logger.info('sync trees for all')
437 sync_all = True
438
439 if sync_all or opts.chromeos:
440 sync_chromeos_code(opts, path_factory)
441 if sync_all or opts.chrome:
442 sync_chrome_code(opts, path_factory)
443
444 if sync_all:
445 android_branches = enumerate_android_branches_available(opts.mirror_base)
446 else:
447 android_branches = opts.android
448 for branch in android_branches:
449 sync_android_code(opts, path_factory, branch)
450
451
Kuang-che Wu22f207e2019-02-23 12:53:53 +0800452def cmd_sync(opts):
453 try:
454 do_sync(opts)
455 except subprocess.CalledProcessError:
456 # Sync may fail due to network or server issues.
457 logger.exception('do_sync failed, will retry one minute later')
458 time.sleep(60)
459 do_sync(opts)
460
461
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800462def cmd_new(opts):
463 work_dir = os.path.join(opts.work_base, opts.session)
464 if not os.path.exists(work_dir):
465 os.makedirs(work_dir)
466
467 template_factory = DefaultProjectPathFactory(opts.mirror_base, opts.work_base,
468 CHECKOUT_TEMPLATE_NAME)
469 path_factory = DefaultProjectPathFactory(opts.mirror_base, opts.work_base,
470 opts.session)
471
472 prepare_all = False
473 if not opts.chromeos and not opts.chrome and not opts.android:
474 logger.info('prepare trees for all')
475 prepare_all = True
476
477 chromeos_template = template_factory.get_chromeos_tree()
478 if (prepare_all and os.path.exists(chromeos_template)) or opts.chromeos:
479 logger.info('prepare tree for chromeos, %s',
480 path_factory.get_chromeos_tree())
481 snapshot_or_copytree(chromeos_template, path_factory.get_chromeos_tree())
482
483 chrome_template = template_factory.get_chrome_tree()
484 if (prepare_all and os.path.exists(chrome_template)) or opts.chrome:
485 logger.info('prepare tree for chrome, %s', path_factory.get_chrome_tree())
486 snapshot_or_copytree(chrome_template, path_factory.get_chrome_tree())
487
488 if prepare_all:
489 android_branches = enumerate_android_branches_available(opts.mirror_base)
490 else:
491 android_branches = opts.android
492 for branch in android_branches:
493 logger.info('prepare tree for android branch=%s, %s', branch,
494 path_factory.get_android_tree(branch))
495 snapshot_or_copytree(
496 template_factory.get_android_tree(branch),
497 path_factory.get_android_tree(branch))
498
499
500def delete_tree(path):
501 if is_btrfs_subvolume(path):
Kuang-che Wu9d3ccde2019-01-03 17:06:09 +0800502 # btrfs should be mounted with 'user_subvol_rm_allowed' option and thus
503 # normal user permission is enough.
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800504 util.check_call('btrfs', 'subvolume', 'delete', path)
505 else:
Kuang-che Wu9d3ccde2019-01-03 17:06:09 +0800506 util.check_call('sudo', 'rm', '-rf', path)
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800507
508
509def cmd_list(opts):
510 print('%-20s %s' % ('Session', 'Path'))
511 for name in os.listdir(opts.work_base):
512 if name == CHECKOUT_TEMPLATE_NAME:
513 continue
514 path = os.path.join(opts.work_base, name)
515 print('%-20s %s' % (name, path))
516
517
518def cmd_delete(opts):
519 assert opts.session
520 path_factory = DefaultProjectPathFactory(opts.mirror_base, opts.work_base,
521 opts.session)
522
523 chromeos_tree = path_factory.get_chromeos_tree()
524 if os.path.exists(chromeos_tree):
525 if os.path.exists(os.path.join(chromeos_tree, 'chromite')):
526 # ignore error
527 util.call('cros_sdk', '--unmount', cwd=chromeos_tree)
528 delete_tree(chromeos_tree)
529
530 chrome_tree = path_factory.get_chrome_tree()
531 if os.path.exists(chrome_tree):
532 delete_tree(chrome_tree)
533
534 android_branches = enumerate_android_branches_available(opts.mirror_base)
535 for branch in android_branches:
536 android_tree = path_factory.get_android_tree(branch)
537 if os.path.exists(android_tree):
538 delete_tree(android_tree)
539
540 os.rmdir(os.path.join(opts.work_base, opts.session))
541
Zheng-Jie Changcd424c12020-01-10 14:32:08 +0800542 # remove caches
543 chromeos_root = os.getenv('DEFAULT_CHROMEOS_ROOT')
544 if chromeos_root:
545 path = os.path.join(chromeos_root, 'devserver/static')
546 if os.path.exists(path):
547 logger.info('remove cache: %s', path)
548 util.call('cros', 'clean', '--flash', cwd=path)
549
550 for path in glob.glob(os.path.join(chromeos_root, 'chroot/tmp/*')):
551 logger.info('remove cache: %s', path)
552 delete_tree(path)
553
554 for path in glob.glob(
555 os.path.join(path_factory.get_chrome_cache(), '_cache_*')):
556 logger.info('remove cache: %s', path)
557 delete_tree(path)
558
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800559
560def create_parser():
561 parser = argparse.ArgumentParser(
562 formatter_class=argparse.RawDescriptionHelpFormatter, description=__doc__)
563 parser.add_argument(
564 '--mirror_base',
565 metavar='MIRROR_BASE',
566 default=configure.get('MIRROR_BASE', DEFAULT_MIRROR_BASE),
567 help='Directory for mirrors (default: %(default)s)')
568 parser.add_argument(
569 '--work_base',
570 metavar='WORK_BASE',
571 default=configure.get('WORK_BASE', DEFAULT_WORK_BASE),
572 help='Directory for bisection working directories (default: %(default)s)')
573 common.add_common_arguments(parser)
574 subparsers = parser.add_subparsers(
575 dest='command', title='commands', metavar='<command>')
576
577 parser_init = subparsers.add_parser(
578 'init', help='Mirror source trees and create template checkout')
579 parser_init.add_argument(
580 '--chrome', action='store_true', help='init chrome mirror and tree')
581 parser_init.add_argument(
582 '--chromeos', action='store_true', help='init chromeos mirror and tree')
583 parser_init.add_argument(
584 '--android',
585 metavar='BRANCH',
586 action='append',
587 default=[],
588 help='init android mirror and tree of BRANCH')
589 parser_init.add_argument(
590 '--btrfs',
591 action='store_true',
592 help='create btrfs subvolume for source tree')
593 parser_init.set_defaults(func=cmd_init)
594
595 parser_sync = subparsers.add_parser(
596 'sync',
597 help='Sync source trees',
598 description='Sync all if no projects are specified '
599 '(--chrome, --chromeos, or --android)')
600 parser_sync.add_argument(
601 '--chrome', action='store_true', help='sync chrome mirror and tree')
602 parser_sync.add_argument(
603 '--chromeos', action='store_true', help='sync chromeos mirror and tree')
604 parser_sync.add_argument(
605 '--android',
606 metavar='BRANCH',
607 action='append',
608 default=[],
609 help='sync android mirror and tree of BRANCH')
610 parser_sync.set_defaults(func=cmd_sync)
611
612 parser_new = subparsers.add_parser(
613 'new',
614 help='Create new source checkout for bisect',
615 description='Create for all if no projects are specified '
616 '(--chrome, --chromeos, or --android)')
617 parser_new.add_argument('--session', required=True)
618 parser_new.add_argument(
619 '--chrome', action='store_true', help='create chrome checkout')
620 parser_new.add_argument(
621 '--chromeos', action='store_true', help='create chromeos checkout')
622 parser_new.add_argument(
623 '--android',
624 metavar='BRANCH',
625 action='append',
626 default=[],
627 help='create android checkout of BRANCH')
628 parser_new.set_defaults(func=cmd_new)
629
630 parser_list = subparsers.add_parser(
631 'list', help='List existing sessions with source checkout')
632 parser_list.set_defaults(func=cmd_list)
633
634 parser_delete = subparsers.add_parser('delete', help='Delete source checkout')
635 parser_delete.add_argument('--session', required=True)
636 parser_delete.set_defaults(func=cmd_delete)
637
638 return parser
639
640
641def main():
642 common.init()
643 parser = create_parser()
644 opts = parser.parse_args()
645 common.config_logging(opts)
646
Kuang-che Wud3a4e842019-12-11 12:15:23 +0800647 # It's optional by default since python3.
648 if not opts.command:
649 parser.error('command is missing')
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800650 opts.func(opts)
651
652
653if __name__ == '__main__':
654 main()