Skip to content

Commit 36de648

Browse files
committed
refactor(scripts): 使用npm包中的内容哈希替代本地版本文件比较
- 修改diff-hash脚本,改为与最新发布的npm包内容哈希比较 - 移除对本地usb.ids.version.json文件的依赖,避免循环依赖问题 - 新增check-version-update.ts脚本,专门用于GitHub Actions中版本更新检测 - 从unpkg CDN获取npm包版本信息,简化获取流程 - 保留错误处理和详细日志输出,确保流程透明且稳定 - 保持更新逻辑以内容哈希为准,提升变更检测准确性
1 parent c40f0f7 commit 36de648

File tree

3 files changed

+152
-50
lines changed

3 files changed

+152
-50
lines changed

scripts/README.md

Lines changed: 8 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,10 @@ This directory contains utility scripts for the USB.IDS project. Each script ser
66

77
### `diff-hash.ts`
88

9-
Compares content hashes between remote USB.IDS data and local processed data to determine if an update is needed. Designed for use in GitHub Actions workflow.
9+
Compares content hashes between remote USB.IDS data and the published npm package to determine if an update is needed. Designed for use in GitHub Actions workflow.
1010

1111
#### Purpose
12-
Determines whether the automated update workflow should proceed by comparing the content hash of remote USB.IDS data with the hash from the local version file. This approach avoids circular dependency logic and provides more reliable change detection.
12+
Determines whether the automated update workflow should proceed by comparing the content hash of remote USB.IDS data with the hash from the latest published npm package.
1313

1414
#### Usage
1515

@@ -23,33 +23,24 @@ tsx scripts/diff-hash.ts
2323

2424
#### What it does
2525

26-
1. Reads local version information from `usb.ids.version.json` file
27-
2. Downloads remote USB.IDS data from official sources using `downloadFromUrls()` from `src/fetcher.ts`
28-
3. Calculates content hash using `generateContentHash()` from `src/parser.ts`
29-
4. Compares the local and remote content hashes
26+
1. Downloads remote USB.IDS data from official sources using `downloadFromUrls()` from `src/fetcher.ts`
27+
2. Calculates content hash using `generateContentHash()` from `src/parser.ts`
28+
3. Fetches version information from the latest npm package
29+
4. Compares the content hashes
3030
5. Exits with appropriate exit codes for shell script integration
3131

32-
#### Comparison Strategy
33-
34-
- **Local baseline**: Uses the local `usb.ids.version.json` file as the comparison baseline
35-
- **Avoids circular logic**: No longer depends on npm package for version comparison
36-
- **First-run handling**: Automatically triggers update if no local version file exists
37-
- **Content-driven**: Only content changes trigger updates, not timestamps
38-
3932
#### Exit Codes
4033

4134
- **0**: No update needed (content hashes match)
42-
- **1**: Update needed (content hashes differ, no local version, or error occurred)
35+
- **1**: Update needed (content hashes differ or error occurred)
4336

4437
#### Key Features
4538

4639
- **Shell Integration**: Designed for use in GitHub Actions workflows
4740
- **Error Handling**: Gracefully handles network errors and missing data
48-
- **Code Reuse**: Leverages existing functions from `src/core.ts`, `src/fetcher.ts`, `src/parser.ts`, and `src/utils.ts`
49-
- **Functional Programming**: Uses pure functions and functional programming style
41+
- **Code Reuse**: Leverages existing functions from `src/fetcher.ts`, `src/parser.ts`, and `src/utils.ts`
5042
- **Detailed Logging**: Provides clear status messages for debugging
5143
- **Content-based Detection**: Uses SHA256 hash comparison for accurate change detection
52-
- **Consistent Logic**: Reuses `loadVersionInfo()` from core.ts for file operations
5344

5445
#### GitHub Actions Integration
5546

