Code Issues Pull Requests Actions Packages Projects Releases 15 Wiki Activity Security Code Quality
45 Commits
17 changed files with 1553 additions and 45 deletions

No files matched your search

+52
View File
@@ -0,0 +1,52 @@
# Actions
## load-env
Copy các biến môi trường có sẵn trong process của runner vào env của job. Bước phía sau đọc được bằng `${{ env.TÊN }}`.
Biến khai báo trên runner không tự vào context `env`. Context đó chỉ chứa biến do workflow đặt. Action đọc biến trong process, ghi vào `$GITHUB_ENV`, và mask giá trị trong log.
### Usage
```yaml
- uses: https://git.sothink.vn/gitea/global-workflow/.gitea/actions/load-env@main
with:
names: RELEASE_TOKEN DT_API_KEY
- name: Use the loaded values
run: echo "token length ${#RELEASE_TOKEN}"
env:
API_KEY: ${{ env.DT_API_KEY }}
```
`names` là danh sách tên, cách nhau bởi khoảng trắng, load đúng thứ tự đó. Trong repo này, workflow release load `GITHUB_TOKEN RELEASE_TOKEN`; workflow quét lỗ hổng load `DT_API_KEY`.
Cùng repo, sau khi đã checkout, có thể gọi local:
```yaml
- uses: ./.gitea/actions/load-env
with:
names: RELEASE_TOKEN
```
Scoped workflow chạy trên repo khác thì không dùng `uses: ./`. Checkout của repo đó không có action này. Dùng URL đầy đủ ở trên. Ref `@main` lấy code trên nhánh mặc định, nên action phải được push lên `main` trước khi workflow khác gọi.
### Inputs
| Input | Bắt buộc | Mặc định | Ý nghĩa |
|---|---|---|---|
| `names` | có | | Tên biến, cách nhau bởi khoảng trắng. Chỉ nhận `[A-Za-z_][A-Za-z0-9_]*`. |
| `required` | không | `true` | `true`: thiếu hoặc rỗng thì dừng job. `false`: bỏ qua biến không có và in `Skipping unset …`. |
### Biến phải có trong container của job
act_runner không đưa env của máy host vào container trừ khi khai báo trong cấu hình runner:
```yaml
runner:
envs:
RELEASE_TOKEN: "…"
DT_API_KEY: "…"
```
Thiếu biến, với `required: true`, log có dòng `<TÊN> is not set on this runner`.
+51
View File
@@ -0,0 +1,51 @@
name: Load runner environment
description: Copy named variables from the runner process into the job env context.
inputs:
names:
description: Space-separated variable names, loaded in the given order.
required: true
required:
description: Fail when a named variable is missing or empty.
required: false
default: "true"
runs:
using: composite
steps:
- name: Load runner environment
shell: bash
env:
LOAD_ENV_NAMES: ${{ inputs.names }}
LOAD_ENV_REQUIRED: ${{ inputs.required }}
run: |
set -euo pipefail
if [[ -z "${LOAD_ENV_NAMES// }" ]]; then
echo "No environment variable names were given"
exit 1
fi
for name in $LOAD_ENV_NAMES; do
if [[ ! "$name" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]]; then
echo "Invalid environment variable name: ${name}"
exit 1
fi
value="${!name-}"
if [[ -z "$value" ]]; then
if [[ "${LOAD_ENV_REQUIRED}" == "true" ]]; then
echo "${name} is not set on this runner"
exit 1
fi
echo "Skipping unset ${name}"
continue
fi
if [[ "$value" != *$'\n'* ]]; then
echo "::add-mask::${value}"
fi
delimiter="LOAD_ENV_${name}_${RANDOM}_$$"
{
printf '%s<<%s\n' "$name" "$delimiter"
printf '%s\n' "$value"
printf '%s\n' "$delimiter"
} >> "$GITHUB_ENV"
echo "Loaded ${name} from the runner"
done
@@ -0,0 +1,61 @@
# resolve-branch-for-tag
Tìm nhánh chứa commit của tag đang checkout. Output `name` là tên nhánh đó.
Tag không thuộc về một nhánh. Action nhìn các ref trên remote, ưu tiên nhánh có tip đúng commit của tag. Không có nhánh nào trùng tip thì lấy nhánh chứa commit đó. Trong danh sách ứng viên, tên trong `prefer` được chọn trước. Không tìm thấy nhánh nào thì dùng `fallback`.
## Usage
Checkout full history trước. Clone nông làm `--contains` thiếu commit.
```yaml
- uses: actions/checkout@v7
with:
fetch-depth: 0
- id: branch
uses: https://git.sothink.vn/gitea/global-workflow/.gitea/actions/resolve-branch-for-tag@main
- run: echo "branch is ${{ steps.branch.outputs.name }}"
```
Cùng repo, sau khi checkout:
```yaml
- id: branch
uses: ./.gitea/actions/resolve-branch-for-tag
```
Scoped workflow trên repo khác dùng URL đầy đủ. `uses: ./` chỉ thấy checkout của repo đang chạy.
Mặc định ưu tiên `main`, rồi `develop`. Đổi thứ tự hoặc nhánh dự phòng:
```yaml
- id: branch
uses: https://git.sothink.vn/gitea/global-workflow/.gitea/actions/resolve-branch-for-tag@main
with:
prefer: develop main
fallback: develop
```
## Inputs
| Input | Bắt buộc | Mặc định | Ý nghĩa |
|---|---|---|---|
| `prefer` | không | `main develop` | Tên nhánh, cách nhau bởi khoảng trắng. Tên nào có trong danh sách ứng viên thì được chọn trước. |
| `fallback` | không | `develop` | Dùng khi không có nhánh remote nào chứa commit. |
| `remote` | không | `origin` | Remote giữ ref của các nhánh. `actions/checkout` tạo `origin`. |
## Output
| Output | Ý nghĩa |
|---|---|
| `name` | Tên nhánh đã chọn. Đọc bằng `${{ steps.<id>.outputs.name }}`. |
## Cách chọn
1. Nhánh có tip đúng commit của tag (`--points-at`).
2. Nếu không có, nhánh chứa commit đó (`--contains`).
3. Trong các ứng viên, lấy tên đầu tiên của `prefer` khớp chính xác.
4. Không khớp tên nào thì lấy ứng viên đầu tiên.
5. Không có ứng viên thì lấy `fallback` và in `No branch contains <sha>`.
@@ -0,0 +1,62 @@
name: Resolve branch for tag
description: Find the branch that contains the checked-out tag commit.
inputs:
prefer:
description: Space-separated branch names. The first one present in the candidate list wins.
required: false
default: main develop
fallback:
description: Branch used when no remote branch contains the commit.
required: false
default: develop
remote:
description: Git remote that holds the branch refs.
required: false
default: origin
outputs:
name:
description: Resolved branch name.
value: ${{ steps.tag-branch.outputs.name }}
runs:
using: composite
steps:
- name: Resolve branch for tag
id: tag-branch
shell: bash
env:
PREFER: ${{ inputs.prefer }}
FALLBACK: ${{ inputs.fallback }}
REMOTE: ${{ inputs.remote }}
run: |
set -euo pipefail
git fetch "$REMOTE" "+refs/heads/*:refs/remotes/${REMOTE}/*"
strip="s|^${REMOTE}/||"
exact=$(git for-each-ref --points-at HEAD --format='%(refname:short)' "refs/remotes/${REMOTE}" \
| sed "$strip" \
| grep -v '^HEAD$' || true)
if [[ -n "$exact" ]]; then
candidates="$exact"
else
candidates=$(git for-each-ref --contains HEAD --format='%(refname:short)' "refs/remotes/${REMOTE}" \
| sed "$strip" \
| grep -v '^HEAD$' || true)
fi
branch=""
for preferred in $PREFER; do
branch=$(printf '%s\n' "$candidates" | grep -x "$preferred" || true)
if [[ -n "$branch" ]]; then
break
fi
done
if [[ -z "$branch" ]]; then
branch=$(printf '%s\n' "$candidates" | head -n 1)
fi
if [[ -z "$branch" ]]; then
branch="$FALLBACK"
echo "No branch contains ${GITHUB_SHA}; using ${branch}"
fi
echo "Ref ${GITHUB_REF_NAME} is on branch ${branch}"
echo "name=${branch}" >> "$GITHUB_OUTPUT"
@@ -0,0 +1,130 @@
name: Conventional Commits Check
on:
pull_request:
types: [opened, edited, synchronize, reopened]
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
env:
BUN_VERSION: 1.4.5
SKIP_AUTHORS: renovate renovatebot
SKIP_PR_TITLES: Develop Master Main
jobs:
lint-commits-and-pr:
runs-on: ubuntu-latest
steps:
- name: Skip bots and reverse merges
id: author
env:
AUTHOR: ${{ github.event.pull_request.user.login }}
PR_TITLE: ${{ github.event.pull_request.title }}
run: |
set -euo pipefail
author=$(printf '%s' "$AUTHOR" | tr '[:upper:]' '[:lower:]')
title=$(printf '%s' "$PR_TITLE" | tr '[:upper:]' '[:lower:]')
skip=false
for name in $SKIP_AUTHORS; do
name=$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]')
if [[ "$author" == "$name" ]]; then
skip=true
break
fi
done
if [[ "$skip" == false ]]; then
for name in $SKIP_PR_TITLES; do
name=$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]')
if [[ "$title" == "$name" ]]; then
skip=true
break
fi
done
fi
if [[ "$skip" == true || "$author" == *bot || "$author" == *'[bot]' ]]; then
echo "skip=true" >> "$GITHUB_OUTPUT"
echo "Skipping commitlint for ${AUTHOR}: ${PR_TITLE}"
else
echo "skip=false" >> "$GITHUB_OUTPUT"
fi
- name: Checkout code
if: steps.author.outputs.skip != 'true'
uses: actions/checkout@v4
with:
fetch-depth: 0
# Local config wins, in this order. Download the shared file only when none exist.
- name: Resolve commitlint config
if: steps.author.outputs.skip != 'true'
id: commitlint-config
env:
COMMITLINT_REPO: ${{ vars.COMMITLINT_CONFIG_REPO || 'gitea/global-workflow' }}
COMMITLINT_CONFIGS: commitlint.config.js .github/commitlint.config.js .gitea/commitlint.config.js
run: |
set -euo pipefail
for candidate in $COMMITLINT_CONFIGS; do
if [[ -f "$candidate" ]]; then
echo "Using ${candidate} from this repository"
echo "config=${candidate}" >> "$GITHUB_OUTPUT"
exit 0
fi
done
url="${GITHUB_API_URL}/repos/${COMMITLINT_REPO}/raw/commitlint.config.js?ref=main"
echo "No local commitlint.config.js; fetching ${url}"
curl --silent --show-error --fail --location --output commitlint.config.js "$url"
echo "config=commitlint.config.js" >> "$GITHUB_OUTPUT"
- name: Setup Bun
if: steps.author.outputs.skip != 'true'
uses: oven-sh/setup-bun@v2
with:
bun-version: ${{ env.BUN_VERSION }}
# Install outside the repo so bun does not migrate its lockfile or install its dependencies.
- name: Install commitlint
if: steps.author.outputs.skip != 'true'
run: |
set -euo pipefail
dir="${RUNNER_TEMP}/commitlint"
mkdir -p "$dir"
bun add --cwd "$dir" @commitlint/cli @commitlint/config-conventional
if [[ -e node_modules && ! -L node_modules ]]; then
ln -sfn "$dir/node_modules/@commitlint" node_modules/@commitlint
else
ln -sfn "$dir/node_modules" node_modules
fi
echo "COMMITLINT_BIN=${dir}/node_modules/.bin/commitlint" >> "$GITHUB_ENV"
- name: Validate PR Title & Description (<= 500 chars)
if: steps.author.outputs.skip != 'true'
env:
PR_TITLE: ${{ github.event.pull_request.title }}
PR_BODY: ${{ github.event.pull_request.body }}
COMMITLINT_CONFIG: ${{ steps.commitlint-config.outputs.config }}
run: |
if [ -z "$PR_BODY" ]; then
printf "%s\n" "$PR_TITLE" | "$COMMITLINT_BIN" --config "$COMMITLINT_CONFIG"
else
printf "%s\n\n%s\n" "$PR_TITLE" "$PR_BODY" | "$COMMITLINT_BIN" --config "$COMMITLINT_CONFIG"
fi
- name: Validate All Commits in PR
if: steps.author.outputs.skip != 'true'
env:
BASE_SHA: ${{ github.event.pull_request.base.sha }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
COMMITLINT_CONFIG: ${{ steps.commitlint-config.outputs.config }}
run: |
set -euo pipefail
mapfile -t shas < <(git rev-list --no-merges "$BASE_SHA...$HEAD_SHA")
if [[ ${#shas[@]} -eq 0 ]]; then
echo "No non-merge commits to lint"
exit 0
fi
for sha in "${shas[@]}"; do
echo "Linting ${sha}"
git log -1 --format=%B "$sha" | "$COMMITLINT_BIN" --verbose --config "$COMMITLINT_CONFIG"
done
+68
View File
@@ -0,0 +1,68 @@
name: Release
on:
push:
tags:
- "v*.*.*"
permissions:
contents: write
releases: write
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
release:
runs-on: ubuntu-latest
name: Release
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0
# Local config wins, in this order. Download the shared file only when none exist.
- name: Resolve cliff.toml
id: cliff-config
env:
CLIFF_REPO: ${{ vars.CLIFF_CONFIG_REPO || 'gitea/global-workflow' }}
CLIFF_CONFIGS: cliff.toml .github/cliff.toml .gitea/cliff.toml
run: |
set -euo pipefail
for candidate in $CLIFF_CONFIGS; do
if [[ -f "$candidate" ]]; then
echo "Using ${candidate} from this repository"
echo "config=${candidate}" >> "$GITHUB_OUTPUT"
exit 0
fi
done
url="${GITHUB_API_URL}/repos/${CLIFF_REPO}/raw/cliff.toml?ref=main"
echo "No local cliff.toml; fetching ${url}"
curl --silent --show-error --fail --location --output cliff.toml "$url"
echo "config=cliff.toml" >> "$GITHUB_OUTPUT"
- name: Read envs from the runner
uses: https://git.sothink.vn/gitea/global-workflow/.gitea/actions/load-env@main
with:
names: GITHUB_TOKEN RELEASE_TOKEN
# Gitea's GITHUB_TOKEN is rejected by api.github.com. Pass a github.com PAT instead.
- name: Generate release notes
uses: orhun/git-cliff-action@v4
with:
config: ${{ steps.cliff-config.outputs.config }}
args: --latest --strip header
github_token: ${{ env.GITHUB_TOKEN }}
env:
OUTPUT: release-notes.md
- name: Create release
uses: softprops/action-gh-release@v3
with:
# prerelease only when the tag contains "-alpha", "-beta" or "-rc". ex: v1.0.0-alpha.1, v1.0.0-beta.1, v1.0.0-rc.1
prerelease: ${{ contains(github.ref, '-alpha') || contains(github.ref, '-beta') || contains(github.ref, '-rc') }}
body_path: release-notes.md
token: ${{ env.RELEASE_TOKEN }} # Use this token if you want user author is 'github-actions' bot
draft: false
@@ -7,6 +7,10 @@ on:
push:
branches: [main]
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
sbom-upload:
runs-on: ubuntu-latest
@@ -21,11 +25,16 @@ jobs:
output-file: sbom.json
upload-artifact: false
- name: Read API key from the runner
uses: https://git.sothink.vn/gitea/global-workflow/.gitea/actions/load-env@main
with:
names: DT_API_KEY
- name: Upload SBOM to Dependency-Track
uses: DependencyTrack/gh-upload-sbom@v4
with:
server-hostname: "${{ vars.DT_HOSTNAME }}"
api-key: "${{ secrets.DT_API_KEY }}"
api-key: ${{ env.DT_API_KEY }}
project-name: "${{ github.repository }}"
project-version: "latest"
bom-filename: "sbom.json"
+42
View File
@@ -0,0 +1,42 @@
name: Gitea badges
on:
schedule:
- cron: "30 * * * *" # every hour, minute 30
workflow_dispatch:
inputs:
dry_run:
description: "Chỉ in kế hoạch, không gán/gỡ badge"
type: boolean
default: false
rebuild_cache:
description: "Bỏ qua cache trên RustFS, quét lại toàn bộ rồi ghi cache mới"
type: boolean
default: false
push:
branches: [main]
paths:
- scripts/gitea-badges/**
- .gitea/workflows/gitea-badges.yaml
jobs:
award:
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
- name: Award badges
env:
GITEA_URL: ${{ vars.INSTANCE_URL || github.server_url }}
BADGE_TOKEN: ${{ secrets.BADGE_ADMIN_TOKEN }}
# push -> dry-run để review thay đổi config; schedule -> chạy thật
DRY_RUN: ${{ github.event_name == 'push' && 'true' || github.event.inputs.dry_run || 'false' }}
# Cache trên RustFS — thiếu bucket/key thì script tự chạy full scan
CACHE_S3_ENDPOINT: ${{ vars.CACHE_S3_ENDPOINT || 'https://rustfs.sothink.vn' }}
CACHE_S3_BUCKET: ${{ vars.CACHE_S3_BUCKET }}
CACHE_S3_KEY: gitea-badges/cache.json.gz
AWS_ACCESS_KEY_ID: ${{ secrets.CACHE_S3_ACCESS_KEY }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.CACHE_S3_SECRET_KEY }}
CACHE_REBUILD: ${{ github.event.inputs.rebuild_cache || 'false' }}
run: python3 scripts/gitea-badges/award_badges.py --config scripts/gitea-badges/badges.json
-40
View File
@@ -1,40 +0,0 @@
name: Release
on:
push:
tags:
- "**"
permissions:
contents: write
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
release:
runs-on: ubuntu-latest
name: Release
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0
# Gitea's GITHUB_TOKEN is rejected by api.github.com. Pass a github.com PAT instead.
- name: Generate release notes
uses: orhun/git-cliff-action@v4
with:
config: cliff.toml
args: --latest --strip header
github_token: ${{ secrets.PAT_GITHUB }}
env:
OUTPUT: release-notes.md
- name: Create release
uses: softprops/action-gh-release@v3
with:
token: ${{ secrets.RELEASE_TOKEN }}
prerelease: true
body_path: release-notes.md
+223
View File
@@ -0,0 +1,223 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[codz]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py.cover
*.lcov
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
# Pipfile.lock
# uv
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# uv.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
# poetry.lock
# poetry.toml
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
# pdm.lock
# pdm.toml
.pdm-python
.pdm-build/
# pixi
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
# pixi.lock
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
# in the .venv directory. It is recommended not to include this directory in version control.
.pixi/*
!.pixi/config.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule*
celerybeat.pid
# Redis
*.rdb
*.aof
*.pid
# RabbitMQ
mnesia/
rabbitmq/
rabbitmq-data/
# ActiveMQ
activemq-data/
# SageMath parsed files
*.sage.py
# Environments
.env
.envrc
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Conda environments
conda-meta/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs/Zensical documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
# .idea/
# Abstra
# Abstra is an AI-powered process automation framework.
# Ignore directories containing user credentials, local state, and settings.
# Learn more at https://abstra.io/docs
.abstra/
# Visual Studio Code
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore that
# can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
# and can be added to the global gitignore or merged into this file. However, if you prefer, you
# could uncomment the following to ignore the entire vscode folder
# .vscode/
# Temporary file for partial code execution
tempCodeRunnerFile.py
# Ruff stuff:
.ruff_cache/
# PyPI configuration file
.pypirc
# Marimo
marimo/_static/
marimo/_lsp/
__marimo__/
# Streamlit
.streamlit/secrets.toml
+11 -4
View File
@@ -25,11 +25,18 @@ body = """
- {% if commit.scope %}**{{ commit.scope }}**: {% endif %}{{ commit.message | upper_first }} ({{ commit.id | truncate(length=7, end="") }})
{%- endfor %}
{% endfor %}
{%- set authors = commits | map(attribute="author.name") | unique | sort %}
{% if authors | length > 0 %}
{#- Author names vary per machine (tienbh / Tien-BH / ...); the email local part matches the Gitea username. -#}
{%- set_global usernames = [] %}
{%- for commit in commits %}
{%- set username = commit.author.email | split(pat="@") | first | lower %}
{%- if username and username is not containing("bot") and username != "github-actions" and not username in usernames %}
{%- set_global usernames = usernames | concat(with=username) %}
{%- endif %}
{%- endfor %}
{% if usernames | length > 0 %}
## Contributors
{% for author in authors %}
* {{ author }}
{% for username in usernames | sort %}
* @{{ username }}
{%- endfor %}
{% endif %}
{% if server and repository and version %}
+22
View File
@@ -0,0 +1,22 @@
module.exports = {
extends: ['@commitlint/config-conventional'],
rules: {
// Allow all types (following the Conventional Commits specification)
'type-enum': [
2,
'always',
['build', 'chore', 'ci', 'docs', 'feat', 'fix', 'perf', 'refactor', 'revert', 'style', 'test'],
],
// Require type and description (cannot be empty)
'type-empty': [2, 'never'],
'subject-empty': [2, 'never'],
// Limit the length of the Title (header) to 128 characters
'header-max-length': [2, 'always', 128],
// Require a blank line between title and body/footer (following the Conventional Commits specification)
'body-leading-blank': [2, 'always'],
'footer-leading-blank': [2, 'always'],
// Limit the length of each line in body/description to 500 characters (optional)
'body-max-line-length': [2, 'always', 500],
},
};
View File
Whitespace-only changes.
+78
View File
@@ -0,0 +1,78 @@
# Gitea badges
Gán badge cho user trên toàn instance `git.sothink.vn` dựa trên hoạt động ở **mọi repo**.
Workflow `.gitea/workflows/gitea-badges.yaml` chạy mỗi giờ, quét toàn bộ repo bằng token
site-admin, rồi đồng bộ badge qua `POST/DELETE /api/v1/admin/users/{user}/badges`.
## Điều kiện
| Badge | Metric | Cách tính |
|---|---|---|
| YOLO | `yolo` | Người merge một PR không có review `APPROVED` (không bị dismiss) |
| Quickdraw | `quickdraw` | Người close issue/PR trong ≤ 300s kể từ lúc tạo (lấy từ timeline, fallback người tạo) |
| Starstruck (0/5/10/20) | `max_stars` | Số sao cao nhất trên một repo **do user sở hữu**, không phải fork |
| Pair-Extraordinaire (1/5/10/20) | `coauthored_commits` | Số commit trong PR đã merge có trailer `Co-authored-by:` trỏ tới email của user |
| Pull-Shark (5/10/50/100) | `merged_prs` | Số PR đã merge do user mở |
| Sponsor, Galaxy-Brain | — | `manual: true`, Gitea không có Sponsors/Discussions → script không đụng tới |
`tier_mode: highest` = mỗi nhóm chỉ giữ tier cao nhất (giống GitHub); `all` = giữ cả tier thấp.
`revoke: true` = gỡ badge (managed) khi user không còn đủ điều kiện.
`exclude_users` = bot (Renovate…) không bao giờ được tính.
`timeout` (mặc định 120s) / `retries` (mặc định 3) = timeout và số lần thử lại cho mỗi request GET
(thử lại khi timeout, lỗi mạng, HTTP 429/5xx).
**An toàn khi thiếu dữ liệu:** nếu có repo quét lỗi, lần chạy đó **chỉ gán thêm, không gỡ badge**
(metric bị đếm thiếu sẽ làm gỡ oan); job vẫn exit 1 để báo lỗi. Repo tắt Issues/Pull Requests
(API trả 403/404) được bỏ qua, không tính là lỗi.
Endpoint Gitea phải chạy git (`/pulls`, `/pulls/{n}`, `/pulls/{n}/commits`) có thể mất vài phút ở
repo lớn, nên: PR được liệt kê qua `/issues?type=pulls`, người merge/close lấy từ **timeline**
(chỉ đọc DB), chỉ có bước quét co-author gọi `/pulls/{n}/commits`. Lỗi ở một PR được ghi vào
`partial:` (không fail cả repo, không cache) và lần chạy sau chỉ thử lại đúng PR đó.
Read timeout không được thử lại trong cùng lần chạy (tránh treo worker 2×120s).
## Cài đặt
1. Badge phải có **slug** đúng với giá trị `slug` trong `badges.json` (đang dùng cột Name: `Pull-Shark-Gold`…).
2. Tạo PAT của một tài khoản **site admin** với scope: `read:repository`, `read:issue`, `read:user`, `write:admin`.
3. Thêm secret `BADGE_ADMIN_TOKEN` cho repo này (Settings → Actions → Secrets).
4. (Tuỳ chọn) variable `INSTANCE_URL` nếu runner phải gọi API qua URL khác `github.server_url`.
5. Chạy tay *Gitea badges* với `dry_run = true` để xem kế hoạch, rồi để schedule tự chạy.
Push thay đổi vào `scripts/gitea-badges/**` sẽ tự chạy ở chế độ dry-run.
## Cache trên RustFS
Mỗi giờ script phải xét lại toàn bộ PR/issue đã đóng. Để không gọi lại API cho những
PR đã xử lý, kết quả theo từng PR/issue (người close, có approve không, email co-author)
được lưu vào `s3://<bucket>/gitea-badges/cache.json.gz`. Mỗi lần chạy, script vẫn liệt kê
PR/issue đã đóng (1 request / 50 mục) nhưng **chỉ gọi reviews/commits/timeline cho mục mới
hoặc vừa thay đổi** (mở lại, close lại → `closed_at` đổi → tính lại).
- Metric luôn được tính lại từ cache + listing, nên đổi `exclude_users`, email, tier… có tác dụng ngay.
- Đổi `quickdraw_seconds` hoặc `CACHE_VERSION` trong script → cache tự bị bỏ, quét lại từ đầu.
- Lỗi đọc/ghi cache chỉ in `warn:`; script vẫn chạy full scan, không fail job.
- Muốn quét lại từ đầu: chạy tay workflow với `rebuild_cache = true`.
- Hạn chế: review bị dismiss **sau khi** PR đã merge sẽ không được phát hiện cho tới khi rebuild.
Cài đặt:
1. Tạo bucket (ví dụ `ci-cache`) trên RustFS và access key chỉ có quyền `GetObject`/`PutObject` trên bucket đó.
2. Variable `CACHE_S3_BUCKET` (và `CACHE_S3_ENDPOINT` nếu khác `https://rustfs.sothink.vn`).
3. Secret `CACHE_S3_ACCESS_KEY`, `CACHE_S3_SECRET_KEY`.
Script dùng path-style URL (`https://rustfs.sothink.vn/<bucket>/<key>`) và SigV4 region `us-east-1`
(đổi bằng `CACHE_S3_REGION`). Log có dòng `scan: …s, N API requests, cache hits … / misses …` để so sánh.
## Test local
```bash
GITEA_URL=https://git.sothink.vn BADGE_TOKEN=xxx DRY_RUN=true \
python3 scripts/gitea-badges/award_badges.py --config scripts/gitea-badges/badges.json
# kèm cache
CACHE_S3_ENDPOINT=https://rustfs.sothink.vn CACHE_S3_BUCKET=ci-cache \
AWS_ACCESS_KEY_ID=xxx AWS_SECRET_ACCESS_KEY=yyy \
GITEA_URL=https://git.sothink.vn BADGE_TOKEN=xxx DRY_RUN=true \
python3 scripts/gitea-badges/award_badges.py --config scripts/gitea-badges/badges.json
```
+527
View File
@@ -0,0 +1,527 @@
#!/usr/bin/env python3
"""
Award Gitea user badges instance-wide, based on activity across all repositories.
Runs from a single scheduled Gitea Actions workflow with a site-admin token.
Stdlib only (no pip install needed on the runner).
Env:
GITEA_URL e.g. https://git.sothink.vn
BADGE_TOKEN site-admin PAT (scopes: read:repository, read:issue, read:user, write:admin)
DRY_RUN "true" -> only print the plan, do not change badges
Optional cache on S3 (RustFS). Facts about closed PRs/issues are stored so each run
only calls the API for PRs/issues that are new or changed since the last run:
CACHE_S3_ENDPOINT e.g. https://rustfs.sothink.vn
CACHE_S3_BUCKET bucket name
CACHE_S3_KEY object key (default: gitea-badges/cache.json.gz)
CACHE_S3_REGION default: us-east-1
AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY
CACHE_REBUILD "true" -> ignore the stored cache, rescan everything, save fresh
Without CACHE_S3_ENDPOINT/BUCKET/keys the script runs a full scan (no cache).
"""
import argparse
import http.client
import json
import os
import re
import socket
import sys
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
from collections import Counter, defaultdict
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
from s3cache import S3Object
PAGE = 50
CACHE_VERSION = 3
COAUTHOR_RE = re.compile(r"^\s*co-authored-by:\s*.*?<([^>]+)>\s*$", re.I | re.M)
# --------------------------------------------------------------------------- API
class ApiError(RuntimeError):
def __init__(self, msg, code=None):
super().__init__(msg)
self.code = code
class Gitea:
RETRY_CODES = {429, 500, 502, 503, 504}
def __init__(self, url, token, timeout=120, retries=3, slow=15):
self.base = url.rstrip("/") + "/api/v1"
self.token = token
self.timeout = timeout
self.retries = retries
self.slow = slow # log requests slower than this (seconds)
self.timings = [] # (seconds, "GET /path?query", outcome)
self.requests = 0
self._lock = threading.Lock()
def call(self, method, path, params=None, body=None):
with self._lock:
self.requests += 1
url = self.base + path
if params:
url += "?" + urllib.parse.urlencode(params)
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(url, data=data, method=method)
req.add_header("Authorization", f"token {self.token}")
req.add_header("Accept", "application/json")
if data is not None:
req.add_header("Content-Type", "application/json")
label = f"{method} {path}" + (f"?{urllib.parse.urlencode(params)}" if params else "")
for attempt in range(1, self.retries + 1):
t = time.monotonic()
outcome = "ok"
try:
with urllib.request.urlopen(req, timeout=self.timeout) as r:
raw = r.read()
return json.loads(raw) if raw else None
except urllib.error.HTTPError as e:
outcome = f"HTTP {e.code}"
msg = e.read().decode(errors="replace")[:300]
err = ApiError(f"{method} {path} -> HTTP {e.code}: {msg}", e.code)
if e.code not in self.RETRY_CODES or method != "GET":
raise err from None
except (OSError, http.client.HTTPException) as e: # timeouts, resets, URLError
outcome = f"{type(e).__name__}: {e}"
read_timeout = isinstance(e, socket.timeout) and getattr(e, "errno", None) is None
err = ApiError(f"{label} -> {type(e).__name__}: {e} "
f"(after {time.monotonic() - t:.0f}s, attempt {attempt}/{self.retries})",
"timeout" if read_timeout else None)
if method != "GET" or read_timeout:
raise err from None
finally:
dt = time.monotonic() - t
with self._lock:
self.timings.append((dt, label, outcome))
if dt >= self.slow:
print(f"slow: {dt:6.1f}s {outcome:<10.40} {label}", flush=True)
if attempt < self.retries:
time.sleep(2 * attempt)
with self._lock:
self.requests += 1
raise err
def get(self, path, **params):
return self.call("GET", path, params)
def paged(self, path, key=None, **params):
page = 1
while True:
res = self.get(path, page=page, limit=PAGE, **params)
items = res.get(key, []) if key else (res or [])
yield from items
if len(items) < PAGE:
return
page += 1
def ts(s):
if not s:
return None
return datetime.fromisoformat(s.replace("Z", "+00:00"))
# ------------------------------------------------------------------ collection
class Stats:
def __init__(self):
self.lock = threading.Lock()
self.max_stars = {} # login -> max stars on an owned (non-fork) repo
self.merged_prs = Counter() # login -> merged PRs opened
self.coauthored = Counter() # login -> co-authored commits on merged PRs
self.yolo = set() # merged a PR without an approving review
self.quickdraw = set() # closed an issue/PR within N seconds of opening
self.cache_hits = 0 # merged/quick PRs + quick issues served from cache
self.cache_misses = 0
self.skipped = set() # "owner/repo (pulls|issues: HTTP 404)"
self.partial = [] # per-PR fetch failures (data retried next run)
def timeline_of(api, owner, repo, number):
"""(closer, merger) from the issue/PR timeline — DB only, no git work.
"" when the event is absent, None on API error."""
try:
closer = merger = ""
for ev in api.paged(f"/repos/{owner}/{repo}/issues/{number}/timeline"):
login = (ev.get("user") or {}).get("login")
if not login:
continue
if ev.get("type") in ("close", "merge_pull"):
closer = login
if ev.get("type") == "merge_pull":
merger = login
return closer, merger
except RuntimeError:
return None, None
def scan_repo(api, repo, cfg, users, email_map, stats, old):
"""Scan one repo. `old` is this repo's cache entry from the last run (or None).
Cache entry layout (keys kept short, the file is gzipped JSON):
prs[number] = {"f": [closed_at, merged], "mb": merger, "ok": approved?,
"co": [[emails]...], "q": closer}
issues[number] = {"f": closed_at, "q": closer}
"f" is the fingerprint: if closed_at/merged changed (reopened, re-closed) the entry is
discarded and refetched. Only PRs/issues that are merged or quickdraw-relevant are stored,
and only those still present in the current "closed" listing are written back.
Gitea endpoints that run git (/pulls, /pulls/{n}, /pulls/{n}/commits) can take minutes on
big repos, so: PRs are listed via /issues?type=pulls, merger/closer come from the timeline
(DB only), and only the co-author scan touches /pulls/{n}/commits. A failure on a single PR
is recorded in stats.partial and left out of the cache, so the next run retries just that PR.
A disabled issues/PR unit (HTTP 403/404 on the listing) is skipped, not an error.
"""
owner, name = repo["owner"]["login"], repo["name"]
quick = cfg["quickdraw_seconds"]
scan_co = cfg.get("scan_coauthors", True)
old = old or {}
old_prs, old_iss = old.get("prs", {}), old.get("issues", {})
new_prs, new_iss = {}, {}
local_merged, local_coauth = Counter(), Counter()
local_yolo, local_quick = set(), set()
hits = misses = 0
def is_quick(item):
c, d = ts(item.get("created_at")), ts(item.get("closed_at"))
return c and d and 0 <= (d - c).total_seconds() <= quick
def entry_for(cache, number, fp):
nonlocal hits, misses
e = cache.get(number)
if e is not None and e.get("f") == fp:
hits += 1
return e
misses += 1
return {"f": fp}
partial = []
def soft(number, what, err):
partial.append(f"{repo['full_name']}#{number} {what}: {err}")
def timeline(entry, number, need_merger):
"""Fill entry["q"] / entry["mb"] from the timeline if missing. False on error."""
if "q" in entry and ("mb" in entry or not need_merger):
return True
closer, merger = timeline_of(api, owner, name, number)
if closer is None:
soft(number, "timeline", "API error")
return False
entry["q"] = closer
if need_merger:
entry["mb"] = merger
return True
def listing(kind):
try:
yield from api.paged(f"/repos/{owner}/{name}/issues", state="closed", type=kind)
except ApiError as e:
if e.code in (403, 404): # unit disabled / external tracker
with stats.lock:
stats.skipped.add(f"{repo['full_name']} ({kind}: HTTP {e.code})")
return
raise
# Pull requests
if repo.get("has_pull_requests", True) and not repo.get("mirror"):
for pr in listing("pulls"):
meta = pr.get("pull_request") or {}
merged, quickpr = bool(meta.get("merged") or meta.get("merged_at")), is_quick(pr)
if not merged and not quickpr:
continue
num = str(pr["number"])
poster = (pr.get("user") or {}).get("login")
e = entry_for(old_prs, num, [pr.get("closed_at"), merged])
new_prs[num] = e
n = pr["number"]
have_tl = timeline(e, n, need_merger=merged)
if quickpr:
who = (e.get("q") or poster) if have_tl else poster
if who:
local_quick.add(who)
if not merged:
continue
if poster:
local_merged[poster] += 1
merger = e.get("mb") or ""
if merger:
if "ok" not in e:
try:
reviews = api.get(f"/repos/{owner}/{name}/pulls/{n}/reviews") or []
e["ok"] = any(r.get("state") == "APPROVED" and not r.get("dismissed")
for r in reviews)
except ApiError as err:
if err.code == 404: # PR unit gone (archived repo)
e["ok"] = True
else:
soft(n, "reviews", err)
if e.get("ok") is False:
local_yolo.add(merger)
if scan_co:
if "co" not in e:
try:
co = []
for c in api.paged(f"/repos/{owner}/{name}/pulls/{n}/commits",
stat="false", verification="false", files="false"):
found = COAUTHOR_RE.findall((c.get("commit") or {}).get("message", ""))
if found:
co.append(found)
e["co"] = co
except ApiError as err:
if err.code == 404: # head ref / PR unit gone
e["co"] = []
else:
soft(n, "commits", err)
for emails in e.get("co", []):
seen = set()
for email in emails:
login = resolve_email(email, email_map, users, cfg)
if login and login not in seen:
seen.add(login)
local_coauth[login] += 1
# Issues (Quickdraw)
if repo.get("has_issues", True) and not repo.get("mirror"):
for iss in listing("issues"):
if not is_quick(iss):
continue
num = str(iss["number"])
poster = (iss.get("user") or {}).get("login")
e = entry_for(old_iss, num, iss.get("closed_at"))
new_iss[num] = e
who = (e.get("q") or poster) if timeline(e, iss["number"], False) else poster
if who:
local_quick.add(who)
with stats.lock:
stats.merged_prs.update(local_merged)
stats.coauthored.update(local_coauth)
stats.yolo |= local_yolo
stats.quickdraw |= local_quick
stats.cache_hits += hits
stats.cache_misses += misses
stats.partial.extend(partial)
return {"name": repo["full_name"], "prs": new_prs, "issues": new_iss}
def resolve_email(email, email_map, users, cfg):
email = email.strip().lower()
if email in email_map:
return email_map[email]
local, _, domain = email.partition("@")
# Gitea "keep email private" addresses: <login>@<NO_REPLY_ADDRESS>
nr = (cfg.get("noreply_domain") or "").lower()
if (nr and domain == nr) or domain.startswith("noreply."):
login = local.split("+")[-1]
if login in users:
return login
return None
# --------------------------------------------------------------------- badges
def badge_slug(b):
"""Gitea's /admin/users/{u}/badges returns the raw DB model (no json tags),
so keys are "Slug"/"ID"/... — accept both spellings to be safe."""
return b.get("slug") or b.get("Slug")
def metric_values(stats, login):
return {
"max_stars": stats.max_stars.get(login, -1), # -1 => owns no repo
"merged_prs": stats.merged_prs.get(login, 0),
"coauthored_commits": stats.coauthored.get(login, 0),
"yolo": 1 if login in stats.yolo else 0,
"quickdraw": 1 if login in stats.quickdraw else 0,
}
def desired_badges(values, families, tier_mode):
want = set()
for fam in families:
if fam.get("manual"):
continue
v = values.get(fam["metric"], 0)
reached = [t for t in sorted(fam["tiers"], key=lambda t: t["min"]) if v >= t["min"]]
if not reached:
continue
if tier_mode == "all":
want.update(t["slug"] for t in reached)
else:
want.add(reached[-1]["slug"])
return want
def open_cache():
"""S3Object for the cache, or None if not configured."""
env = os.environ.get
endpoint, bucket = env("CACHE_S3_ENDPOINT"), env("CACHE_S3_BUCKET")
ak, sk = env("AWS_ACCESS_KEY_ID"), env("AWS_SECRET_ACCESS_KEY")
if not (endpoint and bucket and ak and sk):
print("cache: disabled (CACHE_S3_ENDPOINT/CACHE_S3_BUCKET/AWS_* not set)")
return None
return S3Object(endpoint, bucket, env("CACHE_S3_KEY") or "gitea-badges/cache.json.gz",
ak, sk, env("CACHE_S3_REGION") or "us-east-1")
def load_cache(store, cfg):
empty = {"version": CACHE_VERSION, "repos": {}}
if store is None:
return empty
if os.environ.get("CACHE_REBUILD", "false").lower() in ("1", "true", "yes"):
print("cache: rebuild requested, ignoring stored cache")
return empty
try:
data = store.load_json()
except Exception as e: # never fail the run because of the cache
print(f"warn: cache load failed ({e}); full scan")
return empty
if data is None:
print(f"cache: {store.label} not found; full scan")
return empty
# Facts depend on these settings; if they change, rebuild.
sig = {"quickdraw_seconds": cfg["quickdraw_seconds"]}
if data.get("version") != CACHE_VERSION or data.get("settings") != sig:
print("cache: version/settings changed; full scan")
return empty
print(f"cache: loaded {len(data.get('repos', {}))} repos from {store.label}")
return data
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--config", required=True)
args = ap.parse_args()
cfg = json.load(open(args.config))
cfg.setdefault("quickdraw_seconds", 300)
t0 = time.monotonic()
url = os.environ.get("GITEA_URL") or sys.exit("GITEA_URL is required")
token = os.environ.get("BADGE_TOKEN") or sys.exit("BADGE_TOKEN is required")
dry = os.environ.get("DRY_RUN", "false").lower() in ("1", "true", "yes")
api = Gitea(url, token, timeout=cfg.get("timeout", 120), retries=cfg.get("retries", 3),
slow=cfg.get("slow_log_seconds", 15))
exclude = {u.lower() for u in cfg.get("exclude_users", [])}
families = cfg["families"]
managed = {t["slug"] for f in families if not f.get("manual") for t in f["tiers"]}
# Users + e-mail map
users = {}
for u in api.paged("/admin/users"):
if u["login"].lower() in exclude:
continue
users[u["login"]] = u
email_map = {u["email"].lower(): login for login, u in users.items() if u.get("email")}
try:
for e in api.paged("/admin/emails"):
login = e.get("username") or e.get("user_name")
if login in users:
email_map[e["email"].lower()] = login
except RuntimeError as err:
print(f"warn: /admin/emails unavailable ({err}); using primary e-mails only")
print(f"users: {len(users)}")
# Repos
repos = list(api.paged("/repos/search", key="data", private="true"))
print(f"repos: {len(repos)}")
stats = Stats()
for r in repos:
owner = r["owner"]["login"]
if owner in users and not r.get("fork"):
stats.max_stars[owner] = max(stats.max_stars.get(owner, -1), r.get("stars_count", 0))
store = open_cache()
cache = load_cache(store, cfg)
old_repos = cache.get("repos", {})
new_repos = {}
errors = []
with ThreadPoolExecutor(max_workers=cfg.get("workers", 6)) as pool:
futs = {pool.submit(scan_repo, api, r, cfg, users, email_map, stats,
old_repos.get(str(r["id"]))): r
for r in repos}
for f, r in futs.items():
rid = str(r["id"])
try:
new_repos[rid] = f.result()
except Exception as e: # keep going; report at the end
errors.append(f"{r['full_name']}: {e}")
if rid in old_repos: # keep last good data for this repo
new_repos[rid] = old_repos[rid]
t_scan = time.monotonic() - t0
print(f"scan: {t_scan:.1f}s, {api.requests} API requests, "
f"cache hits {stats.cache_hits} / misses {stats.cache_misses}")
if stats.partial:
print(f"partial: {len(stats.partial)} PR/issue fetch(es) failed (retried next run):")
for line in stats.partial[:30]:
print(f" {line}")
if len(stats.partial) > 30:
print(f" ... {len(stats.partial) - 30} more")
if stats.skipped:
print("skipped (issues/PR unit disabled or unavailable): " + ", ".join(sorted(stats.skipped)))
top = sorted(api.timings, reverse=True)[:10]
if top and top[0][0] >= 1:
print("slowest requests:")
for dt, label, outcome in top:
print(f" {dt:6.1f}s {outcome:<10.40} {label}")
if store is not None:
try:
size = store.save_json({"version": CACHE_VERSION,
"settings": {"quickdraw_seconds": cfg["quickdraw_seconds"]},
"updated_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
"repos": new_repos})
print(f"cache: saved {len(new_repos)} repos ({size} bytes) to {store.label}")
except Exception as e:
print(f"warn: cache save failed ({e})")
# Drop excluded bots from awarded sets (e.g. renovate as merger)
stats.yolo -= exclude
stats.quickdraw -= exclude
# Reconcile
revoke = cfg.get("revoke", True)
if (errors or stats.partial) and revoke:
# Missing data => metrics are undercounted => revoking would remove badges wrongly.
print(f"warn: {len(errors)} repo(s) failed, {len(stats.partial)} partial; "
"skipping revocations this run (adds only)")
revoke = False
tier_mode = cfg.get("tier_mode", "highest")
changes = 0
for login in sorted(users):
want = desired_badges(metric_values(stats, login), families, tier_mode)
have = {badge_slug(b) for b in (api.get(f"/admin/users/{login}/badges") or [])} - {None}
add = sorted(want - have)
rm = sorted((have & managed) - want) if revoke else []
if not add and not rm:
continue
changes += 1
print(f"{login}: +{add or '-'} -{rm or '-'} {metric_values(stats, login)}")
if dry:
continue
if add:
api.call("POST", f"/admin/users/{login}/badges", body={"badge_slugs": add})
if rm:
api.call("DELETE", f"/admin/users/{login}/badges", body={"badge_slugs": rm})
print(f"{'[dry-run] ' if dry else ''}users changed: {changes} "
f"(total {time.monotonic() - t0:.1f}s, {api.requests} API requests)")
if errors:
print("errors:\n " + "\n ".join(errors))
sys.exit(1)
if __name__ == "__main__":
main()
+139
View File
@@ -0,0 +1,139 @@
{
"tier_mode": "highest",
"revoke": true,
"quickdraw_seconds": 300,
"scan_coauthors": true,
"workers": 2,
"noreply_domain": "noreply.git.sothink.vn",
"exclude_users": [
"giteabot",
"github-actions",
"jenkins",
"komodobot",
"renovatebot",
"reviewbot",
"sonarqubebot"
],
"families": [
{
"name": "YOLO",
"metric": "yolo",
"tiers": [
{
"slug": "YOLO",
"min": 1
}
]
},
{
"name": "Quickdraw",
"metric": "quickdraw",
"tiers": [
{
"slug": "Quickdraw",
"min": 1
}
]
},
{
"name": "Starstruck",
"metric": "max_stars",
"tiers": [
{
"slug": "Starstruck",
"min": 0
},
{
"slug": "Starstruck-Bronze",
"min": 5
},
{
"slug": "Starstruck-Silver",
"min": 10
},
{
"slug": "Starstruck-Gold",
"min": 20
}
]
},
{
"name": "Pair Extraordinaire",
"metric": "coauthored_commits",
"tiers": [
{
"slug": "Pair-Extraordinaire",
"min": 1
},
{
"slug": "Pair-Extraordinaire-Bronze",
"min": 5
},
{
"slug": "Pair-Extraordinaire-Silver",
"min": 10
},
{
"slug": "Pair-Extraordinaire-Gold",
"min": 20
}
]
},
{
"name": "Pull Shark",
"metric": "merged_prs",
"tiers": [
{
"slug": "Pull-Shark",
"min": 5
},
{
"slug": "Pull-Shark-Bronze",
"min": 10
},
{
"slug": "Pull-Shark-Silver",
"min": 50
},
{
"slug": "Pull-Shark-Gold",
"min": 100
}
]
},
{
"name": "Sponsor",
"manual": true,
"note": "Gitea has no sponsorship feature - award manually",
"tiers": [
{
"slug": "Sponsor",
"min": 1
}
]
},
{
"name": "Galaxy Brain",
"manual": true,
"note": "Gitea has no Discussions - award manually",
"tiers": [
{
"slug": "Galaxy-Brain",
"min": 1
},
{
"slug": "Galaxy-Brain-Bronze",
"min": 5
},
{
"slug": "Galaxy-Brain-Silver",
"min": 10
},
{
"slug": "Galaxy-Brain-Gold",
"min": 20
}
]
}
]
}
+77
View File
@@ -0,0 +1,77 @@
"""
Tiny S3 client (AWS SigV4, path-style) for a single JSON cache object.
Stdlib only. Tested target: RustFS / MinIO-compatible endpoints.
"""
import datetime
import gzip
import hashlib
import hmac
import json
import urllib.error
import urllib.parse
import urllib.request
class S3Object:
def __init__(self, endpoint, bucket, key, access_key, secret_key, region="us-east-1"):
u = urllib.parse.urlsplit(endpoint.rstrip("/"))
self.scheme = u.scheme or "https"
self.host = u.netloc or u.path
parts = [bucket] + [p for p in key.split("/") if p]
self.path = "/" + "/".join(urllib.parse.quote(p, safe="-_.~") for p in parts)
self.access_key, self.secret_key, self.region = access_key, secret_key, region
self.label = f"s3://{bucket}/{key}"
def _request(self, method, body=b""):
now = datetime.datetime.now(datetime.timezone.utc)
amz_date = now.strftime("%Y%m%dT%H%M%SZ")
day = amz_date[:8]
payload_hash = hashlib.sha256(body).hexdigest()
signed_headers = {"host": self.host, "x-amz-content-sha256": payload_hash,
"x-amz-date": amz_date}
names = sorted(signed_headers)
canonical = "\n".join([
method, self.path, "",
"".join(f"{k}:{signed_headers[k]}\n" for k in names),
";".join(names), payload_hash,
])
scope = f"{day}/{self.region}/s3/aws4_request"
to_sign = "\n".join(["AWS4-HMAC-SHA256", amz_date, scope,
hashlib.sha256(canonical.encode()).hexdigest()])
k = ("AWS4" + self.secret_key).encode()
for part in (day, self.region, "s3", "aws4_request"):
k = hmac.new(k, part.encode(), hashlib.sha256).digest()
sig = hmac.new(k, to_sign.encode(), hashlib.sha256).hexdigest()
req = urllib.request.Request(f"{self.scheme}://{self.host}{self.path}",
data=body if method == "PUT" else None, method=method)
req.add_header("Host", self.host)
req.add_header("x-amz-content-sha256", payload_hash)
req.add_header("x-amz-date", amz_date)
req.add_header("Authorization",
f"AWS4-HMAC-SHA256 Credential={self.access_key}/{scope}, "
f"SignedHeaders={';'.join(names)}, Signature={sig}")
if method == "PUT":
req.add_header("Content-Type", "application/gzip")
with urllib.request.urlopen(req, timeout=60) as r:
return r.read()
def load_json(self):
"""Return the decoded object, or None if it does not exist yet."""
try:
raw = self._request("GET")
except urllib.error.HTTPError as e:
if e.code == 404:
return None
raise RuntimeError(f"GET {self.label} -> HTTP {e.code}: "
f"{e.read().decode(errors='replace')[:300]}") from None
return json.loads(gzip.decompress(raw))
def save_json(self, obj):
body = gzip.compress(json.dumps(obj, separators=(",", ":")).encode())
try:
self._request("PUT", body)
except urllib.error.HTTPError as e:
raise RuntimeError(f"PUT {self.label} -> HTTP {e.code}: "
f"{e.read().decode(errors='replace')[:300]}") from None
return len(body)