Skip to content

Commit 45a1e48

Browse files
committed
chore(workflow): 集成README版本信息自动更新脚本
- 在自动更新工作流中增加运行update-readme-version脚本步骤 - 修改提交操作以同时包含package.json和README.md的变更 - 在package.json添加update-readme-version命令入口 - 新增scripts目录及update-readme-version.ts脚本实现版本同步 - README.md添加版本占位符用于动态更新展示最新数据版本 - 编写测试确保包导出项与快照一致(暂未启用)
1 parent ee9f683 commit 45a1e48

File tree

6 files changed

+216
-5
lines changed

6 files changed

+216
-5
lines changed

.github/workflows/auto-update.yml

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -89,10 +89,10 @@ jobs:
8989
usb.ids.version.json
9090
retention-days: 30
9191

92-
- name: Update package.json version
92+
- name: Update package.json version and README
9393
if: steps.check-update.outputs.skip != 'true'
9494
run: |
95-
# 从 usb.ids.version.json 获取版本号并去掉 v 前缀
95+
# 从 usb.ids.version.json 获取版本号
9696
NEW_VERSION=$(node -p "require('./usb.ids.version.json').version.replace(/^v/, '')")
9797
echo "New version: $NEW_VERSION"
9898
@@ -104,13 +104,20 @@ jobs:
104104
fs.writeFileSync('package.json', JSON.stringify(pkg, null, 2) + '\n');
105105
"
106106
107+
# 使用专门的脚本更新 README.md 版本信息
108+
pnpm run update-readme-version
109+
107110
# 配置 git 用户信息
108111
git config --local user.email "action@github.com"
109112
git config --local user.name "GitHub Action"
110113
111114
# 提交更改
112-
git add package.json
113-
git commit -m "chore: update to version $NEW_VERSION"
115+
git add package.json README.md
116+
git commit -m "chore: update to version $NEW_VERSION
117+
118+
- Updated package.json version to $NEW_VERSION
119+
- Updated README.md with latest version info
120+
- Data updated automatically"
114121
115122
- name: Create and push tag
116123
if: steps.check-update.outputs.skip != 'true'

README.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,14 @@
66

