| 1 |
#!/usr/bin/env python3 |
| 2 |
"""Helper utilities for common libc tasks.""" |
| 3 |
|
| 4 |
import argparse |
| 5 |
import copy |
| 6 |
import datetime as dt |
| 7 |
from enum import StrEnum |
| 8 |
import functools |
| 9 |
import json |
| 10 |
import os |
| 11 |
import pprint |
| 12 |
import re |
| 13 |
import subprocess as sp |
| 14 |
import sys |
| 15 |
from dataclasses import dataclass |
| 16 |
from inspect import cleandoc |
| 17 |
from multiprocessing import Pool |
| 18 |
from pathlib import Path |
| 19 |
|
| 20 |
REPO_OWNER = "rust-lang" |
| 21 |
REPO = "libc" |
| 22 |
|
| 23 |
|
| 24 |
def main() -> None: |
| 25 |
p = argparse.ArgumentParser( |
| 26 |
description="Utilities for helping with libc development" |
| 27 |
) |
| 28 |
sub = p.add_subparsers(required=True) |
| 29 |
|
| 30 |
p_cat = sub.add_parser( |
| 31 |
"check-all-targets", |
| 32 |
aliases=["cat"], |
| 33 |
help="run `cargo check` on some or all targets (see subcommand help for more)", |
| 34 |
description=CheckAllTargets.__doc__, |
| 35 |
formatter_class=argparse.RawDescriptionHelpFormatter, |
| 36 |
) |
| 37 |
p_cat.add_argument("package", help="specify the package to build") |
| 38 |
p_cat.add_argument("-o", "--only", help="filter tested targets by this regex") |
| 39 |
p_cat.add_argument("-s", "--skip", help="skip targets matching this regex") |
| 40 |
p_cat.add_argument( |
| 41 |
"cargo_args", |
| 42 |
nargs="*", |
| 43 |
metavar="cargo-args", |
| 44 |
help="extra arguments for `cargo check`", |
| 45 |
) |
| 46 |
p_cat.set_defaults( |
| 47 |
func=lambda args: CheckAllTargets.prepare().check_all_targets( |
| 48 |
package=args.package, |
| 49 |
only=args.only, |
| 50 |
skip=args.skip, |
| 51 |
cargo_args=args.cargo_args, |
| 52 |
) |
| 53 |
) |
| 54 |
|
| 55 |
p_rel = sub.add_parser( |
| 56 |
"relabel", |
| 57 |
help="replace the stable-nominated label with stable-applied", |
| 58 |
description=Relabel.__doc__, |
| 59 |
formatter_class=argparse.RawDescriptionHelpFormatter, |
| 60 |
) |
| 61 |
p_rel.add_argument( |
| 62 |
"pr_number", metavar="pr-number", help="pull request for the backport" |
| 63 |
) |
| 64 |
p_rel.set_defaults(func=lambda args: Relabel(pr_number=args.pr_number).execute()) |
| 65 |
|
| 66 |
p_log = sub.add_parser( |
| 67 |
"make-changelog", |
| 68 |
help="collect changelog entries", |
| 69 |
description=MakeChangelog.__doc__, |
| 70 |
formatter_class=argparse.ArgumentDefaultsHelpFormatter, |
| 71 |
) |
| 72 |
p_log.add_argument( |
| 73 |
"--old-tag", |
| 74 |
metavar="old-tag", |
| 75 |
help="tag of the previous revision to serve as the changelog base", |
| 76 |
required=True, |
| 77 |
) |
| 78 |
p_log.add_argument( |
| 79 |
"--new-ref", |
| 80 |
metavar="new-ref", |
| 81 |
help="ref to compare to the old tag", |
| 82 |
default="libc-0.2", |
| 83 |
) |
| 84 |
p_log.set_defaults( |
| 85 |
func=lambda args: MakeChangelog( |
| 86 |
old_tag=args.old_tag, new_ref=args.new_ref |
| 87 |
).execute() |
| 88 |
) |
| 89 |
|
| 90 |
p_bkp = sub.add_parser( |
| 91 |
"backport", |
| 92 |
help="prepare to cherry pick to `libc-0.2` (see subcommand help for more)", |
| 93 |
description=Backporter.__doc__, |
| 94 |
formatter_class=argparse.RawDescriptionHelpFormatter, |
| 95 |
) |
| 96 |
p_bkp.add_argument( |
| 97 |
"--branch", help="branch to backport to, must not be checked out", required=True |
| 98 |
) |
| 99 |
p_bkp.set_defaults( |
| 100 |
func=lambda args: Backporter(branch=args.branch).start_backports() |
| 101 |
) |
| 102 |
|
| 103 |
s = sub.add_parser( |
| 104 |
"backport-pr-description", |
| 105 |
help="create a PR description for a backport branch", |
| 106 |
description=Backporter.backport_pr_description.__doc__, |
| 107 |
formatter_class=argparse.RawDescriptionHelpFormatter, |
| 108 |
) |
| 109 |
s.add_argument("--branch", help="name of the backport branch", required=True) |
| 110 |
s.set_defaults(func=lambda args: Backporter.backport_pr_description(args.branch)) |
| 111 |
|
| 112 |
p_amd = sub.add_parser( |
| 113 |
"add-backport-trailer", |
| 114 |
help='add "(backport ...)" to the previous commit', |
| 115 |
description=Backporter.add_backport_trailer.__doc__, |
| 116 |
) |
| 117 |
p_amd.add_argument("pick", help="commit that was cherry picked") |
| 118 |
p_amd.set_defaults(func=lambda args: Backporter.add_backport_trailer(args.pick)) |
| 119 |
|
| 120 |
p_seq = sub.add_parser( |
| 121 |
"_sequence-editor", |
| 122 |
help="hook to update the rebase todo, meant for internal use", |
| 123 |
) |
| 124 |
p_seq.add_argument("path", help="path to the rebase todo") |
| 125 |
p_seq.set_defaults(func=lambda args: Backporter.sequence_editor(args.path)) |
| 126 |
|
| 127 |
args = p.parse_args() |
| 128 |
args.func(args) |
| 129 |
|
| 130 |
|
| 131 |
@dataclass(kw_only=True) |
| 132 |
class Relabel: |
| 133 |
""" |
| 134 |
Replace the stable-nominated label with stable-applied, given the number of |
| 135 |
a PR listing backported PRs. |
| 136 |
|
| 137 |
The backport PR should have a list of items like `* http://.../libc/pull/1234`. |
| 138 |
""" |
| 139 |
|
| 140 |
pr_number: int |
| 141 |
|
| 142 |
def execute(self) -> None: |
| 143 |
num = self.pr_number |
| 144 |
j = check_output( |
| 145 |
[ |
| 146 |
"gh", |
| 147 |
"pr", |
| 148 |
"view", |
| 149 |
f"https://github.com/{REPO_OWNER}/{REPO}/pull/{num}", |
| 150 |
"--json=baseRefName,body,state,title", |
| 151 |
] |
| 152 |
) |
| 153 |
d = json.loads(j) |
| 154 |
base: str = d["baseRefName"] |
| 155 |
body: str = d["body"] |
| 156 |
state: str = d["state"] |
| 157 |
title: str = d["title"] |
| 158 |
|
| 159 |
if state != "MERGED": |
| 160 |
print(f'expected MERGED state; got {state} for "{title}" (#{num})') |
| 161 |
exit(1) |
| 162 |
if base != "libc-0.2": |
| 163 |
print(f'expected libc-0.2 base ref; got {base} for "{title}" (#{num})') |
| 164 |
exit(1) |
| 165 |
|
| 166 |
print(f'Relabling PRs listed in {num} "{title}"') |
| 167 |
|
| 168 |
to_relabel = [] |
| 169 |
for line in body.splitlines(): |
| 170 |
if not re.match(r"^[-*]\s*http", line): |
| 171 |
continue |
| 172 |
|
| 173 |
match = re.match( |
| 174 |
r"^[-*]\s*https?://github.com/rust-lang/libc/pull/(\d+)", line |
| 175 |
) |
| 176 |
if match is None: |
| 177 |
print( |
| 178 |
f"{E.YEL}Line `{line}` does not match expected link pattern{E.RST}" |
| 179 |
) |
| 180 |
continue |
| 181 |
|
| 182 |
num = int(match.group(1)) |
| 183 |
to_relabel.append(num) |
| 184 |
|
| 185 |
# `gh` requests can be pretty slow, parallelize to help with large lists |
| 186 |
with Pool() as p: |
| 187 |
p.map(Relabel.do_relabel_inner, to_relabel) |
| 188 |
|
| 189 |
print("Finished relabeling") |
| 190 |
|
| 191 |
@staticmethod |
| 192 |
def do_relabel_inner(num: int): |
| 193 |
j = check_output(["gh", "pr", "view", pr_url(num), "--json=state,title,labels"]) |
| 194 |
d = json.loads(j) |
| 195 |
state: str = d["state"] |
| 196 |
title: str = d["title"] |
| 197 |
labels: list[str] = [i["name"] for i in d["labels"]] |
| 198 |
|
| 199 |
if state != "MERGED": |
| 200 |
print( |
| 201 |
f'{E.YEL}expected MERGED state; got {state} for "{title}" (#{num}){E.RST}' |
| 202 |
) |
| 203 |
return |
| 204 |
if "stable-nominated" not in labels: |
| 205 |
print( |
| 206 |
f'{E.YEL}`stable-nominated` not in labels for "{title}" (#{num}){E.RST}' |
| 207 |
) |
| 208 |
|
| 209 |
# Use check_output to eat the stdout since otherwise `gh` draws a spinner that |
| 210 |
# messes up interleaved stdout. |
| 211 |
check_output( |
| 212 |
[ |
| 213 |
"gh", |
| 214 |
"pr", |
| 215 |
"edit", |
| 216 |
"--remove-label=stable-nominated", |
| 217 |
"--add-label=stable-applied", |
| 218 |
pr_url(num), |
| 219 |
] |
| 220 |
) |
| 221 |
|
| 222 |
|
| 223 |
@dataclass(kw_only=True) |
| 224 |
class MakeChangelog: |
| 225 |
""" |
| 226 |
Prepare a template with commits merged between `old-tag` and `new-ref`, for |
| 227 |
appending to the changelog. |
| 228 |
""" |
| 229 |
|
| 230 |
old_tag: str |
| 231 |
new_ref: str |
| 232 |
|
| 233 |
def execute(self) -> None: |
| 234 |
old_tag: str = self.old_tag |
| 235 |
new_ref: str = self.new_ref |
| 236 |
date = dt.datetime.now(dt.UTC).strftime("%Y-%m-%d") |
| 237 |
split = old_tag.split(".") |
| 238 |
split[2] = str(int(split[2]) + 1) # increment patch version |
| 239 |
next_tag = ".".join(split) |
| 240 |
|
| 241 |
ret = cleandoc(f""" |
| 242 |
## [{next_tag}](https://github.com/rust-lang/libc/compare/{old_tag}...{next_tag}) - {date} |
| 243 |
|
| 244 |
### Support |
| 245 |
### Added |
| 246 |
### Deprecated |
| 247 |
### Fixed |
| 248 |
### Changed |
| 249 |
### Removed |
| 250 |
### Other |
| 251 |
""") |
| 252 |
ret += "\n\n" |
| 253 |
|
| 254 |
changes = check_output( |
| 255 |
[ |
| 256 |
"git", |
| 257 |
"log", |
| 258 |
f"{old_tag}..{new_ref}", |
| 259 |
"--no-merges", |
| 260 |
"--oneline", |
| 261 |
"--reverse", |
| 262 |
], |
| 263 |
).splitlines() |
| 264 |
|
| 265 |
print( |
| 266 |
f"Generating changelog for {old_tag}..{new_ref}. Make sure {new_ref} " |
| 267 |
"is up to date!" |
| 268 |
) |
| 269 |
|
| 270 |
for logline in changes: |
| 271 |
sha = logline.split()[0] |
| 272 |
summary = check_output(["git", "log", sha, "--format=%s", "-1"], quiet=True) |
| 273 |
body = check_output(["git", "log", sha, "--format=%b", "-1"], quiet=True) |
| 274 |
summary = summary.strip() |
| 275 |
body = body.strip() |
| 276 |
|
| 277 |
link = None |
| 278 |
|
| 279 |
# Extract expected trailers |
| 280 |
orig_sha_opt = re.search(r"\(cherry picked from commit (\w+)\)", body, re.M) |
| 281 |
url_opt = re.search(r"^\(backport <(.*)>\)", body, re.M) |
| 282 |
|
| 283 |
# Prefer a PR URL if available |
| 284 |
if url_opt is not None: |
| 285 |
pr_url = url_opt[1] |
| 286 |
pr_opt = re.match( |
| 287 |
rf"https://github.com/{REPO_OWNER}/{REPO}/pull/(\d+)", pr_url |
| 288 |
) |
| 289 |
if pr_opt is not None: |
| 290 |
pr_num = pr_opt[1] |
| 291 |
link = f"[#{pr_num}]({pr_url})" |
| 292 |
|
| 293 |
# If there is no PR URL, link the backported commit |
| 294 |
if link is None and orig_sha_opt is not None: |
| 295 |
orig_sha = orig_sha_opt[1] |
| 296 |
short = orig_sha[:12] |
| 297 |
link = f"[{short}](https://github.com/rust-lang/libc/commit/{orig_sha})" |
| 298 |
|
| 299 |
# If there is no PR URL or cherry pick commit, link the commit itself |
| 300 |
if link is None: |
| 301 |
patch_sha = check_output(["git", "rev-parse", sha], quiet=True).strip() |
| 302 |
short = patch_sha[:12] |
| 303 |
link = ( |
| 304 |
f"[{short}](https://github.com/rust-lang/libc/commit/{patch_sha})" |
| 305 |
) |
| 306 |
|
| 307 |
line = f"- {summary} ({link})" |
| 308 |
|
| 309 |
ret += "\n" |
| 310 |
ret += line |
| 311 |
|
| 312 |
print( |
| 313 |
"Copy the below to CHANGELOG.md, then sort log messages into the " |
| 314 |
"relevant categories:\n" |
| 315 |
) |
| 316 |
print(ret) |
| 317 |
|
| 318 |
|
| 319 |
@dataclass(kw_only=True) |
| 320 |
class CheckAllTargets: |
| 321 |
""" |
| 322 |
Run `cargo check` on all targets, possibly with filtering. |
| 323 |
|
| 324 |
Query `rustc` for a list of supported targets, then run `cargo check` on each. |
| 325 |
`-Zbuild-std` is used if the toolchain is not installed. |
| 326 |
|
| 327 |
This uses a pinned toolchain and a separate target directory in |
| 328 |
`~/.cache/libc-build`. This is done to avoid accidental cache deletion with `cargo |
| 329 |
clean` or invalidation by changing toolchain, since the initial build takes so long |
| 330 |
that it can be worth keeping the cache around. |
| 331 |
|
| 332 |
The pinned toolchain can be overridden by setting RUSTC_CACHE_TOOLCHAIN. |
| 333 |
""" |
| 334 |
|
| 335 |
toolchain: str |
| 336 |
targets: list["RustcTarget"] |
| 337 |
checks: list["CheckInvocation"] |
| 338 |
failure_limit: int |
| 339 |
|
| 340 |
FREEBSD_VERSIONS = [13, 14, 15] |
| 341 |
|
| 342 |
# Targets that don't pass for one reason or another |
| 343 |
BROKEN_TARGETS = [ |
| 344 |
# libc problems |
| 345 |
("aarch64-unknown-nto-qnx800", "libc error, unsupported arch"), |
| 346 |
("aarch64.*-gnu_ilp32.*time_bits=64", "libc error, time64 mismatches"), |
| 347 |
("armv6k-nintendo-3ds", "libc error, stat missing"), |
| 348 |
("armv7-sony-vita-newlibeabihf", "libc error, stat missing"), |
| 349 |
("csky.*gnu.*time_bits=64", "libc error, time64 mismatches"), |
| 350 |
("i686-pc-nto-qnx700", "libc error, unsupported arch"), |
| 351 |
("managarm-mlibc", "libc error, unresolved import"), |
| 352 |
("x86_64-lynx-lynxos178", "libc error, unresolved import"), |
| 353 |
("x86_64-pc-nto-qnx800", "libc error, unsupported arch"), |
| 354 |
("x86_64-unknown-linux-none", "libc error, unresolved import"), |
| 355 |
# rustc problems |
| 356 |
("xtensa-esp32.*", "target string mismatch in rustc"), |
| 357 |
("amdgcn-amd-amdhsa", "unsupported instructions with some CPUs"), |
| 358 |
# llvm problems |
| 359 |
("m68k-unknown-.*", "llvm crash building core"), |
| 360 |
("mipsisa32r6(el)?-.*", "llvm crash building core"), |
| 361 |
] |
| 362 |
|
| 363 |
# Flags that always need to be passed to specific targets |
| 364 |
EXTRA_TARGET_FLAGS = { |
| 365 |
# Target CPU must be specified |
| 366 |
"avr-none": ["-Ctarget-cpu=atmega328p"], |
| 367 |
# Emits a lot of warnings |
| 368 |
"hexagon-unknown-qurt": ["-Aunused_imports"], |
| 369 |
} |
| 370 |
|
| 371 |
@staticmethod |
| 372 |
def prepare() -> "CheckAllTargets": |
| 373 |
"""Build a list of checks.""" |
| 374 |
toolchain = CheckAllTargets.get_cache_toolchain() |
| 375 |
target_dir = cache_dir() / "libc-build" / toolchain |
| 376 |
all_targets = RustcTarget.fetch_all(toolchain) |
| 377 |
installed_targets = check_output( |
| 378 |
[ |
| 379 |
"rustup", |
| 380 |
"target", |
| 381 |
"list", |
| 382 |
"--installed", |
| 383 |
f"--toolchain={toolchain}", |
| 384 |
] |
| 385 |
).splitlines() |
| 386 |
checks: list[CheckInvocation] = [] |
| 387 |
|
| 388 |
# Add a check for each target and, if applicable, a variant for any cfg options |
| 389 |
# that also make sense to check. |
| 390 |
for t in all_targets: |
| 391 |
base = CheckInvocation( |
| 392 |
target=t.triple, |
| 393 |
name="", |
| 394 |
target_dir=target_dir, |
| 395 |
attributes={}, |
| 396 |
installed=t.triple in installed_targets, |
| 397 |
skip=[], |
| 398 |
extra_rustflags=[], |
| 399 |
) |
| 400 |
|
| 401 |
new_checks = [base] |
| 402 |
|
| 403 |
# When doing variants, use a separate target directory because otherwise |
| 404 |
# running twice with different `RUSTFLAGS` is a cache miss. |
| 405 |
|
| 406 |
if t.os_ == "freebsd": |
| 407 |
new_checks.clear() |
| 408 |
for vers in CheckAllTargets.FREEBSD_VERSIONS: |
| 409 |
new = copy.deepcopy(base) |
| 410 |
new.attributes = base.attributes | {"freebsd": str(vers)} |
| 411 |
new.target_dir = base.target_dir / f"freebsd-{vers}" |
| 412 |
new.extra_rustflags = base.extra_rustflags + [ |
| 413 |
f'--cfg=libc_unstable_freebsd_version="{vers}"' |
| 414 |
] |
| 415 |
|
| 416 |
new_checks.append(new) |
| 417 |
|
| 418 |
if t.env == "gnu" and t.bits == 32: |
| 419 |
new = copy.deepcopy(base) |
| 420 |
new.attributes = base.attributes | {"time_bits": "64"} |
| 421 |
new.target_dir = base.target_dir / "time64" |
| 422 |
new.extra_rustflags = base.extra_rustflags + [ |
| 423 |
'--cfg=libc_unstable_gnu_time_bits="64"' |
| 424 |
] |
| 425 |
new_checks.append(new) |
| 426 |
|
| 427 |
if t.env == "musl" and t.bits == 32: |
| 428 |
new = copy.deepcopy(base) |
| 429 |
new.attributes = base.attributes | {"time_bits": "64"} |
| 430 |
new.target_dir = base.target_dir / "time64" |
| 431 |
new.extra_rustflags = base.extra_rustflags + [ |
| 432 |
"--cfg=libc_unstable_musl_v1_2_3" |
| 433 |
] |
| 434 |
new_checks.append(new) |
| 435 |
|
| 436 |
# Update the name field and check whether there are any targets that we |
| 437 |
# always need to skip, or that need flags. |
| 438 |
for check in new_checks: |
| 439 |
if len(check.attributes) == 0: |
| 440 |
check.name = f"{check.target} (default)" |
| 441 |
else: |
| 442 |
attrs = ",".join(f"{k}={v}" for (k, v) in check.attributes.items()) |
| 443 |
check.name = f"{check.target} ({attrs})" |
| 444 |
|
| 445 |
for pat, reason in CheckAllTargets.BROKEN_TARGETS: |
| 446 |
if check.pattern_matches(pat): |
| 447 |
check.skip.append(reason) |
| 448 |
|
| 449 |
for pat, flags in CheckAllTargets.EXTRA_TARGET_FLAGS.items(): |
| 450 |
if check.pattern_matches(pat): |
| 451 |
check.extra_rustflags.extend(flags) |
| 452 |
|
| 453 |
checks.extend(new_checks) |
| 454 |
|
| 455 |
return CheckAllTargets( |
| 456 |
toolchain=toolchain, |
| 457 |
targets=all_targets, |
| 458 |
checks=checks, |
| 459 |
failure_limit=5, |
| 460 |
) |
| 461 |
|
| 462 |
def check_all_targets( |
| 463 |
self, |
| 464 |
*, |
| 465 |
package: str, |
| 466 |
only: str | None = None, |
| 467 |
skip: str | None = None, |
| 468 |
cargo_args: list[str] = [], |
| 469 |
) -> None: |
| 470 |
"""Run checks from the populated list.""" |
| 471 |
checks = self.checks |
| 472 |
ran = 0 |
| 473 |
passed = 0 |
| 474 |
skipped = 0 |
| 475 |
failures = [] |
| 476 |
matched_only_already_skipped = [] |
| 477 |
|
| 478 |
if only is not None: |
| 479 |
for t in checks: |
| 480 |
if t.pattern_matches(only): |
| 481 |
if t.skip: |
| 482 |
matched_only_already_skipped.append(t.name) |
| 483 |
continue |
| 484 |
t.skip.append("does not match --only pattern") |
| 485 |
|
| 486 |
if skip is not None: |
| 487 |
for t in checks: |
| 488 |
if not t.pattern_matches(skip): |
| 489 |
continue |
| 490 |
t.skip.append("matches --skip pattern") |
| 491 |
|
| 492 |
# `sum(1 for _ in ...)` seems to be the best way to get an iterator's count |
| 493 |
total = sum(1 for _ in (t for t in checks if not t.skip)) |
| 494 |
|
| 495 |
# List skips first so the interesting output is together at the bottom |
| 496 |
checks.sort(key=lambda t: len(t.skip) == 0) |
| 497 |
|
| 498 |
env = os.environ.copy() |
| 499 |
env_rustflags = env.get("RUSTFLAGS") |
| 500 |
|
| 501 |
for t in checks: |
| 502 |
fulldesc = f"{t.name} ({ran + 1} / {total})" |
| 503 |
|
| 504 |
if len(t.skip) > 0: |
| 505 |
print(f"{E.YEL}Skipping {fulldesc} ({", ".join(t.skip)}){E.RST}") |
| 506 |
skipped += 1 |
| 507 |
continue |
| 508 |
|
| 509 |
print(f"{E.CY_B}Checking {fulldesc}{E.RST}") |
| 510 |
|
| 511 |
extra_args = [] if t.installed else ["-Zbuild-std=core"] |
| 512 |
common_args = [ |
| 513 |
f"--package={package}", |
| 514 |
f"--target={t.target}", |
| 515 |
] |
| 516 |
|
| 517 |
# We aim to be warning-free |
| 518 |
rustflags = ["-Dwarnings"] |
| 519 |
rustflags += t.extra_rustflags |
| 520 |
|
| 521 |
# Allow forwarding rustflags |
| 522 |
if env_rustflags is not None: |
| 523 |
rustflags += [env_rustflags] |
| 524 |
|
| 525 |
print(f" {E.GRN_D}Running build{E.RST}") |
| 526 |
|
| 527 |
try: |
| 528 |
run( |
| 529 |
[ |
| 530 |
"cargo", |
| 531 |
f"+{self.toolchain}", |
| 532 |
"check", |
| 533 |
f"--target-dir={t.target_dir}", |
| 534 |
] |
| 535 |
+ common_args |
| 536 |
+ extra_args |
| 537 |
+ cargo_args, |
| 538 |
env=env | {"RUSTFLAGS": " ".join(rustflags)}, |
| 539 |
) |
| 540 |
ok = True |
| 541 |
except sp.CalledProcessError: |
| 542 |
ok = False |
| 543 |
|
| 544 |
ran += 1 |
| 545 |
|
| 546 |
if ok: |
| 547 |
passed += 1 |
| 548 |
else: |
| 549 |
print(f"{E.RED_B}failed: {t.target}{E.RST}") |
| 550 |
failures.append(t.name) |
| 551 |
|
| 552 |
if len(failures) > self.failure_limit: |
| 553 |
break |
| 554 |
|
| 555 |
print( |
| 556 |
f"finished checking {ran} targets. {passed} passed, " |
| 557 |
f"{len(failures)} failed, {skipped} skipped" |
| 558 |
) |
| 559 |
if len(matched_only_already_skipped) > 0: |
| 560 |
print( |
| 561 |
f"note: {len(matched_only_already_skipped)} targets matched `--only` " |
| 562 |
"but were already skipped" |
| 563 |
) |
| 564 |
|
| 565 |
if len(failures) > 0: |
| 566 |
print("failures:") |
| 567 |
pprint.pp(failures) |
| 568 |
|
| 569 |
@staticmethod |
| 570 |
def get_cache_toolchain() -> str: |
| 571 |
# Arbitrary but reasonably recent default if unset. |
| 572 |
return os.environ.get("RUSTC_CACHE_TOOLCHAIN") or "nightly-2026-06-24" |
| 573 |
|
| 574 |
|
| 575 |
@dataclass(kw_only=True) |
| 576 |
class CheckInvocation: |
| 577 |
"""Config for a single invocation of `cargo check`.""" |
| 578 |
|
| 579 |
target: str |
| 580 |
name: str # target plus attributes |
| 581 |
target_dir: Path |
| 582 |
installed: bool |
| 583 |
attributes: dict[str, str] |
| 584 |
# skip reasons, empty if we shouldn't skip |
| 585 |
skip: list[str] |
| 586 |
extra_rustflags: list[str] |
| 587 |
|
| 588 |
def pattern_matches(self, pat: str) -> bool: |
| 589 |
"""Ensure pattern matching is applied consistently""" |
| 590 |
assert self.name != "" |
| 591 |
return re.search(pat, self.name) is not None |
| 592 |
|
| 593 |
|
| 594 |
@dataclass(kw_only=True) |
| 595 |
class Backporter: |
| 596 |
"""Prepare an interactive rebase that will cherry pick commits to `libc-0.2`. |
| 597 |
|
| 598 |
This loosely does the following: |
| 599 |
|
| 600 |
* Create a git worktree at `.libc-backports` |
| 601 |
* Switch to the specified branch |
| 602 |
* Start an interactive rebase that runs `git cherry-pick -x <sha>` for each needed |
| 603 |
commit, then modify the commit to add the `(cherry picked from ...)` and |
| 604 |
`(backport ...)` trailers. |
| 605 |
|
| 606 |
An interactive rebase is used because it's a nice way to create and execute a series |
| 607 |
of shell commands with a chance to resolve conflicts and continue as needed. |
| 608 |
|
| 609 |
Because it is standard `git rebase`, it is possible to use typical options like |
| 610 |
`git rebase --edit-todo` if it pauses due to conflicts. |
| 611 |
""" |
| 612 |
|
| 613 |
branch: str |
| 614 |
|
| 615 |
WORKTREE_DIR = ".libc-backports" |
| 616 |
WORKTREE_GIT = ["git", "-C", WORKTREE_DIR] |
| 617 |
GQL_QUERY = """ |
| 618 |
query ($endCursor: String) { |
| 619 |
repository(name: "libc", owner: "rust-lang") { |
| 620 |
pullRequests( |
| 621 |
first: 25 |
| 622 |
after: $endCursor |
| 623 |
baseRefName: "main" |
| 624 |
states: MERGED |
| 625 |
labels: ["stable-nominated"] |
| 626 |
# Ordering by merge date is not supported, we need to re-sort after fetch. |
| 627 |
orderBy: {field: CREATED_AT, direction: ASC} |
| 628 |
) { |
| 629 |
nodes { |
| 630 |
title |
| 631 |
number |
| 632 |
state |
| 633 |
url |
| 634 |
author { |
| 635 |
login |
| 636 |
} |
| 637 |
mergedAt |
| 638 |
mergeCommit { |
| 639 |
oid |
| 640 |
committedDate |
| 641 |
messageHeadline |
| 642 |
author { |
| 643 |
name |
| 644 |
user { |
| 645 |
login |
| 646 |
} |
| 647 |
} |
| 648 |
} |
| 649 |
commits(first: 100) { |
| 650 |
totalCount |
| 651 |
nodes { |
| 652 |
commit { |
| 653 |
oid |
| 654 |
committedDate |
| 655 |
messageHeadline |
| 656 |
author { |
| 657 |
name |
| 658 |
user { |
| 659 |
login |
| 660 |
} |
| 661 |
} |
| 662 |
} |
| 663 |
} |
| 664 |
} |
| 665 |
} |
| 666 |
pageInfo { |
| 667 |
hasNextPage |
| 668 |
endCursor |
| 669 |
} |
| 670 |
} |
| 671 |
} |
| 672 |
} |
| 673 |
""" |
| 674 |
|
| 675 |
def start_backports(self) -> None: |
| 676 |
self.ensure_local_updated() |
| 677 |
|
| 678 |
try: |
| 679 |
self.ensure_branch() |
| 680 |
self.ensure_worktree() |
| 681 |
self.prepare_rebase_todo() |
| 682 |
seq_ed = "../etc/libc-util.py _sequence-editor" |
| 683 |
run( |
| 684 |
self.WORKTREE_GIT + ["rebase", "-i", "libc-0.2"], |
| 685 |
env=os.environ | {"GIT_SEQUENCE_EDITOR": seq_ed}, |
| 686 |
) |
| 687 |
# Give the user a chance to delete picks if desired |
| 688 |
print("Presenting rebase todo to user for review...") |
| 689 |
run(self.WORKTREE_GIT + ["rebase", "--edit-todo"]) |
| 690 |
run(self.WORKTREE_GIT + ["rebase", "--continue"]) |
| 691 |
except sp.CalledProcessError: |
| 692 |
msg = f""" |
| 693 |
{E.YEL}Rebase failed or incomplete; check the git error above for |
| 694 |
details. |
| 695 |
|
| 696 |
If git stopped because of a conflict or other resolvable error, change |
| 697 |
to the worktree directory at {self.WORKTREE_DIR}. From there, you can |
| 698 |
resolve conflicts or `git rebase --quit` to stop trying to backport the |
| 699 |
rest of the commits. |
| 700 |
|
| 701 |
If needed, `git worktree remove .libc-backports` will allow you to |
| 702 |
delete the branch and start from scratch.{E.RST} |
| 703 |
""" |
| 704 |
print("\n" + mstr(msg)) |
| 705 |
exit(1) |
| 706 |
|
| 707 |
def prepare_rebase_todo(self) -> None: |
| 708 |
"""Create a rebase todo list and cache it, to be picked up by the sequence |
| 709 |
editor. |
| 710 |
""" |
| 711 |
# Start with a break so we can `--edit-todo` |
| 712 |
rebase_todo = "break\n" |
| 713 |
commit_map = "" |
| 714 |
|
| 715 |
pull_requests = self.fetch_needs_backport_list() |
| 716 |
for pr in pull_requests: |
| 717 |
last_sha = pr.merge_commit.oid |
| 718 |
parents = check_output( |
| 719 |
["git", "log", last_sha, "--format=%P", "-1"], quiet=True |
| 720 |
).split() |
| 721 |
|
| 722 |
# If we have a merge commit, take only the second (incoming) commit. |
| 723 |
if len(parents) > 2: |
| 724 |
eprint("Can't backport commits with >1 parent") |
| 725 |
exit(1) |
| 726 |
if len(parents) == 2: |
| 727 |
last_sha = parents[1] |
| 728 |
|
| 729 |
# The commit list is not what we actually want to cherry pick; it has the |
| 730 |
# refs for the commits in the PR but not the ref after merge. The PR's |
| 731 |
# "merge" commit is the last commit on `main` from this PR, so we can |
| 732 |
# work backwards; given N commits, `merge_sha~(N-1)` will be the first PR |
| 733 |
# from the commit on `main`. |
| 734 |
for i in reversed(range(len(pr.commits))): |
| 735 |
n_back = len(pr.commits) - i - 1 |
| 736 |
pick_sha = check_output( |
| 737 |
["git", "rev-parse", f"{last_sha}~{n_back}"], quiet=True |
| 738 |
).strip() |
| 739 |
subject = check_output( |
| 740 |
["git", "log", pick_sha, "--format=%s", "-1"], quiet=True |
| 741 |
).strip() |
| 742 |
pick_short = pick_sha[:12] |
| 743 |
rebase_todo += ( |
| 744 |
f"exec printf '{E.CY_B.u}picking from PR{pr.number}: {pick_short} " |
| 745 |
f'"{subject}"{E.RST.u}\\n\'' |
| 746 |
"\n" |
| 747 |
f'pick {pick_short} # pick "{subject}"' |
| 748 |
"\n" |
| 749 |
f"exec ../etc/libc-util.py add-backport-trailer {pick_short}" |
| 750 |
"\n\n" |
| 751 |
) |
| 752 |
commit_map += f"{pick_sha} {pr.number}\n" |
| 753 |
|
| 754 |
todo_path = self.rebase_todo_tmp_path() |
| 755 |
# may need to create `target/libc-util` |
| 756 |
todo_path.parent.parent.mkdir(exist_ok=True) |
| 757 |
todo_path.parent.mkdir(exist_ok=True) |
| 758 |
todo_path.write_text(rebase_todo) |
| 759 |
|
| 760 |
self.commit_map_path().write_text(commit_map) |
| 761 |
|
| 762 |
def fetch_needs_backport_list(self) -> list["PullRequest"]: |
| 763 |
"""Fetch PRs labeled `stable-nominated` via the GraphQL API""" |
| 764 |
s = check_output( |
| 765 |
[ |
| 766 |
"gh", |
| 767 |
"api", |
| 768 |
"graphql", |
| 769 |
"--paginate", |
| 770 |
"--slurp", |
| 771 |
"-f", |
| 772 |
"query=" + self.GQL_QUERY, |
| 773 |
] |
| 774 |
) |
| 775 |
j: list[dict] = json.loads(s) |
| 776 |
|
| 777 |
# The result is paginated so we get nested lists. Extract the data we want |
| 778 |
# then flatten. |
| 779 |
pages = [page["data"]["repository"]["pullRequests"]["nodes"] for page in j] |
| 780 |
pr_nodes = [pr_node for page in pages for pr_node in page] |
| 781 |
|
| 782 |
pull_requests: list[PullRequest] = [] |
| 783 |
for pr in pr_nodes: |
| 784 |
commits = [node["commit"] for node in pr["commits"]["nodes"]] |
| 785 |
|
| 786 |
new = PullRequest( |
| 787 |
title=pr["title"], |
| 788 |
number=int(pr["number"]), |
| 789 |
state=pr["state"], |
| 790 |
url=pr["url"], |
| 791 |
author_username=pr["author"]["login"], |
| 792 |
merged_at=pr["mergedAt"], |
| 793 |
merge_commit=Commit.from_object(pr["mergeCommit"]), |
| 794 |
commits=[Commit.from_object(c) for c in commits], |
| 795 |
) |
| 796 |
|
| 797 |
total_commits = int(pr["commits"]["totalCount"]) |
| 798 |
new_commit_count = len(new.commits) |
| 799 |
if total_commits != new_commit_count: |
| 800 |
print( |
| 801 |
f"limit reached: {total_commits} total commits but could " |
| 802 |
f"only fetch {new_commit_count}" |
| 803 |
) |
| 804 |
exit(1) |
| 805 |
|
| 806 |
pull_requests.append(new) |
| 807 |
|
| 808 |
# Oldest to newest |
| 809 |
pull_requests.sort(key=lambda pr: pr.merged_at) |
| 810 |
return pull_requests |
| 811 |
|
| 812 |
def ensure_local_updated(self) -> None: |
| 813 |
"""Sanity check that whatever we want to rebase onto is actually updated, and |
| 814 |
fetch `main` to ensure cherry pick sources exist locally.""" |
| 815 |
|
| 816 |
run(["git", "fetch", repo_fetch_url(), "main"]) |
| 817 |
run(["git", "fetch", repo_fetch_url(), "libc-0.2"]) |
| 818 |
upstream = check_output(["git", "rev-parse", "FETCH_HEAD"]).strip() |
| 819 |
local = check_output(["git", "rev-parse", "libc-0.2"]).strip() |
| 820 |
|
| 821 |
if upstream != local: |
| 822 |
print( |
| 823 |
f"local libc-0.2@{local[:12]} does not match upstream/libc-0.2@{upstream[:12]}!" |
| 824 |
"Fetch before retrying." |
| 825 |
) |
| 826 |
exit(1) |
| 827 |
|
| 828 |
def ensure_branch(self) -> None: |
| 829 |
"""Create the branch if it doesn't exist.""" |
| 830 |
try: |
| 831 |
run(["git", "branch", self.branch, "libc-0.2"], stderr=sp.PIPE) |
| 832 |
except sp.CalledProcessError: |
| 833 |
pass |
| 834 |
|
| 835 |
def ensure_worktree(self) -> None: |
| 836 |
"""Set up a worktree pointing to the target branch.""" |
| 837 |
# Prune in case the directory was deleted without going via git. |
| 838 |
run(["git", "worktree", "prune"]) |
| 839 |
|
| 840 |
try: |
| 841 |
print("creating worktree") |
| 842 |
run( |
| 843 |
["git", "worktree", "add", ".libc-backports", self.branch], |
| 844 |
stderr=sp.PIPE, |
| 845 |
) |
| 846 |
except sp.CalledProcessError: |
| 847 |
print("worktree already exists, checking out branch") |
| 848 |
run(self.WORKTREE_GIT + ["switch", self.branch]) |
| 849 |
|
| 850 |
@staticmethod |
| 851 |
def sequence_editor(path: str) -> None: |
| 852 |
"""The script-y way to construct a rebase is by setting the "sequence editor" to |
| 853 |
a script that gets the rebase todo path. That's all this function does, the |
| 854 |
needed contents have already been written. |
| 855 |
""" |
| 856 |
|
| 857 |
print(f"editing rebase todo at {path}") |
| 858 |
|
| 859 |
txt = "\n\n" |
| 860 |
txt += Backporter.rebase_todo_tmp_path().read_text() |
| 861 |
|
| 862 |
with Path(path).open("a") as f: |
| 863 |
f.write(txt) |
| 864 |
|
| 865 |
@staticmethod |
| 866 |
def add_backport_trailer(pick: str) -> None: |
| 867 |
"""Add `(backport ...)` to the previous commit, using `(cherry picked from ...)` |
| 868 |
to know where the commit came from. |
| 869 |
""" |
| 870 |
head_summary = check_output(["git", "log", "-1", "HEAD", "--format=%s"]).strip() |
| 871 |
pick_summary = check_output(["git", "log", "-1", pick, "--format=%s"]).strip() |
| 872 |
head_message = check_output(["git", "log", "-1", "HEAD", "--format=%B"]).strip() |
| 873 |
head = check_output(["git", "rev-parse", "HEAD"]).strip() |
| 874 |
pick = check_output(["git", "rev-parse", pick]).strip() |
| 875 |
|
| 876 |
existing_pick_msg = re.search( |
| 877 |
r"^\(cherry picked from commit (\w+)\)", head_message, re.M |
| 878 |
) |
| 879 |
existing_backport_msg = re.search(r"^\(backport.*\)", head_message, re.M) |
| 880 |
|
| 881 |
if existing_pick_msg is not None: |
| 882 |
print( |
| 883 |
f"{E.YEL}Commit {head} already contains cherry-pick trailer; " |
| 884 |
f"skipping{E.RST}" |
| 885 |
) |
| 886 |
return |
| 887 |
|
| 888 |
if existing_backport_msg is not None: |
| 889 |
print( |
| 890 |
f"{E.YEL}Commit {head} already contains backport trailer; " |
| 891 |
f"skipping{E.RST}" |
| 892 |
) |
| 893 |
return |
| 894 |
|
| 895 |
if head_summary != pick_summary: |
| 896 |
print( |
| 897 |
f"{E.YEL}Commit {head} summary does not match pick {pick} " |
| 898 |
f"summary; skipping{E.RST}" |
| 899 |
) |
| 900 |
return |
| 901 |
|
| 902 |
commit_map = Backporter.commit_map_path().read_text() |
| 903 |
pr = None |
| 904 |
for line in commit_map.splitlines(): |
| 905 |
if not line.startswith(pick): |
| 906 |
continue |
| 907 |
_, _, pr = line.partition(" ") |
| 908 |
break |
| 909 |
|
| 910 |
if pr is None: |
| 911 |
print(f"{E.YEL}could not locate PR for picked commit {pick}{E.RST}") |
| 912 |
return |
| 913 |
|
| 914 |
new_message = head_message.strip() |
| 915 |
new_message += f"\n\n(backport <{pr_url(int(pr))}>)" |
| 916 |
new_message += f"\n(cherry picked from commit {pick})\n" |
| 917 |
run(["git", "commit", "--amend", "--message", new_message]) |
| 918 |
|
| 919 |
@staticmethod |
| 920 |
def backport_pr_description(branch: str) -> None: |
| 921 |
"""List all backported commits for a branch, for pasting into the PR body.""" |
| 922 |
commits = check_output(["git", "log", f"libc-0.2..{branch}", "--format=%b"]) |
| 923 |
urls = {x[1] for x in re.finditer(r"^\(backport <(.*)>\)", commits, re.M)} |
| 924 |
urls = sorted(list(urls)) |
| 925 |
|
| 926 |
s = "Backport the following:\n\n" |
| 927 |
for url in urls: |
| 928 |
s += f"* {url}\n" |
| 929 |
|
| 930 |
print(s) |
| 931 |
|
| 932 |
@staticmethod |
| 933 |
def rebase_todo_tmp_path() -> Path: |
| 934 |
"""Rebase todo to be appended to the default""" |
| 935 |
return Path(__file__).parent.parent / "target" / "libc-util" / "rebase-todo.txt" |
| 936 |
|
| 937 |
@staticmethod |
| 938 |
def commit_map_path() -> Path: |
| 939 |
"""List of `<sha> <pr_number>` mappings.""" |
| 940 |
return Path(__file__).parent.parent / "target" / "libc-util" / "commit-map.txt" |
| 941 |
|
| 942 |
|
| 943 |
@dataclass(kw_only=True) |
| 944 |
class RustcTarget: |
| 945 |
"""Config queried from rustc.""" |
| 946 |
|
| 947 |
triple: str |
| 948 |
arch: str |
| 949 |
os_: str | None |
| 950 |
env: str | None |
| 951 |
bits: int |
| 952 |
|
| 953 |
@staticmethod |
| 954 |
@functools.cache |
| 955 |
def get_one(toolchain: str, triple: str) -> "RustcTarget": |
| 956 |
target_cfg = check_output( |
| 957 |
["rustc", f"+{toolchain}", "--print=cfg", f"--target={triple}"], quiet=True |
| 958 |
) |
| 959 |
return RustcTarget( |
| 960 |
triple=triple, |
| 961 |
arch=re.findall(r'target_arch="(.*)"', target_cfg)[0], |
| 962 |
env=re.findall(r'target_env="(.*)"', target_cfg)[0], |
| 963 |
os_=re.findall(r'target_os="(.*)"', target_cfg)[0], |
| 964 |
bits=int(re.findall(r'target_pointer_width="(.*)"', target_cfg)[0]), |
| 965 |
) |
| 966 |
|
| 967 |
@staticmethod |
| 968 |
@functools.cache |
| 969 |
def fetch_all(toolchain: str) -> list["RustcTarget"]: |
| 970 |
"""Collect all targets for a given toolchain.""" |
| 971 |
all_targets = check_output( |
| 972 |
["rustc", f"+{toolchain}", "--print=target-list"] |
| 973 |
).splitlines() |
| 974 |
|
| 975 |
# Iterating targets is really slow, throw some threads at it. |
| 976 |
with Pool() as p: |
| 977 |
ret = p.starmap(RustcTarget.get_one, [(toolchain, t) for t in all_targets]) |
| 978 |
|
| 979 |
ret.sort(key=lambda t: t.triple) |
| 980 |
return ret |
| 981 |
|
| 982 |
|
| 983 |
@dataclass(kw_only=True) |
| 984 |
class PullRequest: |
| 985 |
"""Pull request built from a GitHub GraphQL API response""" |
| 986 |
|
| 987 |
title: str |
| 988 |
number: int |
| 989 |
state: str |
| 990 |
url: str |
| 991 |
author_username: str |
| 992 |
merged_at: str |
| 993 |
merge_commit: "Commit" |
| 994 |
commits: list["Commit"] |
| 995 |
|
| 996 |
|
| 997 |
@dataclass(kw_only=True) |
| 998 |
class Commit: |
| 999 |
"""Commit built from a GitHub GraphQL API response""" |
| 1000 |
|
| 1001 |
oid: str |
| 1002 |
committed_date: str |
| 1003 |
subject: str |
| 1004 |
author_name: str |
| 1005 |
author_username: str | None |
| 1006 |
|
| 1007 |
def __post_init__(self) -> None: |
| 1008 |
# Give some protection against multiline summaries, since that may confuse |
| 1009 |
# scripts or log messages. |
| 1010 |
self.subject = trunc_lines(self.subject) |
| 1011 |
self.author_name = trunc_lines(self.author_name) |
| 1012 |
if self.author_username is not None: |
| 1013 |
self.author_username = trunc_lines(self.author_username) |
| 1014 |
|
| 1015 |
@staticmethod |
| 1016 |
def from_object(obj) -> "Commit": |
| 1017 |
user = obj["author"]["user"] |
| 1018 |
return Commit( |
| 1019 |
oid=obj["oid"], |
| 1020 |
committed_date=obj["committedDate"], |
| 1021 |
subject=obj["messageHeadline"], |
| 1022 |
author_name=obj["author"]["name"], |
| 1023 |
author_username=user["login"] if user is not None else None, |
| 1024 |
) |
| 1025 |
|
| 1026 |
|
| 1027 |
class E(StrEnum): |
| 1028 |
"""ANSI escapes.""" |
| 1029 |
|
| 1030 |
YEL = "\033[33m" |
| 1031 |
GRN = "\033[32m" |
| 1032 |
|
| 1033 |
# Bright colors |
| 1034 |
CY_B = "\033[1;36m" |
| 1035 |
YEL_B = "\033[1;33m" |
| 1036 |
RED_B = "\033[1;31m" |
| 1037 |
|
| 1038 |
# Dimmed colors |
| 1039 |
DIM = "\033[2m" |
| 1040 |
YEL_D = "\033[2;33m" |
| 1041 |
GRN_D = "\033[2;32m" |
| 1042 |
|
| 1043 |
RST = "\033[0m" |
| 1044 |
|
| 1045 |
@property |
| 1046 |
def u(self) -> str: |
| 1047 |
"""Unescape, for passing to shell printf.""" |
| 1048 |
return self.replace("\033", "\\033") |
| 1049 |
|
| 1050 |
|
| 1051 |
@functools.cache |
| 1052 |
def cache_dir() -> Path: |
| 1053 |
xdg_cache = os.environ.get("XDG_CACHE_DIR") |
| 1054 |
if xdg_cache is not None: |
| 1055 |
return Path(xdg_cache) |
| 1056 |
return Path.home() / ".cache" |
| 1057 |
|
| 1058 |
|
| 1059 |
def repo_fetch_url() -> str: |
| 1060 |
return f"https://github.com/{REPO_OWNER}/{REPO}.git" |
| 1061 |
|
| 1062 |
|
| 1063 |
def pr_url(num: int) -> str: |
| 1064 |
return f"https://github.com/{REPO_OWNER}/{REPO}/pull/{num}" |
| 1065 |
|
| 1066 |
|
| 1067 |
def mstr(s: str) -> str: |
| 1068 |
"""Message string: clean an indented string and convert singular `\\n`s to spaces.""" |
| 1069 |
return re.sub(r"(\S)\n(\S)", r"\1 \2", cleandoc(s)) |
| 1070 |
|
| 1071 |
|
| 1072 |
def check_output(args: list[str], *, quiet: bool = False, **kw) -> str: |
| 1073 |
if not quiet: |
| 1074 |
xtrace(args, env=kw.get("env")) |
| 1075 |
return sp.check_output(args, encoding="utf8", text=True, **kw) |
| 1076 |
|
| 1077 |
|
| 1078 |
def run(args: list[str], *, quiet: bool = False, **kw) -> sp.CompletedProcess: |
| 1079 |
if not quiet: |
| 1080 |
xtrace(args, env=kw.get("env")) |
| 1081 |
return sp.run(args, check=True, text=True, **kw) |
| 1082 |
|
| 1083 |
|
| 1084 |
def xtrace(args: list[str], *, env: dict[str, str] | None) -> None: |
| 1085 |
"""Print commands before running them.""" |
| 1086 |
astr = " ".join(str(arg) for arg in args) |
| 1087 |
|
| 1088 |
# GQL commands are long, trim the next line |
| 1089 |
astr = trunc_lines(astr) |
| 1090 |
|
| 1091 |
if env is None: |
| 1092 |
eprint(f"{E.DIM}+ {astr}{E.RST}") |
| 1093 |
else: |
| 1094 |
envdiff = set(env.items()) - set(os.environ.items()) |
| 1095 |
estr = " ".join(f"{k}='{v}'" for (k, v) in envdiff) |
| 1096 |
eprint(f"{E.DIM}+ {estr} {astr}{E.RST}") |
| 1097 |
|
| 1098 |
|
| 1099 |
def trunc_lines(s: str) -> str: |
| 1100 |
"""If >1 line, replace other lines with `...`.""" |
| 1101 |
first, _, rest = s.partition("\n") |
| 1102 |
if rest != "": |
| 1103 |
first += " ..." |
| 1104 |
return first |
| 1105 |
|
| 1106 |
|
| 1107 |
def eprint(*args, **kw) -> None: |
| 1108 |
print(*args, file=sys.stderr, **kw) |
| 1109 |
|
| 1110 |
|
| 1111 |
if __name__ == "__main__": |
| 1112 |
main() |