Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
269 changes: 269 additions & 0 deletions .github/workflows/update-changelog.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,269 @@
name: update changelog

on:
workflow_dispatch:
inputs:
version:
description: "Target version; leave empty to auto bump from debian/changelog"
required: false
type: string
base_branch:
description: "Base branch to read and target"
required: false
default: master
type: string
distribution:
description: "Changelog distribution"
required: false
default: unstable
type: string
create_pr:
description: "Create a pull request after generating changelog"
required: false
default: false
type: boolean
workflow_call:
inputs:
version:
required: false
type: string
base_branch:
required: false
type: string
default: master
distribution:
required: false
type: string
default: unstable
create_pr:
required: false
type: boolean
default: true

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Default workflow calls fail without secrets

When a reusable-workflow caller omits the optional app secrets and leaves create_pr at its default, the app-token step receives empty credentials and fails before changelog generation completes, so the caller gets no changelog output or artifact.

Default create_pr to false and run the app-token step only when PR creation is enabled.

Also at .github/workflows/update-changelog.yml:44, .github/workflows/update-changelog.yml:46.

Prompt for AI agents
In `.github/workflows/update-changelog.yml` at line 41:

**Default workflow calls fail without secrets**

When a reusable-workflow caller omits the optional app secrets and leaves `create_pr` at its default, the app-token step receives empty credentials and fails before changelog generation completes, so the caller gets no changelog output or artifact.

Default `create_pr` to false and run the app-token step only when PR creation is enabled.

Also at `.github/workflows/update-changelog.yml:44`, `.github/workflows/update-changelog.yml:46`.

secrets:
APP_ID:
required: false
APP_PRIVATE_KEY:
required: false
outputs:
pr_url:
value: ${{ jobs.update_changelog.outputs.pr_url }}
version:
value: ${{ jobs.update_changelog.outputs.version }}

permissions:
contents: write
pull-requests: write

