# Released under the MIT License. See LICENSE for details.
#
"""Utilities for wrangling Android SDK bits."""
from __future__ import annotations # Docs-generation hack.
import os
import sys
from pathlib import Path
from typing import TYPE_CHECKING
from efro.error import CleanError
if TYPE_CHECKING:
pass
def _parse_lprop_file(local_properties_path: str) -> str:
with open(local_properties_path, encoding='utf-8') as infile:
lines = infile.read().splitlines()
sdk_dir_lines = [l for l in lines if 'sdk.dir=' in l]
if len(sdk_dir_lines) != 1:
raise RuntimeError("Couldn't find sdk dir in local.properties.")
sdk_dir = sdk_dir_lines[0].split('=')[1].strip()
if not os.path.isdir(sdk_dir):
raise RuntimeError(
f'Sdk dir from local.properties not found: {sdk_dir}.'
)
return sdk_dir
def _gen_lprop_file(local_properties_path: str) -> str:
os.makedirs(os.path.dirname(local_properties_path), exist_ok=True)
# Ok, we've got no local.properties file; attempt to find
# android sdk in standard locations and create a default
# one if we can.
found = False
sdk_dir = None
# First off, if they have ANDROID_SDK_ROOT set, use that.
envvar = os.environ.get('ANDROID_SDK_ROOT')
if envvar is not None:
if os.path.isdir(envvar):
sdk_dir = envvar
found = True
# Otherwise try some standard locations.
if not found:
home = os.getenv('HOME')
assert home is not None
test_paths = [home + '/Library/Android/sdk', home + '/AndroidSDK']
for sdk_dir in test_paths:
if os.path.exists(sdk_dir):
found = True
break
if not found:
print('WOULD CHECK', os.environ.get('ANDROID_SDK_ROOT'))
assert sdk_dir is not None
if not found:
if not os.path.exists(sdk_dir):
raise CleanError(
f'Android sdk not found at {sdk_dir}; install '
'the android sdk and try again.',
)
config = (
'\n# This file was automatically generated by '
+ os.path.abspath(sys.argv[0])
+ '\n'
'# Feel free to override these paths if you have your android'
' sdk elsewhere\n'
'\n'
'sdk.dir=' + sdk_dir + '\n'
)
with open(local_properties_path, 'w', encoding='utf-8') as outfile:
outfile.write(config)
print(
'Generating local.properties file (found Android SDK at "'
+ sdk_dir
+ '")',
file=sys.stderr,
)
return sdk_dir
[docs]
def get_sdk_dir(projroot: str) -> str:
"""Return the Android SDK dir, creating local.properties if needed.
Sanity-checks that the dir looks like a real SDK (adb present).
"""
local_properties_path = os.path.join(
projroot, 'ballisticakit-android', 'local.properties'
)
if os.path.isfile(local_properties_path):
sdk_dir = _parse_lprop_file(local_properties_path)
else:
sdk_dir = _gen_lprop_file(local_properties_path)
# Sanity check; look for a few things in the sdk that we expect to
# be there.
if not os.path.isfile(sdk_dir + '/platform-tools/adb'):
raise RuntimeError(
'ERROR: android sdk at "' + sdk_dir + '" does not seem valid'
)
return sdk_dir
[docs]
def gradle_sdk_pins(projroot: str) -> list[tuple[str, str]]:
"""The SDK packages the Android project pins, as (package, path).
Reads ``ndkVersion`` and ``compileSdk`` (+ ``compileSdkMinor``)
from the app's build.gradle. ``path`` is the package's dir relative
to the SDK root.
"""
import re
gradlepath = Path(
projroot, 'ballisticakit-android/BallisticaKit/build.gradle'
)
text = gradlepath.read_text(encoding='utf-8')
def _value(name: str) -> str | None:
found = re.findall(
rf'^\s*{name}\s+[\'"]?([0-9.]+)[\'"]?\s*$', text, re.MULTILINE
)
if len(found) > 1:
raise CleanError(f'Expected at most one {name} in {gradlepath}.')
return found[0] if found else None
pins: list[tuple[str, str]] = []
ndk = _value('ndkVersion')
if ndk is not None:
pins.append((f'ndk;{ndk}', f'ndk/{ndk}'))
sdk = _value('compileSdk')
if sdk is not None:
minor = _value('compileSdkMinor')
platform = (
f'android-{sdk}' if minor is None else f'android-{sdk}.{minor}'
)
pins.append((f'platforms;{platform}', f'platforms/{platform}'))
return pins
[docs]
def find_sdkmanager(sdk_dir: str) -> str | None:
"""The SDK manager command to use for ``sdk_dir`` (None if none).
The SDK's own cmdline-tools copy where present (Android Studio
installs, and Macs set up by our tooling); otherwise the snap
wrapper ``androidsdk`` (linbeast) or an ``sdkmanager`` on PATH.
"""
import shutil
own = os.path.join(sdk_dir, 'cmdline-tools', 'latest', 'bin', 'sdkmanager')
if os.path.isfile(own):
return own
# Non-interactive shells (cloudshell builds) may lack /snap/bin or
# /opt/homebrew/bin on PATH, so check those spots directly too.
for path in ('/snap/bin/androidsdk', '/opt/homebrew/bin/sdkmanager'):
if os.path.exists(path):
return path
for name in ('androidsdk', 'sdkmanager'):
found = shutil.which(name)
if found is not None:
return found
return None
[docs]
def sync(projroot: str, sdk_dir: str) -> None:
"""Install any SDK packages the project pins that are missing.
Cheap when everything is present (a few dir checks, no network), so
every Android build runs it (via ``check``); only a pin bump pays
for a download. Never removes anything: several checkouts (e.g. a
spinoff whose pin lags) can share one SDK, so pruning old packages
is left to machine upkeep.
"""
import subprocess
missing = [
pkg
for pkg, path in gradle_sdk_pins(projroot)
if not os.path.isdir(os.path.join(sdk_dir, path))
]
if not missing:
return
manager = find_sdkmanager(sdk_dir)
if manager is None:
raise CleanError(
f'Android SDK at {sdk_dir} is missing {missing} and no'
' sdkmanager was found to install them; install them by hand'
' (sdkmanager --sdk_root=<sdk> <package>...).'
)
print(
f'Installing pinned Android SDK packages {missing} into'
f' {sdk_dir}...',
file=sys.stderr,
)
# License prompts get answered from stdin. The licenses were
# accepted when each SDK was set up; new packages occasionally ask
# again.
subprocess.run(
[manager, f'--sdk_root={sdk_dir}', *missing],
input='y\n' * 20,
text=True,
check=True,
)
still = [
pkg
for pkg, path in gradle_sdk_pins(projroot)
if not os.path.isdir(os.path.join(sdk_dir, path))
]
if still:
raise CleanError(f'SDK packages still missing after install: {still}')
[docs]
def run(projroot: str, args: list[str]) -> None:
"""Main script entry point."""
if len(args) != 1:
raise CleanError('Expected 1 arg')
command = args[0]
valid_args = [
'check',
'sync',
'get-sdk-path',
'get-ndk-path',
'get-adb-path',
]
if command not in valid_args:
print('INVALID ARG; expected one of', valid_args, file=sys.stderr)
sys.exit(255)
# In all cases we make sure there's a local.properties in our android
# dir that contains a valid sdk path. If not, we attempt to create it.
sdk_dir = get_sdk_dir(projroot)
# Sanity check: if they've got ANDROID_HOME set, make sure it lines up with
# what we're pointing at.
android_home = os.getenv('ANDROID_HOME')
if android_home is not None:
if android_home != sdk_dir:
print(
'ERROR: sdk dir mismatch; ANDROID_HOME is "'
+ android_home
+ '" but local.properties set to "'
+ sdk_dir
+ '"',
file=sys.stderr,
)
sys.exit(255)
# Every build's 'check' also makes sure the pinned NDK and platform
# are installed (cheap when they are).
if command in ('check', 'sync'):
sync(projroot, sdk_dir)
if command == 'get-sdk-path':
print(sdk_dir)
# We no longer add the ndk path to local.properties (doing so is
# obsolete) but we still want to support returning the ndk path, as
# some things such as external python builds still ask for this. So
# now we just pull it from the project gradle file where we set it
# explicitly.
if command == 'get-ndk-path':
gradlepath = Path(
projroot, 'ballisticakit-android/BallisticaKit/build.gradle'
)
with gradlepath.open(encoding='utf-8') as infile:
lines = [
l
for l in infile.readlines()
if l.strip().startswith('ndkVersion ')
]
if len(lines) != 1:
raise RuntimeError(
f'Expected exactly one ndkVersion line in build.gradle;'
f' found {len(lines)}'
)
ver = lines[0].strip().replace("'", '').replace('"', '').split()[-1]
path = os.path.join(sdk_dir, 'ndk', ver)
if not os.path.isdir(path):
raise RuntimeError(
f'NDK path listed in gradle file not found: {path}.'
)
print(path)
if command == 'get-adb-path':
import subprocess
adbpath = Path(sdk_dir, 'platform-tools/adb')
if not os.path.exists(adbpath):
raise RuntimeError(f"ADB not found at expected path '{adbpath}'.")
# Ok, we've got a valid adb path.
# Now, for extra credit, let's see if 'which adb' points to the
# same one and simply return 'adb' if so. This makes our make
# output nice and readable (and hopefully won't cause problems)
result = subprocess.run(
'which adb', shell=True, capture_output=True, check=False
)
if result.returncode == 0:
wpath = result.stdout.decode().strip()
if wpath == str(adbpath):
print('adb')
return
print(adbpath)
# Docs-generation hack; import some stuff that we likely only forward-declared
# in our actual source code so that docs tools can find it.
from typing import (Coroutine, Any, Literal, Callable,
Generator, Awaitable, Sequence, Self, TypeIs)
import asyncio
from concurrent.futures import Future
from pathlib import Path
from enum import Enum