治理:建立重构约束与中文注释门禁
This commit is contained in:
1 parent
2d8b319f53
commit
a642b02ec3
10 files changed
+131283
-2
No files matched your search
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -91,6 +91,151 @@ npm run dev
|
||||
|
||||
Vite proxies backend routes to `localhost:59188`. Production builds are written to `internal/webui/static/` and embedded by the Go server.
|
||||
|
||||
## Mandatory refactoring governance — DO NOT SKIP
|
||||
|
||||
The repository is following the authoritative long-term plan in
|
||||
`docs/architecture/refactoring-master-plan.md`. Before changing Go package boundaries, HTTP APIs, database
|
||||
access, account credentials, application wiring, React page structure, tests, CI or compatibility behavior,
|
||||
agents MUST read all of:
|
||||
|
||||
- `docs/architecture/refactoring-master-plan.md`
|
||||
- `docs/architecture/dependency-rules.md`
|
||||
- `docs/architecture/comment-standard.md`
|
||||
- `docs/slider-captcha-frozen-spec.md` when credentials, login, engine, account, server or browser call paths are involved
|
||||
|
||||
The following rules are mandatory:
|
||||
|
||||
1. Identify the current plan stage and the smallest applicable work item before editing. Do not perform a
|
||||
repository-wide rewrite or create a long-lived big-bang refactor.
|
||||
2. Preserve a compiling, runnable and tested state at every merge point. Add or strengthen characterization
|
||||
tests before moving high-risk behavior.
|
||||
3. Keep each change to one reviewable vertical slice. Do not combine broad file moves, behavior changes,
|
||||
schema migrations, compatibility deletion and mass comment backfill in the same change.
|
||||
4. Update the master plan status table, completion evidence, update log and next safe entry point whenever a
|
||||
plan work item is completed or its scope materially changes.
|
||||
5. Do not weaken, skip or delete tests to make a refactor pass. Existing test failures must be explained and
|
||||
resolved or reported as blockers.
|
||||
6. Preserve unrelated working-tree changes. Do not reformat or rename unrelated code as cleanup.
|
||||
7. Compatibility adapters remain until every known caller is migrated and contract tests prove the old path
|
||||
can be removed. New compatibility aliases require an explicit removal condition in the plan.
|
||||
|
||||
Emergency bug or security fixes may precede the planned sequence, but they must stay narrowly scoped, preserve
|
||||
the same architectural constraints, and add a note to the plan update log explaining why the sequence changed.
|
||||
|
||||
## Mandatory Chinese comments for all functions and variables
|
||||
|
||||
`docs/architecture/comment-standard.md` is authoritative. This requirement is intentionally stricter than
|
||||
normal Go exported-symbol documentation rules and applies to Go, TypeScript and TSX production and test code.
|
||||
|
||||
Agents MUST:
|
||||
|
||||
- add accurate Chinese comments for every new or modified function, method, anonymous function, parameter,
|
||||
return value, package/module variable, constant, field, local variable, short declaration, loop variable,
|
||||
callback parameter, React state value, setter, ref and memoized value;
|
||||
- explain all variables in a multi-variable declaration in one nearby comment when appropriate;
|
||||
- explain business meaning, input/output semantics, units, lifecycle, ownership, cancellation, concurrency,
|
||||
sensitivity or compatibility constraints instead of translating the identifier or restating syntax;
|
||||
- update comments in the same change whenever behavior or ownership changes;
|
||||
- clear historical comment-baseline entries for every file or logical unit materially refactored;
|
||||
- keep generated code, third-party code and `internal/webui/static` out of manual comment backfills.
|
||||
|
||||
Automated checks can prove only presence and Chinese text. Reviewers and agents remain responsible for semantic
|
||||
accuracy. Placeholder comments such as “err 表示错误” or “count 表示数量” are forbidden. Comments must never
|
||||
contain real Cookie, Token, password, SMTP credential or production secret values.
|
||||
|
||||
Until the historical baseline is removed, untouched legacy declarations may remain exempt, but no task may add
|
||||
new debt or use the baseline to exempt newly created or semantically modified declarations.
|
||||
|
||||
Run `make comments` (or `go run ./tools/commentlint -mode check -root . -baseline .commentlint/go-baseline.json`
|
||||
and `npm --prefix frontend run comments:check`) for the mandatory AST presence gate. Baseline regeneration is a
|
||||
reviewed maintenance operation only: use `make comments-baseline` after clearing the affected file's historical
|
||||
debt and record the scope in `docs/architecture/refactoring-master-plan.md`.
|
||||
|
||||
## Mandatory target dependency boundaries
|
||||
|
||||
`docs/architecture/dependency-rules.md` is authoritative. During migration, existing violations may remain only
|
||||
until their recorded vertical slice is completed; agents MUST NOT add new violations.
|
||||
|
||||
- `cmd` handles configuration, dependency construction, signals and lifecycle only; no new business rules, SQL,
|
||||
HTTP handlers or protocol parsing belong there.
|
||||
- `internal/server` is the HTTP/SPA transport. Do not add new direct `Store.DB`, transaction, MTOP, browser,
|
||||
credential-renewal, business-worker or platform-session logic. New use cases go through application services.
|
||||
- Application services own use-case orchestration, authorization and transaction boundaries and must not depend
|
||||
on `net/http`, chi or frontend compatibility fields.
|
||||
- Interfaces are defined by consumers and kept minimal. Do not add a service locator, universal repository
|
||||
interface or runtime setter for a required dependency.
|
||||
- `internal/db` owns SQL, dialects, migrations, encryption-at-rest and repository implementations. It must not
|
||||
import upper layers or decide HTTP responses.
|
||||
- `internal/xianyu` and `internal/browser` own platform and browser implementation. They must not write business
|
||||
data directly, decide automation rules or depend on the HTTP/application layer.
|
||||
- `internal/engine` and `internal/automation` must remain independent of Server. New mutable concurrent state
|
||||
requires explicit ownership, lock, Context, goroutine and shutdown documentation plus focused tests.
|
||||
- Cross-repository atomic work belongs behind an application-level Unit of Work. New handlers must not call
|
||||
`BeginTx` directly.
|
||||
|
||||
## Mandatory sensitive-data boundaries
|
||||
|
||||
- Account summaries and ownership checks MUST NOT read or decrypt Cookie, Token, password or encrypted metadata.
|
||||
- Platform credentials and password-login secrets use separate models and purpose-specific repository methods.
|
||||
- Sensitive persistence models MUST NOT be serialized as HTTP responses or frontend state.
|
||||
- Logs, notifications, API errors and test failure output MUST NOT contain plaintext credentials.
|
||||
- New ownership checks return existence/non-sensitive identity rather than maps of decrypted Cookie values.
|
||||
- Do not hold credential locks across slow external I/O unless an authoritative protocol invariant explicitly
|
||||
requires it and the lock order is documented and tested.
|
||||
|
||||
## Mandatory HTTP API constraints
|
||||
|
||||
- New APIs use the `/api/v1` prefix unless the current task is an explicit compatibility fix.
|
||||
- New request and response bodies use named DTOs. Do not add anonymous handler request structs, dynamic
|
||||
`map[string]any` response contracts or direct DB-model serialization.
|
||||
- New failures use the unified error envelope and correct HTTP status. Do not add HTTP 200 + `success:false` or
|
||||
new `detail`/`msg`/`error` aliases.
|
||||
- DB models, domain models and transport DTOs remain distinct. Compatibility normalization belongs only at the
|
||||
transport adapter boundary.
|
||||
- Route-prefix changes require `frontend/vite.config.ts`, frontend API callers, contract tests and embedded assets
|
||||
to be updated together.
|
||||
|
||||
## Mandatory React constraints
|
||||
|
||||
- New frontend code follows `app -> features -> shared`; a feature must not import another feature's internal
|
||||
files, and shared code must not import features.
|
||||
- React components must not call `fetch` or `axios` directly. Use the shared HTTP client through a feature API
|
||||
adapter; keep domain normalization out of the generic client.
|
||||
- Do not store derivable values in state. Put user-triggered side effects in event handlers, split effects with
|
||||
different dependencies, and use functional state updates when the next value depends on the previous value.
|
||||
- Every async effect or request must define cancellation or latest-generation behavior so stale responses cannot
|
||||
replace current state. Independent requests should start in parallel.
|
||||
- Do not add memoization without a concrete expensive calculation or stable-child-prop reason. Do not define
|
||||
child components inside parent components.
|
||||
- Keep server data, form state and transient UI state separate. Heavy pages and heavy optional dependencies use
|
||||
route/feature-level lazy loading where practical.
|
||||
- New or materially changed user flows require behavior tests for success, failure, cancellation, switching and
|
||||
stale responses. Source-string tests are reserved for static architecture rules.
|
||||
- Generated API types are read-only; feature adapters convert transport DTOs to UI models.
|
||||
|
||||
## Mandatory database, transaction and multi-dialect constraints
|
||||
|
||||
- Do not expose new raw `*sql.DB` access to upper layers. Add narrow repository methods or an explicit Unit of
|
||||
Work instead.
|
||||
- SQL row structs, persistence models, domain models and HTTP DTOs must not be collapsed into one convenience
|
||||
type when they have different sensitivity or ownership.
|
||||
- Every migration keeps SQLite, MySQL and PostgreSQL numbering and final schema aligned.
|
||||
- Database behavior changes require focused SQLite tests and, when available, MySQL/Postgres regression or
|
||||
`cmd/dbverify` evidence.
|
||||
- Repository/package splitting is permitted only after consumer interfaces and transaction boundaries are clear;
|
||||
directory count is not a goal and package cycles must not be hidden behind globals or reflection.
|
||||
|
||||
## Mandatory lifecycle and concurrency constraints
|
||||
|
||||
- Background goroutines require a documented owner, Context source, cancellation path and Wait/Join path.
|
||||
- Start methods must not make partially constructed objects observable. Stop/Close must be idempotent when the
|
||||
component contract allows repeated shutdown.
|
||||
- The sender closes a channel unless a more specific documented ownership rule applies.
|
||||
- Do not perform uncontrolled network, browser or user-wait I/O while holding a mutex.
|
||||
- Types with concurrent use must document which locks protect which fields and the allowed lock order.
|
||||
- Required dependencies are constructor inputs and validated before Start; mutable setters are only for optional
|
||||
runtime configuration or isolated tests and must not create an invalid intermediate production state.
|
||||
|
||||
## Desktop packaging and service behavior
|
||||
|
||||
The application defaults to port `59188`; commands using `-addr :59188` listen on all interfaces. Desktop
|
||||
@@ -176,6 +321,10 @@ the directory containing `install.sh`, `uninstall.sh`, the systemd unit, binarie
|
||||
|
||||
## Architecture
|
||||
|
||||
The following paragraphs describe the current runtime wiring. They are not permission to add more business
|
||||
logic to HTTP handlers. The mandatory target architecture and the allowed transition path are defined in
|
||||
`docs/architecture/refactoring-master-plan.md` and `docs/architecture/dependency-rules.md`.
|
||||
|
||||
`cmd/server/main.go` opens the database (SQLite/MySQL/Postgres by URL scheme), constructs the adapter + account manager + automation center + notifier, starts enabled account runtimes, initializes the optional in-process browser manager, and starts the HTTP server. Business logic does not live in `main.go` — it delegates to `internal/adapter` (Handler/OrderDetailFetcher wiring), `internal/engine`, `internal/account`, `internal/automation`, and domain-specific server handlers.
|
||||
|
||||
`internal/xianyu` owns lower-level platform integration:
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
GO ?= go
|
||||
GOLANGCI_LINT ?= golangci-lint
|
||||
|
||||
.PHONY: build build-int build-browser-install build-tray test test-int vet lint cover tidy frontend fmt check
|
||||
.PHONY: build build-int build-browser-install build-tray test test-int vet lint cover tidy frontend fmt comments comments-baseline check
|
||||
|
||||
## build: 编译 server(默认,跳过 integration build tag)
|
||||
build:
|
||||
@@ -53,5 +53,16 @@ tidy:
|
||||
frontend:
|
||||
cd frontend && npm ci && npm run build
|
||||
|
||||
## comments: 检查 Go 与 TypeScript/TSX 新增声明是否有中文注释
|
||||
comments:
|
||||
$(GO) run ./tools/commentlint -mode check -root . -baseline .commentlint/go-baseline.json
|
||||
node frontend/scripts/check-comments.mjs --mode check --root frontend --baseline .commentlint/frontend-baseline.json
|
||||
|
||||
## comments-baseline: 根据当前代码生成一次性历史问题基线(仅在审查后使用)
|
||||
comments-baseline:
|
||||
mkdir -p .commentlint
|
||||
$(GO) run ./tools/commentlint -mode baseline -root . -baseline .commentlint/go-baseline.json
|
||||
node frontend/scripts/check-comments.mjs --mode baseline --root frontend --baseline .commentlint/frontend-baseline.json
|
||||
|
||||
## check: 本地提交前全套检查(fmt + vet + lint + test)
|
||||
check: fmt vet lint test
|
||||
check: fmt vet lint test comments
|
||||
@@ -0,0 +1,163 @@
|
||||
# 全函数与全变量中文注释规范
|
||||
|
||||
## 1. 适用范围
|
||||
|
||||
本规范适用于仓库中的 Go、TypeScript 和 TSX 生产代码与测试代码。
|
||||
生成代码、第三方代码、`internal/webui/static` 构建产物和数据文件不在手工注释范围内。
|
||||
|
||||
所有新增或修改的声明必须立即满足本规范。历史代码通过注释检查基线渐进清理;
|
||||
每个重构阶段必须清除其负责文件内的历史注释债务,最终删除全部基线豁免。
|
||||
|
||||
## 2. 注释质量原则
|
||||
|
||||
注释必须至少解释下列一项实际信息:
|
||||
|
||||
- 业务职责或业务含义;
|
||||
- 输入、输出和错误语义;
|
||||
- 数据单位、格式、取值范围或默认值;
|
||||
- 生命周期、所有权、取消和释放责任;
|
||||
- 并发保护、锁顺序或 goroutine 责任;
|
||||
- 敏感数据的用途和禁止传播范围;
|
||||
- 兼容来源、删除条件或外部协议约束;
|
||||
- 采用某种实现而非直观实现的原因。
|
||||
|
||||
禁止只把标识符翻译成中文或复述语法。例如“err 表示错误”“count 表示数量”不合格;
|
||||
应说明是什么操作的错误、统计什么对象、单位是什么以及如何使用。
|
||||
|
||||
修改代码语义时必须同步更新相关注释。错误注释视为缺陷,不得以“已有注释”为由保留。
|
||||
|
||||
## 3. Go 规范
|
||||
|
||||
### 3.1 Package、类型和函数
|
||||
|
||||
- 每个 package 必须有唯一 package 注释;
|
||||
- 每个导出和未导出类型必须有中文注释;
|
||||
- 每个函数和方法必须有中文注释;
|
||||
- 导出标识符注释遵循 Go 文档约定,以标识符名称或可读主语开头;
|
||||
- 函数注释必须解释所有参数、返回值、主要副作用和错误语义;
|
||||
- 方法注释应说明 receiver 所代表对象以及是否可并发调用;
|
||||
- 匿名函数必须由变量注释或紧邻注释说明用途和回调参数。
|
||||
|
||||
### 3.2 变量与常量
|
||||
|
||||
以下声明必须有准确中文注释:
|
||||
|
||||
- package 级 `var` 与 `const`;
|
||||
- const block 中的每个语义不同成员;
|
||||
- 结构体字段;
|
||||
- 接口方法及参数;
|
||||
- 函数参数和命名返回值;
|
||||
- 局部 `var`;
|
||||
- `:=` 短变量声明;
|
||||
- `for`/`range` 的索引和值变量;
|
||||
- type switch、类型断言和 map 查询中的 `ok`;
|
||||
- 闭包捕获的状态变量;
|
||||
- 锁、Context、CancelFunc、WaitGroup、channel 和 timer。
|
||||
|
||||
同一条声明可以由一条注释分别解释全部变量:
|
||||
|
||||
```go
|
||||
// account 保存已通过所有权校验的账号摘要;queryErr 保存读取摘要时产生的数据库错误。
|
||||
account, queryErr := repository.GetSummary(ctx, accountID)
|
||||
```
|
||||
|
||||
循环变量必须说明当前遍历对象:
|
||||
|
||||
```go
|
||||
// rowIndex 表示导入文件中的数据行下标;row 保存当前待验证的订单数据。
|
||||
for rowIndex, row := range rows {
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
### 3.3 并发注释
|
||||
|
||||
包含锁或 goroutine 的类型和函数必须明确:
|
||||
|
||||
- 锁保护哪些字段;
|
||||
- 是否允许持锁调用外部 I/O;
|
||||
- 多个锁的获取顺序;
|
||||
- goroutine 由谁启动、取消和等待;
|
||||
- channel 的发送者、接收者和关闭者;
|
||||
- Context 的来源和取消责任;
|
||||
- Stop/Close 是否幂等。
|
||||
|
||||
### 3.4 敏感数据注释
|
||||
|
||||
Cookie、Token、密码、SMTP 凭证和远程滑块秘密必须标明:
|
||||
|
||||
- 值是否为明文;
|
||||
- 允许存在的最小作用域;
|
||||
- 是否允许日志记录或 JSON 序列化;
|
||||
- 由谁负责加密、解密和更新。
|
||||
|
||||
## 4. TypeScript 与 TSX 规范
|
||||
|
||||
### 4.1 函数和组件
|
||||
|
||||
- React 组件使用中文 JSDoc 说明页面或组件职责;
|
||||
- Hook 必须说明拥有的状态、执行的副作用、取消方式和返回值;
|
||||
- 事件处理器必须说明由什么用户操作触发以及成功后的状态变化;
|
||||
- 数据转换函数必须说明输入 DTO、输出 UI model 和兼容逻辑;
|
||||
- 回调函数的参数必须由紧邻注释解释;
|
||||
- `useEffect` 必须说明同步的外部系统和 cleanup 责任,不能只写“初始化”。
|
||||
|
||||
### 4.2 变量和状态
|
||||
|
||||
以下声明必须有准确中文注释:
|
||||
|
||||
- module 级 `const`/`let`;
|
||||
- 组件和函数内的 `const`/`let`;
|
||||
- `useState` 的状态值和 setter;
|
||||
- `useRef` 保存的临时值、DOM 或生命周期标记;
|
||||
- `useMemo` 的派生值及其昂贵原因;
|
||||
- `useCallback` 的用途;
|
||||
- 解构变量;
|
||||
- `map`、`filter`、`reduce` 等回调参数;
|
||||
- `catch` 错误变量;
|
||||
- 表单、请求、分页、轮询和 generation 状态。
|
||||
|
||||
同一条 Hook 声明可以共用一条注释:
|
||||
|
||||
```tsx
|
||||
/** accounts 保存账号摘要;setAccounts 只在当前请求仍为最新请求时替换列表。 */
|
||||
const [accounts, setAccounts] = useState<AccountSummary[]>([]);
|
||||
```
|
||||
|
||||
### 4.3 React 注释必须包含的特殊信息
|
||||
|
||||
- 异步请求是否可以取消;
|
||||
- 晚到响应如何防止覆盖新状态;
|
||||
- state 是服务端数据、表单数据还是短暂 UI 状态;
|
||||
- derived value 为什么需要或不需要 memo;
|
||||
- effect 的依赖和 cleanup 是否完整;
|
||||
- 敏感字段是否会进入浏览器状态。
|
||||
|
||||
## 5. 自动检查与人工审查
|
||||
|
||||
自动检查负责:
|
||||
|
||||
- 声明附近是否存在注释;
|
||||
- 注释是否包含中文;
|
||||
- 新增声明是否被历史基线错误豁免。
|
||||
|
||||
导出 Go 标识符的 doc comment 起始词、参数语义和并发/敏感数据说明由人工审查负责,后续可在不放宽中文门禁的前提下增加静态规则。
|
||||
|
||||
人工审查负责:
|
||||
|
||||
- 注释是否准确;
|
||||
- 是否解释实际语义而不是复述代码;
|
||||
- 并发、敏感性和兼容条件是否完整;
|
||||
- 代码变化后注释是否仍然成立。
|
||||
|
||||
PR 描述必须声明本次清理了哪些文件的注释基线,并列出仍保留的历史范围。
|
||||
|
||||
## 6. 禁止做法
|
||||
|
||||
- 禁止为了通过检查批量生成“变量 X 保存 X”一类注释;
|
||||
- 禁止用英文占位注释替代中文解释;
|
||||
- 禁止注释掉旧代码而不删除;
|
||||
- 禁止使用注释掩盖过长函数或错误抽象;
|
||||
- 禁止因补注释顺手修改无关行为;
|
||||
- 禁止修改生成文件来满足手工注释检查;
|
||||
- 禁止让注释泄露密码、Cookie、Token 或真实生产数据。
|
||||
@@ -0,0 +1,174 @@
|
||||
# 架构依赖与边界规则
|
||||
|
||||
## 1. 目的
|
||||
|
||||
本文定义重构期间和目标状态下的依赖方向。过渡期允许保留已有直接依赖,
|
||||
但禁止新增同类耦合;每个重构阶段必须减少而不是扩大例外。
|
||||
|
||||
## 2. 通用规则
|
||||
|
||||
- 接口由能力消费者定义,不在实现包中建立包含所有方法的万能接口;
|
||||
- 上层依赖抽象,下层实现抽象;
|
||||
- 不为消除 import 而创建没有业务语义的中转包;
|
||||
- 不允许全局 service locator;
|
||||
- 必需依赖在构造阶段提供并验证,不使用运行时 setter 回填;
|
||||
- package 不得因测试方便而导出生产不需要的内部状态;
|
||||
- 不允许通过 `any`、动态 map 或反射绕过清晰依赖。
|
||||
|
||||
## 3. Go 目标边界
|
||||
|
||||
### 3.1 `cmd`
|
||||
|
||||
允许:
|
||||
|
||||
- 读取配置和环境;
|
||||
- 构造日志、数据库和应用;
|
||||
- 处理系统信号;
|
||||
- 调用应用 Start/Run/Stop。
|
||||
|
||||
禁止新增:
|
||||
|
||||
- 业务规则;
|
||||
- SQL;
|
||||
- HTTP handler;
|
||||
- 平台协议解析;
|
||||
- 账号状态机。
|
||||
|
||||
### 3.2 `internal/server`
|
||||
|
||||
允许:
|
||||
|
||||
- 路由和 middleware;
|
||||
- 鉴权上下文;
|
||||
- 请求解析、验证和 DTO;
|
||||
- 调用应用服务;
|
||||
- HTTP/WebSocket transport;
|
||||
- SPA 静态资源。
|
||||
|
||||
目标状态禁止:
|
||||
|
||||
- 直接导入 `internal/db`;
|
||||
- 直接导入 `internal/xianyu` 或 `internal/browser`;
|
||||
- 调用 `BeginTx`;
|
||||
- 保存业务 worker、锁、cancel map 或平台会话状态;
|
||||
- 直接实现订单同步、商品发布、凭证续期或自动化动作。
|
||||
|
||||
过渡期已有依赖可以在对应纵向切片完成前保留,但不得新增新的直接调用点。
|
||||
|
||||
### 3.3 应用服务
|
||||
|
||||
允许:
|
||||
|
||||
- 编排一个完整用户用例;
|
||||
- 所有权校验;
|
||||
- 事务边界;
|
||||
- 调用领域服务和消费者定义的 port;
|
||||
- 将基础设施错误转换为应用错误。
|
||||
|
||||
禁止:
|
||||
|
||||
- 依赖 `http.Request`、`http.ResponseWriter` 或 chi;
|
||||
- 依赖 React/前端字段别名;
|
||||
- 拼装 SQL;
|
||||
- 直接读取环境变量;
|
||||
- 返回包含明文秘密的通用模型。
|
||||
|
||||
### 3.4 `internal/db`
|
||||
|
||||
允许:
|
||||
|
||||
- SQL、迁移、方言差异;
|
||||
- repository 实现;
|
||||
- 加密存储;
|
||||
- 事务实现;
|
||||
- 持久化查询模型。
|
||||
|
||||
禁止:
|
||||
|
||||
- 导入 server、应用服务、engine 或 automation;
|
||||
- 依赖 HTTP DTO;
|
||||
- 调用 MTOP、WebSocket 或 browser;
|
||||
- 决定用户可见错误消息;
|
||||
- 将敏感持久化模型直接暴露给 HTTP。
|
||||
|
||||
### 3.5 `internal/xianyu` 与 `internal/browser`
|
||||
|
||||
允许:
|
||||
|
||||
- 平台协议、传输和浏览器实现;
|
||||
- 返回平台级结果和错误分类;
|
||||
- 实现应用层或领域层定义的最小接口。
|
||||
|
||||
禁止:
|
||||
|
||||
- 导入 server;
|
||||
- 直接写业务数据库;
|
||||
- 决定自动化规则或 HTTP 状态;
|
||||
- 反向启动 account manager;
|
||||
- 绕过冻结滑块规范。
|
||||
|
||||
### 3.6 `internal/engine` 与 `internal/automation`
|
||||
|
||||
- Engine 负责单账号消息运行时,不负责 HTTP;
|
||||
- Automation 负责规则运行和动作语义,不负责 HTTP DTO;
|
||||
- 两者不得依赖 Server;
|
||||
- 新依赖必须通过最小接口注入;
|
||||
- 并发状态必须由明确组件拥有,禁止共享无边界的可变结构;
|
||||
- 外部动作必须保留幂等、checkpoint 和结果不确定语义。
|
||||
|
||||
## 4. 数据与秘密边界
|
||||
|
||||
- AccountSummary 不包含 Cookie、Token、密码或加密 metadata;
|
||||
- AccountCredential 只能进入平台调用和凭证更新流程;
|
||||
- AccountLoginSecret 只能进入密码登录或续期流程;
|
||||
- 所有权查询只能返回存在性或非敏感 ID;
|
||||
- HTTP DTO 不得引用敏感模型;
|
||||
- 日志、通知和错误响应不得包含秘密;
|
||||
- 测试失败输出不得打印完整秘密;
|
||||
- 锁住账号凭证期间不得执行未明确允许的慢外部 I/O。
|
||||
|
||||
## 5. API 边界
|
||||
|
||||
- 新 API 使用 `/api/v1`;
|
||||
- 新请求和响应必须使用具名 DTO;
|
||||
- 新错误使用统一错误 envelope;
|
||||
- 禁止新增 HTTP 200 + `success:false`;
|
||||
- 禁止新增 `value/cookie`、`remark/note` 一类双重字段;
|
||||
- 兼容字段只能在边界 adapter 中归一;
|
||||
- 删除兼容层必须有调用方迁移和契约测试证据。
|
||||
|
||||
## 6. React 边界
|
||||
|
||||
目标结构为 `app -> features -> shared`:
|
||||
|
||||
- `app` 负责 shell、路由和顶层认证;
|
||||
- feature 负责自己的页面、Hook、组件、API adapter 和类型;
|
||||
- shared 只包含真正跨 feature 的请求客户端、UI、Hook 和工具;
|
||||
- feature 不得导入另一个 feature 的内部文件;
|
||||
- shared 不得反向导入 feature;
|
||||
- 组件不得直接调用 `fetch` 或 `axios`;
|
||||
- 通用 HTTP client 不包含订单、账号等领域归一逻辑;
|
||||
- 生成 API 类型只读,UI model 由 feature adapter 创建;
|
||||
- 禁止通过大型 barrel 文件隐藏实际依赖。
|
||||
|
||||
## 7. 事务与生命周期边界
|
||||
|
||||
- 跨 repository 原子操作由应用服务通过 Unit of Work 执行;
|
||||
- handler 和 React 层不得控制数据库事务;
|
||||
- goroutine 必须有明确 owner、Context 和 Wait;
|
||||
- channel 只能由约定的发送方关闭;
|
||||
- Start 前不隐式运行后台任务;
|
||||
- Stop/Close 必须幂等;
|
||||
- 不得持锁等待无法控制的网络、浏览器或用户操作;
|
||||
- 凭证锁、自动化卡密锁和 worker 锁的顺序必须被注释和测试保护。
|
||||
|
||||
## 8. 自动门禁路线
|
||||
|
||||
门禁应按目标边界逐步启用:
|
||||
|
||||
1. 先禁止新增不允许依赖;
|
||||
2. 每迁移一个业务切片,删除对应例外;
|
||||
3. 最终使用 `go list` 或自定义 AST 检查完整依赖;
|
||||
4. 前端使用 TypeScript/ESLint import 限制;
|
||||
5. 架构例外必须记录负责人、原因和删除阶段;
|
||||
6. 禁止为了让门禁通过而把依赖藏进反射、动态 import 或 service locator。
|
||||
@@ -0,0 +1,454 @@
|
||||
# Ydisks 闲鱼助手渐进式重构总计划
|
||||
|
||||
## 1. 文档目的
|
||||
|
||||
本文是仓库后续结构治理的唯一长期路线图。任何涉及 Go 包边界、HTTP API、数据库访问、
|
||||
账号凭证、React 页面结构、测试基础设施或依赖装配的修改,都必须先阅读本文、
|
||||
`docs/architecture/dependency-rules.md` 与 `docs/architecture/comment-standard.md`。
|
||||
|
||||
本计划采用小步、可回滚的纵向切片,不允许建立一个长期脱离主分支的大型重构分支,
|
||||
也不允许在一个变更中同时完成大规模移动、行为修改、数据库迁移和兼容清理。
|
||||
|
||||
滑块 CAPTCHA 逻辑继续受 `docs/slider-captcha-frozen-spec.md` 保护;本计划不构成修改授权。
|
||||
|
||||
## 2. 当前问题基线
|
||||
|
||||
截至计划建立时,仓库具有良好的测试和工程化基础,但存在以下主要维护风险:
|
||||
|
||||
- `internal/server` 同时承担 HTTP、业务编排、MTOP 调用、事务、QR 会话和批量发布 worker 生命周期;
|
||||
- `internal/engine/account.go` 集中管理连接、凭证、重试、运行状态、去重、防抖和任务生命周期;
|
||||
- `internal/automation/center.go` 同时管理规则、运行、外部动作、卡密分配、凭证恢复和通知;
|
||||
- `internal/db.Store` 向上层暴露全部 repository 与裸 `*sql.DB`;
|
||||
- 账号列表和所有权检查会读取或解密超过实际需要的敏感字段;
|
||||
- HTTP 响应大量使用动态 map,错误结构和 API 路径不统一;
|
||||
- 前端存在多个 900 至 1800 行的页面组件,API 与类型集中在单文件;
|
||||
- 部分前端测试依赖源码字符串断言,难以保护真实交互;
|
||||
- CI 主要依附发布 workflow,尚未形成独立 PR 质量门禁;
|
||||
- server 测试重复执行全量 SQLite 迁移,使完整 race 测试耗时过高;
|
||||
- 历史代码尚未满足全函数、全变量准确中文注释要求。
|
||||
|
||||
## 3. 不变量与成功标准
|
||||
|
||||
重构期间必须持续满足以下不变量:
|
||||
|
||||
1. 每个合并点都能编译、启动并通过适用测试。
|
||||
2. 未经当前任务明确授权,不改变业务行为、API 兼容语义或冻结滑块行为。
|
||||
3. 敏感凭证不得扩大读取、传递、序列化或日志记录范围。
|
||||
4. SQLite、MySQL 和 PostgreSQL 的行为保持一致。
|
||||
5. 前端源码变化后必须重建并校验 `internal/webui/static`。
|
||||
6. 新增或修改的函数、变量、字段、参数和返回值必须符合中文注释规范。
|
||||
7. 每次完成一个计划步骤,都必须更新本文的状态、验证结果和后续入口。
|
||||
8. 不通过删除、跳过或放宽测试来完成重构。
|
||||
|
||||
最终成功标准:
|
||||
|
||||
- `internal/server` 只负责 HTTP、鉴权、中间件、DTO 映射和静态资源;
|
||||
- 应用服务负责业务用例和事务边界,不依赖 `net/http`;
|
||||
- handler 不直接访问 `Store.DB`、MTOP 或 browser;
|
||||
- 账号摘要、平台凭证、密码登录秘密和运行配置使用不同模型与查询;
|
||||
- HTTP API 使用具名 DTO、统一错误结构和统一版本前缀;
|
||||
- React 按 feature 组织,页面容器、数据 Hook、表单和视图组件职责分离;
|
||||
- `Account` 与 `Center` 成为 facade,内部状态由独立组件拥有;
|
||||
- PR CI、目标 race、多数据库和架构规则均为自动门禁;
|
||||
- Go 与 TypeScript/TSX 源码的中文注释基线清零。
|
||||
|
||||
## 4. 目标依赖方向
|
||||
|
||||
```text
|
||||
cmd/server
|
||||
├── application lifecycle
|
||||
└── HTTP server
|
||||
|
||||
HTTP server
|
||||
└── application services
|
||||
|
||||
application services
|
||||
├── domain/runtime services
|
||||
└── consumer-defined ports
|
||||
|
||||
db / xianyu / browser / notify
|
||||
└── implement consumer-defined ports
|
||||
```
|
||||
|
||||
前端目标方向:
|
||||
|
||||
```text
|
||||
app shell / routes
|
||||
└── feature pages
|
||||
├── feature hooks
|
||||
├── feature components
|
||||
└── feature API adapters
|
||||
└── shared HTTP client
|
||||
```
|
||||
|
||||
详细的允许与禁止依赖见 `docs/architecture/dependency-rules.md`。
|
||||
|
||||
## 5. 阶段状态总表
|
||||
|
||||
状态只允许使用:`未开始`、`进行中`、`已完成`、`阻塞`。
|
||||
|
||||
| 阶段 | 状态 | 目标 | 完成证据 |
|
||||
| --- | --- | --- | --- |
|
||||
| 0. 治理文档与强约束 | 已完成 | 总计划、依赖规则、注释规范、AGENTS 门禁、注释检查器 | 文档、门禁规则、Go/TypeScript 检查器和历史基线已落盘 |
|
||||
| 1. PR CI 与测试基础 | 未开始 | 独立 CI、测试 DB 模板、可执行 race | workflow 与测试耗时记录 |
|
||||
| 2. 敏感数据访问边界 | 未开始 | 摘要、凭证、登录秘密分离 | repository 与多数据库测试 |
|
||||
| 3. HTTP API 契约 | 未开始 | 统一错误、具名 DTO、版本化路径 | 契约测试与前端类型 |
|
||||
| 4. Server 应用服务 | 未开始 | 订单、发布、登录、聊天纵向抽取 | handler 不再直接编排基础设施 |
|
||||
| 5. 应用生命周期装配 | 未开始 | 消除必需依赖 setter 回填 | 构造验证与幂等关闭测试 |
|
||||
| 6. Engine 与 Automation | 未开始 | facade + 独立状态组件 | race、生命周期与冻结规范测试 |
|
||||
| 7. React Feature 化 | 未开始 | 页面、Hook、API、类型按领域拆分 | 行为测试、懒加载和 bundle 记录 |
|
||||
| 8. DB 与事务治理 | 未开始 | 窄接口、事务执行器、方言门禁 | 上层无裸 DB,多数据库回归 |
|
||||
| 9. 架构门禁与兼容清理 | 未开始 | 自动依赖规则、删除到期兼容层 | 架构检查与迁移说明 |
|
||||
| 10. 注释基线清零 | 未开始 | 全仓严格中文注释检查 | baseline 文件删除 |
|
||||
|
||||
### 当前执行入口
|
||||
|
||||
- 当前阶段:阶段 1“PR CI 与测试基础”;
|
||||
- 已完成:总计划、依赖规则、中文注释规范、`AGENTS.md` 强约束,以及 Go/TypeScript AST 注释检查器和历史基线;
|
||||
- 下一最小工作项:新增独立 PR CI,在合并前执行 Go/前端检查、注释门禁和嵌入式前端产物一致性校验;
|
||||
- 随后工作项:优化 server 测试数据库模板,再记录 race 分层结果;
|
||||
- 禁止跳过当前入口直接开始 Engine、Automation 或 DB 的大规模拆分。
|
||||
|
||||
## 6. 阶段 0:治理文档与强约束
|
||||
|
||||
### 工作项
|
||||
|
||||
- 创建本总计划;
|
||||
- 创建依赖边界规则;
|
||||
- 创建全函数、全变量中文注释规范;
|
||||
- 在 `AGENTS.md` 中加入必须阅读、必须更新和禁止绕过的规则;
|
||||
- 增加 Go AST 与 TypeScript AST 注释检查器和历史基线。
|
||||
|
||||
### 完成条件
|
||||
|
||||
- 所有长期约束均能从 `AGENTS.md` 链接到权威文档;
|
||||
- 后续任务可以明确指出所处阶段、工作项和适用验证;
|
||||
- 文档不与冻结滑块规范、打包规则或数据库规则冲突;
|
||||
- `make comments` 与 `npm --prefix frontend run comments:check` 能阻止不在历史基线中的新增声明缺少中文注释。
|
||||
|
||||
### 6.1 注释检查器落地说明
|
||||
|
||||
- `tools/commentlint` 使用 Go AST 检查函数、类型、常量、变量、结构体/接口字段、短变量和范围变量;
|
||||
- `frontend/scripts/check-comments.mjs` 使用 TypeScript Compiler API 检查变量、函数、方法、属性和函数表达式;
|
||||
- `.commentlint/go-baseline.json` 与 `.commentlint/frontend-baseline.json` 只记录当前历史债务,新增或修改声明不得通过追加基线绕过;
|
||||
- 基线使用文件、行号、类别和名称作为审查键。移动或重构文件时,必须清理对应文件的历史问题并重新生成基线;
|
||||
- 检查器只验证“邻近注释 + 至少一个汉字”,注释准确性、参数语义、并发和敏感数据说明仍由人工审查负责;
|
||||
- 注释债务按阶段逐文件清理,阶段 10 完成时删除两个基线文件并启用全仓零问题门禁。
|
||||
|
||||
## 7. 阶段 1:PR CI 与测试基础
|
||||
|
||||
### 1.1 独立 PR CI
|
||||
|
||||
新增 `.github/workflows/ci.yml`,在 pull request 以及 `main`、`dev` push 时执行:
|
||||
|
||||
- Go 格式只读检查;
|
||||
- `go vet ./...`;
|
||||
- `golangci-lint run ./...`;
|
||||
- `go test ./...`;
|
||||
- 中文注释检查;
|
||||
- `npm ci`、typecheck、test、build;
|
||||
- 嵌入式前端产物一致性检查。
|
||||
|
||||
发布 workflow 保持发布职责,不再作为唯一质量门禁。
|
||||
|
||||
### 1.2 Server 测试数据库模板
|
||||
|
||||
- 在测试入口迁移一次 SQLite 模板;
|
||||
- 每个测试复制模板到独立临时目录;
|
||||
- 测试之间不得共享可写数据库连接;
|
||||
- 关闭无必要的 Goose 测试日志;
|
||||
- 记录优化前后的普通测试和 race 时间。
|
||||
|
||||
### 1.3 Race 分层
|
||||
|
||||
普通 PR 先运行并发敏感包的目标 race;server fixture 优化后加入稳定的 server race 子集;
|
||||
全仓 race 可以进入 nightly。任何 race 报告都必须修复,不得加入忽略名单。
|
||||
|
||||
### 完成条件
|
||||
|
||||
- PR 在合并前获得稳定、独立的质量结果;
|
||||
- `internal/server` race 不再因重复迁移触发十分钟超时;
|
||||
- CI 不修改工作区后假装通过格式检查。
|
||||
|
||||
## 8. 阶段 2:敏感数据访问边界
|
||||
|
||||
### 2.1 模型拆分
|
||||
|
||||
建立互不混用的账号摘要、平台凭证、密码登录秘密和运行设置模型。
|
||||
|
||||
### 2.2 Repository 查询
|
||||
|
||||
增加用途明确的查询:
|
||||
|
||||
- `ListSummaries`;
|
||||
- `ListOwnedIDs`;
|
||||
- `ExistsOwned`;
|
||||
- `GetCredential`;
|
||||
- `GetLoginSecret`;
|
||||
- `GetRuntimeSettings`。
|
||||
|
||||
逐步替换使用 `AllForUser` 进行所有权检查以及使用 `GetDetails` 获取非敏感字段的调用。
|
||||
|
||||
### 2.3 安全不变量
|
||||
|
||||
- 列表和所有权检查不解密 Cookie、密码或 metadata;
|
||||
- 只有平台调用流程读取平台凭证;
|
||||
- 只有密码登录或续期流程读取登录秘密;
|
||||
- 敏感模型不得用作 HTTP DTO;
|
||||
- 敏感值不得写入普通日志、错误体或测试失败信息。
|
||||
|
||||
### 完成条件
|
||||
|
||||
- 账号列表没有 N+1 敏感查询;
|
||||
- 用户 ID `0` 不再表示隐式管理员查询;
|
||||
- 三种数据库的查询和并发测试通过。
|
||||
|
||||
## 9. 阶段 3:HTTP API 契约
|
||||
|
||||
### 3.1 统一错误结构
|
||||
|
||||
所有失败响应逐步统一为 `code`、`message` 和可选 `request_id`,并使用正确 HTTP 状态码。
|
||||
禁止新增 HTTP 200 + `success:false`,禁止新增 `detail`、`msg`、`error` 等新的错误别名。
|
||||
|
||||
### 3.2 具名 DTO
|
||||
|
||||
- handler 不新增匿名请求结构或动态 map 响应;
|
||||
- DB model 不直接作为 HTTP 响应;
|
||||
- API DTO 与领域模型显式转换;
|
||||
- 前端不新增 `Promise<any>` 或无边界 `Record<string, any>`。
|
||||
|
||||
### 3.3 版本化路径
|
||||
|
||||
新接口使用 `/api/v1`。旧接口以兼容别名保留,必须记录调用方、迁移步骤和删除条件。
|
||||
只有在前端和外部调用方全部迁移、契约测试覆盖后才能删除兼容路由。
|
||||
|
||||
### 3.4 类型生成
|
||||
|
||||
账号和订单 DTO 稳定后再引入 OpenAPI。生成文件不得手工修改;历史兼容归一只存在于边界 adapter。
|
||||
|
||||
## 10. 阶段 4:Server 应用服务
|
||||
|
||||
按订单、发布、账号登录、聊天/通知顺序纵向提取应用服务。每次只处理一个业务切片。
|
||||
|
||||
### 4.1 订单服务
|
||||
|
||||
应用服务负责列表、详情、更新、导入、同步、手工发货、所有权和事务;handler 只负责 DTO。
|
||||
|
||||
### 4.2 发布服务
|
||||
|
||||
应用服务负责单商品发布、预检、批量任务、恢复、取消、重试和关联自动化规则。
|
||||
完成后发布 worker、锁和 cancel map 不再属于 HTTP Server。
|
||||
|
||||
### 4.3 账号登录服务
|
||||
|
||||
应用服务负责 QR 会话所有权、结果持久化、资料刷新、Cookie 合并、账号重启和登录审计。
|
||||
完成后 QR 状态和持久化锁不再属于 HTTP Server。
|
||||
|
||||
### 4.4 聊天与通知
|
||||
|
||||
继续收紧已有服务的接口,使 handler 不再直接查询 Store 或调用平台客户端。
|
||||
|
||||
### 4.5 事务
|
||||
|
||||
跨 repository 事务由应用服务通过明确的 Unit of Work 执行。禁止 handler 调用 `BeginTx`。
|
||||
|
||||
### 完成条件
|
||||
|
||||
- `internal/server` 不直接访问 `Store.DB`;
|
||||
- handler 不直接调用 MTOP 或 browser;
|
||||
- 应用服务不依赖 `net/http`;
|
||||
- 业务分支由应用服务单元测试保护,HTTP 测试集中验证契约与鉴权。
|
||||
|
||||
## 11. 阶段 5:应用生命周期装配
|
||||
|
||||
应用服务边界稳定后建立应用装配与生命周期层:
|
||||
|
||||
- 构造所有服务并验证必需依赖;
|
||||
- 按明确顺序启动,按逆序关闭;
|
||||
- `Start` 前不得隐式启动 goroutine;
|
||||
- `Stop` 必须幂等并等待其拥有的 worker;
|
||||
- 必需依赖不得通过运行时 setter 回填;
|
||||
- 测试替换通过构造参数或 option 提供。
|
||||
|
||||
`cmd/server` 最终只处理配置、环境、日志、信号和应用启动。
|
||||
|
||||
## 12. 阶段 6:Engine 与 Automation
|
||||
|
||||
### 6.1 Engine
|
||||
|
||||
保留 `Account` facade,按纯策略、运行状态、WS 记录、去重、防抖、任务生命周期、凭证状态、
|
||||
连接循环的顺序提取。每个组件必须拥有自己的状态和锁,禁止只移动方法却继续共享整个 Account。
|
||||
|
||||
每个并发组件必须在中文注释中写明:
|
||||
|
||||
- 锁保护的字段;
|
||||
- 是否允许嵌套持锁;
|
||||
- 持锁时能否执行 I/O;
|
||||
- goroutine 的创建、取消和等待责任;
|
||||
- Stop 的幂等与等待语义。
|
||||
|
||||
### 6.2 Automation
|
||||
|
||||
逐步提取事件事实记录、规则匹配、运行协调、动作执行、发货、卡密分配、凭证门禁和结果通知。
|
||||
规则匹配不得隐式执行外部动作;外部动作必须区分未执行、已执行和结果不确定。
|
||||
|
||||
### 6.3 冻结边界
|
||||
|
||||
本阶段默认不修改任何冻结滑块文件,也不得通过调用方重构改变冻结行为。
|
||||
涉及凭证、连接或风控恢复时必须执行冻结规范规定的测试。
|
||||
|
||||
## 13. 阶段 7:React Feature 化
|
||||
|
||||
### 7.1 目标结构
|
||||
|
||||
按 `app`、`features`、`shared` 和 `generated` 分层。每个 feature 自有 API、类型、Hook、组件、页面和测试。
|
||||
禁止使用会隐藏依赖来源的大型 barrel export。
|
||||
|
||||
### 7.2 拆分顺序
|
||||
|
||||
按 `Rules`、`ItemList`、`AccountList`、`CardList`、`OrderList`、`Notifications`、
|
||||
`Dashboard`、`Settings`、`Chat` 的顺序拆分。
|
||||
|
||||
### 7.3 React 强约束
|
||||
|
||||
- 可由 props/state 计算的值不得重复存入 state;
|
||||
- 用户操作副作用放在事件处理器中,不使用 state + effect 间接触发;
|
||||
- 依赖不同的副作用拆成不同 effect;
|
||||
- 基于旧值更新必须使用函数式 setState;
|
||||
- 异步请求必须支持取消或 generation gate;
|
||||
- 独立请求应并行启动;
|
||||
- memo 只用于实际昂贵计算或稳定子组件输入;
|
||||
- 不在组件内部声明子组件;
|
||||
- 服务端数据、表单状态和短暂 UI 状态必须分开;
|
||||
- 重页面和重依赖使用 `lazy`/`Suspense` 按页面加载;
|
||||
- 组件不得直接调用 `fetch` 或 `axios`。
|
||||
|
||||
### 7.4 测试
|
||||
|
||||
关键流程使用行为测试覆盖成功、失败、取消、切换、过期响应和重复提交。
|
||||
源码字符串测试只保留真正的静态架构规则。
|
||||
|
||||
## 14. 阶段 8:DB 与事务治理
|
||||
|
||||
- 上层逐步改为持有窄 repository 接口,而不是完整 Store;
|
||||
- 上层不得访问裸 `*sql.DB`;
|
||||
- SQL 行结构、持久化模型、领域模型和 HTTP DTO 分离;
|
||||
- 是否拆物理 package 由稳定后的事务与依赖方向决定,不以目录数量为目标;
|
||||
- 三套迁移编号和关键 schema 自动校验;
|
||||
- 新迁移必须在 SQLite、MySQL、Postgres 上验证;
|
||||
- Credential 锁最终迁移到职责明确的凭证协调组件。
|
||||
|
||||
## 15. 阶段 9:架构门禁与兼容清理
|
||||
|
||||
目标结构稳定后加入自动检查:
|
||||
|
||||
- `internal/server` 禁止导入 `internal/db` 和 `internal/xianyu`;
|
||||
- `internal/db`、`internal/xianyu`、`internal/browser` 禁止导入上层应用包;
|
||||
- 前端 feature 禁止跨 feature 导入内部文件;
|
||||
- React 组件禁止直接调用网络客户端;
|
||||
- 到期兼容字段和路由必须先确认调用方为零,再删除;
|
||||
- 架构门禁只能约束目标结构,不得把过渡期错误依赖永久合法化。
|
||||
|
||||
## 16. 阶段 10:注释基线清零
|
||||
|
||||
注释治理贯穿所有阶段。最终阶段负责:
|
||||
|
||||
- 清理所有历史基线豁免;
|
||||
- 检查 Go 与 TypeScript/TSX 生产和测试源码;
|
||||
- 抽样审查注释准确性;
|
||||
- 确认注释描述的是职责、语义、单位、敏感性和并发约束,而非复述语法;
|
||||
- 将全仓严格检查加入 PR CI。
|
||||
|
||||
## 17. 推荐变更序列
|
||||
|
||||
1. 治理文档、AGENTS 强约束和注释基线工具;
|
||||
2. 独立 PR CI;
|
||||
3. server SQLite 测试模板与 race 优化;
|
||||
4. 前端行为测试基础;
|
||||
5. AccountSummary 与所有权查询;
|
||||
6. AccountCredential 与 AccountLoginSecret;
|
||||
7. 统一 API 错误;
|
||||
8. 账号 DTO 与版本化接口;
|
||||
9. 订单 DTO 与版本化接口;
|
||||
10. 前端 shared client 与 feature API;
|
||||
11. Rules 页面;
|
||||
12. ItemList 页面;
|
||||
13. 订单应用服务;
|
||||
14. 发布应用服务与 worker;
|
||||
15. 账号登录与 QR 服务;
|
||||
16. 应用生命周期装配;
|
||||
17. Automation 内部组件;
|
||||
18. Engine 纯策略与状态组件;
|
||||
19. Engine 连接与凭证组件;
|
||||
20. DB Store 与事务边界;
|
||||
21. 旧 API 和旧字段清理;
|
||||
22. 架构门禁与注释基线清零。
|
||||
|
||||
## 18. 每个变更的执行模板
|
||||
|
||||
开始前:
|
||||
|
||||
1. 在本文状态表中确认所属阶段;
|
||||
2. 写明本次改动的行为不变量;
|
||||
3. 列出涉及文件、风险、回滚方式和验证命令;
|
||||
4. 检查是否触及敏感凭证、多数据库、并发、前端产物或冻结滑块边界。
|
||||
|
||||
实施时:
|
||||
|
||||
1. 先补足或建立保护行为的测试;
|
||||
2. 一次只移动一个职责;
|
||||
3. 不顺手清理无关代码;
|
||||
4. 为所有新增或修改声明补准确中文注释;
|
||||
5. 保留兼容 adapter,直到调用方迁移完成。
|
||||
|
||||
完成时:
|
||||
|
||||
1. 执行适用验证矩阵;
|
||||
2. 检查工作区没有意外生成物;
|
||||
3. 更新本计划状态和完成证据;
|
||||
4. 记录下一步最小安全入口;
|
||||
5. 确认未放宽测试或安全边界。
|
||||
|
||||
## 19. 验证矩阵
|
||||
|
||||
所有 Go 修改至少执行:
|
||||
|
||||
```bash
|
||||
go vet ./...
|
||||
golangci-lint run ./...
|
||||
go test ./...
|
||||
```
|
||||
|
||||
并发和生命周期修改增加:
|
||||
|
||||
```bash
|
||||
go test -race ./internal/engine ./internal/account ./internal/automation ./internal/renewal ./internal/notify
|
||||
```
|
||||
|
||||
数据库修改增加:
|
||||
|
||||
```bash
|
||||
go test ./internal/db
|
||||
go run ./cmd/dbverify "sqlite:///tmp/xianyu-verify.db"
|
||||
```
|
||||
|
||||
并在可用环境执行 MySQL/Postgres 多数据库回归。
|
||||
|
||||
前端修改执行:
|
||||
|
||||
```bash
|
||||
npm --prefix frontend run typecheck
|
||||
npm --prefix frontend test
|
||||
npm --prefix frontend run build
|
||||
```
|
||||
|
||||
涉及凭证、登录、engine、account、server 或 browser 调用关系时,额外执行
|
||||
`docs/slider-captcha-frozen-spec.md` 中规定的测试,即使未直接修改受保护文件。
|
||||
|
||||
## 20. 计划更新记录
|
||||
|
||||
| 日期 | 变更 | 结果 | 下一步 |
|
||||
| --- | --- | --- | --- |
|
||||
| 2026-08-14 | 建立长期重构计划、依赖规则和中文注释规范 | 阶段 0 开始 | 将强约束接入 AGENTS,随后实现注释基线工具与独立 CI |
|
||||
| 2026-08-14 | 将计划治理、注释、依赖、敏感数据、API、React、数据库和并发规则接入 AGENTS | 后续任务已有强制入口 | 实现注释检查器和历史基线 |
|
||||
| 2026-08-14 | 落地 Go/TypeScript AST 注释检查器、Make 目标、npm 脚本和历史基线 | 阶段 0 完成;`make comments`、前端注释检查和 typecheck 通过 | 阶段 1.1:新增独立 PR CI |
|
||||
@@ -8,6 +8,8 @@
|
||||
"build": "vite build",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run",
|
||||
"comments:check": "node scripts/check-comments.mjs --mode check --root . --baseline ../.commentlint/frontend-baseline.json",
|
||||
"comments:baseline": "node scripts/check-comments.mjs --mode baseline --root . --baseline ../.commentlint/frontend-baseline.json",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
// check-comments 检查 TypeScript/TSX 声明是否带有准确的中文注释。
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import process from "node:process";
|
||||
import ts from "typescript";
|
||||
|
||||
// HAN_PATTERN 用于识别至少包含一个汉字的注释文本。
|
||||
const HAN_PATTERN = /\p{Script=Han}/u;
|
||||
|
||||
// parseArguments 解析注释门禁所需的少量命令行参数。
|
||||
function parseArguments(argv) {
|
||||
// options 保存命令行参数及其默认值。
|
||||
const options = {
|
||||
mode: "check",
|
||||
root: ".",
|
||||
baseline: ".commentlint/frontend-baseline.json",
|
||||
};
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
// argument 是当前处理的命令行参数。
|
||||
const argument = argv[index];
|
||||
if (argument === "--mode" || argument === "--root" || argument === "--baseline") {
|
||||
// value 是当前选项紧随其后的值。
|
||||
const value = argv[index + 1];
|
||||
if (!value) {
|
||||
throw new Error(`${argument} 缺少参数值`);
|
||||
}
|
||||
options[argument.slice(2)] = value;
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
if (options.mode !== "check" && options.mode !== "baseline") {
|
||||
throw new Error(`不支持的模式:${options.mode}`);
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
// collectSourceFiles 递归找到需要检查的 TypeScript 和 TSX 源文件。
|
||||
function collectSourceFiles(rootDirectory) {
|
||||
// sourceFiles 保存按路径排序后的源码文件。
|
||||
const sourceFiles = [];
|
||||
// visit 递归遍历单个目录并跳过依赖与构建产物。
|
||||
function visit(directory) {
|
||||
// entries 是当前目录的文件系统条目。
|
||||
const entries = fs.readdirSync(directory, { withFileTypes: true });
|
||||
for (const entry of entries) {
|
||||
// absolutePath 是当前条目的绝对路径。
|
||||
const absolutePath = path.join(directory, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
if (["node_modules", "dist", "coverage", "generated"].includes(entry.name)) {
|
||||
continue;
|
||||
}
|
||||
visit(absolutePath);
|
||||
continue;
|
||||
}
|
||||
if (entry.isFile() && /\.(ts|tsx)$/.test(entry.name) && !entry.name.endsWith(".d.ts")) {
|
||||
sourceFiles.push(absolutePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
visit(rootDirectory);
|
||||
return sourceFiles.sort();
|
||||
}
|
||||
|
||||
// getCommentAnchor 返回声明对应的语句节点,确保变量前的注释能够覆盖每个声明项。
|
||||
function getCommentAnchor(node) {
|
||||
if (ts.isVariableDeclaration(node)) {
|
||||
// variableStatement 是变量声明所在的完整语句节点。
|
||||
const variableStatement = node.parent?.parent;
|
||||
if (variableStatement && ts.isVariableStatement(variableStatement)) {
|
||||
return variableStatement;
|
||||
}
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
// hasChineseComment 判断声明前方或同一行尾部是否存在中文注释。
|
||||
function hasChineseComment(sourceFile, node) {
|
||||
// anchor 是真正承载注释的声明或语句节点。
|
||||
const anchor = getCommentAnchor(node);
|
||||
// sourceText 是当前文件的原始文本,用于读取注释范围。
|
||||
const sourceText = sourceFile.getFullText();
|
||||
// startLine 是声明起始位置所在的零基行号。
|
||||
const startLine = sourceFile.getLineAndCharacterOfPosition(anchor.getStart(sourceFile)).line;
|
||||
// leadingRanges 是声明前方的注释范围。
|
||||
const leadingRanges = ts.getLeadingCommentRanges(sourceText, anchor.getFullStart()) ?? [];
|
||||
for (const range of leadingRanges) {
|
||||
// commentEndLine 是注释末尾所在的零基行号。
|
||||
const commentEndLine = sourceFile.getLineAndCharacterOfPosition(range.end).line;
|
||||
if (commentEndLine <= startLine && commentEndLine >= startLine - 1 && HAN_PATTERN.test(sourceText.slice(range.pos, range.end))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
// trailingRanges 允许同一行的行尾注释为短小声明提供说明。
|
||||
const trailingRanges = ts.getTrailingCommentRanges(sourceText, anchor.end) ?? [];
|
||||
return trailingRanges.some((range) => {
|
||||
// commentStartLine 是行尾注释起始所在的零基行号。
|
||||
const commentStartLine = sourceFile.getLineAndCharacterOfPosition(range.pos).line;
|
||||
return commentStartLine === startLine && HAN_PATTERN.test(sourceText.slice(range.pos, range.end));
|
||||
});
|
||||
}
|
||||
|
||||
// getNodeName 返回 AST 节点的可读名称。
|
||||
function getNodeName(node) {
|
||||
if (node.name) {
|
||||
return node.name.getText();
|
||||
}
|
||||
if (ts.isParameter(node) && node.name) {
|
||||
return node.name.getText();
|
||||
}
|
||||
return "anonymous";
|
||||
}
|
||||
|
||||
// findingFor 将一个 AST 节点转换成稳定的基线记录。
|
||||
function findingFor(relativePath, sourceFile, node, kind) {
|
||||
// line 是声明所在的一基行号。
|
||||
const line = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
|
||||
return { file: relativePath, line, kind, name: getNodeName(node) };
|
||||
}
|
||||
|
||||
// inspectSourceFile 遍历一个文件并收集缺少中文注释的声明。
|
||||
function inspectSourceFile(rootDirectory, filePath) {
|
||||
// sourceText 是待解析文件内容。
|
||||
const sourceText = fs.readFileSync(filePath, "utf8");
|
||||
// sourceFile 是开启父节点信息的 TypeScript AST。
|
||||
const sourceFile = ts.createSourceFile(filePath, sourceText, ts.ScriptTarget.Latest, true, filePath.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
|
||||
// relativePath 使基线在不同机器上保持可复用。
|
||||
const relativePath = path.relative(rootDirectory, filePath).split(path.sep).join("/");
|
||||
// findings 保存当前文件的注释问题。
|
||||
const findings = [];
|
||||
// visit 递归检查支持注释的声明节点。
|
||||
function visit(node) {
|
||||
// shouldCheckArrow 表示当前函数表达式没有被变量声明注释覆盖。
|
||||
const shouldCheckArrow = (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) && !ts.isVariableDeclaration(node.parent);
|
||||
if (ts.isVariableDeclaration(node) && !hasChineseComment(sourceFile, node)) {
|
||||
findings.push(findingFor(relativePath, sourceFile, node, "variable"));
|
||||
} else if (ts.isFunctionDeclaration(node) && !hasChineseComment(sourceFile, node)) {
|
||||
findings.push(findingFor(relativePath, sourceFile, node, "function"));
|
||||
} else if ((ts.isMethodDeclaration(node) || ts.isMethodSignature(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node)) && !hasChineseComment(sourceFile, node)) {
|
||||
findings.push(findingFor(relativePath, sourceFile, node, "member"));
|
||||
} else if (shouldCheckArrow && !hasChineseComment(sourceFile, node)) {
|
||||
findings.push(findingFor(relativePath, sourceFile, node, "function-expression"));
|
||||
}
|
||||
ts.forEachChild(node, visit);
|
||||
}
|
||||
visit(sourceFile);
|
||||
return findings;
|
||||
}
|
||||
|
||||
// findingKey 生成历史基线中的稳定键。
|
||||
function findingKey(finding) {
|
||||
return `${finding.file}:${finding.line}:${finding.kind}:${finding.name}`;
|
||||
}
|
||||
|
||||
// sortFindings 按文件、行号、类别和名称对结果排序。
|
||||
function sortFindings(findings) {
|
||||
return findings.sort((left, right) => findingKey(left).localeCompare(findingKey(right)));
|
||||
}
|
||||
|
||||
// writeBaseline 写入缩进格式的前端历史问题基线。
|
||||
function writeBaseline(filePath, findings) {
|
||||
// parentDirectory 是基线文件所属目录。
|
||||
const parentDirectory = path.dirname(filePath);
|
||||
fs.mkdirSync(parentDirectory, { recursive: true });
|
||||
fs.writeFileSync(filePath, `${JSON.stringify(findings, null, 2)}\n`, "utf8");
|
||||
}
|
||||
|
||||
// readBaseline 读取历史问题并建立快速查询集合。
|
||||
function readBaseline(filePath) {
|
||||
// baselineText 是基线文件的 JSON 文本。
|
||||
const baselineText = fs.readFileSync(filePath, "utf8");
|
||||
// baselineFindings 是反序列化后的历史问题数组。
|
||||
const baselineFindings = JSON.parse(baselineText);
|
||||
return new Set(baselineFindings.map(findingKey));
|
||||
}
|
||||
|
||||
// main 执行前端源码扫描、基线生成或新增问题检查。
|
||||
function main() {
|
||||
// options 保存解析后的命令行选项。
|
||||
const options = parseArguments(process.argv.slice(2));
|
||||
// rootDirectory 是规范化后的源码根目录。
|
||||
const rootDirectory = path.resolve(options.root);
|
||||
// baselinePath 是规范化后的历史基线路径。
|
||||
const baselinePath = path.resolve(options.baseline);
|
||||
// findings 是当前所有 TypeScript/TSX 文件的检查结果。
|
||||
const findings = sortFindings(collectSourceFiles(rootDirectory).flatMap((filePath) => inspectSourceFile(rootDirectory, filePath)));
|
||||
if (options.mode === "baseline") {
|
||||
writeBaseline(baselinePath, findings);
|
||||
console.log(`commentlint: 已记录 ${findings.length} 个历史问题到 ${options.baseline}`);
|
||||
return;
|
||||
}
|
||||
// baselineKeys 保存允许继续存在的历史问题。
|
||||
const baselineKeys = readBaseline(baselinePath);
|
||||
// newFindings 只包含本次新增或位置变化的问题。
|
||||
const newFindings = findings.filter((finding) => !baselineKeys.has(findingKey(finding)));
|
||||
for (const finding of newFindings) {
|
||||
console.log(`${finding.file}:${finding.line}: [${finding.kind}] ${finding.name} 缺少中文注释`);
|
||||
}
|
||||
if (newFindings.length > 0) {
|
||||
throw new Error(`发现 ${newFindings.length} 个新增问题`);
|
||||
}
|
||||
console.log(`commentlint: 通过(扫描 ${findings.length} 个历史问题)`);
|
||||
}
|
||||
|
||||
try {
|
||||
main();
|
||||
} catch (error) {
|
||||
console.error(`commentlint: ${error instanceof Error ? error.message : String(error)}`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
// commentlint 检查 Go 源码是否为新增或修改的声明提供了准确的中文注释。
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
// Finding 描述一个缺少中文注释的 Go 声明。
|
||||
type Finding struct {
|
||||
// File 是相对于检查根目录的源码路径。
|
||||
File string `json:"file"`
|
||||
// Line 是声明在源码中的起始行号。
|
||||
Line int `json:"line"`
|
||||
// Kind 是声明类别,例如 function、variable 或 field。
|
||||
Kind string `json:"kind"`
|
||||
// Name 是声明名称,匿名声明使用 anonymous。
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
// main 根据命令行模式生成历史基线或检查当前源码。
|
||||
func main() {
|
||||
// modeFlag 表示本次运行是生成基线还是执行门禁检查。
|
||||
modeFlag := flag.String("mode", "check", "运行模式:check 或 baseline")
|
||||
// rootFlag 指定需要递归扫描的仓库根目录。
|
||||
rootFlag := flag.String("root", ".", "源码扫描根目录")
|
||||
// baselineFlag 指定保存或读取历史问题基线的 JSON 文件。
|
||||
baselineFlag := flag.String("baseline", ".commentlint/go-baseline.json", "历史问题基线文件")
|
||||
flag.Parse()
|
||||
|
||||
// findings 保存本次扫描发现的全部缺少中文注释项。
|
||||
findings, err := collectFindings(*rootFlag)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "commentlint: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// sortFindings 保证基线内容和门禁输出在不同机器上保持稳定顺序。
|
||||
sortFindings(findings)
|
||||
if *modeFlag == "baseline" {
|
||||
// writeErr 保存写入历史基线时的文件系统错误。
|
||||
if err := writeBaseline(*baselineFlag, findings); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "commentlint: 写入基线失败:%v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
fmt.Printf("commentlint: 已记录 %d 个历史问题到 %s\n", len(findings), *baselineFlag)
|
||||
return
|
||||
}
|
||||
if *modeFlag != "check" {
|
||||
fmt.Fprintf(os.Stderr, "commentlint: 不支持的模式 %q\n", *modeFlag)
|
||||
os.Exit(2)
|
||||
}
|
||||
|
||||
// baseline 保存允许继续存在的历史问题,不允许新增问题混入主干。
|
||||
baseline, err := readBaseline(*baselineFlag)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "commentlint: 读取基线失败:%v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
// newFindings 只保留不在历史基线中的新增问题。
|
||||
newFindings := filterNewFindings(findings, baseline)
|
||||
// finding 表示当前待输出的一条新增注释问题。
|
||||
for _, finding := range newFindings {
|
||||
fmt.Printf("%s:%d: [%s] %s 缺少中文注释\n", finding.File, finding.Line, finding.Kind, finding.Name)
|
||||
}
|
||||
if len(newFindings) > 0 {
|
||||
fmt.Fprintf(os.Stderr, "commentlint: 发现 %d 个新增问题\n", len(newFindings))
|
||||
os.Exit(1)
|
||||
}
|
||||
fmt.Printf("commentlint: 通过(扫描 %d 个历史问题)\n", len(findings))
|
||||
}
|
||||
|
||||
// collectFindings 递归解析根目录下所有 Go 文件并收集缺少中文注释的声明。
|
||||
func collectFindings(root string) ([]Finding, error) {
|
||||
// findings 汇总所有文件的检查结果。
|
||||
findings := make([]Finding, 0)
|
||||
// walkErr 保存遍历过程中遇到的第一个错误。
|
||||
walkErr := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if info.IsDir() {
|
||||
if shouldSkipDirectory(path, root) {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, ".gen.go") {
|
||||
return nil
|
||||
}
|
||||
// fileFindings 是当前文件的问题;parseErr 表示 AST 解析失败的原因。
|
||||
fileFindings, parseErr := inspectGoFile(root, path)
|
||||
if parseErr != nil {
|
||||
return parseErr
|
||||
}
|
||||
findings = append(findings, fileFindings...)
|
||||
return nil
|
||||
})
|
||||
if walkErr != nil {
|
||||
return nil, walkErr
|
||||
}
|
||||
return findings, nil
|
||||
}
|
||||
|
||||
// shouldSkipDirectory 判断目录是否为依赖、构建产物或运行时数据目录。
|
||||
func shouldSkipDirectory(path, root string) bool {
|
||||
// relativePath 用统一的分隔符表达目录,避免跨平台判断差异。
|
||||
relativePath, err := filepath.Rel(root, path)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
// ignoredNames 是不属于业务源码、不能进入注释门禁的目录集合。
|
||||
ignoredNames := map[string]bool{
|
||||
".git": true, "vendor": true, "node_modules": true, "dist": true,
|
||||
"browser_data": true, "data": true, "internal/webui/static": true,
|
||||
}
|
||||
if ignoredNames[relativePath] {
|
||||
return true
|
||||
}
|
||||
// ignoredPath 表示当前检查的被忽略目录前缀。
|
||||
for ignoredPath := range ignoredNames {
|
||||
if strings.HasPrefix(relativePath, ignoredPath+string(filepath.Separator)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// inspectGoFile 解析单个 Go 文件并返回其中缺少中文注释的声明。
|
||||
func inspectGoFile(root, path string) ([]Finding, error) {
|
||||
// fileSet 保存 AST 位置到源码行号的映射。
|
||||
fileSet := token.NewFileSet()
|
||||
// fileNode 是当前文件的语法树和注释信息。
|
||||
fileNode, err := parser.ParseFile(fileSet, path, nil, parser.ParseComments)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("解析 %s 失败:%w", path, err)
|
||||
}
|
||||
// relativePath 让基线不依赖开发者本机的绝对路径。
|
||||
relativePath, err := filepath.Rel(root, path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// findings 保存当前文件的检查结果。
|
||||
findings := make([]Finding, 0)
|
||||
// nodeStack 用于判断字段属于结构体/接口,还是函数参数/返回值。
|
||||
nodeStack := make([]ast.Node, 0)
|
||||
ast.Inspect(fileNode, func(node ast.Node) bool {
|
||||
if node == nil {
|
||||
nodeStack = nodeStack[:len(nodeStack)-1]
|
||||
return true
|
||||
}
|
||||
// parent 是当前 AST 节点的直接父节点,用于识别结构体或接口字段。
|
||||
var parent ast.Node
|
||||
if len(nodeStack) > 0 {
|
||||
parent = nodeStack[len(nodeStack)-1]
|
||||
}
|
||||
// current 是经过类型断言后的具体 AST 节点。
|
||||
switch current := node.(type) {
|
||||
case *ast.FuncDecl:
|
||||
if !hasChineseComment(fileNode, fileSet, current) {
|
||||
findings = append(findings, newFinding(relativePath, fileSet, current, "function", funcName(current.Name)))
|
||||
}
|
||||
case *ast.GenDecl:
|
||||
// spec 表示当前声明块中的一条常量、变量或类型规范。
|
||||
for _, spec := range current.Specs {
|
||||
checkSpec(fileNode, fileSet, relativePath, current, spec, &findings)
|
||||
}
|
||||
case *ast.Field:
|
||||
// isStruct 表示字段是否属于结构体定义。
|
||||
if _, isStruct := parent.(*ast.StructType); isStruct {
|
||||
checkField(fileNode, fileSet, relativePath, current, &findings)
|
||||
}
|
||||
// isInterface 表示字段是否属于接口定义。
|
||||
if _, isInterface := parent.(*ast.InterfaceType); isInterface {
|
||||
checkField(fileNode, fileSet, relativePath, current, &findings)
|
||||
}
|
||||
case *ast.AssignStmt:
|
||||
if current.Tok == token.DEFINE {
|
||||
checkIdentifiers(fileNode, fileSet, relativePath, current, current.Lhs, "local-variable", &findings)
|
||||
}
|
||||
case *ast.RangeStmt:
|
||||
checkIdentifiers(fileNode, fileSet, relativePath, current, []ast.Expr{current.Key, current.Value}, "range-variable", &findings)
|
||||
}
|
||||
nodeStack = append(nodeStack, node)
|
||||
return true
|
||||
})
|
||||
return findings, nil
|
||||
}
|
||||
|
||||
// checkSpec 检查常量、变量、类型声明及其名称是否有中文注释。
|
||||
func checkSpec(fileNode *ast.File, fileSet *token.FileSet, relativePath string, declaration *ast.GenDecl, spec ast.Spec, findings *[]Finding) {
|
||||
// kind 用于把 Go 声明映射到可读的门禁错误类别。
|
||||
kind := strings.ToLower(declaration.Tok.String())
|
||||
// current 是当前规范的具体 AST 类型。
|
||||
switch current := spec.(type) {
|
||||
case *ast.ValueSpec:
|
||||
// name 表示常量或变量规范中的一个绑定名称。
|
||||
for _, name := range current.Names {
|
||||
if name.Name == "_" || hasChineseComment(fileNode, fileSet, current) {
|
||||
continue
|
||||
}
|
||||
*findings = append(*findings, newFinding(relativePath, fileSet, current, kind, name.Name))
|
||||
}
|
||||
case *ast.TypeSpec:
|
||||
if !hasChineseComment(fileNode, fileSet, current) {
|
||||
*findings = append(*findings, newFinding(relativePath, fileSet, current, "type", current.Name.Name))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// checkField 检查结构体和接口字段,匿名字段以其类型名作为声明名称。
|
||||
func checkField(fileNode *ast.File, fileSet *token.FileSet, relativePath string, field *ast.Field, findings *[]Finding) {
|
||||
if hasChineseComment(fileNode, fileSet, field) {
|
||||
return
|
||||
}
|
||||
// names 保存显式字段名;匿名字段没有 Names,需要使用类型文本兜底。
|
||||
names := make([]string, 0, len(field.Names))
|
||||
// name 表示结构体或接口字段中的一个显式名称。
|
||||
for _, name := range field.Names {
|
||||
names = append(names, name.Name)
|
||||
}
|
||||
if len(names) == 0 {
|
||||
names = append(names, "anonymous")
|
||||
}
|
||||
// name 表示已经归一化后的字段名称。
|
||||
for _, name := range names {
|
||||
*findings = append(*findings, newFinding(relativePath, fileSet, field, "field", name))
|
||||
}
|
||||
}
|
||||
|
||||
// checkIdentifiers 检查短变量声明或范围变量中的每个有效标识符。
|
||||
func checkIdentifiers(fileNode *ast.File, fileSet *token.FileSet, relativePath string, node ast.Node, expressions []ast.Expr, kind string, findings *[]Finding) {
|
||||
if hasChineseComment(fileNode, fileSet, node) {
|
||||
return
|
||||
}
|
||||
// expression 表示短变量或范围变量绑定列表中的一个表达式。
|
||||
for _, expression := range expressions {
|
||||
// identifier 是表达式对应的变量名;ok 表示表达式是否确实是标识符。
|
||||
identifier, ok := expression.(*ast.Ident)
|
||||
if !ok || identifier.Name == "_" {
|
||||
continue
|
||||
}
|
||||
*findings = append(*findings, newFinding(relativePath, fileSet, node, kind, identifier.Name))
|
||||
}
|
||||
}
|
||||
|
||||
// hasChineseComment 判断声明附近是否存在包含汉字的文档或行注释。
|
||||
func hasChineseComment(fileNode *ast.File, fileSet *token.FileSet, node ast.Node) bool {
|
||||
// startLine 和 endLine 限制注释必须紧邻声明,避免误认远处说明。
|
||||
startLine := fileSet.Position(node.Pos()).Line
|
||||
// endLine 是声明末尾所在的行,用于允许同一声明范围内的尾部注释。
|
||||
endLine := fileSet.Position(node.End()).Line
|
||||
// group 表示当前文件中的一组连续注释。
|
||||
for _, group := range fileNode.Comments {
|
||||
// commentStart 和 commentEnd 是注释组的首尾行。
|
||||
commentStart := fileSet.Position(group.Pos()).Line
|
||||
// commentEnd 是注释组末尾所在的行。
|
||||
commentEnd := fileSet.Position(group.End()).Line
|
||||
if commentEnd > startLine || commentStart < startLine-1 {
|
||||
continue
|
||||
}
|
||||
if commentStart == startLine || commentEnd == startLine-1 || commentStart <= endLine && commentEnd >= startLine {
|
||||
if containsChinese(group.Text()) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// containsChinese 判断文本中是否至少包含一个汉字。
|
||||
func containsChinese(text string) bool {
|
||||
// character 是待检查文本中的一个 Unicode 字符。
|
||||
for _, character := range text {
|
||||
if unicode.Is(unicode.Han, character) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// newFinding 将 AST 节点转换成稳定的基线记录。
|
||||
func newFinding(relativePath string, fileSet *token.FileSet, node ast.Node, kind, name string) Finding {
|
||||
return Finding{File: filepath.ToSlash(relativePath), Line: fileSet.Position(node.Pos()).Line, Kind: kind, Name: name}
|
||||
}
|
||||
|
||||
// funcName 返回函数名称,匿名函数统一使用 anonymous。
|
||||
func funcName(identifier *ast.Ident) string {
|
||||
if identifier == nil || identifier.Name == "" {
|
||||
return "anonymous"
|
||||
}
|
||||
return identifier.Name
|
||||
}
|
||||
|
||||
// sortFindings 按文件、行号、类别和名称对检查结果排序。
|
||||
func sortFindings(findings []Finding) {
|
||||
sort.Slice(findings, func(left, right int) bool {
|
||||
if findings[left].File != findings[right].File {
|
||||
return findings[left].File < findings[right].File
|
||||
}
|
||||
if findings[left].Line != findings[right].Line {
|
||||
return findings[left].Line < findings[right].Line
|
||||
}
|
||||
if findings[left].Kind != findings[right].Kind {
|
||||
return findings[left].Kind < findings[right].Kind
|
||||
}
|
||||
return findings[left].Name < findings[right].Name
|
||||
})
|
||||
}
|
||||
|
||||
// findingKey 生成基线记录的稳定键。
|
||||
func findingKey(finding Finding) string {
|
||||
return fmt.Sprintf("%s:%d:%s:%s", finding.File, finding.Line, finding.Kind, finding.Name)
|
||||
}
|
||||
|
||||
// writeBaseline 将当前发现写成可审查、可版本控制的 JSON 文件。
|
||||
func writeBaseline(path string, findings []Finding) error {
|
||||
// mkdirErr 表示创建基线目录时的文件系统错误。
|
||||
if mkdirErr := os.MkdirAll(filepath.Dir(path), 0o755); mkdirErr != nil {
|
||||
return mkdirErr
|
||||
}
|
||||
// file 是基线输出文件,使用缩进格式方便代码审查。
|
||||
file, err := os.Create(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
// encoder 负责以稳定缩进格式输出基线 JSON。
|
||||
encoder := json.NewEncoder(file)
|
||||
encoder.SetIndent("", " ")
|
||||
return encoder.Encode(findings)
|
||||
}
|
||||
|
||||
// readBaseline 读取历史基线并转换为快速查询集合。
|
||||
func readBaseline(path string) (map[string]struct{}, error) {
|
||||
// data 是基线文件的 JSON 内容。
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// findings 是反序列化后的历史问题列表。
|
||||
var findings []Finding
|
||||
// unmarshalErr 表示基线 JSON 无法解析的原因。
|
||||
if unmarshalErr := json.Unmarshal(data, &findings); unmarshalErr != nil {
|
||||
return nil, unmarshalErr
|
||||
}
|
||||
// baseline 是稳定键集合,避免检查阶段重复遍历历史列表。
|
||||
baseline := make(map[string]struct{}, len(findings))
|
||||
// finding 表示历史基线中的一条问题记录。
|
||||
for _, finding := range findings {
|
||||
baseline[findingKey(finding)] = struct{}{}
|
||||
}
|
||||
return baseline, nil
|
||||
}
|
||||
|
||||
// filterNewFindings 过滤掉已记录在历史基线中的问题。
|
||||
func filterNewFindings(findings []Finding, baseline map[string]struct{}) []Finding {
|
||||
// newFindings 保存真正需要开发者处理的新增问题。
|
||||
newFindings := make([]Finding, 0)
|
||||
// finding 表示本次扫描发现的一条问题记录。
|
||||
for _, finding := range findings {
|
||||
// exists 表示该问题是否已经被历史基线允许。
|
||||
if _, exists := baseline[findingKey(finding)]; !exists {
|
||||
newFindings = append(newFindings, finding)
|
||||
}
|
||||
}
|
||||
return newFindings
|
||||
}
|
||||
Reference in new issue
Block a user