jobs:
update_changelog:
runs-on: ubuntu-latest
outputs:
pr_url: ${{ steps.create_pr.outputs.pull-request-url }}
version: ${{ steps.prepare.outputs.version }}
steps:
- name: Create GitHub App token
id: app_token
if: ${{ inputs.create_pr }}
uses: actions/create-github-app-token@v3
with:
app-id: ${{ secrets.APP_ID }}
private-key: ${{ secrets.APP_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
permission-contents: write
permission-pull-requests: write

- name: Checkout base branch
uses: actions/checkout@v5
with:
ref: ${{ inputs.base_branch }}
fetch-depth: 1
persist-credentials: false

- name: Install changelog tools
run: |
sudo apt-get update
sudo apt-get install -y devscripts

- name: Prepare changelog data
id: prepare
shell: python
env:
INPUT_VERSION: ${{ inputs.version }}
INPUT_BASE_BRANCH: ${{ inputs.base_branch }}
INPUT_DISTRIBUTION: ${{ inputs.distribution }}
GITHUB_TOKEN: ${{ steps.app_token.outputs.token || github.token }}
GITHUB_REPOSITORY: ${{ github.repository }}
run: |
import json
import os
import pathlib
import re
import subprocess
import urllib.parse
import urllib.request

def output_line(name, value):
with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as fh:
fh.write(f"{name}={value}\n")

def get_current_version(changelog_path):
try:
result = subprocess.run(
["dpkg-parsechangelog", "-l", str(changelog_path), "-S", "Version"],
capture_output=True,
text=True,
check=True,
)
return result.stdout.strip()
except Exception:
first_line = changelog_path.read_text(encoding="utf-8").splitlines()[0].strip()
match = re.match(r"^[^(]+\(([^)]+)\)", first_line)
if not match:
raise RuntimeError(f"cannot parse version from {changelog_path}")
return match.group(1)

def bump_version(version):
epoch = ""
value = version
if ":" in value:
epoch_part, value = value.split(":", 1)
if epoch_part.isdigit():
epoch = epoch_part + ":"
if "-" in value:
value = value.rsplit("-", 1)[0]
parts = value.split(".")
if len(parts) < 2 or any(not part.isdigit() for part in parts):
raise RuntimeError(f"unsupported version format: {version}")
parts[-1] = str(int(parts[-1]) + 1)
return epoch + ".".join(parts)

def github_get(url):
headers = {
"Accept": "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
"User-Agent": "deepin-autopack-update-changelog",
"Authorization": f"Bearer {os.environ['GITHUB_TOKEN']}",
}
req = urllib.request.Request(url, headers=headers)
with urllib.request.urlopen(req, timeout=30) as resp:
body = resp.read().decode("utf-8")
data = json.loads(body) if body else None
resp_headers = {k.lower(): v for k, v in resp.headers.items()}
return data, resp_headers

def parse_link_header(value):
links = {}
if not value:
return links
for item in value.split(","):
item = item.strip()
match = re.match(r'<([^>]+)>;\s*rel="([^"]+)"', item)
if match:
links[match.group(2)] = match.group(1)
return links

def commit_titles_since_changelog(owner, repo, base_branch, head_sha):
base_url = f"https://api.github.com/repos/{owner}/{repo}"
commits_url = f"{base_url}/commits?{urllib.parse.urlencode({'sha': base_branch, 'path': 'debian/changelog', 'per_page': 1})}"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Branch updates produce an empty changelog

When the base branch advances with a changelog change after checkout but before the API query, the API query can return a changelog commit newer than the checked-out head_sha. commit_titles_since_changelog then compares that newer base against the older checkout, yielding no forward commit titles (or failing the compare); the workflow generates a release-only changelog or stops instead of including the commits.

Resolve the base branch to one commit SHA and use that same SHA for checkout and all changelog-history queries.

Prompt for AI agents
In `.github/workflows/update-changelog.yml` at line 167:

**Branch updates produce an empty changelog**

When the base branch advances with a changelog change after checkout but before the API query, the API query can return a changelog commit newer than the checked-out `head_sha`. `commit_titles_since_changelog` then compares that newer base against the older checkout, yielding no forward commit titles (or failing the compare); the workflow generates a release-only changelog or stops instead of including the commits.

Resolve the base branch to one commit SHA and use that same SHA for checkout and all changelog-history queries.

commits, _ = github_get(commits_url)
if not commits:
raise RuntimeError(f"no commit found for debian/changelog on {base_branch}")

base_sha = commits[0]["sha"]
compare_url = f"{base_url}/compare/{urllib.parse.quote(base_sha, safe='')}...{urllib.parse.quote(head_sha, safe='')}?per_page=100"
titles = []
next_url = compare_url
while next_url:
page, page_headers = github_get(next_url)
for item in page.get("commits", []):
message = item.get("commit", {}).get("message", "")
title = message.splitlines()[0].strip()
if title:
titles.append(title)
next_url = parse_link_header(page_headers.get("link")).get("next")
return base_sha, titles

repo_root = pathlib.Path(os.environ["GITHUB_WORKSPACE"])
changelog_path = repo_root / "debian" / "changelog"
if not changelog_path.exists():
raise RuntimeError(f"missing changelog: {changelog_path}")

requested_version = os.environ.get("INPUT_VERSION", "").strip()
distribution = os.environ.get("INPUT_DISTRIBUTION", "").strip() or "unstable"
base_branch = os.environ.get("INPUT_BASE_BRANCH", "").strip() or "master"
owner, repo = os.environ["GITHUB_REPOSITORY"].split("/", 1)
head_sha = subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip()

current_version = get_current_version(changelog_path)
version = requested_version or bump_version(current_version)
if not version:
raise RuntimeError(f"unable to determine version from {current_version!r}")

base_sha, titles = commit_titles_since_changelog(owner, repo, base_branch, head_sha)
safe_version = re.sub(r"[^A-Za-z0-9._-]+", "-", version).strip("-")

output_line("version", version)
output_line("safe_version", safe_version)
output_line("distribution", distribution)
output_line("base_branch", base_branch)
output_line("base_sha", base_sha)
output_line("head_sha", head_sha)
output_line("titles_json", json.dumps(titles, ensure_ascii=False))

- name: Generate changelog
shell: python
env:
VERSION: ${{ steps.prepare.outputs.version }}
DISTRIBUTION: ${{ steps.prepare.outputs.distribution }}
TITLES_JSON: ${{ steps.prepare.outputs.titles_json }}
DEBFULLNAME: Deepin CI
DEBEMAIL: deepin-ci@deepin.org
TZ: Asia/Shanghai
run: |
import json
import os
import subprocess

version = os.environ["VERSION"].strip()
distribution = os.environ["DISTRIBUTION"].strip() or "unstable"
titles = json.loads(os.environ["TITLES_JSON"])
if not titles:
titles = [f"Release {version}"]

subprocess.run(
["dch", "-v", version, "-D", distribution, titles[0]],
check=True,
)
for title in titles[1:]:
subprocess.run(["dch", "-a", title], check=True)

- name: Show changelog diff
if: ${{ !inputs.create_pr }}
run: git diff -- debian/changelog

- name: Upload generated changelog
if: ${{ !inputs.create_pr }}
uses: actions/upload-artifact@v4
with:
name: generated-changelog
path: debian/changelog

- name: Create pull request
id: create_pr
if: ${{ inputs.create_pr }}
uses: peter-evans/create-pull-request@v6

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · PR targets the wrong branch

When base_branch differs from the repository’s default branch and PR creation is enabled, create-pull-request defaults its base to the repository’s default branch because the step does not pass base_branch, so the generated PR targets the wrong branch.

Pass ${{ inputs.base_branch }} as the base input to create-pull-request.

Also at .github/workflows/update-changelog.yml:257.

Prompt for AI agents
In `.github/workflows/update-changelog.yml` at line 254:

**PR targets the wrong branch**

When `base_branch` differs from the repository’s default branch and PR creation is enabled, `create-pull-request` defaults its base to the repository’s default branch because the step does not pass `base_branch`, so the generated PR targets the wrong branch.

Pass `${{ inputs.base_branch }}` as the `base` input to `create-pull-request`.

Also at `.github/workflows/update-changelog.yml:257`.

with:
token: ${{ steps.app_token.outputs.token }}
branch: changelog/${{ steps.prepare.outputs.safe_version }}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Older runs replace newer changelog contents

When two changelog runs for the same version overlap and the older run pushes last, both runs push to the same version-derived branch, so the older run replaces the newer contents and the PR loses commit titles included only in the newer changelog.

Prevent overlapping runs for the same version from updating the shared branch, ensuring the newer changelog is the one that remains.

Prompt for AI agents
In `.github/workflows/update-changelog.yml` at line 257:

**Older runs replace newer changelog contents**

When two changelog runs for the same version overlap and the older run pushes last, both runs push to the same version-derived branch, so the older run replaces the newer contents and the PR loses commit titles included only in the newer changelog.

Prevent overlapping runs for the same version from updating the shared branch, ensuring the newer changelog is the one that remains.

title: "chore: update changelog to ${{ steps.prepare.outputs.version }}"
commit-message: "chore: update changelog to ${{ steps.prepare.outputs.version }}"
body: |
Automated changelog update.

- Version: `${{ steps.prepare.outputs.version }}`
- Base branch: `${{ steps.prepare.outputs.base_branch }}`
- Base changelog commit: `${{ steps.prepare.outputs.base_sha }}`
- Head commit: `${{ steps.prepare.outputs.head_sha }}`
add-paths: |
debian/changelog
delete-branch: true
Loading
Loading