77
[![GitHub Pages](https://img.shields.io/github/actions/workflow/status/Drswith/usb.ids/github-pages.yml?label=github%20pages)](https://github.com/Drswith/usb.ids/actions/workflows/github-pages.yml)
88

9+
<!-- START VERSION PLACEHOLDER -->
10+
> **📦 Latest Release**
11+
> **Version:** `1.0.1756734426891`
12+
> **Updated:** `2025-09-01 13:47:06 UTC`
13+
> **Status:** ✅ Auto-updated daily
14+
15+
<!-- END VERSION PLACEHOLDER -->
16+
917
An automated USB device ID database project that provides a CLI tool and data files. It fetches the latest USB.IDS data every 24 hours and publishes updated data files to npm.
1018

1119
## 🚀 Features

package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,8 @@
5858
"typecheck": "tsc --noEmit",
5959
"prepare": "simple-git-hooks",
6060
"bumpp": "bumpp",
61-
"lint-staged": "lint-staged"
61+
"lint-staged": "lint-staged",
62+
"update-readme-version": "tsx scripts/update-readme-version.ts"
6263
},
6364
"devDependencies": {
6465
"@antfu/eslint-config": "^4.2.1",

scripts/README.md

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
# Scripts Directory
2+
3+
This directory contains utility scripts for the USB.IDS project. Each script serves a specific purpose in the project's automation and maintenance workflow.
4+
5+
## Available Scripts
6+
7+
### `update-readme-version.ts`
8+
9+
Updates the version information in the project's README.md file based on data from `usb.ids.version.json`.
10+
11+
#### Purpose
12+
Synchronizes the version information displayed in README.md with the actual data version to ensure documentation accuracy.
13+
14+
#### Usage
15+
16+
```bash
17+
# Run using npm script (recommended)
18+
pnpm run update-readme-version
19+
20+
# Or run directly with tsx
21+
tsx scripts/update-readme-version.ts
22+
```
23+
24+
#### What it does
25+
26+
1. Uses `loadVersionInfo()` from `src/core.ts` to read version data
27+
2. Locates the version placeholder markers in README.md
28+
3. Updates the version block with new information using proper Markdown formatting
29+
4. Provides detailed logging using the project's logger utility
30+
31+
#### Key Features
32+
33+
- **TypeScript Support**: Written in TypeScript for type safety
34+
- **Code Reuse**: Leverages existing functions from `src/core.ts`, `src/config.ts`, and `src/utils.ts`
35+
- **ES Module Compatible**: Properly handles ES module imports and execution detection
36+
- **Robust Error Handling**: Comprehensive error checking with helpful messages
37+
- **Standardized Logging**: Uses the project's logger utility for consistent output formatting
38+
- **Detailed Statistics**: Shows version, update time, vendor count, and device count
39+
40+
#### Requirements
41+
42+
- `usb.ids.version.json` must exist in the project root
43+
- README.md must contain the version placeholders:
44+
```markdown
45+
<!-- START VERSION PLACEHOLDER -->
46+
<!-- END VERSION PLACEHOLDER -->
47+
```
48+
- TypeScript dependencies (`tsx`) must be installed
49+
50+
#### Output Format
51+
52+
The script updates README.md with a styled version block:
53+
54+
```markdown
55+
> **📦 Latest Release**
56+
> **Version:** `1.0.xxxxx`
57+
> **Updated:** `YYYY-MM-DD HH:MM:SS UTC`
58+
> **Status:** ✅ Auto-updated daily
59+
```
60+
61+
---
62+
63+
## Script Development Guidelines
64+
65+
When adding new scripts to this directory:
66+
67+
1. **Use TypeScript**: All scripts should be written in TypeScript for type safety
68+
2. **Reuse Existing Code**: Leverage functions from `src/` modules instead of reimplementing
69+
3. **Follow Naming Convention**: Use descriptive kebab-case names ending with `.ts`
70+
4. **Add Documentation**: Update this README.md with script description and usage
71+
5. **Use Project Logger**: Use `logger` from `src/utils.ts` for consistent output formatting
72+
6. **Include npm Script**: Add corresponding script entry in `package.json`
73+
7. **Handle Errors Gracefully**: Provide helpful error messages and proper exit codes

scripts/update-readme-version.ts

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
#!/usr/bin/env tsx
2+
3+
import * as fs from 'node:fs'
4+
import * as path from 'node:path'
5+
import { fileURLToPath } from 'node:url'
6+
import { USB_IDS_VERSION_JSON_FILE } from '../src/config.js'
7+
import { loadVersionInfo } from '../src/core.js'
8+
import { logger } from '../src/utils.js'
9+
10+
// ES module 中获取当前文件路径
11+
const __filename = fileURLToPath(import.meta.url)
12+
const __dirname = path.dirname(__filename)
13+
14+
/**
15+
* 更新 README.md 中的版本信息
16+
* 从 usb.ids.version.json 读取版本信息并更新到 README.md 的指定位置
17+
*/
18+
function updateReadmeVersion(): void {
19+
try {
20+
const root = process.cwd()
21+
22+
// 使用 src 中的函数读取版本信息
23+
const versionFilePath = path.join(root, USB_IDS_VERSION_JSON_FILE)
24+
const versionData = loadVersionInfo(versionFilePath)
25+
26+
if (!versionData) {
27+
logger.error(`Failed to load version info from ${USB_IDS_VERSION_JSON_FILE}`)
28+
logger.error('Please ensure the file exists and is valid JSON')
29+
process.exit(1)
30+
}
31+
32+
const version = versionData.version.replace(/^v/, '') // 移除 v 前缀
33+
const updateTime = versionData.fetchTimeFormatted
34+
35+
logger.info(`Updating README.md with version: ${version}`)
36+
logger.info(`Update time: ${updateTime}`)
37+
38+
// 读取 README.md 文件
39+
const readmePath = path.join(root, 'README.md')
40+
if (!fs.existsSync(readmePath)) {
41+
logger.error('README.md not found')
42+
process.exit(1)
43+
}
44+
45+
const readmeContent = fs.readFileSync(readmePath, 'utf8')
46+
47+
// 查找版本占位符
48+
const startMarker = '<!-- START VERSION PLACEHOLDER -->'
49+
const endMarker = '<!-- END VERSION PLACEHOLDER -->'
50+
51+
const startIndex = readmeContent.indexOf(startMarker)
52+
const endIndex = readmeContent.indexOf(endMarker)
53+
54+
if (startIndex === -1 || endIndex === -1) {
55+
logger.error('Version placeholders not found in README.md')
56+
logger.error('Please ensure the README.md contains:')
57+
logger.error('<!-- START VERSION PLACEHOLDER -->')
58+
logger.error('<!-- END VERSION PLACEHOLDER -->')
59+
process.exit(1)
60+
}
61+
62+
// 构建新的版本信息块
63+
const newVersionBlock = `
64+
> **📦 Latest Release**
65+
> **Version:** \`${version}\`
66+
> **Updated:** \`${updateTime}\`
67+
> **Status:** ✅ Auto-updated daily
68+
69+
`
70+
71+
// 替换版本信息
72+
const beforeMarker = readmeContent.substring(0, startIndex + startMarker.length)
73+
const afterMarker = readmeContent.substring(endIndex)
74+
const newReadmeContent = beforeMarker + newVersionBlock + afterMarker
75+
76+
// 写入更新后的内容
77+
fs.writeFileSync(readmePath, newReadmeContent, 'utf8')
78+
79+
logger.success('README.md version info updated successfully')
80+
logger.info(`Version: ${version}`)
81+
logger.info(`Updated: ${updateTime}`)
82+
logger.info(`Vendor count: ${versionData.vendorCount}`)
83+
logger.info(`Device count: ${versionData.deviceCount}`)
84+
}
85+
catch (error) {
86+
logger.error(`Failed to update README.md: ${(error as Error).message}`)
87+
process.exit(1)
88+
}
89+
}
90+
91+
// 如果直接运行此脚本
92+
if (import.meta.url === `file://${process.argv[1]}`) {
93+
updateReadmeVersion()
94+
}
95+
96+
export { updateReadmeVersion }

tests/exports.test.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import { x } from 'tinyexec'
2+
import { describe, expect, it } from 'vitest'
3+
import { getPackageExportsManifest } from 'vitest-package-exports'
4+
import yaml from 'yaml'
5+
6+
// TODO: remove this when you are ready for the first release
7+
const IS_READY = false
8+
9+
describe.runIf(IS_READY)('exports-snapshot', async () => {
10+
const packages: { name: string, path: string, private?: boolean }[] = JSON.parse(
11+
await x('pnpm', ['ls', '--only-projects', '-r', '--json']).then(r => r.stdout),
12+
)
13+
14+
for (const pkg of packages) {
15+
if (pkg.private)
16+
continue
17+
it(`${pkg.name}`, async () => {
18+
const manifest = await getPackageExportsManifest({
19+
importMode: 'src',
20+
cwd: pkg.path,
21+
})
22+
await expect(yaml.stringify(manifest.exports))
23+
.toMatchFileSnapshot(`./exports/${pkg.name}.yaml`)
24+
})
25+
}
26+
})

0 commit comments

Comments
 (0)