Skip to content

Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.

Release notes in CI: a reviewed file per version plus GitHub's generated notes

v0lumehi160fcd888636
diff --git a/.github/workflows/build-mac-app.yml b/.github/workflows/build-mac-app.yml
index c6b7038b..03474dbf 100644
--- a/.github/workflows/build-mac-app.yml
+++ b/.github/workflows/build-mac-app.yml
@@ -401,8 +401,22 @@ jobs:
else
notes="$notes"$'\n\n'"Published without a release candidate (release_without_rc)."
fi
- gh release view "$GITHUB_REF_NAME" >/dev/null 2>&1 || \
- gh release create "$GITHUB_REF_NAME" --verify-tag --title "$GITHUB_REF_NAME" --notes "$notes"
+ if ! gh release view "$GITHUB_REF_NAME" >/dev/null 2>&1; then
+ # The body is the reviewed release-notes/<tag>.md plus GitHub's generated notes (contributors, Full Changelog). Without that file
+ # it is the short body above plus the generated notes. If the tool fails for any reason, the release gets the short body
+ # alone: a problem with the notes never stops a release. The release is created only when it does not exist, so notes someone
+ # edited by hand are never overwritten.
+ printf '%s\n' "$notes" > "$RUNNER_TEMP/short-notes.md"
+ body="$RUNNER_TEMP/short-notes.md"
+ if previous=$(python tools/release_notes.py previous "$GITHUB_REF_NAME") && \
+ python tools/release_notes.py build "$GITHUB_REF_NAME" --previous "$previous" --file "release-notes/$GITHUB_REF_NAME.md" \
+ --short-body "$RUNNER_TEMP/short-notes.md" --out "$RUNNER_TEMP/release-body.md"; then
+ body="$RUNNER_TEMP/release-body.md"
+ else
+ echo "::warning title=Release notes::tools/release_notes.py failed, so $GITHUB_REF_NAME gets the short body. Fix the notes with: gh release edit $GITHUB_REF_NAME --notes-file <file> (RELEASING.md, Release notes)"
+ fi
+ gh release create "$GITHUB_REF_NAME" --verify-tag --title "$GITHUB_REF_NAME" --notes-file "$body"
+ fi
fi
# All three names, one build: NX2Apple is current. The older two keep self-update working
# for installs from before each rename (an app replaces the bundle at its own path).
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index 65d6f5f9..b22a0f0a 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -125,6 +125,30 @@ jobs:
path: engine/logs
retention-days: 7
+ # The notes of a final release live in release-notes/vX.Y.Z.md and are merged before the tag (RELEASING.md, "Release notes"). A pull request that changes
+ # one is linted here: no emojis or symbols, no semicolons or dashes, Chinese then English, no template leftovers. Nothing runs when no notes file changed.
+ release-notes:
+ name: Release notes lint (release-notes/*.md)
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ - name: Lint the changed notes files
+ if: ${{ github.event_name == 'pull_request' }}
+ env:
+ BASE: ${{ github.event.pull_request.base.sha }}
+ run: |
+ git fetch --no-tags --depth=1 origin "$BASE"
+ files=$(git diff --name-only --diff-filter=d "$BASE" HEAD -- 'release-notes/*.md')
+ if [ -z "$files" ]; then
+ echo "No release notes file changed"
+ exit 0
+ fi
+ echo "$files"
+ echo "$files" | xargs python3 tools/release_notes.py check
+
patch-queue:
name: Patch queue (series applies to the pin, tool tests, dry bump against seedds main, issues #123 and #214)
runs-on: ubuntu-latest
@@ -152,7 +176,7 @@ jobs:
- name: Install the signing tool's package (tools/release_manifest.py)
run: python -m pip install -r tools/requirements-release.txt
- name: Patch, engine and release tool tests
- run: python -m unittest -v tools/tests/test_patches.py tools/tests/test_engine.py tools/tests/test_release_manifest.py
+ run: python -m unittest -v tools/tests/test_patches.py tools/tests/test_engine.py tools/tests/test_release_manifest.py tools/tests/test_release_notes.py
- name: Dry bump to seedds main (report only)
run: python tools/engine.py bump --dry --to main || true
diff --git a/RELEASING.md b/RELEASING.md
index 997b5937..1ff518b2 100644
--- a/RELEASING.md
+++ b/RELEASING.md
@@ -57,6 +57,8 @@ A final tag on a commit without a candidate fails. In an emergency, a manual run
CI writes a short body: the version and the tested candidate. The readable notes are written by a person or an agent from [.github/release_notes_template.md](.github/release_notes_template.md).
+The notes of a final release are a file in the repository, `release-notes/vX.Y.Z.md`, in the form of the template (the Chinese part, then the English part, no generated block). Merge it in a normal pull request before the final tag is pushed. When the final tag is built, CI creates the release with that file, a `---` line and GitHub's generated notes appended (`python3 tools/release_notes.py build`, the previous tag is the newest final tag before this one). `python3 tools/release_notes.py check release-notes/vX.Y.Z.md` runs the rules below and also runs in the pull request CI. Without the file CI writes the short body (the version and the tested candidate) and appends the generated notes. If the tool fails, the release gets the short body and CI prints a warning: a notes problem never stops a release. CI creates the release only when it does not exist, so notes edited by hand are never overwritten, and `gh release edit <tag> --notes-file <file>` stays the way to fix them later.
+
- Chinese first, English second, under `## 中文` and `## English`, with the same content in both. Each part has one bullet per change, grouped in bold: a notice, Highlights, New, Fixed, Known issues, Requires.
- No emojis, no pictograms and no symbols in the text. No semicolons (also not the full-width one) and no em-dashes. Plain English and plain Chinese.
- People are written as `@login`, the owner as `@LNPANDY`.
diff --git a/tools/release_notes.py b/tools/release_notes.py
new file mode 100644
index 00000000..97e22f44
--- /dev/null
+++ b/tools/release_notes.py
@@ -0,0 +1,251 @@
+#!/usr/bin/env python3
+"""The notes of a final release: a reviewed file per version plus the notes GitHub generates (RELEASING.md, "Release notes").
+
+release-notes/vX.Y.Z.md is written by a person or an agent in a normal pull request before the final tag, in the form of
+.github/release_notes_template.md (a Chinese part, then an English part, no generated block). When the final tag is built, CI runs `build`:
+the file, a `---` line, then the generated notes (merged pull requests with their authors, first-time contributors, the Full Changelog link)
+appended unchanged.
+
+Subcommands (Python 3.9+, no packages):
+ check FILE... lint notes files: no emojis, pictograms or symbols, no semicolons (also the full-width one), no em-dashes or
+ en-dashes, a `## 中文` and then a `## English` section, no template comments or placeholders, no generated block.
+ Exit 1 when any file has a problem, and print every problem as file:line.
+ previous TAG [--remote R] print the newest final tag (no `-rc`) before TAG, read from `git ls-remote --tags R` (default origin).
+ Prints nothing when there is none.
+ build TAG --out FILE [--previous TAG0] [--file NOTES] [--short-body FILE] [--repo OWNER/NAME]
+ write the release body to FILE. With an existing NOTES file (checked first, a bad file is an error) the body is
+ that file. Without one it is the short body from --short-body (the text CI wrote before this tool existed).
+ Either way `---` and the output of
+ gh api -X POST repos/OWNER/NAME/releases/generate-notes -f tag_name=TAG -f previous_tag_name=TAG0 --jq .body
+ follow. Nothing is published: `gh release create --notes-file FILE` does that, in the workflow.
+"""
+import argparse
+import os
+import re
+import subprocess
+import sys
+import unicodedata
+
+DEFAULT_REPO = 'LNPANDY/NX2Apple'
+FINAL_TAG = re.compile(r'^v(\d+)\.(\d+)\.(\d+)$')
+
+HEADING_ZH = '## 中文'
+HEADING_EN = '## English'
+
+SEMICOLONS = {';': 'semicolon', ';': 'full-width semicolon', '﹔': 'small semicolon', ';': 'Greek question mark (looks like a semicolon)'}
+DASHES = {'—': 'em-dash', '–': 'en-dash', '―': 'horizontal bar', '⸺': 'two-em dash', '⸻': 'three-em dash',
+ '﹘': 'small em-dash', '﹣': 'small hyphen-minus', '-': 'full-width hyphen-minus'}
+
+# Left behind when the template is copied and not finished.
+PLACEHOLDERS = [
+ (re.compile(r'<!--|-->'), 'a template comment'),
+ (re.compile(r'\bv?X\.Y\.Z\b'), 'the placeholder vX.Y.Z'),
+ (re.compile(r'(?<![\w&])#[NM]\b'), 'the placeholder #N or #M'),
+ (re.compile(r'\b(?:TODO|TBD|FIXME)\b'), 'a TODO marker'),
+ (re.compile(r'the one thing this release is about|Name of the feature|Lead of the (?:change|fix|issue)|One point\b', re.I), 'template text'),
+ (re.compile(r'一个要点|功能的名称|改动的标题|修复的标题|问题的标题'), 'template text'),
+]
+# The generated block is added by `build`, never written into the file.
+GENERATED = [
+ (re.compile(r"^#+\s*What's Changed\b", re.I), 'the generated block (build adds it)'),
+ (re.compile(r'\*\*Full Changelog\*\*|^Full Changelog\b', re.I), 'the Full Changelog link (build adds it)'),
+ (re.compile(r'^#+\s*New Contributors\b', re.I), 'the generated block (build adds it)'),
+]
+
+
+def symbol_problem(ch):
+ """Why a character is an emoji, a pictogram or a symbol, or None. ASCII and normal text (Latin, CJK, punctuation) pass."""
+ if ord(ch) < 0x80:
+ return None
+ cat = unicodedata.category(ch)
+ if cat in ('So', 'Sm', 'Sk', 'Sc'):
+ return 'a symbol or pictogram'
+ if cat in ('Cs', 'Co'):
+ return 'a private or surrogate code point'
+ if ch in '‍​‌⁠':
+ return 'an invisible character (emoji joiner or zero-width)'
+ if '︀' <= ch <= '️' or cat == 'Me':
+ return 'an emoji variation selector or keycap'
+ if '\U0001f3fb' <= ch <= '\U0001f3ff':
+ return 'an emoji skin tone'
+ if '\U000e0000' <= ch <= '\U000e007f':
+ return 'an emoji tag character'
+ return None
+
+
+def check_text(text):
+ """Problems of one notes file as a list of (line number, message)."""
+ problems = []
+ zh = en = None
+ in_comment = False
+ for no, line in enumerate(text.splitlines(), 1):
+ if line.rstrip() == HEADING_ZH:
+ if zh is not None:
+ problems.append((no, 'the section "%s" appears twice' % HEADING_ZH))
+ zh = zh if zh is not None else no
+ elif line.rstrip() == HEADING_EN:
+ if en is not None:
+ problems.append((no, 'the section "%s" appears twice' % HEADING_EN))
+ en = en if en is not None else no
+ for ch in line:
+ if ch in SEMICOLONS:
+ problems.append((no, 'no semicolons (found a %s)' % SEMICOLONS[ch]))
+ elif ch in DASHES:
+ problems.append((no, 'no em-dashes or en-dashes (found %s U+%04X)' % (DASHES[ch], ord(ch))))
+ else:
+ why = symbol_problem(ch)
+ if why:
+ problems.append((no, 'no emojis, pictograms or symbols (found %s U+%04X, %s)' % (ch, ord(ch), why)))
+ for pattern, what in PLACEHOLDERS + GENERATED:
+ if pattern.search(line):
+ problems.append((no, 'leftover from the template: %s' % what))
+ if zh is None:
+ problems.append((1, 'the section "%s" is missing' % HEADING_ZH))
+ if en is None:
+ problems.append((1, 'the section "%s" is missing' % HEADING_EN))
+ if zh is not None and en is not None and zh > en:
+ problems.append((zh, 'the Chinese part comes first: "%s" before "%s"' % (HEADING_ZH, HEADING_EN)))
+ if zh is not None and en is not None:
+ lines = text.splitlines()
+ first, second = sorted((zh, en))
+ for start, end, name in ((first, second, lines[first - 1].strip()), (second, len(lines) + 1, lines[second - 1].strip())):
+ body = [l for l in lines[start:end - 1] if l.strip() and l.strip() != '---']
+ if not body:
+ problems.append((start, 'the section "%s" is empty' % name))
+ # One report per line and message, not one per character.
+ seen, unique = set(), []
+ for item in problems:
+ if item not in seen:
+ seen.add(item)
+ unique.append(item)
+ return unique
+
+
+def check_file(path):
+ try:
+ with open(path, encoding='utf-8') as f:
+ text = f.read()
+ except FileNotFoundError:
+ return [(0, 'the file does not exist')]
+ except UnicodeDecodeError:
+ return [(0, 'the file is not UTF-8')]
+ return check_text(text)
+
+
+def cmd_check(args):
+ bad = 0
+ for path in args.files:
+ problems = check_file(path)
+ for no, message in problems:
+ print('%s:%d: %s' % (path, no, message))
+ if os.environ.get('GITHUB_ACTIONS'):
+ print('::error file=%s,line=%d,title=Release notes::%s' % (path, max(no, 1), message))
+ if problems:
+ bad += 1
+ else:
+ print('%s: ok' % path)
+ if bad:
+ print('%d of %d file(s) have problems. The rules are in RELEASING.md, "Release notes".' % (bad, len(args.files)), file=sys.stderr)
+ return 1 if bad else 0
+
+
+def final_key(tag):
+ m = FINAL_TAG.match(tag)
+ return tuple(int(x) for x in m.groups()) if m else None
+
+
+def previous_final(tag, tags):
+ """The newest final tag (vX.Y.Z, no -rc) that is older than `tag`, or ''."""
+ me = final_key(tag)
+ if me is None:
+ raise ValueError('%r is not a final tag (vX.Y.Z)' % tag)
+ older = [(final_key(t), t) for t in set(tags) if final_key(t) is not None and final_key(t) < me]
+ return max(older)[1] if older else ''
+
+
+def remote_tags(remote):
+ out = subprocess.run(['git', 'ls-remote', '--tags', remote], capture_output=True, text=True, check=True).stdout
+ tags = []
+ for line in out.splitlines():
+ parts = line.split()
+ if len(parts) == 2 and parts[1].startswith('refs/tags/') and not parts[1].endswith('^{}'):
+ tags.append(parts[1][len('refs/tags/'):])
+ return tags
+
+
+def cmd_previous(args):
+ try:
+ print(previous_final(args.tag, remote_tags(args.remote)))
+ except (ValueError, subprocess.CalledProcessError) as e:
+ print('previous: %s' % e, file=sys.stderr)
+ return 1
+ return 0
+
+
+def generated_notes(repo, tag, previous):
+ cmd = ['gh', 'api', '-X', 'POST', 'repos/%s/releases/generate-notes' % repo, '-f', 'tag_name=%s' % tag]
+ if previous:
+ cmd += ['-f', 'previous_tag_name=%s' % previous]
+ cmd += ['--jq', '.body']
+ body = subprocess.run(cmd, capture_output=True, text=True, check=True).stdout.rstrip('\n')
+ if not body.strip():
+ raise RuntimeError('GitHub returned empty generated notes')
+ return body
+
+
+def cmd_build(args):
+ if final_key(args.tag) is None:
+ print('build: %r is not a final tag (vX.Y.Z)' % args.tag, file=sys.stderr)
+ return 1
+ if args.file and os.path.exists(args.file):
+ problems = check_file(args.file)
+ if problems:
+ for no, message in problems:
+ print('%s:%d: %s' % (args.file, no, message), file=sys.stderr)
+ print('build: %s fails the check' % args.file, file=sys.stderr)
+ return 1
+ with open(args.file, encoding='utf-8') as f:
+ head = f.read().strip()
+ elif args.short_body:
+ with open(args.short_body, encoding='utf-8') as f:
+ head = f.read().strip()
+ print('build: %s, the body is the short one' % ('%s does not exist' % args.file if args.file else 'no notes file'), file=sys.stderr)
+ else:
+ print('build: no notes file and no --short-body', file=sys.stderr)
+ return 1
+ try:
+ generated = generated_notes(args.repo, args.tag, args.previous)
+ except (subprocess.CalledProcessError, OSError, RuntimeError) as e:
+ detail = getattr(e, 'stderr', '') or e
+ print('build: the generated notes failed: %s' % str(detail).strip(), file=sys.stderr)
+ return 1
+ with open(args.out, 'w', encoding='utf-8') as f:
+ f.write('%s\n\n---\n\n%s\n' % (head, generated))
+ print('build: wrote %s (previous tag %s)' % (args.out, args.previous or 'none'))
+ return 0
+
+
+def main(argv=None):
+ p = argparse.ArgumentParser(description=__doc__.split('\n')[0])
+ sub = p.add_subparsers(dest='cmd', required=True)
+ c = sub.add_parser('check')
+ c.add_argument('files', nargs='+')
+ c.set_defaults(fn=cmd_check)
+ pr = sub.add_parser('previous')
+ pr.add_argument('tag')
+ pr.add_argument('--remote', default='origin')
+ pr.set_defaults(fn=cmd_previous)
+ b = sub.add_parser('build')
+ b.add_argument('tag')
+ b.add_argument('--out', required=True)
+ b.add_argument('--previous', default='')
+ b.add_argument('--file', default='')
+ b.add_argument('--short-body', default='')
+ b.add_argument('--repo', default=os.environ.get('GITHUB_REPOSITORY') or DEFAULT_REPO)
+ b.set_defaults(fn=cmd_build)
+ args = p.parse_args(argv)
+ return args.fn(args)
+
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/tools/tests/test_release_notes.py b/tools/tests/test_release_notes.py
new file mode 100644
index 00000000..3a668dce
--- /dev/null
+++ b/tools/tests/test_release_notes.py
@@ -0,0 +1,194 @@
+"""tools/release_notes.py: `check` accepts a notes file in the form of .github/release_notes_template.md and rejects each kind of bad file,
+`previous` picks the newest final tag, and `build` writes the file, a `---` line and the generated notes unchanged, with a fake `gh` and no network."""
+import importlib
+import os
+import stat
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+TOOLS = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(TOOLS))
+N = importlib.import_module('release_notes')
+
+GOOD = """**v1.2.3: the iPhone app.**
+
+## 中文
+
+**重点**
+
+**iPhone 应用**
+- 现在可以在 iPhone 上运行游戏
+- 支持手柄
+
+**修复**
+- **修复崩溃**:启动时崩溃,现在不会了(#12)
+
+## English
+
+**Highlights**
+
+**iPhone app**
+- Games run on the iPhone now
+- Controllers work
+
+**Fixed**
+- **Crash fixed**: it crashed at launch, now it does not (#12)
+
+---
+
+**Install:** download `NX2Apple-macOS-arm64.zip`, unzip, drag it to Applications. 中文:下载后解压,拖进「应用程序」。
+"""
+
+GENERATED = "## What's Changed\n* Fix a crash by @v0lumehi in #12\n\n**Full Changelog**: https://github.com/LNPANDY/NX2Apple/compare/v1.0.0...v1.2.3"
+
+FAKE_GH = """#!/bin/sh
+printf '%s\\n' "$@" > "$FAKE_GH_ARGS"
+if [ -n "$FAKE_GH_FAIL" ]; then echo "HTTP 500" >&2; exit 1; fi
+cat "$FAKE_GH_BODY"
+"""
+
+
+def problems(text):
+ return [m for _, m in N.check_text(text)]
+
+
+class Check(unittest.TestCase):
+ def test_good_file(self):
+ self.assertEqual(N.check_text(GOOD), [])
+
+ def test_the_template_itself_fails(self):
+ template = TOOLS.parent / '.github' / 'release_notes_template.md'
+ if template.exists():
+ self.assertTrue(N.check_text(template.read_text(encoding='utf-8')))
+
+ def test_emojis_and_symbols(self):
+ for bad in ('\U0001f680', '⚠️', '→', '✓', '©', '\U0001f1e9\U0001f1ea', '1️⃣', '\U0001f44d\U0001f3fd', '™'):
+ with self.subTest(bad=bad):
+ self.assertTrue(any('emojis' in m for m in problems(GOOD.replace('Controllers work', 'Controllers work ' + bad))))
+
+ def test_chinese_and_normal_punctuation_pass(self):
+ self.assertEqual(N.check_text(GOOD.replace('Controllers work', 'Controllers work, "quoted" and it’s fine…')), [])
+
+ def test_semicolons(self):
+ for bad in (';', ';'):
+ with self.subTest(bad=bad):
+ self.assertTrue(any('semicolon' in m for m in problems(GOOD.replace('Controllers work', 'Controllers work' + bad + ' yes'))))
+
+ def test_dashes(self):
+ for bad in ('—', '–', '——'):
+ with self.subTest(bad=bad):
+ self.assertTrue(any('dash' in m for m in problems(GOOD.replace('Controllers work', 'Controllers ' + bad + ' work'))))
+
+ def test_sections(self):
+ self.assertTrue(any('中文' in m and 'missing' in m for m in problems(GOOD.replace('## 中文', '## Chinese'))))
+ self.assertTrue(any('English' in m and 'missing' in m for m in problems(GOOD.replace('## English', '## Englisch'))))
+ zh, en = GOOD.split('## English')
+ swapped = '## English' + en.split('---')[0] + '\n' + zh.replace('## 中文', '## 中文', 1)
+ self.assertTrue(any('comes first' in m for m in problems(swapped)))
+ self.assertTrue(any('empty' in m for m in problems(GOOD.split('**重点**')[0] + '## English\n\ntext\n')))
+
+ def test_leftovers(self):
+ for bad in ('<!-- a comment -->', 'vX.Y.Z', 'X.Y.Z', 'see #N', 'TODO', 'One point', '一个要点'):
+ with self.subTest(bad=bad):
+ self.assertTrue(any('template' in m for m in problems(GOOD.replace('Controllers work', bad))))
+
+ def test_generated_block_does_not_belong_in_the_file(self):
+ self.assertTrue(any('generated' in m or 'Full Changelog' in m for m in problems(GOOD + '\n' + GENERATED)))
+
+ def test_check_file_cli(self):
+ with tempfile.TemporaryDirectory() as d:
+ good, bad = Path(d, 'v1.2.3.md'), Path(d, 'v1.2.4.md')
+ good.write_text(GOOD, encoding='utf-8')
+ bad.write_text(GOOD + '\n\U0001f680\n', encoding='utf-8')
+ self.assertEqual(N.main(['check', str(good)]), 0)
+ self.assertEqual(N.main(['check', str(good), str(bad)]), 1)
+ self.assertEqual(N.main(['check', str(Path(d, 'missing.md'))]), 1)
+ Path(d, 'binary.md').write_bytes(b'\xff\xfe\x00')
+ self.assertEqual(N.main(['check', str(Path(d, 'binary.md'))]), 1)
+
+
+class Previous(unittest.TestCase):
+ TAGS = ['v0.7.5', 'v0.8.0-rc1', 'v0.8.0-rc8', 'v1.0.0-rc1', 'v1.0.0', 'v1.0.0-rc2', 'v0.7.10', 'v0.7.9', 'nightly', 'v1.1.0-rc1']
+
+ def test_newest_final_before(self):
+ self.assertEqual(N.previous_final('v1.0.0', self.TAGS), 'v0.7.10')
+ self.assertEqual(N.previous_final('v1.1.0', self.TAGS), 'v1.0.0')
+ self.assertEqual(N.previous_final('v0.7.10', self.TAGS), 'v0.7.9')
+
+ def test_none(self):
+ self.assertEqual(N.previous_final('v0.7.5', ['v0.7.5', 'v0.8.0-rc1']), '')
+
+ def test_not_a_final_tag(self):
+ for tag in ('v1.0.0-rc1', '1.0.0', 'main'):
+ with self.assertRaises(ValueError):
+ N.previous_final(tag, self.TAGS)
+
+ def test_remote_tags_skip_peeled_lines(self):
+ out = 'abc\trefs/tags/v1.0.0\ndef\trefs/tags/v1.0.0^{}\n123\trefs/heads/main\n'
+ with mock.patch('subprocess.run', return_value=mock.Mock(stdout=out)):
+ self.assertEqual(N.remote_tags('origin'), ['v1.0.0'])
+
+
+class Build(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.tmp.cleanup)
+ d = Path(self.tmp.name)
+ self.bin = d / 'bin'
+ self.bin.mkdir()
+ gh = self.bin / 'gh'
+ gh.write_text(FAKE_GH)
+ gh.chmod(gh.stat().st_mode | stat.S_IXUSR)
+ (d / 'generated.txt').write_text(GENERATED + '\n')
+ self.args_file = d / 'gh-args.txt'
+ self.notes = d / 'v1.2.3.md'
+ self.short = d / 'short.md'
+ self.short.write_text('NX2Apple v1.2.3\n\nThe files of the release candidate v1.2.3-rc1.\n')
+ self.out = d / 'out.md'
+ env = {'PATH': str(self.bin) + os.pathsep + os.environ['PATH'], 'FAKE_GH_ARGS': str(self.args_file), 'FAKE_GH_BODY': str(d / 'generated.txt')}
+ patcher = mock.patch.dict(os.environ, env)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ os.environ.pop('FAKE_GH_FAIL', None)
+
+ def run_build(self, *extra):
+ return N.main(['build', 'v1.2.3', '--out', str(self.out), '--previous', 'v1.0.0', '--repo', 'LNPANDY/NX2Apple', *extra])
+
+ def test_notes_file_then_generated_block(self):
+ self.notes.write_text(GOOD, encoding='utf-8')
+ self.assertEqual(self.run_build('--file', str(self.notes), '--short-body', str(self.short)), 0)
+ self.assertEqual(self.out.read_text(encoding='utf-8'), GOOD.strip() + '\n\n---\n\n' + GENERATED + '\n')
+ self.assertEqual(self.args_file.read_text().split(), [
+ 'api', '-X', 'POST', 'repos/LNPANDY/NX2Apple/releases/generate-notes', '-f', 'tag_name=v1.2.3', '-f', 'previous_tag_name=v1.0.0', '--jq', '.body'])
+
+ def test_missing_file_uses_the_short_body(self):
+ self.assertEqual(self.run_build('--file', str(self.notes), '--short-body', str(self.short)), 0)
+ self.assertEqual(self.out.read_text(), self.short.read_text().strip() + '\n\n---\n\n' + GENERATED + '\n')
+
+ def test_no_previous_tag_leaves_the_argument_out(self):
+ self.assertEqual(N.main(['build', 'v1.2.3', '--out', str(self.out), '--short-body', str(self.short)]), 0)
+ self.assertNotIn('previous_tag_name', self.args_file.read_text())
+
+ def test_bad_notes_file_fails_and_writes_nothing(self):
+ self.notes.write_text(GOOD + '\n\U0001f680\n', encoding='utf-8')
+ self.assertEqual(self.run_build('--file', str(self.notes), '--short-body', str(self.short)), 1)
+ self.assertFalse(self.out.exists())
+
+ def test_gh_failure_fails_and_writes_nothing(self):
+ self.notes.write_text(GOOD, encoding='utf-8')
+ with mock.patch.dict(os.environ, {'FAKE_GH_FAIL': '1'}):
+ self.assertEqual(self.run_build('--file', str(self.notes)), 1)
+ self.assertFalse(self.out.exists())
+
+ def test_not_a_final_tag(self):
+ self.assertEqual(N.main(['build', 'v1.2.3-rc1', '--out', str(self.out), '--short-body', str(self.short)]), 1)
+
+ def test_nothing_to_build_from(self):
+ self.assertEqual(self.run_build('--file', str(self.notes)), 1)
+
+
+if __name__ == '__main__':
+ unittest.main()