diff --git a/.github/workflows/changelog-archive.yml b/.github/workflows/changelog-archive.yml deleted file mode 100644 index ac8d52df5..000000000 --- a/.github/workflows/changelog-archive.yml +++ /dev/null @@ -1,354 +0,0 @@ -name: Archive Old Changelog Entries - -on: - schedule: - # Run every Sunday at 00:00 UTC - - cron: '0 0 * * 0' - workflow_dispatch: - -jobs: - archive-changelog: - if: github.repository == 'community-scripts/ProxmoxVE' - runs-on: ubuntu-latest - env: - BRANCH_NAME: github-action-archive-changelog - AUTOMATED_PR_LABEL: "automated pr" - permissions: - contents: write - pull-requests: write - steps: - - name: Generate a token - id: generate-token - uses: actions/create-github-app-token@v3 - with: - app-id: ${{ vars.GHAPP_PR_ID }} - private-key: ${{ secrets.GHAPP_PR_PRIVATE_KEY }} - - - name: Generate a token for PR approval and merge - id: generate-token-merge - uses: actions/create-github-app-token@v3 - with: - app-id: ${{ vars.GHAPP_MERGEBOT_ID }} - private-key: ${{ secrets.GHAPP_MERGEBOT_PRIVATE_KEY }} - - - name: Checkout code - uses: actions/checkout@v7 - with: - fetch-depth: 0 - - - name: Archive old changelog entries - uses: actions/github-script@v9 - with: - script: | - const fs = require('fs').promises; - const path = require('path'); - - const KEEP_DAYS = 30; - const ARCHIVE_PATH = '.github/changelogs'; - const CHANGELOG_PATH = 'CHANGELOG.md'; - - // Calculate cutoff date - const cutoffDate = new Date(); - cutoffDate.setDate(cutoffDate.getDate() - KEEP_DAYS); - cutoffDate.setHours(0, 0, 0, 0); - - console.log(`Cutoff date: ${cutoffDate.toISOString().split('T')[0]}`); - - // Read changelog and normalize line endings - let content = await fs.readFile(CHANGELOG_PATH, 'utf-8'); - content = content.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); - const lines = content.split('\n'); - - // Parse entries - const datePattern = /^## (\d{4})-(\d{2})-(\d{2})$/; - let header = []; - let recentEntries = []; - let archiveData = {}; - let currentDate = null; - let currentContent = []; - let inHeader = true; - let inOldHistory = false; - let historyDetailsDepth = 0; - - for (let i = 0; i < lines.length; i++) { - const line = lines[i]; - const match = line.match(datePattern); - - // Detect the start of History section:
followed by line with πŸ“œ History - if (inHeader && !inOldHistory && line.trim() === '
') { - // Look ahead to see if this is the History section - const nextLine = lines[i + 1] || ''; - if (nextLine.includes('πŸ“œ History')) { - inOldHistory = true; - historyDetailsDepth = 1; - continue; - } - } - - // Track nested details tags to find the end of History section - if (inOldHistory) { - if (line.trim() === '
') { - historyDetailsDepth++; - } - if (line.trim() === '
') { - historyDetailsDepth--; - if (historyDetailsDepth === 0) { - // We've closed the main History details tag - inOldHistory = false; - } - } - continue; - } - - if (match) { - inHeader = false; - - // Save previous entry - if (currentDate && currentContent.length > 0) { - const entryText = currentContent.join('\n').trim(); - const dateObj = new Date(`${currentDate}T00:00:00Z`); - - // Always add to archive (by month) - const year = currentDate.substring(0, 4); - const month = currentDate.substring(5, 7); - - if (!archiveData[year]) archiveData[year] = {}; - if (!archiveData[year][month]) archiveData[year][month] = []; - - archiveData[year][month].push(`## ${currentDate}\n\n${entryText}`); - - // Also add to recent entries if within cutoff - if (dateObj >= cutoffDate) { - recentEntries.push(`## ${currentDate}\n\n${entryText}`); - } - } - - currentDate = `${match[1]}-${match[2]}-${match[3]}`; - currentContent = []; - } else if (inHeader) { - header.push(line); - } else if (currentDate) { - currentContent.push(line); - } - } - - // Don't forget the last entry - if (currentDate && currentContent.length > 0) { - const entryText = currentContent.join('\n').trim(); - const dateObj = new Date(`${currentDate}T00:00:00Z`); - - // Always add to archive (by month) - const year = currentDate.substring(0, 4); - const month = currentDate.substring(5, 7); - - if (!archiveData[year]) archiveData[year] = {}; - if (!archiveData[year][month]) archiveData[year][month] = []; - - archiveData[year][month].push(`## ${currentDate}\n\n${entryText}`); - - // Also add to recent entries if within cutoff - if (dateObj >= cutoffDate) { - recentEntries.push(`## ${currentDate}\n\n${entryText}`); - } - } - - console.log(`Recent entries: ${recentEntries.length}`); - console.log(`Years to archive: ${Object.keys(archiveData).length}`); - - // Month names in English - const monthNames = { - '01': 'January', '02': 'February', '03': 'March', '04': 'April', - '05': 'May', '06': 'June', '07': 'July', '08': 'August', - '09': 'September', '10': 'October', '11': 'November', '12': 'December' - }; - - // Create/update archive files - for (const year of Object.keys(archiveData).sort().reverse()) { - const yearPath = path.join(ARCHIVE_PATH, year); - - try { - await fs.mkdir(yearPath, { recursive: true }); - } catch (e) { - // Directory exists - } - - for (const month of Object.keys(archiveData[year]).sort().reverse()) { - const monthPath = path.join(yearPath, `${month}.md`); - - // Read existing content if exists - let existingContent = ''; - try { - existingContent = await fs.readFile(monthPath, 'utf-8'); - // Normalize line endings to prevent regex issues - existingContent = existingContent.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); - } catch (e) { - // File doesn't exist - } - - // Parse existing entries into a Map (date -> content) for deduplication - const allEntries = new Map(); - - // Helper function to parse entries from content - const parseEntries = (content) => { - const entries = new Map(); - const parts = content.split(/(?=^## \d{4}-\d{2}-\d{2}$)/m); - for (const part of parts) { - const trimmed = part.trim(); - if (!trimmed) continue; - const dateMatch = trimmed.match(/^## (\d{4}-\d{2}-\d{2})/); - if (dateMatch) { - entries.set(dateMatch[1], trimmed); - } - } - return entries; - }; - - // Parse existing content - if (existingContent) { - const existingEntries = parseEntries(existingContent); - for (const [date, content] of existingEntries) { - allEntries.set(date, content); - } - } - - // Add new entries (existing entries take precedence to avoid overwriting) - let addedCount = 0; - for (const entry of archiveData[year][month]) { - const dateMatch = entry.match(/^## (\d{4}-\d{2}-\d{2})/); - if (dateMatch && !allEntries.has(dateMatch[1])) { - allEntries.set(dateMatch[1], entry.trim()); - addedCount++; - } - } - - // Sort entries by date (newest first) and write - const sortedDates = [...allEntries.keys()].sort().reverse(); - const sortedContent = sortedDates.map(date => allEntries.get(date)).join('\n\n'); - - if (addedCount > 0 || !existingContent) { - await fs.writeFile(monthPath, sortedContent + '\n', 'utf-8'); - console.log(`Updated: ${monthPath} (${allEntries.size} total entries, +${addedCount} new)`); - } - } - } - - // Build history section - let historySection = []; - historySection.push(''); - historySection.push('
'); - historySection.push('

πŸ“œ History

'); - historySection.push(''); - - // Get all years from archive directory - let allYears = []; - try { - const archiveDir = await fs.readdir(ARCHIVE_PATH); - allYears = archiveDir.filter(f => /^\d{4}$/.test(f)).sort().reverse(); - } catch (e) { - allYears = Object.keys(archiveData).sort().reverse(); - } - - for (const year of allYears) { - historySection.push(''); - historySection.push('
'); - historySection.push(`

${year}

`); - historySection.push(''); - - // Get months for this year - let months = []; - try { - const yearDir = await fs.readdir(path.join(ARCHIVE_PATH, year)); - months = yearDir - .filter(f => f.endsWith('.md')) - .map(f => f.replace('.md', '')) - .sort() - .reverse(); - } catch (e) { - months = Object.keys(archiveData[year] || {}).sort().reverse(); - } - - for (const month of months) { - const monthName = monthNames[month] || month; - const monthPath = path.join(ARCHIVE_PATH, year, `${month}.md`); - - // Count entries in month file - let entryCount = 0; - try { - let monthContent = await fs.readFile(monthPath, 'utf-8'); - monthContent = monthContent.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); - entryCount = (monthContent.match(/^## \d{4}-\d{2}-\d{2}$/gm) || []).length; - } catch (e) { - entryCount = (archiveData[year]?.[month] || []).length; - } - - const relativePath = `.github/changelogs/${year}/${month}.md`; - historySection.push(''); - historySection.push('
'); - historySection.push(`

${monthName} (${entryCount} entries)

`); - historySection.push(''); - historySection.push(`[View ${monthName} ${year} Changelog](${relativePath})`); - historySection.push(''); - historySection.push('
'); - } - - historySection.push(''); - historySection.push('
'); - } - - historySection.push(''); - historySection.push('
'); - - // Build new CHANGELOG.md (History first, then recent entries) - const newChangelog = [ - ...header, - '', - historySection.join('\n'), - '', - recentEntries.join('\n\n') - ].join('\n'); - - await fs.writeFile(CHANGELOG_PATH, newChangelog, 'utf-8'); - console.log('CHANGELOG.md updated successfully'); - - - name: Check for changes - id: verify-diff - run: | - git diff --quiet . || echo "changed=true" >> $GITHUB_ENV - - - name: Commit and push changes - if: env.changed == 'true' - run: | - git config --global user.name "github-actions[bot]" - git config --global user.email "github-actions[bot]@users.noreply.github.com" - git add CHANGELOG.md .github/changelogs/ - git commit -m "Archive old changelog entries" - git checkout -b $BRANCH_NAME || git checkout $BRANCH_NAME - git push origin $BRANCH_NAME --force - echo "HEAD_SHA=$(git rev-parse HEAD)" >> "$GITHUB_ENV" - - - name: Create pull request if not exists - if: env.changed == 'true' - env: - GH_TOKEN: ${{ steps.generate-token.outputs.token }} - run: | - PR_EXISTS=$(gh pr list --head "${BRANCH_NAME}" --state open --json number,isCrossRepository --jq '[.[] | select(.isCrossRepository == false)][0].number // empty') - if [ -z "$PR_EXISTS" ]; then - gh pr create --title "[Github Action] Archive old changelog entries" \ - --body "This PR is auto-generated by a Github Action to archive old changelog entries (older than 14 days) to .github/changelogs/YEAR/MONTH.md" \ - --head $BRANCH_NAME \ - --base main \ - --label "$AUTOMATED_PR_LABEL" - fi - - - name: Approve and merge pull request - if: env.changed == 'true' - env: - GH_TOKEN: ${{ steps.generate-token-merge.outputs.token }} - run: | - git config --global user.name "github-actions-automege[bot]" - git config --global user.email "github-actions-automege[bot]@users.noreply.github.com" - PR_NUMBER=$(gh pr list --head "${BRANCH_NAME}" --state open --json number,isCrossRepository --jq '[.[] | select(.isCrossRepository == false)][0].number // empty') - if [ -n "$PR_NUMBER" ]; then - gh pr review "$PR_NUMBER" --approve - gh pr merge "$PR_NUMBER" --squash --admin --match-head-commit "$HEAD_SHA" - fi diff --git a/.github/workflows/changelog-pr.yml b/.github/workflows/changelog-pr.yml deleted file mode 100644 index 7cd7d4d8e..000000000 --- a/.github/workflows/changelog-pr.yml +++ /dev/null @@ -1,439 +0,0 @@ -name: Create Changelog Pull Request - -on: - push: - branches: ["main"] - workflow_dispatch: - # Fired by community-scripts/core when an engine pull request is merged, so a - # change there does not wait for the next push here. Optional: engine PRs are - # collected on every run regardless, this only decides how soon. - repository_dispatch: - types: [core-pr-merged] - -jobs: - update-changelog-pull-request: - if: github.repository == 'community-scripts/ProxmoxVE' - runs-on: ubuntu-latest - env: - CONFIG_PATH: .github/changelog-pr-config.json - BRANCH_NAME: github-action-update-changelog - AUTOMATED_PR_LABEL: "automated pr" - permissions: - contents: write - pull-requests: write - steps: - - name: Generate a token - id: generate-token - uses: actions/create-github-app-token@v3 - with: - app-id: ${{ vars.GHAPP_PR_ID }} - private-key: ${{ secrets.GHAPP_PR_PRIVATE_KEY }} - - - name: Generate a token for PR approval and merge - id: generate-token-merge - uses: actions/create-github-app-token@v3 - with: - app-id: ${{ vars.GHAPP_MERGEBOT_ID }} - private-key: ${{ secrets.GHAPP_MERGEBOT_PRIVATE_KEY }} - - - name: Checkout code - uses: actions/checkout@v7 - with: - fetch-depth: 0 - - - name: Get latest dates in changelog - run: | - DATES=$(grep -E '^## [0-9]{4}-[0-9]{2}-[0-9]{2}' CHANGELOG.md | head -n 2 | awk '{print $2}') - - LATEST_DATE=$(echo "$DATES" | sed -n '1p') - SECOND_LATEST_DATE=$(echo "$DATES" | sed -n '2p') - TODAY=$(date -u +%Y-%m-%d) - - echo "TODAY=$TODAY" >> $GITHUB_ENV - if [[ "$LATEST_DATE" == "$TODAY" ]]; then - echo "LATEST_DATE=$SECOND_LATEST_DATE" >> $GITHUB_ENV - else - echo "LATEST_DATE=$LATEST_DATE" >> $GITHUB_ENV - fi - - - name: Get categorized pull requests - id: get-categorized-prs - uses: actions/github-script@v9 - with: - script: | - async function main() { - const fs = require('fs').promises; - const path = require('path'); - - const configPath = path.resolve(process.env.CONFIG_PATH); - const fileContent = await fs.readFile(configPath, 'utf-8'); - const changelogConfig = JSON.parse(fileContent); - - const categorizedPRs = changelogConfig.map(obj => ({ - ...obj, - notes: [], - subCategories: obj.subCategories ?? ( - obj.labels.includes("update script") ? [ - { title: "🐞 Bug Fixes", labels: ["bugfix"], notes: [] }, - { title: "✨ New Features", labels: ["feature"], notes: [] }, - { title: "πŸ’₯ Breaking Changes", labels: ["breaking change"], notes: [] }, - { title: "πŸ”§ Refactor", labels: ["refactor"], notes: [] }, - ] : - obj.labels.includes("maintenance") ? [ - { title: "🐞 Bug Fixes", labels: ["bugfix"], notes: [] }, - { title: "✨ New Features", labels: ["feature"], notes: [] }, - { title: "πŸ’₯ Breaking Changes", labels: ["breaking change"], notes: [] }, - { title: "πŸ“‘ API", labels: ["api"], notes: [] }, - { title: "Github", labels: ["github"], notes: [] }, - { title: "πŸ“ Documentation", labels: ["maintenance"], notes: [] }, - { title: "πŸ”§ Refactor", labels: ["refactor"], notes: [] } - ] : - obj.labels.includes("website") ? [ - { title: "🐞 Bug Fixes", labels: ["bugfix"], notes: [] }, - { title: "✨ New Features", labels: ["feature"], notes: [] }, - { title: "πŸ’₯ Breaking Changes", labels: ["breaking change"], notes: [] }, - { title: "Script Information", labels: ["json"], notes: [] } - ] : [] - ) - })); - - const latestDateInChangelog = new Date(process.env.LATEST_DATE); - latestDateInChangelog.setUTCHours(23, 59, 59, 999); - - const { data: pulls } = await github.rest.pulls.list({ - owner: context.repo.owner, - repo: "ProxmoxVE", - base: "main", - state: "closed", - sort: "updated", - direction: "desc", - per_page: 100, - }); - - const filteredPRs = pulls.filter(pr => - pr.merged_at && - new Date(pr.merged_at) > latestDateInChangelog && - !pr.labels.some(label => - ["invalid", "wontdo", process.env.AUTOMATED_PR_LABEL].includes(label.name.toLowerCase()) - ) - ); - - async function getScriptAuthors(pr) { - try { - const { data: files } = await github.rest.pulls.listFiles({ - owner: context.repo.owner, - repo: "ProxmoxVE", - pull_number: pr.number, - per_page: 100, - }); - const ctFile = files.find(file => file.status === "added" && /^ct\/[^/]+\.sh$/.test(file.filename)); - if (!ctFile) return ""; - - const { data: script } = await github.rest.repos.getContent({ - owner: context.repo.owner, - repo: "ProxmoxVE", - path: ctFile.filename, - ref: pr.merge_commit_sha, - }); - const header = Buffer.from(script.content, "base64").toString("utf-8") - .split("\n").slice(0, 20) - .find(line => /^#\s*Authors?:/i.test(line)); - if (!header) return ""; - - // "MickLesk (CanbiZ)" puts the handle first, "SlaviΕ‘a AreΕΎina (tremor021)" in the parentheses - const candidates = header.replace(/^#\s*Authors?:/i, "").split("|").map(part => { - part = part.trim().replace(/^[A-Za-z-]+:\s*/, ""); - const match = part.match(/^([^(]*)\(([^)]*)\)/); - if (!match) return part; - const words = match[1].trim().split(/\s+/).filter(Boolean); - return words.length === 1 ? words[0] : match[2].trim(); - }); - - // A display name used alone in a header; the GitHub account of that name is someone else - const authorAliases = { canbiz: "MickLesk" }; - const logins = []; - for (let candidate of candidates) { - if (!/^[A-Za-z0-9-]+$/.test(candidate)) continue; - candidate = authorAliases[candidate.toLowerCase()] ?? candidate; - try { - const { data: user } = await github.rest.users.getByUsername({ username: candidate }); - if (user.type === "User" && !logins.includes(user.login)) logins.push(user.login); - } catch (error) { - console.log(`No GitHub user ${candidate} (${ctFile.filename}): ${error}`); - } - } - return logins.map(login => `[@${login}](https://github.com/${login})`).join(", "); - } catch (error) { - console.error(`Could not read the author of #${pr.number}: ${error}`); - return ""; - } - } - - for (const pr of filteredPRs) { - const prLabels = pr.labels.map(label => label.name.toLowerCase()); - const scriptAuthors = prLabels.includes("new script") ? await getScriptAuthors(pr) : ""; - if (scriptAuthors) { - prNote = `- ${pr.title} ${scriptAuthors} ([#${pr.number}](${pr.html_url}))`; - } else if (pr.user.login.includes("push-app-to-main[bot]")) { - - const scriptName = pr.title; - try { - const { data: relatedIssues } = await github.rest.issues.listForRepo({ - owner: context.repo.owner, - repo: "DevScripts", - state: "all", - labels: ["Started Migration To ProxmoxVE"], - per_page: 100, - }); - - const matchingIssue = relatedIssues.find(issue => - issue.title.trim().toLowerCase() === scriptName.trim().toLowerCase() - ); - - if (matchingIssue) { - const issueAuthor = matchingIssue.user.login; - const issueAuthorUrl = `https://github.com/${issueAuthor}`; - prNote = `- ${pr.title} [@${issueAuthor}](${issueAuthorUrl}) ([#${pr.number}](${pr.html_url}))`; - } - else { - prNote = `- ${pr.title} ([#${pr.number}](${pr.html_url}))`; - } - } catch (error) { - console.error(`Error fetching related issues: ${error}`); - prNote = `- ${pr.title} ([#${pr.number}](${pr.html_url}))`; - } - }else{ - prNote = `- ${pr.title} [@${pr.user.login}](https://github.com/${pr.user.login}) ([#${pr.number}](${pr.html_url}))`; - } - - - if (prLabels.includes("new script")) { - const newScriptCategory = categorizedPRs.find(category => - category.title === "New Scripts" || category.labels.includes("new script")); - if (newScriptCategory) { - newScriptCategory.notes.push(prNote); - } - } else { - - let categorized = false; - const priorityCategories = categorizedPRs.slice(); - - // Priority order for content-type labels (highest priority first) - const subCategoryPriority = ["breaking change", "bugfix", "feature", "refactor"]; - - for (const category of priorityCategories) { - if (categorized) break; - if (category.labels.some(label => prLabels.includes(label))) { - if (category.subCategories && category.subCategories.length > 0) { - // Find subcategory by priority order instead of first match - let subCategory = null; - for (const priorityLabel of subCategoryPriority) { - if (prLabels.includes(priorityLabel)) { - subCategory = category.subCategories.find(sub => - sub.labels.includes(priorityLabel) - ); - if (subCategory) break; - } - } - - // Fallback: check for any other subcategory match (api, github, json, etc.) - if (!subCategory) { - subCategory = category.subCategories.find(sub => - sub.labels.some(label => prLabels.includes(label)) - ); - } - - if (subCategory) { - subCategory.notes.push(prNote); - } else { - category.notes.push(prNote); - } - } else { - category.notes.push(prNote); - } - categorized = true; - } - } - - // Fallback: Add to Uncategorized if no category matched - if (!categorized) { - const uncategorized = categorizedPRs.find(category => - category.title.includes("Uncategorized") || category.labels.includes("needs triage")); - if (uncategorized) { - uncategorized.notes.push(prNote); - } - } - } - - } - - // ── Pull requests from other repositories ─────────────────────── - const externalRepos = [ - { repo: "core", category: "πŸ’Ύ Core", prefix: "core" }, - { repo: "services", category: "πŸ›°οΈ Services", prefix: "services" }, - { repo: "ProxmoxVE-Frontend", category: "🌐 Website", prefix: "website" }, - ]; - const externalLabelAliases = { - bug: "bugfix", - bugfix: "bugfix", - enhancement: "feature", - feature: "feature", - refactor: "refactor", - "breaking change": "breaking change", - }; - const externalPriority = ["breaking change", "bugfix", "feature", "refactor"]; - - for (const { repo, category: categoryTitle, prefix } of externalRepos) { - try { - const { data: externalPulls } = await github.rest.pulls.list({ - owner: context.repo.owner, - repo, - base: "main", - state: "closed", - sort: "updated", - direction: "desc", - per_page: 100, - }); - - const category = categorizedPRs.find(c => c.title === categoryTitle); - - for (const pr of externalPulls) { - if (!pr.merged_at) continue; - if (new Date(pr.merged_at) <= latestDateInChangelog) continue; - - const rawLabels = pr.labels.map(label => label.name.toLowerCase()); - if (rawLabels.some(l => ["invalid", "wontdo", "wontfix", "duplicate", process.env.AUTOMATED_PR_LABEL].includes(l))) continue; - - if (!category) { - console.log(`No ${categoryTitle} category configured; skipping ${prefix}#${pr.number}`); - continue; - } - - // core#N rather than #N: a bare #N links to a pull request in this repository. - const note = `- ${pr.title} [@${pr.user.login}](https://github.com/${pr.user.login}) ([${prefix}#${pr.number}](${pr.html_url}))`; - - const mapped = rawLabels.map(l => externalLabelAliases[l]).filter(Boolean); - let placed = false; - if (category.subCategories && category.subCategories.length > 0) { - for (const priorityLabel of externalPriority) { - if (!mapped.includes(priorityLabel)) continue; - const subCategory = category.subCategories.find(sub => - sub.labels.includes(priorityLabel)); - if (subCategory) { - subCategory.notes.push(note); - placed = true; - break; - } - } - } - if (!placed) category.notes.push(note); - } - } catch (error) { - console.error(`Could not read ${repo} pull requests: ${error}`); - } - } - - return categorizedPRs; - } - - return await main(); - - - name: Update CHANGELOG.md - uses: actions/github-script@v9 - with: - script: | - const fs = require('fs').promises; - const path = require('path'); - - const today = process.env.TODAY; - const latestDateInChangelog = process.env.LATEST_DATE; - const changelogPath = path.resolve('CHANGELOG.md'); - const categorizedPRs = ${{ steps.get-categorized-prs.outputs.result }}; - - console.log(JSON.stringify(categorizedPRs, null, 2)); - - - let newReleaseNotes = `## ${today}\n\n`; - for (const { title, notes, subCategories } of categorizedPRs) { - const hasSubcategories = subCategories && subCategories.length > 0; - const hasMainNotes = notes.length > 0; - const hasSubNotes = hasSubcategories && subCategories.some(sub => sub.notes && sub.notes.length > 0); - - if (hasMainNotes || hasSubNotes) { - newReleaseNotes += `### ${title}\n\n`; - } - - if (hasMainNotes) { - newReleaseNotes += ` ${notes.join("\n")}\n\n`; - } - if (hasSubcategories) { - for (const { title: subTitle, notes: subNotes } of subCategories) { - if (subNotes && subNotes.length > 0) { - newReleaseNotes += ` - #### ${subTitle}\n\n`; - newReleaseNotes += ` ${subNotes.join("\n ")}\n\n`; - } - } - } - } - const changelogContent = await fs.readFile(changelogPath, 'utf-8'); - const changelogIncludesTodaysReleaseNotes = changelogContent.includes(`\n## ${today}`); - - const regex = changelogIncludesTodaysReleaseNotes - ? new RegExp(`## ${today}.*(?=## ${latestDateInChangelog})`, "gs") - : new RegExp(`(?=## ${latestDateInChangelog})`, "gs"); - - const newChangelogContent = changelogContent.replace(regex, newReleaseNotes); - await fs.writeFile(changelogPath, newChangelogContent); - - - name: Check for changes - id: verify-diff - run: | - git diff --quiet . || echo "changed=true" >> $GITHUB_ENV - - - name: Commit and push changes - if: env.changed == 'true' - run: | - git config --global user.name "github-actions[bot]" - git config --global user.email "github-actions[bot]@users.noreply.github.com" - git add CHANGELOG.md - git commit -m "Update CHANGELOG.md" - git checkout -b $BRANCH_NAME || git checkout $BRANCH_NAME - git push origin $BRANCH_NAME --force - echo "HEAD_SHA=$(git rev-parse HEAD)" >> "$GITHUB_ENV" - - - name: Create pull request if not exists - if: env.changed == 'true' - env: - GH_TOKEN: ${{ steps.generate-token.outputs.token }} - run: | - PR_EXISTS=$(gh pr list --head "${BRANCH_NAME}" --state open --json number,isCrossRepository --jq '[.[] | select(.isCrossRepository == false)][0].number // empty') - if [ -z "$PR_EXISTS" ]; then - gh pr create --title "[Github Action] Update CHANGELOG.md" \ - --body "This PR is auto-generated by a Github Action to update the CHANGELOG.md file." \ - --head $BRANCH_NAME \ - --base main \ - --label "$AUTOMATED_PR_LABEL" - fi - - - name: Approve pull request - if: env.changed == 'true' - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - PR_NUMBER=$(gh pr list --head "${BRANCH_NAME}" --state open --json number,isCrossRepository --jq '[.[] | select(.isCrossRepository == false)][0].number // empty') - if [ -n "$PR_NUMBER" ]; then - gh pr review "$PR_NUMBER" --approve - fi - - - name: Approve pull request and merge - if: env.changed == 'true' - env: - GH_TOKEN: ${{ steps.generate-token-merge.outputs.token }} - run: | - git config --global user.name "github-actions-automege[bot]" - git config --global user.email "github-actions-automege[bot]@users.noreply.github.com" - PR_NUMBER=$(gh pr list --head "${BRANCH_NAME}" --state open --json number,isCrossRepository --jq '[.[] | select(.isCrossRepository == false)][0].number // empty') - if [ -n "$PR_NUMBER" ]; then - gh pr review "$PR_NUMBER" --approve - gh pr merge "$PR_NUMBER" --squash --admin --match-head-commit "$HEAD_SHA" - fi diff --git a/.github/workflows/check-node-versions.yml b/.github/workflows/check-node-versions.yml index 7204207ef..46ad5057e 100644 --- a/.github/workflows/check-node-versions.yml +++ b/.github/workflows/check-node-versions.yml @@ -579,7 +579,7 @@ jobs: # "opened" β€” a label added a moment later can arrive too late. # # "keep-open" rather than "automated pr" for that exemption: both - # skip the template check, but changelog-pr.yml drops every PR + # skip the template check, but daily-release.yml drops every PR # carrying "automated pr" (it marks its own PR with it), so that # label would keep these bumps out of the changelog entirely. # "update script" and "bugfix" place them under Updated Scripts β†’ diff --git a/.github/workflows/check-php-versions.yml b/.github/workflows/check-php-versions.yml index 5c1955110..5f4d1bb43 100644 --- a/.github/workflows/check-php-versions.yml +++ b/.github/workflows/check-php-versions.yml @@ -555,7 +555,7 @@ jobs: # Labels go on at creation: they exempt the PR from the template check, # which runs on "opened". "keep-open" rather than "automated pr", which - # changelog-pr.yml drops. + # daily-release.yml drops. if url=$(gh pr create \ --title "${slug}: bump PHP from ${our} to ${upstream}" \ --body "$body" \ diff --git a/.github/workflows/check-python-versions.yml b/.github/workflows/check-python-versions.yml index 37753f80c..f5138d82e 100644 --- a/.github/workflows/check-python-versions.yml +++ b/.github/workflows/check-python-versions.yml @@ -524,7 +524,7 @@ jobs: # Labels go on at creation: they exempt the PR from the template check, # which runs on "opened". "keep-open" rather than "automated pr", which - # changelog-pr.yml drops. + # daily-release.yml drops. if url=$(gh pr create \ --title "${slug}: bump Python from ${our} to ${upstream}" \ --body "$body" \ diff --git a/.github/workflows/daily-release.yml b/.github/workflows/daily-release.yml new file mode 100644 index 000000000..194e89f5f --- /dev/null +++ b/.github/workflows/daily-release.yml @@ -0,0 +1,792 @@ +name: Daily Changelog and Release + +# Once a day, shortly after midnight UTC: collect the pull requests merged +# during the previous day, add them to CHANGELOG.md through one pull request, +# and publish the same notes as a GitHub release. On Sundays the entries older +# than 30 days are archived into .github/changelogs/ in the same pull request. + +on: + schedule: + - cron: '1 0 * * *' # Runs daily at 00:01 UTC + workflow_dispatch: + inputs: + date: + description: "Day to release (YYYY-MM-DD, UTC). Defaults to yesterday." + required: false + type: string + archive: + description: "Archive old changelog entries even if it is not Sunday" + required: false + type: boolean + default: false + +concurrency: + group: daily-release + cancel-in-progress: false + +jobs: + daily-release: + if: github.repository == 'community-scripts/ProxmoxVE' + runs-on: ubuntu-latest + env: + CONFIG_PATH: .github/changelog-pr-config.json + BRANCH_NAME: github-action-update-changelog + AUTOMATED_PR_LABEL: "automated pr" + permissions: + contents: write + pull-requests: write + steps: + - name: Generate a token + id: generate-token + uses: actions/create-github-app-token@v3 + with: + app-id: ${{ vars.GHAPP_PR_ID }} + private-key: ${{ secrets.GHAPP_PR_PRIVATE_KEY }} + + - name: Generate a token for PR approval and merge + id: generate-token-merge + uses: actions/create-github-app-token@v3 + with: + app-id: ${{ vars.GHAPP_MERGEBOT_ID }} + private-key: ${{ secrets.GHAPP_MERGEBOT_PRIVATE_KEY }} + + - name: Checkout code + uses: actions/checkout@v7 + with: + fetch-depth: 0 + + - name: Resolve the day to release + env: + INPUT_DATE: ${{ inputs.date }} + INPUT_ARCHIVE: ${{ inputs.archive }} + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + if [[ -n "$INPUT_DATE" ]]; then + RELEASE_DATE=$(date -u -d "$INPUT_DATE" +%Y-%m-%d) || exit 1 + else + RELEASE_DATE=$(date -u -d yesterday +%Y-%m-%d) + fi + echo "RELEASE_DATE=$RELEASE_DATE" >> $GITHUB_ENV + echo "DAY_START=${RELEASE_DATE}T00:00:00Z" >> $GITHUB_ENV + echo "DAY_END=$(date -u -d "$RELEASE_DATE +1 day" +%Y-%m-%d)T00:00:00Z" >> $GITHUB_ENV + + if [[ "$(date -u +%u)" == "7" || "$INPUT_ARCHIVE" == "true" ]]; then + echo "RUN_ARCHIVE=true" >> $GITHUB_ENV + fi + + if gh release view "$RELEASE_DATE" >/dev/null 2>&1; then + echo "RELEASE_EXISTS=true" >> $GITHUB_ENV + fi + + - name: Get categorized pull requests + id: get-categorized-prs + uses: actions/github-script@v9 + with: + script: | + async function main() { + const fs = require('fs').promises; + const path = require('path'); + + const configPath = path.resolve(process.env.CONFIG_PATH); + const fileContent = await fs.readFile(configPath, 'utf-8'); + const changelogConfig = JSON.parse(fileContent); + + const categorizedPRs = changelogConfig.map(obj => ({ + ...obj, + notes: [], + subCategories: obj.subCategories ?? ( + obj.labels.includes("update script") ? [ + { title: "🐞 Bug Fixes", labels: ["bugfix"], notes: [] }, + { title: "✨ New Features", labels: ["feature"], notes: [] }, + { title: "πŸ’₯ Breaking Changes", labels: ["breaking change"], notes: [] }, + { title: "πŸ”§ Refactor", labels: ["refactor"], notes: [] }, + ] : + obj.labels.includes("maintenance") ? [ + { title: "🐞 Bug Fixes", labels: ["bugfix"], notes: [] }, + { title: "✨ New Features", labels: ["feature"], notes: [] }, + { title: "πŸ’₯ Breaking Changes", labels: ["breaking change"], notes: [] }, + { title: "πŸ“‘ API", labels: ["api"], notes: [] }, + { title: "Github", labels: ["github"], notes: [] }, + { title: "πŸ“ Documentation", labels: ["maintenance"], notes: [] }, + { title: "πŸ”§ Refactor", labels: ["refactor"], notes: [] } + ] : + obj.labels.includes("website") ? [ + { title: "🐞 Bug Fixes", labels: ["bugfix"], notes: [] }, + { title: "✨ New Features", labels: ["feature"], notes: [] }, + { title: "πŸ’₯ Breaking Changes", labels: ["breaking change"], notes: [] }, + { title: "Script Information", labels: ["json"], notes: [] } + ] : [] + ) + })); + + const dayStart = new Date(process.env.DAY_START); + const dayEnd = new Date(process.env.DAY_END); + + // Closed pull requests come newest-update first, and a pull request merged + // during the day was updated at or after its merge. So once a page ends with + // one last updated before the day began, nothing further can belong to it. + async function listMergedPRs(repo) { + const merged = []; + for (let page = 1; ; page++) { + const { data } = await github.rest.pulls.list({ + owner: context.repo.owner, + repo, + base: "main", + state: "closed", + sort: "updated", + direction: "desc", + per_page: 100, + page, + }); + for (const pr of data) { + if (!pr.merged_at) continue; + const mergedAt = new Date(pr.merged_at); + if (mergedAt >= dayStart && mergedAt < dayEnd) merged.push(pr); + } + if (data.length < 100 || new Date(data[data.length - 1].updated_at) < dayStart) return merged; + } + } + + const filteredPRs = (await listMergedPRs("ProxmoxVE")).filter(pr => + !pr.labels.some(label => + ["invalid", "wontdo", process.env.AUTOMATED_PR_LABEL].includes(label.name.toLowerCase()) + ) + ); + + async function getScriptAuthors(pr) { + try { + const { data: files } = await github.rest.pulls.listFiles({ + owner: context.repo.owner, + repo: "ProxmoxVE", + pull_number: pr.number, + per_page: 100, + }); + const ctFile = files.find(file => file.status === "added" && /^ct\/[^/]+\.sh$/.test(file.filename)); + if (!ctFile) return ""; + + const { data: script } = await github.rest.repos.getContent({ + owner: context.repo.owner, + repo: "ProxmoxVE", + path: ctFile.filename, + ref: pr.merge_commit_sha, + }); + const header = Buffer.from(script.content, "base64").toString("utf-8") + .split("\n").slice(0, 20) + .find(line => /^#\s*Authors?:/i.test(line)); + if (!header) return ""; + + // "MickLesk (CanbiZ)" puts the handle first, "SlaviΕ‘a AreΕΎina (tremor021)" in the parentheses + const candidates = header.replace(/^#\s*Authors?:/i, "").split("|").map(part => { + part = part.trim().replace(/^[A-Za-z-]+:\s*/, ""); + const match = part.match(/^([^(]*)\(([^)]*)\)/); + if (!match) return part; + const words = match[1].trim().split(/\s+/).filter(Boolean); + return words.length === 1 ? words[0] : match[2].trim(); + }); + + // A display name used alone in a header; the GitHub account of that name is someone else + const authorAliases = { canbiz: "MickLesk" }; + const logins = []; + for (let candidate of candidates) { + if (!/^[A-Za-z0-9-]+$/.test(candidate)) continue; + candidate = authorAliases[candidate.toLowerCase()] ?? candidate; + try { + const { data: user } = await github.rest.users.getByUsername({ username: candidate }); + if (user.type === "User" && !logins.includes(user.login)) logins.push(user.login); + } catch (error) { + console.log(`No GitHub user ${candidate} (${ctFile.filename}): ${error}`); + } + } + return logins.map(login => `[@${login}](https://github.com/${login})`).join(", "); + } catch (error) { + console.error(`Could not read the author of #${pr.number}: ${error}`); + return ""; + } + } + + for (const pr of filteredPRs) { + const prLabels = pr.labels.map(label => label.name.toLowerCase()); + const scriptAuthors = prLabels.includes("new script") ? await getScriptAuthors(pr) : ""; + if (scriptAuthors) { + prNote = `- ${pr.title} ${scriptAuthors} ([#${pr.number}](${pr.html_url}))`; + } else if (pr.user.login.includes("push-app-to-main[bot]")) { + + const scriptName = pr.title; + try { + const { data: relatedIssues } = await github.rest.issues.listForRepo({ + owner: context.repo.owner, + repo: "DevScripts", + state: "all", + labels: ["Started Migration To ProxmoxVE"], + per_page: 100, + }); + + const matchingIssue = relatedIssues.find(issue => + issue.title.trim().toLowerCase() === scriptName.trim().toLowerCase() + ); + + if (matchingIssue) { + const issueAuthor = matchingIssue.user.login; + const issueAuthorUrl = `https://github.com/${issueAuthor}`; + prNote = `- ${pr.title} [@${issueAuthor}](${issueAuthorUrl}) ([#${pr.number}](${pr.html_url}))`; + } + else { + prNote = `- ${pr.title} ([#${pr.number}](${pr.html_url}))`; + } + } catch (error) { + console.error(`Error fetching related issues: ${error}`); + prNote = `- ${pr.title} ([#${pr.number}](${pr.html_url}))`; + } + }else{ + prNote = `- ${pr.title} [@${pr.user.login}](https://github.com/${pr.user.login}) ([#${pr.number}](${pr.html_url}))`; + } + + + if (prLabels.includes("new script")) { + const newScriptCategory = categorizedPRs.find(category => + category.title === "New Scripts" || category.labels.includes("new script")); + if (newScriptCategory) { + newScriptCategory.notes.push(prNote); + } + } else { + + let categorized = false; + const priorityCategories = categorizedPRs.slice(); + + // Priority order for content-type labels (highest priority first) + const subCategoryPriority = ["breaking change", "bugfix", "feature", "refactor"]; + + for (const category of priorityCategories) { + if (categorized) break; + if (category.labels.some(label => prLabels.includes(label))) { + if (category.subCategories && category.subCategories.length > 0) { + // Find subcategory by priority order instead of first match + let subCategory = null; + for (const priorityLabel of subCategoryPriority) { + if (prLabels.includes(priorityLabel)) { + subCategory = category.subCategories.find(sub => + sub.labels.includes(priorityLabel) + ); + if (subCategory) break; + } + } + + // Fallback: check for any other subcategory match (api, github, json, etc.) + if (!subCategory) { + subCategory = category.subCategories.find(sub => + sub.labels.some(label => prLabels.includes(label)) + ); + } + + if (subCategory) { + subCategory.notes.push(prNote); + } else { + category.notes.push(prNote); + } + } else { + category.notes.push(prNote); + } + categorized = true; + } + } + + // Fallback: Add to Uncategorized if no category matched + if (!categorized) { + const uncategorized = categorizedPRs.find(category => + category.title.includes("Uncategorized") || category.labels.includes("needs triage")); + if (uncategorized) { + uncategorized.notes.push(prNote); + } + } + } + + } + + // ── Pull requests from other repositories ─────────────────────── + const externalRepos = [ + { repo: "core", category: "πŸ’Ύ Core", prefix: "core" }, + { repo: "services", category: "πŸ›°οΈ Services", prefix: "services" }, + { repo: "ProxmoxVE-Frontend", category: "🌐 Website", prefix: "website" }, + ]; + const externalLabelAliases = { + bug: "bugfix", + bugfix: "bugfix", + enhancement: "feature", + feature: "feature", + refactor: "refactor", + "breaking change": "breaking change", + }; + const externalPriority = ["breaking change", "bugfix", "feature", "refactor"]; + + for (const { repo, category: categoryTitle, prefix } of externalRepos) { + try { + const externalPulls = await listMergedPRs(repo); + + const category = categorizedPRs.find(c => c.title === categoryTitle); + + for (const pr of externalPulls) { + const rawLabels = pr.labels.map(label => label.name.toLowerCase()); + if (rawLabels.some(l => ["invalid", "wontdo", "wontfix", "duplicate", process.env.AUTOMATED_PR_LABEL].includes(l))) continue; + + if (!category) { + console.log(`No ${categoryTitle} category configured; skipping ${prefix}#${pr.number}`); + continue; + } + + // core#N rather than #N: a bare #N links to a pull request in this repository. + const note = `- ${pr.title} [@${pr.user.login}](https://github.com/${pr.user.login}) ([${prefix}#${pr.number}](${pr.html_url}))`; + + const mapped = rawLabels.map(l => externalLabelAliases[l]).filter(Boolean); + let placed = false; + if (category.subCategories && category.subCategories.length > 0) { + for (const priorityLabel of externalPriority) { + if (!mapped.includes(priorityLabel)) continue; + const subCategory = category.subCategories.find(sub => + sub.labels.includes(priorityLabel)); + if (subCategory) { + subCategory.notes.push(note); + placed = true; + break; + } + } + } + if (!placed) category.notes.push(note); + } + } catch (error) { + console.error(`Could not read ${repo} pull requests: ${error}`); + } + } + + return categorizedPRs; + } + + return await main(); + + - name: Build the changelog entry + id: notes + uses: actions/github-script@v9 + with: + script: | + const fs = require('fs').promises; + const path = require('path'); + + const releaseDate = process.env.RELEASE_DATE; + const changelogPath = path.resolve('CHANGELOG.md'); + const categorizedPRs = ${{ steps.get-categorized-prs.outputs.result }}; + + console.log(JSON.stringify(categorizedPRs, null, 2)); + + let hasNotes = false; + let newReleaseNotes = `## ${releaseDate}\n\n`; + for (const { title, notes, subCategories } of categorizedPRs) { + const hasSubcategories = subCategories && subCategories.length > 0; + const hasMainNotes = notes.length > 0; + const hasSubNotes = hasSubcategories && subCategories.some(sub => sub.notes && sub.notes.length > 0); + + if (hasMainNotes || hasSubNotes) { + hasNotes = true; + newReleaseNotes += `### ${title}\n\n`; + } + + if (hasMainNotes) { + newReleaseNotes += ` ${notes.join("\n")}\n\n`; + } + if (hasSubcategories) { + for (const { title: subTitle, notes: subNotes } of subCategories) { + if (subNotes && subNotes.length > 0) { + newReleaseNotes += ` - #### ${subTitle}\n\n`; + newReleaseNotes += ` ${subNotes.join("\n ")}\n\n`; + } + } + } + } + + if (!hasNotes) { + console.log(`No pull requests were merged on ${releaseDate}.`); + core.setOutput('empty', 'true'); + return; + } + core.setOutput('empty', 'false'); + await fs.writeFile(path.join(process.env.RUNNER_TEMP, 'release_section.md'), newReleaseNotes.trimEnd() + '\n'); + + const changelogContent = await fs.readFile(changelogPath, 'utf-8'); + if (new RegExp(`^## ${releaseDate}$`, 'm').test(changelogContent)) { + console.log(`CHANGELOG.md already has an entry for ${releaseDate}.`); + return; + } + + // Newest first: go in above the first entry that is older than this one + let insertAt = changelogContent.length; + for (const match of changelogContent.matchAll(/^## (\d{4}-\d{2}-\d{2})/gm)) { + if (match[1] < releaseDate) { + insertAt = match.index; + break; + } + } + const updated = insertAt === changelogContent.length + ? `${changelogContent.trimEnd()}\n\n${newReleaseNotes}` + : changelogContent.slice(0, insertAt) + newReleaseNotes + changelogContent.slice(insertAt); + await fs.writeFile(changelogPath, updated); + + - name: Create GitHub release + if: steps.notes.outputs.empty != 'true' && env.RELEASE_EXISTS != 'true' + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + cd "$RUNNER_TEMP" + + # GitHub fills a release's Contributors only from bare @login mentions + sed -E 's#\[@([A-Za-z0-9-]+)\]\(https://github\.com/\1\)#@\1#g' release_section.md > release_full.md + + # Keep whole lines up to 120000 characters (GitHub allows 125000) + export LC_ALL=C.UTF-8 + SIZE=0 + TRUNCATED=false + while IFS= read -r line || [ -n "$line" ]; do + SIZE=$((SIZE + ${#line} + 1)) + if [ "$SIZE" -gt 120000 ]; then + TRUNCATED=true + break + fi + printf '%s\n' "$line" + done < release_full.md > release_notes.md + if [ "$TRUNCATED" = true ]; then + printf '\nCut to fit the release size limit. The full list is in [CHANGELOG.md](https://github.com/community-scripts/ProxmoxVE/blob/main/CHANGELOG.md).\n' >> release_notes.md + fi + + PREVIOUS=$(gh release view --json tagName --jq .tagName 2>/dev/null || true) + if [ -n "$PREVIOUS" ]; then + printf '\n**Full Changelog**: https://github.com/community-scripts/ProxmoxVE/compare/%s...%s\n' "$PREVIOUS" "$RELEASE_DATE" >> release_notes.md + fi + + cat release_notes.md + gh release create "$RELEASE_DATE" -t "$RELEASE_DATE" -F release_notes.md + + - name: Archive old changelog entries + if: env.RUN_ARCHIVE == 'true' + uses: actions/github-script@v9 + with: + script: | + const fs = require('fs').promises; + const path = require('path'); + + const KEEP_DAYS = 30; + const ARCHIVE_PATH = '.github/changelogs'; + const CHANGELOG_PATH = 'CHANGELOG.md'; + + // Calculate cutoff date + const cutoffDate = new Date(); + cutoffDate.setDate(cutoffDate.getDate() - KEEP_DAYS); + cutoffDate.setHours(0, 0, 0, 0); + + console.log(`Cutoff date: ${cutoffDate.toISOString().split('T')[0]}`); + + // Read changelog and normalize line endings + let content = await fs.readFile(CHANGELOG_PATH, 'utf-8'); + content = content.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); + const lines = content.split('\n'); + + // Parse entries + const datePattern = /^## (\d{4})-(\d{2})-(\d{2})$/; + let header = []; + let recentEntries = []; + let archiveData = {}; + let currentDate = null; + let currentContent = []; + let inHeader = true; + let inOldHistory = false; + let historyDetailsDepth = 0; + + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + const match = line.match(datePattern); + + // Detect the start of History section:
followed by line with πŸ“œ History + if (inHeader && !inOldHistory && line.trim() === '
') { + // Look ahead to see if this is the History section + const nextLine = lines[i + 1] || ''; + if (nextLine.includes('πŸ“œ History')) { + inOldHistory = true; + historyDetailsDepth = 1; + continue; + } + } + + // Track nested details tags to find the end of History section + if (inOldHistory) { + if (line.trim() === '
') { + historyDetailsDepth++; + } + if (line.trim() === '
') { + historyDetailsDepth--; + if (historyDetailsDepth === 0) { + // We've closed the main History details tag + inOldHistory = false; + } + } + continue; + } + + if (match) { + inHeader = false; + + // Save previous entry + if (currentDate && currentContent.length > 0) { + const entryText = currentContent.join('\n').trim(); + const dateObj = new Date(`${currentDate}T00:00:00Z`); + + // Always add to archive (by month) + const year = currentDate.substring(0, 4); + const month = currentDate.substring(5, 7); + + if (!archiveData[year]) archiveData[year] = {}; + if (!archiveData[year][month]) archiveData[year][month] = []; + + archiveData[year][month].push(`## ${currentDate}\n\n${entryText}`); + + // Also add to recent entries if within cutoff + if (dateObj >= cutoffDate) { + recentEntries.push(`## ${currentDate}\n\n${entryText}`); + } + } + + currentDate = `${match[1]}-${match[2]}-${match[3]}`; + currentContent = []; + } else if (inHeader) { + header.push(line); + } else if (currentDate) { + currentContent.push(line); + } + } + + // Don't forget the last entry + if (currentDate && currentContent.length > 0) { + const entryText = currentContent.join('\n').trim(); + const dateObj = new Date(`${currentDate}T00:00:00Z`); + + // Always add to archive (by month) + const year = currentDate.substring(0, 4); + const month = currentDate.substring(5, 7); + + if (!archiveData[year]) archiveData[year] = {}; + if (!archiveData[year][month]) archiveData[year][month] = []; + + archiveData[year][month].push(`## ${currentDate}\n\n${entryText}`); + + // Also add to recent entries if within cutoff + if (dateObj >= cutoffDate) { + recentEntries.push(`## ${currentDate}\n\n${entryText}`); + } + } + + console.log(`Recent entries: ${recentEntries.length}`); + console.log(`Years to archive: ${Object.keys(archiveData).length}`); + + // Month names in English + const monthNames = { + '01': 'January', '02': 'February', '03': 'March', '04': 'April', + '05': 'May', '06': 'June', '07': 'July', '08': 'August', + '09': 'September', '10': 'October', '11': 'November', '12': 'December' + }; + + // Create/update archive files + for (const year of Object.keys(archiveData).sort().reverse()) { + const yearPath = path.join(ARCHIVE_PATH, year); + + try { + await fs.mkdir(yearPath, { recursive: true }); + } catch (e) { + // Directory exists + } + + for (const month of Object.keys(archiveData[year]).sort().reverse()) { + const monthPath = path.join(yearPath, `${month}.md`); + + // Read existing content if exists + let existingContent = ''; + try { + existingContent = await fs.readFile(monthPath, 'utf-8'); + // Normalize line endings to prevent regex issues + existingContent = existingContent.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); + } catch (e) { + // File doesn't exist + } + + // Parse existing entries into a Map (date -> content) for deduplication + const allEntries = new Map(); + + // Helper function to parse entries from content + const parseEntries = (content) => { + const entries = new Map(); + const parts = content.split(/(?=^## \d{4}-\d{2}-\d{2}$)/m); + for (const part of parts) { + const trimmed = part.trim(); + if (!trimmed) continue; + const dateMatch = trimmed.match(/^## (\d{4}-\d{2}-\d{2})/); + if (dateMatch) { + entries.set(dateMatch[1], trimmed); + } + } + return entries; + }; + + // Parse existing content + if (existingContent) { + const existingEntries = parseEntries(existingContent); + for (const [date, content] of existingEntries) { + allEntries.set(date, content); + } + } + + // Add new entries (existing entries take precedence to avoid overwriting) + let addedCount = 0; + for (const entry of archiveData[year][month]) { + const dateMatch = entry.match(/^## (\d{4}-\d{2}-\d{2})/); + if (dateMatch && !allEntries.has(dateMatch[1])) { + allEntries.set(dateMatch[1], entry.trim()); + addedCount++; + } + } + + // Sort entries by date (newest first) and write + const sortedDates = [...allEntries.keys()].sort().reverse(); + const sortedContent = sortedDates.map(date => allEntries.get(date)).join('\n\n'); + + if (addedCount > 0 || !existingContent) { + await fs.writeFile(monthPath, sortedContent + '\n', 'utf-8'); + console.log(`Updated: ${monthPath} (${allEntries.size} total entries, +${addedCount} new)`); + } + } + } + + // Build history section + let historySection = []; + historySection.push(''); + historySection.push('
'); + historySection.push('

πŸ“œ History

'); + historySection.push(''); + + // Get all years from archive directory + let allYears = []; + try { + const archiveDir = await fs.readdir(ARCHIVE_PATH); + allYears = archiveDir.filter(f => /^\d{4}$/.test(f)).sort().reverse(); + } catch (e) { + allYears = Object.keys(archiveData).sort().reverse(); + } + + for (const year of allYears) { + historySection.push(''); + historySection.push('
'); + historySection.push(`

${year}

`); + historySection.push(''); + + // Get months for this year + let months = []; + try { + const yearDir = await fs.readdir(path.join(ARCHIVE_PATH, year)); + months = yearDir + .filter(f => f.endsWith('.md')) + .map(f => f.replace('.md', '')) + .sort() + .reverse(); + } catch (e) { + months = Object.keys(archiveData[year] || {}).sort().reverse(); + } + + for (const month of months) { + const monthName = monthNames[month] || month; + const monthPath = path.join(ARCHIVE_PATH, year, `${month}.md`); + + // Count entries in month file + let entryCount = 0; + try { + let monthContent = await fs.readFile(monthPath, 'utf-8'); + monthContent = monthContent.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); + entryCount = (monthContent.match(/^## \d{4}-\d{2}-\d{2}$/gm) || []).length; + } catch (e) { + entryCount = (archiveData[year]?.[month] || []).length; + } + + const relativePath = `.github/changelogs/${year}/${month}.md`; + historySection.push(''); + historySection.push('
'); + historySection.push(`

${monthName} (${entryCount} entries)

`); + historySection.push(''); + historySection.push(`[View ${monthName} ${year} Changelog](${relativePath})`); + historySection.push(''); + historySection.push('
'); + } + + historySection.push(''); + historySection.push('
'); + } + + historySection.push(''); + historySection.push('
'); + + // Build new CHANGELOG.md (History first, then recent entries) + const newChangelog = [ + ...header, + '', + historySection.join('\n'), + '', + recentEntries.join('\n\n') + ].join('\n'); + + await fs.writeFile(CHANGELOG_PATH, newChangelog, 'utf-8'); + console.log('CHANGELOG.md updated successfully'); + + - name: Check for changes + run: | + if [ -n "$(git status --porcelain CHANGELOG.md .github/changelogs)" ]; then + echo "changed=true" >> $GITHUB_ENV + fi + + - name: Commit and push changes + if: env.changed == 'true' + run: | + git config --global user.name "github-actions[bot]" + git config --global user.email "github-actions[bot]@users.noreply.github.com" + git add CHANGELOG.md .github/changelogs/ + git commit -m "Update CHANGELOG.md" + git checkout -b $BRANCH_NAME || git checkout $BRANCH_NAME + git push origin $BRANCH_NAME --force + echo "HEAD_SHA=$(git rev-parse HEAD)" >> "$GITHUB_ENV" + + - name: Create pull request if not exists + if: env.changed == 'true' + env: + GH_TOKEN: ${{ steps.generate-token.outputs.token }} + run: | + PR_EXISTS=$(gh pr list --head "${BRANCH_NAME}" --state open --json number,isCrossRepository --jq '[.[] | select(.isCrossRepository == false)][0].number // empty') + if [ -z "$PR_EXISTS" ]; then + gh pr create --title "[Github Action] Update CHANGELOG.md" \ + --body "This PR is auto-generated by a Github Action to update the CHANGELOG.md file." \ + --head $BRANCH_NAME \ + --base main \ + --label "$AUTOMATED_PR_LABEL" + fi + + - name: Approve pull request + if: env.changed == 'true' + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + PR_NUMBER=$(gh pr list --head "${BRANCH_NAME}" --state open --json number,isCrossRepository --jq '[.[] | select(.isCrossRepository == false)][0].number // empty') + if [ -n "$PR_NUMBER" ]; then + gh pr review "$PR_NUMBER" --approve + fi + + - name: Approve pull request and merge + if: env.changed == 'true' + env: + GH_TOKEN: ${{ steps.generate-token-merge.outputs.token }} + run: | + git config --global user.name "github-actions-automege[bot]" + git config --global user.email "github-actions-automege[bot]@users.noreply.github.com" + PR_NUMBER=$(gh pr list --head "${BRANCH_NAME}" --state open --json number,isCrossRepository --jq '[.[] | select(.isCrossRepository == false)][0].number // empty') + if [ -n "$PR_NUMBER" ]; then + gh pr review "$PR_NUMBER" --approve + gh pr merge "$PR_NUMBER" --squash --admin --match-head-commit "$HEAD_SHA" + fi diff --git a/.github/workflows/github-release.yml b/.github/workflows/github-release.yml deleted file mode 100644 index a381e0163..000000000 --- a/.github/workflows/github-release.yml +++ /dev/null @@ -1,69 +0,0 @@ -name: Create Daily Release - -on: - schedule: - - cron: '1 0 * * *' # Runs daily at 00:01 UTC - workflow_dispatch: - -jobs: - create-daily-release: - if: github.repository == 'community-scripts/ProxmoxVE' - runs-on: ubuntu-latest - permissions: - contents: write - steps: - - name: Checkout repository - uses: actions/checkout@v7 - - - name: Clean CHANGELOG (remove HTML header) - run: sed -n '/^## /,$p' CHANGELOG.md > changelog_cleaned.md - - - name: Extract relevant changelog section - id: extract - run: | - YESTERDAY=$(date -u --date="yesterday" +%Y-%m-%d) - echo "Checking for changes on: $YESTERDAY" - - # Extract the section from "## $YESTERDAY" until the next "## YYYY-MM-DD" - sed -n "/^## $YESTERDAY/,/^## [0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}/p" changelog_cleaned.md | head -n -1 > changelog_tmp_full.md - - # GitHub fills a release's Contributors only from bare @login mentions - sed -i -E 's#\[@([A-Za-z0-9-]+)\]\(https://github\.com/\1\)#@\1#g' changelog_tmp_full.md - - # Keep whole lines up to 120000 characters (GitHub allows 125000) - export LC_ALL=C.UTF-8 - SIZE=0 - TRUNCATED=false - while IFS= read -r line || [ -n "$line" ]; do - SIZE=$((SIZE + ${#line} + 1)) - if [ "$SIZE" -gt 120000 ]; then - TRUNCATED=true - break - fi - printf '%s\n' "$line" - done < changelog_tmp_full.md > changelog_tmp.md - if [ "$TRUNCATED" = true ]; then - printf '\nCut to fit the release size limit. The full list is in [CHANGELOG.md](https://github.com/community-scripts/ProxmoxVE/blob/main/CHANGELOG.md).\n' >> changelog_tmp.md - fi - - echo "=== Extracted Changelog ===" - cat changelog_tmp.md - echo "===========================" - - # Abort if no content was found - if [ ! -s changelog_tmp.md ]; then - echo "No changes found for $YESTERDAY, skipping release." - echo "skip=true" >> "$GITHUB_OUTPUT" - fi - - - name: Create GitHub release - if: steps.extract.outputs.skip != 'true' - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - YESTERDAY=$(date -u --date="yesterday" +%Y-%m-%d) - PREVIOUS=$(gh release view --json tagName --jq .tagName 2>/dev/null || true) - if [ -n "$PREVIOUS" ]; then - printf '\n**Full Changelog**: https://github.com/community-scripts/ProxmoxVE/compare/%s...%s\n' "$PREVIOUS" "$YESTERDAY" >> changelog_tmp.md - fi - gh release create "$YESTERDAY" -t "$YESTERDAY" -F changelog_tmp.md