Skip to content

Commit 0615113

Browse files
authored
Merge branch 'main' into gh-144278
2 parents 3f4b3c5 + 53fecbe commit 0615113

34 files changed

+392
-257
lines changed

Android/android.py

Lines changed: 80 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
from asyncio import wait_for
1616
from contextlib import asynccontextmanager
1717
from datetime import datetime, timezone
18+
from enum import IntEnum, auto
1819
from glob import glob
1920
from os.path import abspath, basename, relpath
2021
from pathlib import Path
@@ -61,6 +62,19 @@
6162
hidden_output = []
6263

6364

65+
# Based on android/log.h in the NDK.
66+
class LogPriority(IntEnum):
67+
UNKNOWN = 0
68+
DEFAULT = auto()
69+
VERBOSE = auto()
70+
DEBUG = auto()
71+
INFO = auto()
72+
WARN = auto()
73+
ERROR = auto()
74+
FATAL = auto()
75+
SILENT = auto()
76+
77+
6478
def log_verbose(context, line, stream=sys.stdout):
6579
if context.verbose:
6680
stream.write(line)
@@ -505,47 +519,47 @@ async def logcat_task(context, initial_devices):
505519
pid = await wait_for(find_pid(serial), startup_timeout)
506520

507521
# `--pid` requires API level 24 or higher.
508-
args = [adb, "-s", serial, "logcat", "--pid", pid, "--format", "tag"]
522+
#
523+
# `--binary` mode is used in order to detect which messages end with a
524+
# newline, which most of the other modes don't indicate (except `--format
525+
# long`). For example, every time pytest runs a test, it prints a "." and
526+
# flushes the stream. Each "." becomes a separate log message, but we should
527+
# show them all on the same line.
528+
args = [adb, "-s", serial, "logcat", "--pid", pid, "--binary"]
509529
logcat_started = False
510530
async with async_process(
511-
*args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
531+
*args, stdout=subprocess.PIPE, stderr=None
512532
) as process:
513-
while line := (await process.stdout.readline()).decode(*DECODE_ARGS):
514-
if match := re.fullmatch(r"([A-Z])/(.*)", line, re.DOTALL):
533+
while True:
534+
try:
535+
priority, tag, message = await read_logcat(process.stdout)
515536
logcat_started = True
516-
level, message = match.groups()
517-
else:
518-
# If the regex doesn't match, this is either a logcat startup
519-
# error, or the second or subsequent line of a multi-line
520-
# message. Python won't produce multi-line messages, but other
521-
# components might.
522-
level, message = None, line
537+
except asyncio.IncompleteReadError:
538+
break
523539

524540
# Exclude high-volume messages which are rarely useful.
525541
if context.verbose < 2 and "from python test_syslog" in message:
526542
continue
527543

528544
# Put high-level messages on stderr so they're highlighted in the
529545
# buildbot logs. This will include Python's own stderr.
530-
stream = (
531-
sys.stderr
532-
if level in ["W", "E", "F"] # WARNING, ERROR, FATAL (aka ASSERT)
533-
else sys.stdout
534-
)
535-
536-
# To simplify automated processing of the output, e.g. a buildbot
537-
# posting a failure notice on a GitHub PR, we strip the level and
538-
# tag indicators from Python's stdout and stderr.
539-
for prefix in ["python.stdout: ", "python.stderr: "]:
540-
if message.startswith(prefix):
541-
global python_started
542-
python_started = True
543-
stream.write(message.removeprefix(prefix))
544-
break
546+
stream = sys.stderr if priority >= LogPriority.WARN else sys.stdout
547+
548+
# The app's stdout and stderr should be passed through transparently
549+
# to our own corresponding streams.
550+
if tag in ["python.stdout", "python.stderr"]:
551+
global python_started
552+
python_started = True
553+
stream.write(message)
554+
stream.flush()
545555
else:
546556
# Non-Python messages add a lot of noise, but they may
547-
# sometimes help explain a failure.
548-
log_verbose(context, line, stream)
557+
# sometimes help explain a failure. Format them in the same way
558+
# as `logcat --format tag`.
559+
formatted = f"{priority.name[0]}/{tag}: {message}"
560+
if not formatted.endswith("\n"):
561+
formatted += "\n"
562+
log_verbose(context, formatted, stream)
549563

550564
# If the device disconnects while logcat is running, which always
551565
# happens in --managed mode, some versions of adb return non-zero.
@@ -556,6 +570,44 @@ async def logcat_task(context, initial_devices):
556570
raise CalledProcessError(status, args)
557571

558572

