/
util.py
685 lines (546 loc) · 21.5 KB
/
util.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
# Of the form:
# https://github.com/{owner}/{repo}/releases/tag/{tag}
import atexit
import hashlib
import json
import os
import os.path as osp
import re
import shlex
import shutil
import subprocess
import sys
import tempfile
import time
import warnings
from datetime import datetime
from glob import glob
from io import BytesIO
from pathlib import Path
from subprocess import PIPE, CalledProcessError, check_output
import requests
import toml
from ghapi import core
from importlib_resources import files
from jsonschema import Draft4Validator as Validator
from packaging.version import Version
from packaging.version import parse as parse_version
from pkginfo import Wheel
from jupyter_releaser.tee import run as tee
PYPROJECT = Path("pyproject.toml")
SETUP_PY = Path("setup.py")
SETUP_CFG = Path("setup.cfg")
PACKAGE_JSON = Path("package.json")
MANIFEST = Path("MANIFEST.in")
YARN_LOCK = Path("yarn.lock")
JUPYTER_RELEASER_CONFIG = Path(".jupyter-releaser.toml")
METADATA_JSON = Path("metadata.json")
BUF_SIZE = 65536
TBUMP_CMD = "pipx run tbump --non-interactive --only-patch"
CHECKOUT_NAME = ".jupyter_releaser_checkout"
MOCK_GITHUB_URL = "http://127.0.0.1:8000"
RELEASE_HTML_PATTERN = f"(?:https://github.com|{MOCK_GITHUB_URL})/(?P<owner>[^/]+)/(?P<repo>[^/]+)/releases/tag/(?P<tag>.*)"
RELEASE_API_PATTERN = (
"https://api.github.com/repos/(?P<owner>[^/]+)/(?P<repo>[^/]+)/releases/tags/(?P<tag>.*)"
)
SCHEMA = files("jupyter_releaser").joinpath("schema.json").read_text()
SCHEMA = json.loads(SCHEMA)
GIT_FETCH_CMD = "git fetch origin --filter=blob:none --quiet"
def run(cmd, **kwargs):
"""Run a command as a subprocess and get the output as a string"""
quiet_error = kwargs.pop("quiet_error", False)
show_cwd = kwargs.pop("show_cwd", False)
quiet = kwargs.pop("quiet", False)
echo = kwargs.pop("echo", False)
if echo:
prefix = "COMMAND"
if show_cwd:
prefix += f" (in '{os.getcwd()}')"
prefix += ":"
log(f"{prefix} {cmd}")
if sys.platform.startswith("win"):
# Async subprocesses do not work well on Windows, use standard
# subprocess methods
return _run_win(cmd, **kwargs)
quiet = kwargs.get("quiet")
kwargs.setdefault("check", True)
try:
process = tee(cmd, **kwargs)
return (process.stdout or "").strip()
except CalledProcessError as e:
if quiet and not quiet_error:
if e.stderr:
log("stderr:\n", e.stderr.strip(), "\n\n")
if e.stdout:
log("stdout:\n", e.stdout.strip(), "\n\n")
raise e
def _run_win(cmd, **kwargs):
"""Run a command as a subprocess and get the output as a string"""
quiet = kwargs.pop("quiet", False)
if not quiet:
kwargs.setdefault("stderr", PIPE)
kwargs.setdefault("shell", True)
parts = shlex.split(cmd)
if "/" not in parts[0]:
executable = shutil.which(parts[0])
if not executable:
raise CalledProcessError(1, f'Could not find executable "{parts[0]}"')
parts[0] = normalize_path(executable)
check = kwargs.pop("check", True)
try:
output = check_output(parts, **kwargs).decode("utf-8").strip()
log(output)
return output
except CalledProcessError as e:
e.output = e.output.decode("utf-8")
if quiet:
e.stderr = e.stderr.decode("utf-8")
log("stderr:\n", e.stderr.strip(), "\n\n")
log("stdout:\n", e.output.strip(), "\n\n")
if check:
raise e
def log(*outputs, **kwargs):
"""Log an output to stderr"""
kwargs.setdefault("file", sys.stderr)
print(*outputs, **kwargs)
def get_branch():
"""Get the appropriate git branch"""
return run("git branch --show-current")
def get_default_branch():
"""Get the default remote branch"""
info = run("git remote show origin")
for line in info.splitlines():
if line.strip().startswith("HEAD branch:"):
return line.strip().split()[-1]
def get_repo():
"""Get the remote repo owner and name"""
url = run("git remote get-url origin")
url = normalize_path(url)
parts = url.split("/")[-2:]
if ":" in parts[0]:
parts[0] = parts[0].split(":")[-1]
parts[1] = parts[1].replace(".git", "")
return "/".join(parts)
def get_version():
"""Get the current package version"""
# Prefer to get a static version from pyproject.toml.
if PYPROJECT.exists():
text = PYPROJECT.read_text(encoding="utf-8")
data = toml.loads(text)
project = data.get("project", {})
version = project.get("version")
if version:
return version
# If this is a hatchling project, use hatch to get
# the dynamic version.
if data.get("build-system", {}).get("build-backend") == "hatchling.build":
return run("pipx run hatch version").split("\n")[-1]
if SETUP_PY.exists():
warnings.warn("Using deprecated setup.py invocation")
try:
return run("python setup.py --version").split("\n")[-1]
except CalledProcessError as e:
log(e)
# Build the wheel and extract the version.
if PYPROJECT.exists():
with tempfile.TemporaryDirectory() as tempdir:
run(f"pipx run build --wheel --outdir {tempdir}")
wheel_path = glob(f"{tempdir}/*.whl")[0]
wheel = Wheel(wheel_path)
version = wheel.version
return version
if PACKAGE_JSON.exists():
return json.loads(PACKAGE_JSON.read_text(encoding="utf-8")).get("version", "")
raise ValueError("No version identifier could be found!")
def normalize_path(path):
"""Normalize a path to use backslashes"""
return str(path).replace(os.sep, "/")
def compute_sha256(path):
"""Compute the sha256 of a file"""
sha256 = hashlib.sha256()
with open(path, "rb") as f:
while True:
data = f.read(BUF_SIZE)
if not data:
break
sha256.update(data)
return sha256.hexdigest()
def create_release_commit(version, release_message=None, dist_dir="dist"):
"""Generate a release commit that has the sha256 digests for the release files"""
release_message = release_message or "Publish {version}"
release_message = release_message.format(version=version)
cmd = f'git commit -am "{release_message}"'
shas = {}
files = glob(f"{dist_dir}/*")
if files: # pragma: no cover
cmd += ' -m "SHA256 hashes:"'
for path in sorted(files):
path = normalize_path(path)
sha256 = compute_sha256(path)
shas[path] = sha256
name = osp.basename(path)
cmd += f' -m "{name}: {sha256}"'
run(cmd)
return shas
def bump_version(version_spec, *, changelog_path="", version_cmd=""):
"""Bump the version"""
# Look for config files to determine version command if not given
if not version_cmd:
for name in "bumpversion", ".bumpversion", "bump2version", ".bump2version":
if osp.exists(name + ".cfg"):
version_cmd = "bump2version"
if osp.exists("tbump.toml"):
version_cmd = version_cmd or TBUMP_CMD
if PYPROJECT.exists():
pyproject_text = PYPROJECT.read_text(encoding="utf-8")
if "tool.tbump" in pyproject_text:
version_cmd = version_cmd or TBUMP_CMD
elif "hatchling.build" in pyproject_text:
version_cmd = version_cmd or "pipx run hatch version"
if SETUP_CFG.exists():
if "bumpversion" in SETUP_CFG.read_text(encoding="utf-8"):
version_cmd = version_cmd or "bump2version"
if not version_cmd and PACKAGE_JSON.exists():
version_cmd = "npm version --git-tag-version false"
if not version_cmd: # pragma: no cover
raise ValueError("Please specify a version bump command to run")
# Assign default values if no version spec was given
if not version_spec:
if "tbump" in version_cmd or "hatch" in version_cmd:
version_spec = "next"
else:
version_spec = "patch"
# Add some convenience options on top of "tbump" and "hatch"
if "tbump" in version_cmd or "hatch" in version_cmd:
v = parse_version(get_version())
assert isinstance(v, Version)
if v.is_devrelease:
# bump from the version in the changelog.
if version_spec in ["patch", "next"]:
raise ValueError(
"We do not support 'patch' or 'next' when dev versions are used, please use an explicit version."
)
# Drop the dev portion and move to the minor release.
elif version_spec == "minor":
version_spec = f"{v.major}.{v.minor}.{v.micro}"
# Bump to the next dev version.
elif version_spec == "dev":
assert v.dev is not None
version_spec = f"{v.major}.{v.minor}.{v.micro}.dev{v.dev + 1}"
else:
# Bump to next minor for dev.
if version_spec == "dev":
version_spec = f"{v.major}.{v.minor + 1}.0.dev0"
# For next, go to next prerelease or patch if it is a final version.
elif version_spec == "next":
if v.is_prerelease:
assert v.pre is not None
version_spec = f"{v.major}.{v.minor}.{v.micro}{v.pre[0]}{v.pre[1] + 1}"
else:
version_spec = f"{v.major}.{v.minor}.{v.micro + 1}"
# For patch, always patch.
elif version_spec == "patch":
version_spec = f"{v.major}.{v.minor}.{v.micro + 1}"
# For minor, always minor.
elif version_spec == "minor":
version_spec = f"{v.major}.{v.minor + 1}.0"
# Bump the version
run(f"{version_cmd} {version_spec}")
return get_version()
def is_prerelease(version):
"""Test whether a version is a prerelease version"""
match = re.match("([0-9]+.[0-9]+.[0-9]+)", version)
assert match is not None
final_version = match.groups()[0]
return final_version != version
def release_for_url(gh, url):
"""Get release response data given a release url"""
release = None
for rel in gh.repos.list_releases():
if rel.html_url == url or rel.url == url:
release = rel
if not release:
raise ValueError(f"No release found for url {url}")
return release
def latest_draft_release(gh, branch=None):
"""Get the latest draft release for a given repo"""
newest_time = None
newest_release = None
if branch:
log(f"Getting latest draft release on branch {branch}")
else:
log("Getting latest draft release")
for release in gh.repos.list_releases():
if str(release.draft).lower() == "false":
continue
if branch and release.target_commitish != branch:
continue
created = release.created_at
d_created = datetime.strptime(created, r"%Y-%m-%dT%H:%M:%SZ")
if newest_time is None or d_created > newest_time:
newest_time = d_created
newest_release = release
if not newest_release:
log("No draft release found!")
else:
log(f"Found draft release at {newest_release.html_url}")
return newest_release
def actions_output(name, value):
"Print the special GitHub Actions `::set-output` line for `name::value`"
log(f"\n\nSetting output {name}={value}")
if "GITHUB_ACTIONS" in os.environ:
log(f"::set-output name={name}::{value}")
def get_latest_tag(source, since_last_stable=False):
"""Get the default 'since' value for a branch"""
source = source or get_branch()
tags = run(f"git --no-pager tag --sort=-creatordate --merged {source}", quiet=True)
if not tags:
return ""
tags = tags.splitlines()
if since_last_stable:
stable_tag = re.compile(r"\d\.\d\.\d$")
tags = [t for t in tags if re.search(stable_tag, t)]
if not tags:
return ""
return tags[0]
return tags[0]
def get_first_commit(source):
"""Get the default 'since' value for a branch"""
source = source or get_branch()
commit = run("git rev-list --max-parents=0 HEAD", quiet=True)
return commit
def retry(cmd, **kwargs):
"""Run a command with retries"""
attempt = 0
while True:
time.sleep(attempt)
try:
run(cmd, **kwargs)
return
except Exception as e:
attempt += 1
if attempt == 3:
raise e
def read_config():
"""Read the jupyter-releaser config data"""
config = None
if JUPYTER_RELEASER_CONFIG.exists():
config = toml.loads(JUPYTER_RELEASER_CONFIG.read_text(encoding="utf-8"))
if not config and PYPROJECT.exists():
data = toml.loads(PYPROJECT.read_text(encoding="utf-8"))
pyproject_config = data.get("tool", {}).get("jupyter-releaser")
if pyproject_config:
config = pyproject_config
if not config and PACKAGE_JSON.exists():
data = json.loads(PACKAGE_JSON.read_text(encoding="utf-8"))
if "jupyter-releaser" in data:
config = data["jupyter-releaser"]
config = config or {}
validator = Validator(SCHEMA)
validator.validate(config)
return config
def parse_release_url(release_url):
"""Parse a release url into a regex match"""
match = re.match(RELEASE_HTML_PATTERN, release_url)
match = match or re.match(RELEASE_API_PATTERN, release_url)
if not match:
raise ValueError(f"Release url is not valid: {release_url}")
return match
def fetch_release_asset(target_dir, asset, auth):
"""Fetch a release asset into a target directory."""
log(f"Fetching {asset.name}...")
url = asset.url
headers = dict(Authorization=f"token {auth}", Accept="application/octet-stream")
path = Path(target_dir) / asset.name
with requests.get(url, headers=headers, stream=True) as r:
r.raise_for_status()
with open(path, "wb") as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
return path
def fetch_release_asset_data(asset, auth):
"""Fetch the data for a release asset."""
log(f"Fetching data for {asset.name}...")
url = asset.url
headers = dict(Authorization=f"token {auth}", Accept="application/octet-stream")
sink = BytesIO()
with requests.get(url, headers=headers, stream=True) as r:
r.raise_for_status()
for chunk in r.iter_content(chunk_size=8192):
sink.write(chunk)
sink.seek(0)
return json.loads(sink.read().decode("utf-8"))
def upload_assets(gh, assets, release, auth):
"""Upload assets to a release."""
log(f"Uploading assets: {assets}")
asset_shas = {}
for fpath in assets:
gh.upload_file(release, fpath)
asset_shas[os.path.basename(fpath)] = compute_sha256(fpath)
# Create an asset_shas file.
with tempfile.TemporaryDirectory() as td:
asset_shas_file = os.path.join(td, "asset_shas.json")
with open(asset_shas_file, "w") as fid:
json.dump(asset_shas, fid)
gh.upload_file(release, asset_shas_file)
return release
def extract_metadata_from_release_url(gh, release_url, auth):
log(f"Extracting metadata for release: {release_url}")
release = release_for_url(gh, release_url)
data = None
for asset in release.assets:
if asset.name != METADATA_JSON.name:
continue
data = fetch_release_asset_data(asset, auth)
if data is None:
raise ValueError(
f'Could not find "{METADATA_JSON.name}" file in draft release {release_url}'
)
# Update environment variables.
for key, value in data.items():
if value is not None:
env_name = f"RH_{key.upper()}"
os.environ[env_name] = str(value)
return data
def prepare_environment(fetch_draft_release=True):
"""Prepare the environment variables, for use when running one of the
action scripts."""
# Set up env variables
if not os.environ.get("RH_REPOSITORY"):
if os.environ.get("RH_RELEASE_URL"):
match = parse_release_url(os.environ["RH_RELEASE_URL"])
owner, repo = match["owner"], match["repo"]
os.environ["RH_REPOSITORY"] = f"{owner}/{repo}"
else:
os.environ["RH_REPOSITORY"] = os.environ["GITHUB_REPOSITORY"]
if not os.environ.get("RH_REF"):
os.environ["RH_REF"] = os.environ["GITHUB_REF"]
dry_run = os.environ.get("RH_DRY_RUN", "").lower() == "true"
# Set the branch when using check release.
if not os.environ.get("RH_BRANCH") and dry_run:
if os.environ.get("GITHUB_BASE_REF"):
base_ref = os.environ.get("GITHUB_BASE_REF", "")
log(f"Using GITHUB_BASE_REF: ${base_ref}")
os.environ["RH_BRANCH"] = base_ref
else:
# e.g refs/head/foo or refs/tag/bar
ref = os.environ["GITHUB_REF"]
log(f"Using GITHUB_REF: {ref}")
os.environ["RH_BRANCH"] = "/".join(ref.split("/")[2:])
# Start the mock GitHub server if in a dry run.
if dry_run:
static_dir = os.path.join(tempfile.gettempdir(), "gh_static")
os.makedirs(static_dir, exist_ok=True)
os.environ["RH_GITHUB_STATIC_DIR"] = static_dir
ensure_mock_github()
# Set up GitHub object.
branch = os.environ.get("RH_BRANCH")
log(f"Getting GitHub connection for {os.environ['RH_REPOSITORY']}")
owner, repo_name = os.environ["RH_REPOSITORY"].split("/")
auth = os.environ.get("GITHUB_ACCESS_TOKEN", "")
gh = get_gh_object(dry_run=dry_run, owner=owner, repo=repo_name, token=auth)
# Ensure the user is an admin.
if not dry_run:
user = gh.users.get_authenticated()["login"]
collab_level = gh.repos.get_collaborator_permission_level(user)
if not collab_level["permission"] == "admin":
raise RuntimeError(f"User {user} does not have admin permission")
# Get the latest draft release if none is given.
release_url = os.environ.get("RH_RELEASE_URL")
log(f"Environment release url was {release_url}")
if not release_url and fetch_draft_release:
release = latest_draft_release(gh, branch)
if release:
release_url = release.html_url
if release_url:
os.environ["RH_RELEASE_URL"] = release_url
# Extract the metadata from the release url.
return extract_metadata_from_release_url(gh, release_url, auth)
return release_url
def handle_since():
"""Capture the "since" argument in case we add tags before checking changelog."""
if os.environ.get("RH_SINCE"):
log(f"Using RH_SINCE from env: {os.environ.get('RH_SINCE')}")
return
curr_dir = os.getcwd()
os.chdir(CHECKOUT_NAME)
since_last_stable_env = os.environ.get("RH_SINCE_LAST_STABLE", "")
since_last_stable = since_last_stable_env.lower() == "true"
log(f"Since last stable? {since_last_stable}")
since = get_latest_tag(os.environ.get("RH_BRANCH"), since_last_stable)
if since:
log(f"Capturing {since} in RH_SINCE variable")
os.environ["RH_SINCE"] = since
else:
log("No last stable found!")
os.chdir(curr_dir)
return since
def ensure_sha():
"""Ensure the sha of the remote branch matches the expected sha"""
current_sha = os.environ["RH_CURRENT_SHA"]
branch = os.environ["RH_BRANCH"]
log("Ensuring sha...")
remote_name = get_remote_name(False)
run("git remote -v", echo=True)
run(f"git fetch {remote_name} {branch}", echo=True)
sha = run(f"git rev-parse {remote_name}/{branch}", echo=True)
if sha != current_sha:
log(f"{branch} current sha {sha} is not equal to expected sha {current_sha}")
def get_gh_object(dry_run=False, **kwargs):
"""Get a properly configured GhAPi object"""
if dry_run:
ensure_mock_github()
return core.GhApi(**kwargs)
_local_remote = None
def get_remote_name(dry_run):
"""Get the appropriate remote git name."""
global _local_remote
if not dry_run:
return "origin"
if _local_remote:
try:
run(f"git remote add test {_local_remote}")
except Exception:
pass
return "test"
tfile = tempfile.NamedTemporaryFile(suffix=".git")
tfile.close()
_local_remote = tfile.name.replace(os.sep, "/")
run(f"git init --bare {_local_remote}")
run(f"git remote add test {_local_remote}")
return "test"
def ensure_mock_github():
"""Check for or start a mock github server."""
core.GH_HOST = MOCK_GITHUB_URL
log("Ensuring mock GitHub")
# First see if it is already running.
try:
requests.get(MOCK_GITHUB_URL)
return
except requests.ConnectionError:
pass
# Next make sure we have the required libraries.
python = sys.executable.replace(os.sep, "/")
try:
import fastapi # noqa
import univcorn # type: ignore # noqa
except ImportError:
run(f"{python} -m pip install fastapi uvicorn")
proc = subprocess.Popen([python, "-m", "uvicorn", "jupyter_releaser.mock_github:app"])
try:
ret = proc.wait(1)
if ret > 0:
raise ValueError(f"mock_github failed with {proc.returncode}")
except subprocess.TimeoutExpired:
pass
log("Mock GitHub started")
atexit.register(proc.kill)
while 1:
try:
requests.get(MOCK_GITHUB_URL)
break
except requests.ConnectionError:
pass
return proc