Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
157 changes: 157 additions & 0 deletions src/plugin/command-args.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 dsh-code-review contributors

/**
* command-args.ts —— `/review` 的参数解析(纯函数,无 IO)。
*
* 背景:这个命令的提示写着 `repo_path [mode] [focus]`,但 handler 从来不解析它,
* 永远拿会话 cwd 去评审 —— 等于提示在骗人。这里把语法落地。
*
* 支持的写法(位置参数 + key=value 混用):
*
* /review 当前目录、uncommitted
* /review D:/repo 指定仓库
* /review D:/repo scan 指定仓库 + 全仓扫描
* /review scan 重点看并发 指定模式 + 重点
* /review D:/repo branch base=main head=dev
* /review commit=abc123 等价于 mode=commit + commit=abc123
* /review repo=D:/repo focus=鉴权问题 纯 key=value 写法
*
* 判定顺序(避免歧义):
* 1. `key=value` 先抽走(repo/base/head/commit/focus/mode);
* 2. 剩下的按位置取:第一个"看着像路径"的当 repo_path,第一个模式关键字当 mode;
* 3. 其余全部拼成 focus(保持用户原文顺序,便于模型理解意图)。
*
* 为什么"看着像路径"要包含 existsSync:用户可能写相对路径 `.` 或 `../x`,
* 那种既没有盘符也不含分隔符;存在性判断能把它认出来。为了可测,exists 可注入。
*/

import { existsSync } from 'node:fs'

/** 合法模式关键字。 */
export const REVIEW_MODES = ['uncommitted', 'branch', 'commit', 'scan'] as const

/** 解析结果:直接喂给 submitReview 的参数 + 给用户看的提示。 */
export interface ParsedReviewCommand {
readonly args: {
readonly repo_path?: string
readonly mode?: string
readonly base_ref?: string
readonly head_ref?: string
readonly commit?: string
readonly focus?: string
}
/** 需要回显的告警(例如 key=value 值可疑)。 */
readonly notes: readonly string[]
}

/** 解析依赖(测试可注入)。 */
export interface ParseDeps {
/** 判断一个字符串是否指向已存在的路径。 */
readonly exists?: (p: string) => boolean
}

/** 是否是模式关键字。 */
function asMode(token: string): string | null {
const lower = token.toLowerCase()
return (REVIEW_MODES as readonly string[]).includes(lower) ? lower : null
}

/** 是否看起来像路径(盘符、分隔符,或磁盘上确实存在)。 */
function looksLikePath(token: string, exists: (p: string) => boolean): boolean {
if (/^[A-Za-z]:[\\/]/.test(token)) return true
if (token.includes('/') || token.includes('\\')) return true
if (token === '.' || token === '..' || token.startsWith('./') || token.startsWith('.\\')) return true
try {
return exists(token)
} catch {
return false
}
}