573+
# Read one binary log message from the given StreamReader. The message format is
574+
# described at https://android.stackexchange.com/a/74660. All supported versions
575+
# of Android use format version 2 or later.
576+
async def read_logcat(stream):
577+
async def read_bytes(size):
578+
return await stream.readexactly(size)
579+
580+
async def read_int(size):
581+
return int.from_bytes(await read_bytes(size), "little")
582+
583+
payload_len = await read_int(2)
584+
if payload_len < 2:
585+
# 1 byte for priority, 1 byte for null terminator of tag.
586+
raise ValueError(f"payload length {payload_len} is too short")
587+
588+
header_len = await read_int(2)
589+
if header_len < 4:
590+
raise ValueError(f"header length {header_len} is too short")
591+
await read_bytes(header_len - 4) # Ignore other header fields.
592+
593+
priority_int = await read_int(1)
594+
try:
595+
priority = LogPriority(priority_int)
596+
except ValueError:
597+
priority = LogPriority.UNKNOWN
598+
599+
payload_fields = (await read_bytes(payload_len - 1)).split(b"\0")
600+
if len(payload_fields) < 2:
601+
raise ValueError(
602+
f"payload {payload!r} does not contain at least 2 "
603+
f"null-separated fields"
604+
)
605+
tag, message, *_ = [
606+
field.decode(*DECODE_ARGS) for field in payload_fields
607+
]
608+
return priority, tag, message
609+
610+
559611
def stop_app(serial):
560612
run([adb, "-s", serial, "shell", "am", "force-stop", APP_ID], log=False)
561613

Android/testbed/app/build.gradle.kts

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -94,10 +94,13 @@ android {
9494
}
9595

9696
// This controls the API level of the maxVersion managed emulator, which is used
97-
// by CI and cibuildwheel. 34 takes up too much disk space (#142289), 35 has
98-
// issues connecting to the internet (#142387), and 36 and later are not
99-
// available as aosp_atd images yet.
100-
targetSdk = 33
97+
// by CI and cibuildwheel.
98+
// * 33 has excessive buffering in the logcat client
99+
// (https://cs.android.com/android/_/android/platform/system/logging/+/d340721894f223327339010df59b0ac514308826).
100+
// * 34 consumes too much disk space on GitHub Actions (#142289).
101+
// * 35 has issues connecting to the internet (#142387).
102+
// * 36 and later are not available as aosp_atd images yet.
103+
targetSdk = 32
101104

102105
versionCode = 1
103106
versionName = "1.0"
@@ -130,9 +133,10 @@ android {
130133
path("src/main/c/CMakeLists.txt")
131134
}
132135

133-
// Set this property to something non-empty, otherwise it'll use the default
134-
// list, which ignores asset directories beginning with an underscore.
135-
aaptOptions.ignoreAssetsPattern = ".git"
136+
// Set this property to something nonexistent but non-empty. Otherwise it'll use the
137+
// default list, which ignores asset directories beginning with an underscore, and
138+
// maybe also other files required by tests.
139+
aaptOptions.ignoreAssetsPattern = "android-testbed-dont-ignore-anything"
136140

137141
compileOptions {
138142
sourceCompatibility = JavaVersion.VERSION_1_8
@@ -234,6 +238,12 @@ androidComponents.onVariants { variant ->
234238
from(cwd)
235239
}
236240
}
241+
242+
// A filename ending with .gz will be automatically decompressed
243+
// while building the APK. Avoid this by adding a dash to the end,
244+
// and add an extra dash to any filenames that already end with one.
245+
// This will be undone in MainActivity.kt.
246+
rename(""".*(\.gz|-)""", "$0-")
237247
}
238248
}
239249

Android/testbed/app/src/main/java/org/python/testbed/MainActivity.kt

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,9 @@ class PythonTestRunner(val context: Context) {
8080
continue
8181
}
8282
input.use {
83-
File(targetSubdir, name).outputStream().use { output ->
83+
// Undo the .gz workaround from build.gradle.kts.
84+
val outputName = name.replace(Regex("""(.*)-"""), "$1")
85+
File(targetSubdir, outputName).outputStream().use { output ->
8486
input.copyTo(output)
8587
}
8688
}

Doc/howto/logging-cookbook.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,7 @@ messages should not. Here's how you can achieve this::
229229
# tell the handler to use this format
230230
console.setFormatter(formatter)
231231
# add the handler to the root logger
232-
logging.getLogger('').addHandler(console)
232+
logging.getLogger().addHandler(console)
233233

234234
# Now, we can log to the root logger, or any other logger. First the root...
235235
logging.info('Jackdaws love my big sphinx of quartz.')
@@ -650,7 +650,7 @@ the receiving end. A simple way of doing this is attaching a
650650

651651
import logging, logging.handlers
652652

653-
rootLogger = logging.getLogger('')
653+
rootLogger = logging.getLogger()
654654
rootLogger.setLevel(logging.DEBUG)
655655
socketHandler = logging.handlers.SocketHandler('localhost',
656656
logging.handlers.DEFAULT_TCP_LOGGING_PORT)

Doc/library/os.path.rst

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -97,15 +97,17 @@ the :mod:`glob` module.)
9797

9898
.. function:: commonprefix(list, /)
9999

100-
Return the longest path prefix (taken character-by-character) that is a
101-
prefix of all paths in *list*. If *list* is empty, return the empty string
100+
Return the longest string prefix (taken character-by-character) that is a
101+
prefix of all strings in *list*. If *list* is empty, return the empty string
102102
(``''``).
103103

