Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
63 changes: 33 additions & 30 deletions .github/scripts/count-reward.ts
Original file line number Diff line number Diff line change
@@ -1,57 +1,60 @@
import { $, YAML } from "npm:zx";
import { $, YAML } from 'npm:zx'

import { Reward } from "./type.ts";
import { Reward } from './type.ts'

$.verbose = true;
$.verbose = true

const rawTags =
await $`git tag --list "reward-*" --format="%(refname:short) %(creatordate:short)"`;
await $`git tag --list "reward-*" --format="%(refname:short) %(creatordate:short)"`

const lastMonth = new Date();
lastMonth.setMonth(lastMonth.getMonth() - 1);
const lastMonthStr = lastMonth.toJSON().slice(0, 7);
const lastMonth = new Date()
lastMonth.setMonth(lastMonth.getMonth() - 1)
const lastMonthStr = lastMonth.toJSON().slice(0, 7)

const rewardTags = rawTags.stdout
.split("\n")
.split('\n')
.filter((line) => line.split(/\s+/)[1] >= lastMonthStr)
.map((line) => line.split(/\s+/)[0]);
.map((line) => line.split(/\s+/)[0])

let rawYAML = "";
let rawYAML = ''

for (const tag of rewardTags)
rawYAML += (await $`git tag -l --format="%(contents)" ${tag}`) + "\n";
rawYAML += (await $`git tag -l --format="%(contents)" ${tag}`) + '\n'

if (!rawYAML.trim())
throw new ReferenceError("No reward data is found for the last month.");
throw new ReferenceError('No reward data is found for the last month.')

const rewards = YAML.parse(rawYAML) as Reward[];
const rewards = YAML.parse(rawYAML) as Reward[]

const groupedRewards = Object.groupBy(rewards, ({ payee }) => payee);
const groupedRewards = Object.groupBy(rewards, ({ payee }) => payee)

const summaryList = Object.entries(groupedRewards).map(([payee, rewards]) => {
const reward = rewards!.reduce((acc, { currency, reward }) => {
acc[currency] ??= 0;
acc[currency] += reward;
return acc;
}, {} as Record<string, number>);
const reward = rewards!.reduce(
(acc, { currency, reward }) => {
acc[currency] ??= 0
acc[currency] += reward
return acc
},
{} as Record<string, number>,
)

return {
payee,
reward,
accounts: rewards!.map(({ payee: _, ...account }) => account),
};
});
accounts: rewards!.map(({ payee: _payee, ...account }) => account),
}
})

const summaryText = YAML.stringify(summaryList);
const summaryText = YAML.stringify(summaryList)

console.log(summaryText);
console.log(summaryText)

const tagName = `statistic-${new Date().toJSON().slice(0, 7)}`;
const tagName = `statistic-${new Date().toJSON().slice(0, 7)}`

await $`git config user.name "github-actions[bot]"`;
await $`git config user.email "github-actions[bot]@users.noreply.github.com"`;
await $`git config user.name "github-actions[bot]"`
await $`git config user.email "github-actions[bot]@users.noreply.github.com"`

await $`git tag -a ${tagName} $(git rev-parse HEAD) -m ${summaryText}`;
await $`git push origin --tags --no-verify`;
await $`git tag -a ${tagName} $(git rev-parse HEAD) -m ${summaryText}`
await $`git push origin --tags --no-verify`

await $`gh release create ${tagName} --notes ${summaryText}`;
await $`gh release create ${tagName} --notes ${summaryText}`
78 changes: 39 additions & 39 deletions .github/scripts/share-reward.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { components } from "npm:@octokit/openapi-types";
import { $, argv, YAML } from "npm:zx";
import { components } from 'npm:@octokit/openapi-types'
import { $, argv, YAML } from 'npm:zx'

import { Reward } from "./type.ts";
import { Reward } from './type.ts'

$.verbose = true;
$.verbose = true

const [
repositoryOwner,
Expand All @@ -12,11 +12,11 @@ const [
payer, // GitHub username of the payer (provided by workflow, defaults to issue creator)
currency,
reward,
] = argv._;
] = argv._

interface PRMeta {
author: components["schemas"]["simple-user"];
assignees: components["schemas"]["simple-user"][];
author: components['schemas']['simple-user']
assignees: components['schemas']['simple-user'][]
}

const PR_DATA = await $`gh api graphql -f query='{
Expand All @@ -33,75 +33,75 @@ const PR_DATA = await $`gh api graphql -f query='{
}
}
}
}' --jq '.data.repository.issue.closedByPullRequestsReferences.nodes[] | select(.merged == true) | {url: .url, mergeCommitSha: .mergeCommit.oid}' | head -n 1`;
}' --jq '.data.repository.issue.closedByPullRequestsReferences.nodes[] | select(.merged == true) | {url: .url, mergeCommitSha: .mergeCommit.oid}' | head -n 1`

