blob: 6937742227fd59465771203165f0c52dc97a4461 [file]
#!/usr/bin/env python3
# Copyright 2026 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# Note: AI-generated developer script for local benchmarking with realistic
# user profiles instead of empty profiles.
#
# Intended behavior / design spec:
# - `create <snapshot>`: Force-stops Chrome, archives
# `/data/user/<user_id>/<package>` on the device as root (`su 0` preferred
# over `adb root` so forwarded TCP connections stay up) into a `0700`
# `/data/local/tmp` staging tarball, pulls it locally, and writes an
# uncompressed (`ZIP_STORED`) `.snapshot` zip containing `metadata.json` +
# `data.tar.gz` (avoiding recompressing the device-built tarball on the host
# or injecting metadata files into `/data/user/...` on restore). On-device
# `tar` is used instead of recursive `adb pull`/`adb push` because non-root
# `adbd` cannot access `/data/user/...` directly, profiles hold thousands
# of small files (and names with whitespace/newlines), and `tar` preserves
# mtimes, permissions, symlinks, and hardlinks.
# - `restore <snapshot>`: Validates `data.tar.gz` locally, pushes it to
# `/data/local/tmp`, clears target data via `pm clear`, extracts with
# `tar -xozf` (preserving mtimes, symlinks, and hardlinks), and restores
# app UID/GID, cache-group ownership, and SELinux labels.
# - `extract <snapshot> [output_dir]`: Unpacks `metadata.json` and `data/`
# into a local `0700` directory.
# - `wipe`: Resets the target package's data directory via `pm clear`.
#
# On-disk paths relied on inside `/data/user/<user_id>/<package>`:
# - Captures the full package data directory rather than an allowlist of
# Chrome subdirectories.
# - `./lib`: Excluded on `create` and rejected on `restore`
# (`PackageManager`-managed native-library symlink).
# - `./code_cache`: Always excluded. This is Android's `getCodeCacheDir()`
# (device/GPU/APK-specific shader and DEX caches, wiped by Android on app
# updates), not Chrome's V8 JS/Wasm `Code Cache` (`./cache/Code Cache`).
# - `./cache`: Excluded by default because HTTP `Cache/` can be multiple GiB;
# included with `--include-disk-caches` (still excluding Crashpad/Crash
# Reports, Local Traces, and `oat_primary`).
# - `shared_prefs/<package>_preferences.xml` (and `.bak`): Renamed from
# `<source_package>` to `<target_package>` when restoring across channels.
# - `cache` and `code_cache`: If present after `restore`, chowned to
# `<uid>:<app_user>_cache` with `mode 2771` (`drwxrws--x`, matching Android
# `installd` / `ContextImpl.fixupCacheDir`'s setgid cache-quota directory
# mode after `chown -hR <uid>:<gid>` resets their group).
"""Create, restore, extract, and wipe Chrome Android data snapshots via adb.
Useful for benchmarking Chrome with a realistic user profile instead of an
empty profile.
WARNING: Snapshots include sensitive user data such as cookies and signed-in
sessions. Keep snapshot files private, delete them when no longer needed, and
run the `wipe` subcommand on the target device afterwards to clear transferred
data.
Examples:
tools/android/device_data_snapshot.py create foo.snapshot --channel canary
tools/android/device_data_snapshot.py restore foo.snapshot --channel stable
tools/android/device_data_snapshot.py extract foo.snapshot [output_dir]
tools/android/device_data_snapshot.py wipe --channel stable
"""
import argparse
import contextlib
import datetime
import gzip
import json
import logging
import os
import pathlib
import posixpath
import re
import shlex
import shutil
import sys
import tarfile
import tempfile
import uuid
import zipfile
import zlib
_SRC_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
sys.path.append(os.path.join(_SRC_PATH, 'third_party', 'catapult', 'devil'))
sys.path.append(os.path.join(_SRC_PATH, 'build', 'android'))
import devil_chromium
from devil import base_error
from devil.android import device_utils
from devil.android.constants import chrome
from devil.android.sdk import adb_wrapper
_CHANNEL_TO_PACKAGE = {
'stable': chrome.PACKAGE_INFO['chrome_stable'].package,
'beta': chrome.PACKAGE_INFO['chrome_beta'].package,
'dev': chrome.PACKAGE_INFO['chrome_dev'].package,
'canary': chrome.PACKAGE_INFO['chrome_canary'].package,
'chrome': chrome.PACKAGE_INFO['chrome'].package,
'chromium': chrome.PACKAGE_INFO['chromium'].package,
}
_PACKAGE_TO_CHANNEL = {pkg: ch for ch, pkg in _CHANNEL_TO_PACKAGE.items()}
_DEFAULT_CHANNEL = 'stable'
_PACKAGE_RE = re.compile(r'[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)+')
_APP_USER_RE = re.compile(r'u\d+_a\d+')
_SNAPSHOT_FORMAT_VERSION = 1
_METADATA_ENTRY = 'metadata.json'
_DATA_ARCHIVE_ENTRY = 'data.tar.gz'
_STREAM_CHUNK_SIZE = 65536
_ARCHIVE_ERRORS = (
tarfile.TarError,
zipfile.BadZipFile,
zlib.error,
EOFError,
KeyError,
ValueError,
OSError,
)
_ALWAYS_EXCLUDES = (
'./code_cache',
'./lib',
)
_CACHE_EXCLUDES = (
'./cache/Crash Reports',
'./cache/Crashpad',
'./cache/Local Traces',
'./cache/oat_primary',
)
class _SnapshotError(RuntimeError):
"""Raised when a snapshot operation fails."""
def _format_size(num_bytes):
size = float(num_bytes)
for unit in ('B', 'KiB', 'MiB', 'GiB'):
if size < 1024.0:
if unit == 'B':
return f'{int(size)} B'
return f'{size:.1f} {unit}'
size /= 1024.0
return f'{size:.1f} TiB'
def _parse_major_version(version_name):
if not isinstance(version_name, str) or not version_name:
return None
match = re.match(r'^(\d+)\.', version_name.strip())
return int(match.group(1)) if match else None
def _resolve_package(channel, package, default_package=None):
if package is not None:
if not _PACKAGE_RE.fullmatch(package):
raise _SnapshotError(f'Invalid Android package name: {package!r}')
return package, _PACKAGE_TO_CHANNEL.get(package)
if channel is None and default_package is not None:
return default_package, _PACKAGE_TO_CHANNEL.get(default_package)
resolved_channel = channel or _DEFAULT_CHANNEL
return _CHANNEL_TO_PACKAGE[resolved_channel], resolved_channel
def _format_source_desc(metadata):
source_desc = metadata.get('source_package') or 'unknown package'
source_version = metadata.get('chrome_version')
if source_version:
source_desc += f' (Chrome {source_version})'
return source_desc
def _ensure_root(device):
if device.HasRoot() or device.NeedsSU():
return
try:
device.EnableRoot()
except base_error.BaseError as e:
raise _SnapshotError(
f'Root access is required on {device.serial} to access Chrome data '
f'directories (requires a userdebug/eng build or rooted emulator): {e}'
) from e
@contextlib.contextmanager
def _remote_temp_file(device):
staging_dir = (
f'/data/local/tmp/device_data_snapshot_{os.getpid()}_{uuid.uuid4().hex[:8]}'
)
remote_path = f'{staging_dir}/{_DATA_ARCHIVE_ENTRY}'
# Create without as_root so the 0700 staging directory is owned by the adbd
# user (`shell` in su mode, `root` in direct mode), allowing adb push/pull
# while keeping the archive inaccessible to other users on the device.
device.RunShellCommand(['mkdir', '-m', '700', staging_dir], check_return=True)
try:
yield remote_path
finally:
device.RunShellCommand(
['rm', '-rf', staging_dir],
as_root=True,
check_return=False,
)
def _connect_target(args, default_package=None):
if args.device is not None and not args.device.strip():
raise _SnapshotError('Device serial cannot be empty.')
package, channel = _resolve_package(
args.channel, args.package, default_package=default_package
)
devil_chromium.Initialize()
device = device_utils.DeviceUtils.HealthyDevices(
device_arg=[args.device] if args.device is not None else None,
retries=0,
persistent_shell=False,
)[0]
if not device.IsOnline():
raise _SnapshotError(f'Device {device.serial} is not online.')
device.target_user = device.GetCurrentUser()
if not device.IsApplicationInstalled(package):
raise _SnapshotError(
f'Package {package} is not installed on {device.serial}.'
)
return device, package, channel
@contextlib.contextmanager
def _open_snapshot(snapshot_path):
if not snapshot_path.is_file():
raise _SnapshotError(f'Snapshot file not found: {snapshot_path}')
zf = None
try:
try:
zf = zipfile.ZipFile(snapshot_path)
zf.getinfo(_DATA_ARCHIVE_ENTRY)
metadata = json.loads(zf.read(_METADATA_ENTRY))
except _ARCHIVE_ERRORS as e:
raise _SnapshotError(
f'Not a valid snapshot archive {snapshot_path}: {e}'
) from e
if not isinstance(metadata, dict):
raise _SnapshotError(
f'Corrupt metadata in snapshot {snapshot_path}: expected JSON object.'
)
fmt_version = metadata.get('format_version')
if fmt_version != _SNAPSHOT_FORMAT_VERSION:
raise _SnapshotError(
f'Unsupported snapshot format version {fmt_version!r} '
f'(expected {_SNAPSHOT_FORMAT_VERSION}).'
)
source_package = metadata.get('source_package')
if source_package is not None and not (
isinstance(source_package, str) and _PACKAGE_RE.fullmatch(source_package)
):
raise _SnapshotError(
f'Invalid source_package in snapshot metadata: {source_package!r}'
)
yield zf, metadata
finally:
if zf is not None:
zf.close()
def _write_snapshot_atomically(snapshot_path, metadata, data_tar_gz_path):
tmp_path = None
try:
snapshot_path.parent.mkdir(parents=True, exist_ok=True)
# NamedTemporaryFile creates the temp file with 0600 permissions before
# writing any sensitive data. Default ZIP_STORED avoids recompressing the
# already gzipped tar archive.
with tempfile.NamedTemporaryFile(
dir=snapshot_path.parent,
prefix=f'.{snapshot_path.name}.',
suffix='.tmp',
delete=False,
) as f:
tmp_path = pathlib.Path(f.name)
with zipfile.ZipFile(f, 'w') as zf:
zf.writestr(_METADATA_ENTRY, json.dumps(metadata, indent=2) + '\n')
zf.write(data_tar_gz_path, arcname=_DATA_ARCHIVE_ENTRY)
size_bytes = f.tell()
os.replace(tmp_path, snapshot_path)
return size_bytes
except BaseException as e:
if tmp_path is not None:
tmp_path.unlink(missing_ok=True)
if isinstance(e, OSError):
raise _SnapshotError(
f'Failed to write snapshot {snapshot_path}: {e}'
) from e
raise
def _cmd_create(args):
snapshot_path = pathlib.Path(args.snapshot)
if snapshot_path.is_dir():
raise _SnapshotError(f'Snapshot path is a directory: {snapshot_path}')
device, package, channel = _connect_target(args)
_ensure_root(device)
user_id = device.target_user
data_dir = f'/data/user/{user_id}/{package}'
if not device.PathExists(data_dir, as_root=True):
raise _SnapshotError(
f'Data directory {data_dir} does not exist on {device.serial}.'
)
excludes = list(_ALWAYS_EXCLUDES)
if args.include_disk_caches:
excludes.extend(_CACHE_EXCLUDES)
else:
excludes.append('./cache')
print(
'Excluding cache/ (pass --include-disk-caches to include HTTP and V8 '
'code caches).'
)
print(f'Stopping {package} on {device.serial}...')
device.RunShellCommand(
['am', 'force-stop', '--user', str(user_id), package],
check_return=True,
)
with _remote_temp_file(device) as remote_tmp:
tar_cmd = ['tar', '-czf', remote_tmp, '-C', data_dir]
for pattern in excludes:
tar_cmd.extend(['--exclude', pattern])
tar_cmd.append('.')
archive_script = ' && '.join(
[
'umask 077',
shlex.join(tar_cmd),
shlex.join(['chown', 'shell:shell', remote_tmp]),
]
)
print(f'Archiving {data_dir} on {device.serial}...')
device.RunShellCommand(
archive_script,
shell=True,
as_root=True,
check_return=True,
timeout=adb_wrapper.DEFAULT_SUPER_LONG_TIMEOUT,
retries=0,
)
with tempfile.TemporaryDirectory(prefix='chrome_snapshot_') as tmpdir:
local_tar_gz = pathlib.Path(tmpdir) / _DATA_ARCHIVE_ENTRY
print(f'Pulling snapshot data from {device.serial}...')
device.adb.Pull(remote_tmp, str(local_tar_gz))
_validate_tar_gz(local_tar_gz)
metadata = {
'format_version': _SNAPSHOT_FORMAT_VERSION,
'source_package': package,
'source_channel': channel,
'chrome_version': device.GetApplicationVersion(package),
'android_sdk': device.build_version_sdk,
'device_abi': device.product_cpu_abi or None,
'include_disk_caches': bool(args.include_disk_caches),
'created_at': datetime.datetime.now(datetime.timezone.utc).strftime(
'%Y-%m-%dT%H:%M:%SZ'
),
}
print(f'Writing {snapshot_path}...')
size_bytes = _write_snapshot_atomically(
snapshot_path, metadata, local_tar_gz
)
size_str = _format_size(size_bytes)
print(
f'Created snapshot {snapshot_path} ({size_str}) '
f'from {_format_source_desc(metadata)}.'
)
print(
'\nWARNING: This snapshot contains sensitive user data, including cookies\n'
'and signed-in sessions. Keep it private, delete it when no longer\n'
'needed, and run `wipe` on any target device after restoring.',
file=sys.stderr,
)
return 0
def _has_unsafe_relpath(path):
return not path or path.startswith(('/', '\\')) or '..' in path.split('/')
def _is_forbidden_lib_path(norm_path):
return norm_path == 'lib' or norm_path.startswith('lib/')
class _TarValidator:
"""Stateful tar member validator usable standalone or as extractall filter."""
def __init__(self):
self._default_root = (
pathlib.Path(tempfile.gettempdir()) / f'root_{uuid.uuid4().hex}'
)
self._files = set()
self._dirs = set()
self._symlinks = {}
self._has_entries = False
def __call__(self, member, dest_path=None):
self._has_entries = True
if _has_unsafe_relpath(member.name):
raise _SnapshotError(
f'Unsafe member path in snapshot archive: {member.name!r}'
)
filtered = tarfile.data_filter(member, dest_path or self._default_root)
norm = posixpath.normpath(member.name)
if _is_forbidden_lib_path(norm):
raise _SnapshotError(
f'Snapshot archive contains forbidden top-level lib entry: '
f'{member.name!r}'
)
parent = posixpath.dirname(norm)
while parent and parent != '.':
if parent in self._symlinks or parent in self._files:
raise _SnapshotError(
f'Snapshot archive traverses non-directory {parent!r}: '
f'{member.name!r}'
)
self._dirs.add(parent)
parent = posixpath.dirname(parent)
if member.isdir():
if norm in self._files or norm in self._symlinks:
raise _SnapshotError(
f'Conflicting directory entry in snapshot archive: {member.name!r}'
)
if norm != '.':
self._dirs.add(norm)
return filtered
if (
norm == '.'
or norm in self._files
or norm in self._dirs
or norm in self._symlinks
):
raise _SnapshotError(
f'Duplicate or conflicting entry in snapshot archive: {member.name!r}'
)
if member.issym():
if _has_unsafe_relpath(member.linkname):
raise _SnapshotError(
f'Unsafe symlink target {member.linkname!r} for {member.name!r}'
)
target_norm = posixpath.normpath(
posixpath.join(posixpath.dirname(norm), member.linkname)
)
if target_norm == '.' or _is_forbidden_lib_path(target_norm):
raise _SnapshotError(
f'Unsafe symlink target {member.linkname!r} for {member.name!r}'
)
self._symlinks[norm] = target_norm
elif member.islnk():
if (
_has_unsafe_relpath(member.linkname)
or posixpath.normpath(member.linkname) not in self._files
):
raise _SnapshotError(
f'Unsafe hardlink target {member.linkname!r} for {member.name!r}'
)
self._files.add(norm)
elif member.isreg():
self._files.add(norm)
else:
raise _SnapshotError(
f'Unsupported tar member type in snapshot archive: {member.name!r}'
)
return filtered
def finish(self):
if not self._has_entries:
raise _SnapshotError('Snapshot data archive is empty.')
for link_name, target_norm in self._symlinks.items():
cur = target_norm
while cur and cur != '.':
if cur in self._symlinks:
raise _SnapshotError(
f'Chained symlink {link_name!r} is unsupported in snapshot archive.'
)
cur = posixpath.dirname(cur)
def _stream_tar_gz(fileobj, extract_to=None):
validator = _TarValidator()
with gzip.GzipFile(fileobj=fileobj) as gz:
with tarfile.open(fileobj=gz, mode='r|') as tf:
if extract_to is None:
for member in tf:
validator(member)
else:
tf.extractall(extract_to, filter=validator)
# Drain past tar's EOF zero blocks so gzip verifies trailing CRC32/ISIZE.
while gz.read(_STREAM_CHUNK_SIZE):
pass
validator.finish()
def _validate_tar_gz(tar_gz_path):
try:
with open(tar_gz_path, 'rb') as f:
_stream_tar_gz(f)
except _ARCHIVE_ERRORS as e:
raise _SnapshotError(
f'Corrupt or invalid snapshot data archive: {e}'
) from e
def _cmd_restore(args):
snapshot_path = pathlib.Path(args.snapshot)
with (
_open_snapshot(snapshot_path) as (zf, metadata),
tempfile.TemporaryDirectory(prefix='chrome_snapshot_') as tmpdir,
):
source_package = metadata.get('source_package')
device, target_package, target_channel = _connect_target(
args, default_package=source_package
)
source_version = metadata.get('chrome_version')
target_version = device.GetApplicationVersion(target_package)
source_major = _parse_major_version(source_version)
target_major = _parse_major_version(target_version)
if (
source_major is not None
and target_major is not None
and source_major > target_major
):
print(
f'WARNING: Snapshot was created from Chrome {source_version}, which is '
f'newer than target Chrome {target_version}. Downgrading profile data '
'across major Chrome versions may fail or cause crashes.',
file=sys.stderr,
)
_ensure_root(device)
user_id = device.target_user
data_dir = f'/data/user/{user_id}/{target_package}'
# Extract, validate, and push before clearing the target so a corrupt or
# unsafe snapshot or failed transfer does not destroy existing profile data.
try:
local_tar_gz = pathlib.Path(zf.extract(_DATA_ARCHIVE_ENTRY, tmpdir))
except _ARCHIVE_ERRORS as e:
raise _SnapshotError(
f'Corrupt or invalid snapshot data archive in {snapshot_path}: {e}'
) from e
_validate_tar_gz(local_tar_gz)
with _remote_temp_file(device) as remote_tmp:
print(f'Pushing snapshot data to {device.serial}...')
device.adb.Push(str(local_tar_gz), remote_tmp)
print(
f'Clearing existing data for {target_package} on {device.serial}...'
)
device.ClearApplicationState(target_package)
stat_out = device.RunShellCommand(
['stat', '-c', '%u %g %U %a %C', data_dir],
as_root=True,
check_return=True,
single_line=True,
)
parts = stat_out.split()
if len(parts) != 5:
raise _SnapshotError(
f'Unexpected stat output for {data_dir}: {stat_out!r}'
)
uid, gid, user_name, mode, secontext = parts
force_stop_cmd = shlex.join(
['am', 'force-stop', '--user', str(user_id), target_package]
)
steps = [
force_stop_cmd,
shlex.join(['tar', '-xozf', remote_tmp, '-C', data_dir]),
]
if source_package and source_package != target_package:
prefs_dir = f'{data_dir}/shared_prefs'
q_prefs_dir = shlex.quote(prefs_dir)
for suffix in ('_preferences.xml', '_preferences.xml.bak'):
q_src = shlex.quote(f'{prefs_dir}/{source_package}{suffix}')
q_dst = shlex.quote(f'{prefs_dir}/{target_package}{suffix}')
steps.append(
f'if [ -d {q_prefs_dir} ] && [ ! -L {q_prefs_dir} ] && '
f'[ -f {q_src} ] && [ ! -L {q_src} ] && [ ! -d {q_dst} ]; then '
f'mv -f {q_src} {q_dst}; fi'
)
steps.append(shlex.join(['chmod', mode, data_dir]))
steps.append(shlex.join(['chown', '-hR', f'{uid}:{gid}', data_dir]))
if _APP_USER_RE.fullmatch(user_name):
cache_owner = shlex.quote(f'{uid}:{user_name}_cache')
for subdir in ('cache', 'code_cache'):
cache_path = shlex.quote(f'{data_dir}/{subdir}')
steps.append(
f'if [ -d {cache_path} ] && [ ! -L {cache_path} ]; then '
f'(chown -hR {cache_owner} {cache_path} || true) && '
f'chmod 2771 {cache_path}; fi'
)
if secontext != '?':
steps.append(shlex.join(['chcon', '-hR', secontext, data_dir]))
steps.append(force_stop_cmd)
print(f'Restoring data into {data_dir} on {device.serial}...')
device.RunShellCommand(
' && '.join(steps),
shell=True,
as_root=True,
check_return=True,
timeout=adb_wrapper.DEFAULT_SUPER_LONG_TIMEOUT,
retries=0,
)
print(
f'Restored snapshot from {_format_source_desc(metadata)} '
f'to {target_package} on {device.serial}.'
)
wipe_parts = [
'tools/android/device_data_snapshot.py',
'wipe',
'--device',
device.serial,
]
if target_channel:
wipe_parts.extend(['--channel', target_channel])
else:
wipe_parts.extend(['--package', target_package])
wipe_cmd = shlex.join(wipe_parts)
print(
f'\nWARNING: Cookies and signed-in sessions were transferred to '
f'{target_package} on {device.serial}.\n'
f'When finished, wipe the transferred data with:\n'
f' {wipe_cmd}',
file=sys.stderr,
)
return 0
def _cmd_extract(args):
snapshot_path = pathlib.Path(args.snapshot)
if args.output_dir is not None:
if not args.output_dir:
raise _SnapshotError('Output directory cannot be empty.')
output_dir = pathlib.Path(args.output_dir)
elif snapshot_path.suffix:
output_dir = snapshot_path.with_suffix('')
else:
output_dir = snapshot_path.with_name(f'{snapshot_path.name}.extracted')
with _open_snapshot(snapshot_path) as (zf, metadata):
try:
created_output_dir = not output_dir.exists()
if created_output_dir:
output_dir.mkdir(parents=True, mode=0o700)
elif not output_dir.is_dir():
raise _SnapshotError(
f'Output path exists and is not a directory: {output_dir}'
)
elif any(output_dir.iterdir()):
raise _SnapshotError(f'Output directory is not empty: {output_dir}')
except OSError as e:
raise _SnapshotError(
f'Failed to prepare output directory {output_dir}: {e}'
) from e
data_out = output_dir / 'data'
metadata_out = output_dir / _METADATA_ENTRY
try:
data_out.mkdir(mode=0o700)
print(f'Extracting {snapshot_path} to {output_dir}...')
with zf.open(_DATA_ARCHIVE_ENTRY) as src:
_stream_tar_gz(src, extract_to=data_out)
os.chmod(data_out, 0o700)
metadata_out.write_text(
json.dumps(metadata, indent=2) + '\n',
encoding='utf-8',
newline='',
)
except BaseException as e:
shutil.rmtree(data_out, ignore_errors=True)
metadata_out.unlink(missing_ok=True)
if created_output_dir:
with contextlib.suppress(OSError):
output_dir.rmdir()
if isinstance(e, _ARCHIVE_ERRORS):
raise _SnapshotError(
f'Failed to extract snapshot {snapshot_path}: {e}'
) from e
raise
print(
f'Extracted snapshot from {_format_source_desc(metadata)} to {output_dir}:'
)
print(f' metadata: {metadata_out}')
print(f' data: {data_out}')
print(
'\nWARNING: The extracted directory contains sensitive user data,\n'
'including cookies and signed-in sessions. Keep it private and delete it\n'
'when no longer needed.',
file=sys.stderr,
)
return 0
def _cmd_wipe(args):
device, package, _ = _connect_target(args)
print(f'Wiping data for {package} on {device.serial}...')
device.ClearApplicationState(package)
print(f'Cleared data for {package} on {device.serial}.')
return 0
def _build_parser():
common = argparse.ArgumentParser(add_help=False)
common.add_argument(
'-d',
'--device',
metavar='ADB_SERIAL',
help='Target adb device serial (defaults to ANDROID_SERIAL or the sole '
'connected device).',
)
target_group = common.add_mutually_exclusive_group()
target_group.add_argument(
'--channel',
choices=tuple(_CHANNEL_TO_PACKAGE),
help='Chrome channel (default: snapshot source on restore, else '
f'{_DEFAULT_CHANNEL}).',
)
target_group.add_argument(
'--package',
help='Explicit Android package name (mutually exclusive with --channel).',
)
common.add_argument(
'-v',
'--verbose',
action='store_true',
help='Log adb commands executed on the device.',
)
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
subparsers = parser.add_subparsers(required=True)
create_parser = subparsers.add_parser(
'create',
parents=[common],
help='Create a snapshot archive of Chrome data from a device.',
)
create_parser.add_argument(
'snapshot',
help='Path to the output snapshot file.',
)
create_parser.add_argument(
'--include-disk-caches',
action='store_true',
help='Include cache/ (HTTP and V8 code caches) in the snapshot. Excluded '
'by default because it can be multiple GiB.',
)
create_parser.set_defaults(func=_cmd_create)
restore_parser = subparsers.add_parser(
'restore',
parents=[common],
help='Restore a snapshot archive onto a device.',
)
restore_parser.add_argument(
'snapshot',
help='Path to the snapshot file to restore.',
)
restore_parser.set_defaults(func=_cmd_restore)
extract_parser = subparsers.add_parser(
'extract',
help='Extract a snapshot archive to a local directory.',
)
extract_parser.add_argument(
'snapshot',
help='Path to the snapshot file to extract.',
)
extract_parser.add_argument(
'output_dir',
nargs='?',
help='Destination directory (defaults to the snapshot path without its '
'extension, or <snapshot>.extracted).',
)
extract_parser.set_defaults(func=_cmd_extract)
wipe_parser = subparsers.add_parser(
'wipe',
parents=[common],
help='Reset Chrome data on a device via `pm clear`.',
)
wipe_parser.set_defaults(func=_cmd_wipe)
return parser
def main(argv=None):
parser = _build_parser()
args = parser.parse_args(argv)
if getattr(args, 'verbose', False):
logging.basicConfig(level=logging.DEBUG, format='%(levelname)s:%(message)s')
try:
return args.func(args)
except (_SnapshotError, base_error.BaseError) as e:
print(f'Error: {e}', file=sys.stderr)
return 1
if __name__ == '__main__':
sys.exit(main())