104-
.. note::
104+
.. warning::
105105

106106
This function may return invalid paths because it works a
107-
character at a time. To obtain a valid path, see
108-
:func:`commonpath`.
107+
character at a time.
108+
If you need a **common path prefix**, then the algorithm
109+
implemented in this function is not secure. Use
110+
:func:`commonpath` for finding a common path prefix.
109111

110112
::
111113

Doc/library/stdtypes.rst

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2163,6 +2163,8 @@ expression support in the :mod:`re` module).
21632163

21642164
.. doctest::
21652165

2166+
>>> 'spam, spam, spam'.index('spam')
2167+
0
21662168
>>> 'spam, spam, spam'.index('eggs')
21672169
Traceback (most recent call last):
21682170
File "<python-input-0>", line 1, in <module>
@@ -2546,6 +2548,20 @@ expression support in the :mod:`re` module).
25462548

25472549
Like :meth:`rfind` but raises :exc:`ValueError` when the substring *sub* is not
25482550
found.
2551+
For example:
2552+
2553+
.. doctest::
2554+
2555+
>>> 'spam, spam, spam'.rindex('spam')
2556+
12
2557+
>>> 'spam, spam, spam'.rindex('eggs')
2558+
Traceback (most recent call last):
2559+
File "<stdin-0>", line 1, in <module>
2560+
'spam, spam, spam'.rindex('eggs')
2561+
~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^
2562+
ValueError: substring not found
2563+
2564+
See also :meth:`index` and :meth:`find`.
25492565

25502566

25512567
.. method:: str.rjust(width, fillchar=' ', /)

Doc/library/tomllib.rst

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,25 @@
44
.. module:: tomllib
55
:synopsis: Parse TOML files.
66

7-
.. versionadded:: 3.11
8-
97
.. moduleauthor:: Taneli Hukkinen
108
.. sectionauthor:: Taneli Hukkinen
119

1210
**Source code:** :source:`Lib/tomllib`
1311

1412
--------------
1513

16-
This module provides an interface for parsing TOML 1.0.0 (Tom's Obvious Minimal
14+
This module provides an interface for parsing TOML 1.1.0 (Tom's Obvious Minimal
1715
Language, `https://toml.io <https://toml.io/en/>`_). This module does not
1816
support writing TOML.
1917

18+
.. versionadded:: 3.11
19+
The module was added with support for TOML 1.0.0.
20+
21+
.. versionchanged:: next
22+
Added TOML 1.1.0 support.
23+
See the :ref:`What's New <whatsnew315-tomllib-1-1-0>` for details.
24+
25+
2026
.. seealso::
2127

2228
The :pypi:`Tomli-W package <tomli-w>`

Doc/whatsnew/3.15.rst

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -867,6 +867,56 @@ tkinter
867867
with outdated names.
868868
(Contributed by Serhiy Storchaka in :gh:`143754`)
869869

870+
871+
.. _whatsnew315-tomllib-1-1-0:
872+
873+
tomllib
874+
-------
875+
876+
* The :mod:`tomllib` module now supports TOML 1.1.0.
877+
This is a backwards compatible update, meaning that all valid TOML 1.0.0
878+
documents are parsed the same way.
879+
880+
The changes, according to the `official TOML changelog`_, are:
881+
882+
- Allow newlines and trailing commas in inline tables.
883+
884+
Previously an inline table had to be on a single line and couldn't end
885+
with a trailing comma. This is now relaxed so that the following is valid:
886+
887+
.. syntax highlighting needs TOML 1.1.0 support in Pygments,
888+
see https://github.com/pygments/pygments/issues/3026
889+
890+
.. code-block:: text
891+
892+
tbl = {
893+
key = "a string",
894+
moar-tbl = {
895+
key = 1,
896+
},
897+
}
898+
899+
- Add ``\xHH`` notation to basic strings for codepoints under 255,
900+
and the ``\e`` escape for the escape character:
901+
902+
.. code-block:: text
903+
904+
null = "null byte: \x00; letter a: \x61"
905+
csi = "\e["
906+
907+
- Seconds in datetime and time values are now optional.
908+
The following are now valid:
909+
910+
.. code-block:: text
911+
912+
dt = 2010-02-03 14:15
913+
t = 14:15
914+
915+
(Contributed by Taneli Hukkinen in :gh:`142956`.)
916+
917+
.. _official TOML changelog: https://github.com/toml-lang/toml/blob/main/CHANGELOG.md
918+
919+
870920
types
871921
------
872922

Lib/_android_support.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,13 @@ def write(self, prio, tag, message):
168168
# message.
169169
message = message.replace(b"\x00", b"\xc0\x80")
170170

171+
# On API level 30 and higher, Logcat will strip any number of leading
172+
# newlines. This is visible in all `logcat` modes, even --binary. Work
173+
# around this by adding a leading space, which shouldn't make any
174+
# difference to the log's usability.
175+
if message.startswith(b"\n"):
176+
message = b" " + message
177+
171178
with self._lock:
172179
now = time()
173180
self._bucket_level += (

0 commit comments

Comments
 (0)