scripts/check-version-update.ts

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
#!/usr/bin/env tsx
2+
3+
/**
4+
* 版本更新检查脚本
5+
* 该脚本用于GitHub Actions工作流中,检查远程USB.IDS数据是否需要更新
6+
* 通过比较远程数据的contentHash与npm包中的contentHash来判断
7+
*/
8+
9+
import { USB_IDS_SOURCE } from '../src/config'
10+
import { downloadFromUrls } from '../src/fetcher'
11+
import { generateContentHash } from '../src/parser'
12+
import { logger } from '../src/utils'
13+
14+
interface NpmVersionInfo {
15+
contentHash: string
16+
version: string
17+
fetchTime: number
18+
}
19+
20+
/**
21+
* 获取npm包中的版本信息
22+
*/
23+
async function getNpmVersionInfo(): Promise<NpmVersionInfo | null> {
24+
try {
25+
// 尝试直接从unpkg CDN获取版本信息文件
26+
const versionUrl = 'https://unpkg.com/usb.ids@latest/usb.ids.version.json'
27+
const response = await fetch(versionUrl)
28+
29+
if (!response.ok) {
30+
logger.warn(`Failed to fetch version info from unpkg: ${response.status}`)
31+
return null
32+
}
33+
34+
const versionInfo = await response.json() as NpmVersionInfo
35+
logger.info(`NPM package version: ${versionInfo.version}`)
36+
return versionInfo
37+
}
38+
catch (error) {
39+
logger.warn(`Error fetching npm version info: ${(error as Error).message}`)
40+
return null
41+
}
42+
}
43+
44+
/**
45+
* 获取远程数据的contentHash
46+
*/
47+
async function getRemoteContentHash(): Promise<string | null> {
48+
try {
49+
logger.info('Downloading remote USB.IDS data...')
50+
const content = await downloadFromUrls(USB_IDS_SOURCE)
51+
52+
if (!content) {
53+
logger.warn('Failed to download remote USB.IDS data')
54+
return null
55+
}
56+
57+
const hash = generateContentHash(content)
58+
logger.info(`Remote content hash: ${hash}`)
59+
return hash
60+
}
61+
catch (error) {
62+
logger.warn(`Error downloading remote data: ${(error as Error).message}`)
63+
return null
64+
}
65+
}
66+
67+
/**
68+
* 主函数:检查是否需要更新
69+
*/
70+
async function checkVersionUpdate(): Promise<void> {
71+
try {
72+
logger.start('Checking if version update is needed...')
73+
74+
// 获取npm包版本信息
75+
const npmInfo = await getNpmVersionInfo()
76+
if (!npmInfo) {
77+
logger.info('No npm version info available, forcing update')
78+
process.exit(1) // 退出码1表示需要更新
79+
}
80+
81+
logger.info(`NPM package hash: ${npmInfo.contentHash}`)
82+
83+
// 获取远程数据hash
84+
const remoteHash = await getRemoteContentHash()
85+
if (!remoteHash) {
86+
logger.info('Failed to get remote hash, forcing update')
87+
process.exit(1) // 退出码1表示需要更新
88+
}
89+
90+
// 比较hash值
91+
if (remoteHash === npmInfo.contentHash) {
92+
logger.success('No update needed, content hash is the same')
93+
process.exit(0) // 退出码0表示不需要更新
94+
}
95+
else {
96+
logger.info('Update needed, content hash is different')
97+
logger.info(`Remote: ${remoteHash}`)
98+
logger.info(`NPM: ${npmInfo.contentHash}`)
99+
process.exit(1) // 退出码1表示需要更新
100+
}
101+
}
102+
catch (error) {
103+
logger.error(`Version check failed: ${(error as Error).message}`)
104+
process.exit(1) // 出错时也强制更新
105+
}
106+
}
107+
108+
// 当直接运行此脚本时执行检查
109+
if (import.meta.url === `file://${process.argv[1]}`) {
110+
checkVersionUpdate()
111+
}
112+
113+
export { checkVersionUpdate }

scripts/diff-hash.ts

Lines changed: 31 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -2,47 +2,46 @@
22

33
/**
44
* USB.IDS数据哈希差异检查脚本
5-
* 该脚本比较远程数据与本地已处理数据的contentHash来判断是否需要更新
6-
* 避免了使用npm包作为基准的循环逻辑问题
7-
* 复用core.ts中的现有函数以保持代码一致性
5+
* 该脚本用于GitHub Actions工作流中,通过比较远程数据与npm包中的contentHash来判断是否需要更新
86
*/
97

10-
import type { VersionInfo } from '../src/types'
11-
import * as path from 'node:path'
12-
import { USB_IDS_SOURCE, USB_IDS_VERSION_JSON_FILE } from '../src/config'
13-
import { loadVersionInfo } from '../src/core'
8+
import { USB_IDS_SOURCE } from '../src/config'
149
import { downloadFromUrls } from '../src/fetcher'
1510
import { generateContentHash } from '../src/parser'
1611
import { logger } from '../src/utils'
1712

