blob: 70ab98b351ce3fcf13b99d53420226980f8ef0bf [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')
319 gclient_util.sync(
320 chrome_tree, with_branch_heads=True, with_tags=True, ignore_locks=True)
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800321
Kuang-che Wudc714412018-10-17 16:06:39 +0800322 # It's possible that some repos are removed from latest branch and thus
323 # their commit history is not fetched in recent gclient sync. So we call
324 # 'git fetch' for all existing git mirrors.
325 # TODO(kcwu): only sync repos not in DEPS files of latest branch
326 logger.info('additional sync for chrome mirror')
327 for git_repo_name in os.listdir(chrome_cache):
328 # another gclient is running or leftover of previous run; skip
329 if git_repo_name.startswith('_cache_tmp'):
330 continue
331 git_repo = os.path.join(chrome_cache, git_repo_name)
Kuang-che Wu08366542019-01-12 12:37:49 +0800332 if not git_util.is_git_bare_dir(git_repo):
Kuang-che Wudc714412018-10-17 16:06:39 +0800333 continue
Kuang-che Wu2b1286b2019-05-20 20:37:26 +0800334 git_util.fetch(git_repo)
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800335
Kuang-che Wu1e49f512018-12-06 15:27:42 +0800336 # Some repos were removed from the DEPS and won't be synced here. They will
337 # be synced during DEPS file processing because the necessary information
338 # requires full DEPS parsing. (crbug.com/902238)
339
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800340
341def sync_chrome_code(opts, path_factory):
342 # The sync step is identical to the initial gclient config step.
343 setup_chrome_repos(opts, path_factory)
344
345
346def setup_android_repos(opts, path_factory, branch):
347 android_mirror = path_factory.get_android_mirror(branch)
348 android_tree = path_factory.get_android_tree(branch)
349 subvolume_or_makedirs(opts, android_mirror)
350 subvolume_or_makedirs(opts, android_tree)
351
352 manifest_url = ('persistent-https://googleplex-android.git.corp.google.com'
353 '/platform/manifest')
354 repo_url = 'https://gerrit.googlesource.com/git-repo'
355
356 if os.path.exists(os.path.join(android_mirror, '.repo', 'manifests')):
357 logger.warning(
358 '%s has already been initialized, assume it is setup properly',
359 android_mirror)
360 else:
361 logger.info('repo init for android mirror branch=%s', branch)
362 repo_util.init(
363 android_mirror,
364 manifest_url=manifest_url,
365 repo_url=repo_url,
366 manifest_branch=branch,
367 mirror=True)
368
369 logger.info('repo init for android tree branch=%s', branch)
370 repo_util.init(
371 android_tree,
372 manifest_url=manifest_url,
373 repo_url=repo_url,
374 manifest_branch=branch,
375 reference=android_mirror)
376
377 logger.info('repo sync for android mirror (this takes hours; be patient)')
378 repo_util.sync(android_mirror, current_branch=True)
379
380 logger.info('repo sync for android tree branch=%s', branch)
381 repo_util.sync(android_tree, current_branch=True)
382
383
384def sync_android_code(opts, path_factory, branch):
385 del opts # unused
Kuang-che Wu67be74b2018-10-15 14:17:26 +0800386 start_sync_time = int(time.time())
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800387 android_mirror = path_factory.get_android_mirror(branch)
388 android_tree = path_factory.get_android_tree(branch)
389
Kuang-che Wudc714412018-10-17 16:06:39 +0800390 with locking.lock_file(
391 os.path.join(android_mirror, locking.LOCK_FILE_FOR_MIRROR_SYNC)):
392 logger.info('repo sync for android mirror branch=%s', branch)
Kuang-che Wub76b7f62019-09-16 10:06:18 +0800393 repo_util.sync(android_mirror, current_branch=True)
Kuang-che Wudc714412018-10-17 16:06:39 +0800394 # Android usually big jump between milestone releases and add/delete lots of
395 # repos when switch releases. Because it's infeasible to bisect between such
396 # big jump, the deleted repo is useless. In order to save disk, do not sync
397 # repos deleted in other branches.
Kuang-che Wub76b7f62019-09-16 10:06:18 +0800398 if generate_extra_manifest_for_deleted_repo(
399 android_mirror, only_branch=branch) != 0:
400 logger.info('repo sync again')
401 repo_util.sync(android_mirror, current_branch=True)
Kuang-che Wudc714412018-10-17 16:06:39 +0800402 write_sync_time(android_mirror, start_sync_time)
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800403
404 logger.info('repo sync for android tree branch=%s', branch)
405 repo_util.sync(android_tree, current_branch=True)
406
407
408def cmd_init(opts):
409 path_factory = DefaultProjectPathFactory(opts.mirror_base, opts.work_base,
410 CHECKOUT_TEMPLATE_NAME)
411
412 if opts.chromeos:
413 setup_chromeos_repos(opts, path_factory)
414 if opts.chrome:
415 setup_chrome_repos(opts, path_factory)
416 for branch in opts.android:
417 setup_android_repos(opts, path_factory, branch)
418
419
420def enumerate_android_branches_available(base):
421 branches = []
422 for name in os.listdir(base):
423 if name.startswith('android.'):
424 branches.append(name.partition('.')[2])
425 return branches
426
427
Kuang-che Wu22f207e2019-02-23 12:53:53 +0800428def do_sync(opts):
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800429 path_factory = DefaultProjectPathFactory(opts.mirror_base, opts.work_base,
430 CHECKOUT_TEMPLATE_NAME)
431
432 sync_all = False
433 if not opts.chromeos and not opts.chrome and not opts.android:
434 logger.info('sync trees for all')
435 sync_all = True
436
437 if sync_all or opts.chromeos:
438 sync_chromeos_code(opts, path_factory)
439 if sync_all or opts.chrome:
440 sync_chrome_code(opts, path_factory)
441
442 if sync_all:
443 android_branches = enumerate_android_branches_available(opts.mirror_base)
444 else:
445 android_branches = opts.android
446 for branch in android_branches:
447 sync_android_code(opts, path_factory, branch)
448
449
Kuang-che Wu22f207e2019-02-23 12:53:53 +0800450def cmd_sync(opts):
451 try:
452 do_sync(opts)
453 except subprocess.CalledProcessError:
454 # Sync may fail due to network or server issues.
455 logger.exception('do_sync failed, will retry one minute later')
456 time.sleep(60)
457 do_sync(opts)
458
459
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800460def cmd_new(opts):
461 work_dir = os.path.join(opts.work_base, opts.session)
462 if not os.path.exists(work_dir):
463 os.makedirs(work_dir)
464
465 template_factory = DefaultProjectPathFactory(opts.mirror_base, opts.work_base,
466 CHECKOUT_TEMPLATE_NAME)
467 path_factory = DefaultProjectPathFactory(opts.mirror_base, opts.work_base,
468 opts.session)
469
470 prepare_all = False
471 if not opts.chromeos and not opts.chrome and not opts.android:
472 logger.info('prepare trees for all')
473 prepare_all = True
474
475 chromeos_template = template_factory.get_chromeos_tree()
476 if (prepare_all and os.path.exists(chromeos_template)) or opts.chromeos:
477 logger.info('prepare tree for chromeos, %s',
478 path_factory.get_chromeos_tree())
479 snapshot_or_copytree(chromeos_template, path_factory.get_chromeos_tree())
480
481 chrome_template = template_factory.get_chrome_tree()
482 if (prepare_all and os.path.exists(chrome_template)) or opts.chrome:
483 logger.info('prepare tree for chrome, %s', path_factory.get_chrome_tree())
484 snapshot_or_copytree(chrome_template, path_factory.get_chrome_tree())
485
486 if prepare_all:
487 android_branches = enumerate_android_branches_available(opts.mirror_base)
488 else:
489 android_branches = opts.android
490 for branch in android_branches:
491 logger.info('prepare tree for android branch=%s, %s', branch,
492 path_factory.get_android_tree(branch))
493 snapshot_or_copytree(
494 template_factory.get_android_tree(branch),
495 path_factory.get_android_tree(branch))
496
497
498def delete_tree(path):
499 if is_btrfs_subvolume(path):
Kuang-che Wu9d3ccde2019-01-03 17:06:09 +0800500 # btrfs should be mounted with 'user_subvol_rm_allowed' option and thus
501 # normal user permission is enough.
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800502 util.check_call('btrfs', 'subvolume', 'delete', path)
503 else:
Kuang-che Wu9d3ccde2019-01-03 17:06:09 +0800504 util.check_call('sudo', 'rm', '-rf', path)
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800505
506
507def cmd_list(opts):
508 print('%-20s %s' % ('Session', 'Path'))
509 for name in os.listdir(opts.work_base):
510 if name == CHECKOUT_TEMPLATE_NAME:
511 continue
512 path = os.path.join(opts.work_base, name)
513 print('%-20s %s' % (name, path))
514
515
516def cmd_delete(opts):
517 assert opts.session
518 path_factory = DefaultProjectPathFactory(opts.mirror_base, opts.work_base,
519 opts.session)
520
521 chromeos_tree = path_factory.get_chromeos_tree()
522 if os.path.exists(chromeos_tree):
523 if os.path.exists(os.path.join(chromeos_tree, 'chromite')):
524 # ignore error
525 util.call('cros_sdk', '--unmount', cwd=chromeos_tree)
526 delete_tree(chromeos_tree)
527
528 chrome_tree = path_factory.get_chrome_tree()
529 if os.path.exists(chrome_tree):
530 delete_tree(chrome_tree)
531
532 android_branches = enumerate_android_branches_available(opts.mirror_base)
533 for branch in android_branches:
534 android_tree = path_factory.get_android_tree(branch)
535 if os.path.exists(android_tree):
536 delete_tree(android_tree)
537
538 os.rmdir(os.path.join(opts.work_base, opts.session))
539
Zheng-Jie Changcd424c12020-01-10 14:32:08 +0800540 # remove caches
541 chromeos_root = os.getenv('DEFAULT_CHROMEOS_ROOT')
542 if chromeos_root:
543 path = os.path.join(chromeos_root, 'devserver/static')
544 if os.path.exists(path):
Kuang-che Wud2747442020-07-01 16:50:24 +0800545 logger.debug('remove cache (cros flash): %s', path)
Zheng-Jie Changcd424c12020-01-10 14:32:08 +0800546 util.call('cros', 'clean', '--flash', cwd=path)
547
548 for path in glob.glob(os.path.join(chromeos_root, 'chroot/tmp/*')):
Kuang-che Wud2747442020-07-01 16:50:24 +0800549 logger.debug('remove cache (chroot/tmp): %s', path)
Zheng-Jie Changcd424c12020-01-10 14:32:08 +0800550 delete_tree(path)
551
Zheng-Jie Changd164da42020-03-12 10:33:23 +0800552 for path in glob.glob(os.path.join(chromeos_root, 'tmp/*')):
Kuang-che Wud2747442020-07-01 16:50:24 +0800553 logger.debug('remove cache (chromeos root tmp): %s', path)
Zheng-Jie Changd164da42020-03-12 10:33:23 +0800554 delete_tree(path)
555
Zheng-Jie Changcd424c12020-01-10 14:32:08 +0800556 for path in glob.glob(
557 os.path.join(path_factory.get_chrome_cache(), '_cache_*')):
Kuang-che Wud2747442020-07-01 16:50:24 +0800558 logger.debug('remove cache (chrome gclient cache): %s', path)
Zheng-Jie Changcd424c12020-01-10 14:32:08 +0800559 delete_tree(path)
560
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800561
562def create_parser():
563 parser = argparse.ArgumentParser(
564 formatter_class=argparse.RawDescriptionHelpFormatter, description=__doc__)
565 parser.add_argument(
566 '--mirror_base',
567 metavar='MIRROR_BASE',
568 default=configure.get('MIRROR_BASE', DEFAULT_MIRROR_BASE),
569 help='Directory for mirrors (default: %(default)s)')
570 parser.add_argument(
571 '--work_base',
572 metavar='WORK_BASE',
573 default=configure.get('WORK_BASE', DEFAULT_WORK_BASE),
574 help='Directory for bisection working directories (default: %(default)s)')
575 common.add_common_arguments(parser)
576 subparsers = parser.add_subparsers(
577 dest='command', title='commands', metavar='<command>')
578
579 parser_init = subparsers.add_parser(
580 'init', help='Mirror source trees and create template checkout')
581 parser_init.add_argument(
582 '--chrome', action='store_true', help='init chrome mirror and tree')
583 parser_init.add_argument(
584 '--chromeos', action='store_true', help='init chromeos mirror and tree')
585 parser_init.add_argument(
586 '--android',
587 metavar='BRANCH',
588 action='append',
589 default=[],
590 help='init android mirror and tree of BRANCH')
591 parser_init.add_argument(
592 '--btrfs',
593 action='store_true',
594 help='create btrfs subvolume for source tree')
595 parser_init.set_defaults(func=cmd_init)
596
597 parser_sync = subparsers.add_parser(
598 'sync',
599 help='Sync source trees',
600 description='Sync all if no projects are specified '
601 '(--chrome, --chromeos, or --android)')
602 parser_sync.add_argument(
603 '--chrome', action='store_true', help='sync chrome mirror and tree')
604 parser_sync.add_argument(
605 '--chromeos', action='store_true', help='sync chromeos mirror and tree')
606 parser_sync.add_argument(
607 '--android',
608 metavar='BRANCH',
609 action='append',
610 default=[],
611 help='sync android mirror and tree of BRANCH')
612 parser_sync.set_defaults(func=cmd_sync)
613
614 parser_new = subparsers.add_parser(
615 'new',
616 help='Create new source checkout for bisect',
617 description='Create for all if no projects are specified '
618 '(--chrome, --chromeos, or --android)')
619 parser_new.add_argument('--session', required=True)
620 parser_new.add_argument(
621 '--chrome', action='store_true', help='create chrome checkout')
622 parser_new.add_argument(
623 '--chromeos', action='store_true', help='create chromeos checkout')
624 parser_new.add_argument(
625 '--android',
626 metavar='BRANCH',
627 action='append',
628 default=[],
629 help='create android checkout of BRANCH')
630 parser_new.set_defaults(func=cmd_new)
631
632 parser_list = subparsers.add_parser(
633 'list', help='List existing sessions with source checkout')
634 parser_list.set_defaults(func=cmd_list)
635
636 parser_delete = subparsers.add_parser('delete', help='Delete source checkout')
637 parser_delete.add_argument('--session', required=True)
638 parser_delete.set_defaults(func=cmd_delete)
639
640 return parser
641
642
643def main():
644 common.init()
645 parser = create_parser()
646 opts = parser.parse_args()
647 common.config_logging(opts)
648
Kuang-che Wud3a4e842019-12-11 12:15:23 +0800649 # It's optional by default since python3.
650 if not opts.command:
651 parser.error('command is missing')
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800652 opts.func(opts)
653
654
655if __name__ == '__main__':
656 main()