/**
* 解析 `/review` 后面的原始文本。
* @param rawInput 用户输入的命令原文(不含 `/review` 本身)
* @param deps 可注入的判定依赖
*/
export function parseReviewCommand(rawInput: string, deps: ParseDeps = {}): ParsedReviewCommand {
const exists = deps.exists ?? ((p: string) => existsSync(p))
const notes: string[] = []
const tokens = rawInput.trim().split(/\s+/).filter((t) => t !== '')

const pairs: Record<string, string> = {}
const rest: string[] = []

for (const token of tokens) {
const eq = token.indexOf('=')
if (eq > 0) {
const key = token.slice(0, eq).toLowerCase()
const value = token.slice(eq + 1)
if (['repo', 'repo_path', 'base', 'head', 'commit', 'focus', 'mode'].includes(key)) {
if (value === '') {
notes.push('参数 ' + key + '= 没有值,已忽略')
continue
}
pairs[key] = value
continue
}
// 不是我们认识的键:可能只是 focus 里带等号,原样保留
}
rest.push(token)
}

const args: {
repo_path?: string
mode?: string
base_ref?: string
head_ref?: string
commit?: string
focus?: string
} = {}

// ① key=value 优先
const repoPair = pairs.repo ?? pairs.repo_path
if (repoPair !== undefined) args.repo_path = repoPair
if (pairs.base !== undefined) args.base_ref = pairs.base
if (pairs.head !== undefined) args.head_ref = pairs.head
if (pairs.commit !== undefined) args.commit = pairs.commit
if (pairs.mode !== undefined) {
const mode = asMode(pairs.mode)
if (mode === null) notes.push('未知 mode "' + pairs.mode + '",可用:' + REVIEW_MODES.join(' / '))
else args.mode = mode
}
if (pairs.focus !== undefined) args.focus = pairs.focus

// ② 位置参数
const leftovers: string[] = []
let modeTaken = args.mode !== undefined
let repoTaken = args.repo_path !== undefined

for (const token of rest) {
if (!modeTaken) {
const mode = asMode(token)
if (mode !== null) {
args.mode = mode
modeTaken = true
continue
}
}
if (!repoTaken && looksLikePath(token, exists)) {
args.repo_path = token
repoTaken = true
continue
}
leftovers.push(token)
}

// ③ 剩下的都是 focus
if (leftovers.length > 0) {
const text = leftovers.join(' ')
args.focus = args.focus === undefined ? text : args.focus + ' ' + text
}

// ④ commit= 隐含 mode=commit(否则 submitReview 会以"模式冲突"拒绝)
if (args.commit !== undefined && args.mode === undefined) args.mode = 'commit'

return { args, notes }
}
20 changes: 16 additions & 4 deletions src/plugin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { fileURLToPath } from 'node:url'
import { normalizeConfig } from '../config/schema.js'
import { writeCachedCredential } from '../store/credential-cache.js'
import { configFilePath, legacyConfigFilePath, resolveDshRoot } from '../store/paths.js'
import { parseReviewCommand } from './command-args.js'
import { resolveCredentialFromHost } from './credentials.js'
import { listTasks, readTask, requestCancellation } from '../store/task-store.js'
import { settingsConfig, CONFIG_FIELDS, configObject } from '../settings/schema.js'
Expand Down Expand Up @@ -397,16 +398,27 @@ export function apply(ctx: Ctx, rawConfig?: unknown): () => void {
// 契约:input 若提供,必须是 { hint: string }。
// 传字符串会让 register 直接抛 TypeError,而异常会被下面的 try/catch 吞掉——
// 表现就是「斜杠命令死活不出现、日志里也没有任何东西」。实机踩过。
input: { hint: 'repo_path [mode] [focus]' },
handler: async (invocation: { agent?: { session?: { id?: string; header?: { cwd?: string } } } }) => {
input: { hint: '[repo_path] [uncommitted|branch|commit|scan] [focus](也可用 repo= base= head= commit= focus= 写法)' },
handler: async (invocation: {
readonly rawInput?: string
readonly agent?: { session?: { id?: string; header?: { cwd?: string } } }
}) => {
const raw = invocation?.agent?.session
const cwd = raw?.header?.cwd
const sid = typeof raw?.id === 'string' ? raw.id : null
const r = await doSubmit({ repo_path: cwd }, ctx, cwd, sid, config)

// 解析用户在 /review 后面写的东西。
// 之前这里完全不看 rawInput,永远用会话 cwd —— 提示写着可传参数,实际不认。
const parsed = parseReviewCommand(
typeof invocation?.rawInput === 'string' ? invocation.rawInput : '',
{ exists: (q) => existsSync(q) },
)
const noteText = parsed.notes.length > 0 ? '\n\n⚠ ' + parsed.notes.join(';') : ''
const r = await doSubmit(parsed.args, ctx, cwd, sid, config)
// 契约:handler 必须返回 { kind: 'success' | 'error', text? }。
// 返回纯字符串会被判为非法结果,命令看起来「执行了但什么也没发生」。
return r.ok
? { kind: 'success' as const, text: r.text }
? { kind: 'success' as const, text: r.text + noteText }
: { kind: 'error' as const, text: r.text === '' ? '评审未提交' : r.text }
},
}))
Expand Down
110 changes: 110 additions & 0 deletions test/plugin/command-args.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 dsh-code-review contributors