const prData = PR_DATA.text().trim();
const prData = PR_DATA.text().trim()

if (!prData)
throw new ReferenceError("No merged PR is found for the given issue number.");
throw new ReferenceError('No merged PR is found for the given issue number.')

const { url: PR_URL, mergeCommitSha } = JSON.parse(prData);
const { url: PR_URL, mergeCommitSha } = JSON.parse(prData)

if (!PR_URL || !mergeCommitSha)
throw new Error("Missing required fields in PR data");
throw new Error('Missing required fields in PR data')

console.table({ PR_URL, mergeCommitSha });
console.table({ PR_URL, mergeCommitSha })

const { author, assignees }: PRMeta = await (
await $`gh pr view ${PR_URL} --json author,assignees`
).json();
).json()

function isBotUser(login: string) {
const lowerLogin = login.toLowerCase();
const lowerLogin = login.toLowerCase()
return (
lowerLogin.includes("copilot") ||
lowerLogin.includes("[bot]") ||
lowerLogin === "github-actions[bot]" ||
lowerLogin.endsWith("[bot]")
);
lowerLogin.includes('copilot') ||
lowerLogin.includes('[bot]') ||
lowerLogin === 'github-actions[bot]' ||
lowerLogin.endsWith('[bot]')
)
}

// Filter out Bot users from the list
const allUsers = [author.login, ...assignees.map(({ login }) => login)];
const users = allUsers.filter((login) => !isBotUser(login));
const allUsers = [author.login, ...assignees.map(({ login }) => login)]
const users = allUsers.filter((login) => !isBotUser(login))

console.log(`All users: ${allUsers.join(", ")}`);
console.log(`Filtered users (excluding bots): ${users.join(", ")}`);
console.log(`All users: ${allUsers.join(', ')}`)
console.log(`Filtered users (excluding bots): ${users.join(', ')}`)

if (!users[0])
throw new ReferenceError(
"No real users found (all users are bots). Skipping reward distribution."
);
'No real users found (all users are bots). Skipping reward distribution.',
)

const rewardNumber = parseFloat(reward);
const rewardNumber = parseFloat(reward)

if (isNaN(rewardNumber) || rewardNumber <= 0)
throw new RangeError(
`Reward amount is not a valid number, can not proceed with reward distribution. Received reward value: ${reward}`
);
`Reward amount is not a valid number, can not proceed with reward distribution. Received reward value: ${reward}`,
)

const averageReward = (rewardNumber / users.length).toFixed(2);
const averageReward = (rewardNumber / users.length).toFixed(2)

const list: Reward[] = users.map((login) => ({
issue: `#${issueNumber}`,
payer: `@${payer}`,
payee: `@${login}`,
currency,
reward: parseFloat(averageReward),
}));
const listText = YAML.stringify(list);
}))
const listText = YAML.stringify(list)

console.log(listText);
console.log(listText)

await $`git config user.name "github-actions[bot]"`;
await $`git config user.email "github-actions[bot]@users.noreply.github.com"`;
await $`git tag -a "reward-${issueNumber}" ${mergeCommitSha} -m ${listText}`;
await $`git push origin --tags --no-verify`;
await $`git config user.name "github-actions[bot]"`
await $`git config user.email "github-actions[bot]@users.noreply.github.com"`
await $`git tag -a "reward-${issueNumber}" ${mergeCommitSha} -m ${listText}`
await $`git push origin --tags --no-verify`

const commentBody = `## Reward data

\`\`\`yml
${listText}
\`\`\`
`;
await $`gh issue comment ${issueNumber} --body ${commentBody}`;
`
await $`gh issue comment ${issueNumber} --body ${commentBody}`
10 changes: 5 additions & 5 deletions .github/scripts/type.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export interface Reward {
issue: string;
payer: string;
payee: string;
currency: string;
reward: number;
issue: string
payer: string
payee: string
currency: string
reward: number
}
4 changes: 4 additions & 0 deletions .prettierrc
Comment thread
TechQuery marked this conversation as resolved.
Outdated
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"semi": false,
"singleQuote": true
}
12 changes: 6 additions & 6 deletions app/Barrier-Free-Bites/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import type { Metadata } from "next";
import React from "react";
import type { Metadata } from 'next'
import React from 'react'

export const metadata: Metadata = {
title: "无障碍友好美食指南",
};
title: '无障碍友好美食指南',
}

export default function Layout({ children }: { children: React.ReactNode }) {
return children;
}
return children
}
Loading