13+
interface NpmVersionInfo {
14+
contentHash: string
15+
version: string
16+
fetchTime: number
17+
}
18+
1819
/**
19-
* 获取本地版本信息
20-
* 复用core.ts中的loadVersionInfo函数
20+
* 获取npm包中的版本信息
2121
*/
22-
function getLocalVersionInfo(): VersionInfo | null {
22+
async function getNpmVersionInfo(): Promise<NpmVersionInfo | null> {
2323
try {
24-
const versionFilePath = path.resolve(process.cwd(), USB_IDS_VERSION_JSON_FILE)
25-
const versionInfo = loadVersionInfo(versionFilePath)
24+
// 尝试直接从unpkg CDN获取版本信息文件
25+
const versionUrl = 'https://unpkg.com/usb.ids@latest/usb.ids.version.json'
26+
const response = await fetch(versionUrl)
2627

27-
if (!versionInfo) {
28-
logger.warn('Local version file does not exist')
28+
if (!response.ok) {
29+
logger.warn(`Failed to fetch version info from unpkg: ${response.status}`)
2930
return null
3031
}
3132

32-
logger.info(`Local version: ${versionInfo.version}`)
33-
logger.info(`Local hash: ${versionInfo.contentHash}`)
34-
33+
const versionInfo = await response.json() as NpmVersionInfo
34+
logger.info(`NPM package version: ${versionInfo.version}`)
3535
return versionInfo
3636
}
3737
catch (error) {
38-
logger.warn(`Error reading local version info: ${(error as Error).message}`)
38+
logger.warn(`Error fetching npm version info: ${(error as Error).message}`)
3939
return null
4040
}
4141
}
4242

4343
/**
4444
* 获取远程数据的contentHash
45-
* 复用fetcher.ts中的downloadFromUrls和parser.ts中的generateContentHash
4645
*/
4746
async function getRemoteContentHash(): Promise<string | null> {
4847
try {
@@ -65,38 +64,37 @@ async function getRemoteContentHash(): Promise<string | null> {
6564
}
6665

6766
/**
68-
* 主函数:比较本地与远程数据的哈希差异
69-
* 使用函数式编程风格,保持逻辑清晰简洁
67+
* 主函数:比较哈希差异
7068
*/
7169
async function diffHash(): Promise<void> {
7270
try {
73-
logger.start('Comparing local and remote content hashes...')
71+
logger.start('Comparing content hashes...')
7472

75-
// 获取本地版本信息(复用core.ts逻辑)
76-
const localInfo = getLocalVersionInfo()
73+
// 获取npm包版本信息
74+
const npmInfo = await getNpmVersionInfo()
75+
if (!npmInfo) {
76+
logger.info('No npm version info available, forcing update')
77+
process.exit(1) // 退出码1表示需要更新
78+
}
7779

78-
// 获取远程数据hash(复用fetcher和parser逻辑)
80+
logger.info(`NPM package hash: ${npmInfo.contentHash}`)
81+
82+
// 获取远程数据hash
7983
const remoteHash = await getRemoteContentHash()
8084
if (!remoteHash) {
8185
logger.info('Failed to get remote hash, forcing update')
8286
process.exit(1) // 退出码1表示需要更新
8387
}
8488

85-
// 如果没有本地版本信息,说明是首次运行,需要更新
86-
if (!localInfo) {
87-
logger.info('No local version info found, update needed for initial setup')
88-
process.exit(1) // 退出码1表示需要更新
89-
}
90-
9189
// 比较hash值
92-
if (remoteHash === localInfo.contentHash) {
90+
if (remoteHash === npmInfo.contentHash) {
9391
logger.success('No difference found, content hash is the same')
9492
process.exit(0) // 退出码0表示不需要更新
9593
}
9694
else {
9795
logger.info('Hash difference detected')
9896
logger.info(`Remote: ${remoteHash}`)
99-
logger.info(`Local: ${localInfo.contentHash}`)
97+
logger.info(`NPM: ${npmInfo.contentHash}`)
10098
process.exit(1) // 退出码1表示需要更新
10199
}
102100
}

0 commit comments

Comments
 (0)