/**
* command-args.test.ts —— `/review` 参数解析的契约测试。
*
* 这个解析器的存在本身就是修复:此前命令的提示写着可传 repo/mode/focus,
* 但 handler 完全不看 rawInput,永远用会话 cwd。测试锁住"提示与行为一致"。
*/

import { describe, expect, it } from 'vitest'
import { parseReviewCommand } from '../../src/plugin/command-args.js'

/** 什么都不存在的 exists(避免测试受本机文件影响)。 */
const none = { exists: () => false }

describe('空输入', () => {
it('什么都不传时不给任何参数(交给 submitReview 用 cwd 兜底)', () => {
expect(parseReviewCommand('', none).args).toEqual({})
expect(parseReviewCommand(' ', none).args).toEqual({})
})
})

describe('位置参数', () => {
it('盘符路径被认成 repo_path', () => {
expect(parseReviewCommand('D:/repo', none).args.repo_path).toBe('D:/repo')
})

it('模式关键字被认成 mode', () => {
expect(parseReviewCommand('scan', none).args).toEqual({ mode: 'scan' })
})

it('路径 + 模式', () => {
expect(parseReviewCommand('D:/repo scan', none).args).toEqual({ repo_path: 'D:/repo', mode: 'scan' })
})

it('模式 + 重点(重点保留原文顺序)', () => {
expect(parseReviewCommand('scan 重点看并发与资源泄漏', none).args).toEqual({
mode: 'scan',
focus: '重点看并发与资源泄漏',
})
})

it('路径 + 模式 + 重点', () => {
expect(parseReviewCommand('D:/repo uncommitted 鉴权', none).args).toEqual({
repo_path: 'D:/repo',
mode: 'uncommitted',
focus: '鉴权',
})
})

it('存在的相对路径也能被认出来', () => {
const r = parseReviewCommand('.', { exists: () => true })
expect(r.args.repo_path).toBe('.')
})

it('模式关键字大小写不敏感', () => {
expect(parseReviewCommand('SCAN', none).args.mode).toBe('scan')
})
})

describe('key=value 写法', () => {
it('repo= 覆盖路径', () => {
expect(parseReviewCommand('repo=D:/x', none).args.repo_path).toBe('D:/x')
})

it('commit= 隐含 mode=commit', () => {
expect(parseReviewCommand('commit=abc123', none).args).toEqual({ commit: 'abc123', mode: 'commit' })
})

it('branch 模式带 base/head', () => {
expect(parseReviewCommand('D:/r branch base=main head=dev', none).args).toEqual({
repo_path: 'D:/r',
mode: 'branch',
base_ref: 'main',
head_ref: 'dev',
})
})

it('focus= 与位置重点合并', () => {
expect(parseReviewCommand('scan focus=并发 补充说明', none).args).toEqual({
mode: 'scan',
focus: '并发 补充说明',
})
})

it('未知 mode 值给出提示且不设 mode', () => {
const r = parseReviewCommand('mode=fast', none)
expect(r.args.mode).toBeUndefined()
expect(r.notes.join()).toContain('未知 mode')
})

it('空值给出提示', () => {
const r = parseReviewCommand('base=', none)
expect(r.notes.join()).toContain('没有值')
})
})

describe('不误伤', () => {
it('带等号的普通文字留在 focus 里', () => {
const r = parseReviewCommand('检查 a=b 这种写法', none)
expect(r.args.focus).toBe('检查 a=b 这种写法')
})

it('模式关键字只吃第一次,后面的当重点', () => {
const r = parseReviewCommand('scan scan 两个字', none)
expect(r.args.mode).toBe('scan')
expect(r.args.focus).toBe('scan 两个字')
})
})
Loading