mirror of
https://github.com/larksuite/cli.git
synced 2026-07-04 06:29:52 +08:00
* feat(doc): add pre-write semantic warnings to docs +update Two static checks run before the MCP update-doc call: 1. replace_* + blank-line markdown: replace_range / replace_all only swap text inside an existing block — a \n\n in the payload will render as literal text, not a paragraph break. Hint to use delete_range + insert_before instead. 2. Combined bold+italic emphases (***text***, **_text_**, _**text**_) cannot round-trip through Lark and are silently downgraded to a single emphasis. Hint to split into two separate emphases. Both warnings go to stderr and never block the update — they inform, not gate. Adds table-driven tests for each check plus an aggregation test, and wires the checks into Execute right before CallMCPTool. Closes the first batch of items from the docs +update pitfalls review (Cases 1 and 5). * fix(doc): exclude code regions and escaped markers from docs +update checks (#578) * fix(doc): exclude code regions and escaped markers from docs +update checks Addresses the three review comments on #569: the blank-line paragraph check and the bold+italic emphasis check both operate on the raw markdown string, so fenced code blocks / inline code spans / literal escaped markers produce false-positive warnings on content users expect to pass through verbatim. Changes: - Add proseHasBlankLine(): fence-aware detector that returns true only when a blank line sits outside of ```...``` or ~~~...~~~ regions. Replaces the raw strings.Contains("\n\n") check in checkDocsUpdateReplaceMultilineMarkdown. - Add stripMarkdownCodeRegions(): blanks out fenced code lines and masks inline code spans (via scanInlineCodeSpans from markdown_fix.go) with equal-length whitespace so byte offsets outside the stripped regions are preserved. - Add stripEscapedEmphasisMarkers(): removes "\*" and "\_" so literal sequences like "\***text***" — which CommonMark renders as a literal asterisk plus bold — don't match the combined bold+italic regex. - Wire both helpers into checkDocsUpdateBoldItalic(): the regex now runs on stripEscapedEmphasisMarkers(stripMarkdownCodeRegions(markdown)), so code samples and escaped markers are sanitized away before detection. Shared fence-parsing helpers (codeFenceOpenMarker, isCodeFenceClose, leadingRun) are kept local to this file to avoid touching files outside the scope of the reviewed PR. If a future change wants to reuse them across the doc package, they can be promoted then. Tests: - TestCheckDocsUpdateReplaceMultilineMarkdown: add 4 negative/positive cases — blank line inside backtick and tilde fences (no flag), blank line in prose while fence also has blanks (flag wins), fenced code with no blank lines (no flag). - TestCheckDocsUpdateBoldItalic: add 9 cases — ***text*** / **_text_** / _**text**_ inside fenced code (backtick and tilde), inside inline code spans, and escaped \***text*** / \*\*_text_\*\* (none flagged); plus two positive cases to verify the strip doesn't over-sanitize (real emphasis in prose still fires when inline/fenced code is nearby). * fix(doc): close CommonMark gaps and add three more combined-emphasis shapes Self-review of the first commit turned up three issues: - isCodeFenceClose was strict on exact marker length. Per CommonMark §4.5, a closing fence must be at least as long as the opener, not exactly the same length. A 3-backtick open legitimately closed by a 4-backtick closer (used to embed triple-backticks inside the code sample) was left open-ended, causing the rest of the document to be treated as code and both checks to silently skip it. - Both fence helpers accepted any amount of leading whitespace because they ran on strings.TrimSpace(line). CommonMark allows 0..3 leading spaces before a fence marker; 4+ spaces (or any tab in leading position, which expands to 4 columns) makes the line indented code block content, not a fence open/close. Indented fence-like lines now correctly remain prose and blank lines around them are detected. - The bold/italic check only covered three of the six documented combined-emphasis shapes. Added ___text___, __*text*__, and *__text__* so parity with the asterisk variants is complete. The regex set is now table-driven (combinedEmphasisPatterns) to make adding future shapes a one-line change. Implementation changes: - New fenceIndentOK(line) helper: returns (body, true) for 0..3 leading spaces with no tabs, else (_, false). Used by both codeFenceOpenMarker and isCodeFenceClose. - isCodeFenceClose now counts the fence-char run and accepts any run length >= len(marker), with trailing whitespace only. - checkDocsUpdateBoldItalic replaced three named var regexes with a table of six {shape, re} entries and a single early-exit loop. - Updated docsUpdateWarnings top docstring to list all six shapes. - Noted the known limitation of stripEscapedEmphasisMarkers around doubled backslash escapes ("\\***text***"), which is a false negative we accept in exchange for keeping this a simple string replace. Test additions (docs_update_check_test.go): - Fence close: longer-marker close correctly ends fence; real prose blank after a longer-close fence is still detected. - Indentation: 4-space indented fence-like line is not a fence open, so a surrounding blank line still flags; tab-indented variant same; 3-space indented fence is still a real fence. - New shapes: ___text___ positive + all three negative-guards (fenced code, inline code, escaped); __*text*__ and *__text__* positive + fenced/inline negative-guards; plus two composition tests to ensure the strip does not over-sanitize across the six-regex alternative set. All 53 sub-tests in this file pass; go vet and gofmt are clean. --------- Co-authored-by: fangshuyu-768 <shuyufang768@outlook.com> * fix(doc): address CodeRabbit review on docs +update warnings (#581) Two CodeRabbit nits from #569: 1. Unit test hint assertion only checked for `delete_range` in the remediation message; the companion `insert_before` half of the guidance could regress undetected. Broaden the assertion to require both tokens so a future edit that drops half the remediation produces an immediate test failure. 2. No E2E coverage proved the dry-run contract in the PR description ("Not emitted in dry-run mode — kept quiet during planning"). The helper itself is unit-tested, but nothing caught a regression where a later refactor wired docsUpdateWarnings into the DryRun path. Add tests/cli_e2e/docs/docs_update_dryrun_test.go: TestDocs_UpdateDryRunSuppressesSemanticWarnings invokes `docs +update --dry-run --mode=replace_range --markdown "***x***\n\nb"` — an input crafted to trip BOTH pre-write warnings — and asserts neither the "warning:" prefix, the blank-line message, nor the combined-emphasis message appears on stdout or stderr. Note: the file needs -f to add because .gitignore has a bare `docs/` rule that accidentally matches tests/cli_e2e/docs/. The existing tracked files under that directory predate the rule; new additions have to be force-added until the ignore pattern is narrowed. Not worth rewriting .gitignore for one file. Verified manually that the new E2E fails cleanly when warnings are injected into DryRun and passes again after reverting — the test has real regression-detection power, not just a sticker. Co-authored-by: fangshuyu-768 <shuyufang768@outlook.com>
282 lines
9.9 KiB
Go
282 lines
9.9 KiB
Go
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
package doc
|
|
|
|
import (
|
|
"regexp"
|
|
"strings"
|
|
)
|
|
|
|
// docsUpdateWarnings returns a list of human-readable warnings for a
|
|
// `docs +update` invocation based on static analysis of the mode and
|
|
// Markdown payload. The warnings describe CLI/MCP contract edges that
|
|
// commonly surprise users; the update is still executed — callers
|
|
// decide whether to stop at a warning.
|
|
//
|
|
// Both checks ignore fenced code blocks (```…``` and ~~~…~~~, with up
|
|
// to 3 leading spaces per CommonMark §4.5), inline code spans, and
|
|
// backslash-escaped emphasis markers so that literal Markdown content
|
|
// embedded in code samples or escaped prose does not produce false
|
|
// positives.
|
|
//
|
|
// Warnings emitted (current):
|
|
//
|
|
// 1. replace_* modes do not split blocks. A Markdown payload containing
|
|
// a blank line (\n\n) in prose implies the caller expects multiple
|
|
// paragraphs, but replace_range / replace_all only swap in-block
|
|
// text. The resulting block will contain the blank line as literal
|
|
// text and appear as a single paragraph in the UI.
|
|
//
|
|
// 2. Lark does not round-trip bold+italic. Six shapes are detected:
|
|
// ***text*** ___text___
|
|
// **_text_** __*text*__
|
|
// _**text**_ *__text__*
|
|
// Lark stores only one of the two emphases (usually italic), silently
|
|
// dropping the other. The user wanted both; they will get one.
|
|
func docsUpdateWarnings(mode, markdown string) []string {
|
|
var warnings []string
|
|
if w := checkDocsUpdateReplaceMultilineMarkdown(mode, markdown); w != "" {
|
|
warnings = append(warnings, w)
|
|
}
|
|
if w := checkDocsUpdateBoldItalic(markdown); w != "" {
|
|
warnings = append(warnings, w)
|
|
}
|
|
return warnings
|
|
}
|
|
|
|
// checkDocsUpdateReplaceMultilineMarkdown flags markdown that contains a
|
|
// blank-line paragraph break outside fenced code blocks under a replace_*
|
|
// mode. Blank lines inside code fences are literal content and don't
|
|
// imply paragraph semantics, so they are deliberately ignored.
|
|
func checkDocsUpdateReplaceMultilineMarkdown(mode, markdown string) string {
|
|
if mode != "replace_range" && mode != "replace_all" {
|
|
return ""
|
|
}
|
|
// A CR/LF-robust check: both "\n\n" and "\r\n\r\n" count as paragraph
|
|
// separators. We normalize line endings once before detection.
|
|
normalized := strings.ReplaceAll(markdown, "\r\n", "\n")
|
|
if !proseHasBlankLine(normalized) {
|
|
return ""
|
|
}
|
|
return "--mode=" + mode + " does not split a block into multiple paragraphs; " +
|
|
"the blank line in --markdown will render as literal text. " +
|
|
"For multiple paragraphs, use --mode=delete_range followed by --mode=insert_before."
|
|
}
|
|
|
|
// combinedEmphasisPatterns holds the six documented combined-emphasis shapes
|
|
// that Lark downgrades to a single emphasis. Each entry pairs a regex with a
|
|
// short shape label for the warning message. The two forms per shape (with
|
|
// and without `[^…]*?`) are there because the lazy quantifier needs at least
|
|
// one non-delimiter character to match; single-rune payloads (e.g. `***X***`)
|
|
// take the second alternation.
|
|
var combinedEmphasisPatterns = []struct {
|
|
shape string
|
|
re *regexp.Regexp
|
|
}{
|
|
// Bold+italic with a single delimiter char.
|
|
{"***text***", regexp.MustCompile(`\*\*\*\S[^*]*?\S\*\*\*|\*\*\*\S\*\*\*`)},
|
|
{"___text___", regexp.MustCompile(`___\S[^_]*?\S___|___\S___`)},
|
|
|
|
// Bold wrapping italic (asterisk outside).
|
|
{"**_text_**", regexp.MustCompile(`\*\*_\S[^_*]*?\S_\*\*|\*\*_\S_\*\*`)},
|
|
{"__*text*__", regexp.MustCompile(`__\*\S[^_*]*?\S\*__|__\*\S\*__`)},
|
|
|
|
// Italic wrapping bold (asterisk inside).
|
|
{"_**text**_", regexp.MustCompile(`_\*\*\S[^_*]*?\S\*\*_|_\*\*\S\*\*_`)},
|
|
{"*__text__*", regexp.MustCompile(`\*__\S[^_*]*?\S__\*|\*__\S__\*`)},
|
|
}
|
|
|
|
// checkDocsUpdateBoldItalic flags Markdown emphases that attempt to
|
|
// combine bold and italic in a way Lark cannot represent. Fenced code
|
|
// blocks, inline code spans, and backslash-escaped emphasis markers are
|
|
// stripped first so that literal markdown examples ("here is a
|
|
// `***keyword***` to flag") do not trigger the warning.
|
|
func checkDocsUpdateBoldItalic(markdown string) string {
|
|
if markdown == "" {
|
|
return ""
|
|
}
|
|
sanitized := stripEscapedEmphasisMarkers(stripMarkdownCodeRegions(markdown))
|
|
for _, p := range combinedEmphasisPatterns {
|
|
if p.re.MatchString(sanitized) {
|
|
return "Lark does not support combined bold+italic markers " +
|
|
"(e.g. ***text***, ___text___, **_text_**, _**text**_, __*text*__, *__text__*); " +
|
|
"the emphasis will be downgraded to either bold or italic. " +
|
|
"Split into two separate emphases or drop one of them."
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// proseHasBlankLine reports whether markdown contains a blank line outside
|
|
// of fenced code blocks. Blank lines inside ```...``` or ~~~...~~~ fences
|
|
// are code content, not paragraph separators, and must not trip the
|
|
// "replace_* cannot split paragraphs" warning.
|
|
//
|
|
// A blank line counts only when it sits between two non-blank boundaries
|
|
// (other prose, or a fence open/close). A trailing empty line at EOF is
|
|
// not treated as "\n\n".
|
|
func proseHasBlankLine(markdown string) bool {
|
|
lines := strings.Split(markdown, "\n")
|
|
inFence := false
|
|
var fenceMarker string
|
|
for i, line := range lines {
|
|
if inFence {
|
|
if isCodeFenceClose(line, fenceMarker) {
|
|
inFence = false
|
|
fenceMarker = ""
|
|
}
|
|
continue
|
|
}
|
|
if marker := codeFenceOpenMarker(line); marker != "" {
|
|
inFence = true
|
|
fenceMarker = marker
|
|
continue
|
|
}
|
|
if strings.TrimSpace(line) == "" && i > 0 && i+1 < len(lines) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// stripMarkdownCodeRegions returns markdown with fenced code blocks blanked
|
|
// out and inline code spans replaced by whitespace of equivalent length.
|
|
// Byte offsets outside the masked regions are preserved, so follow-on
|
|
// regex matches still point at real prose positions.
|
|
func stripMarkdownCodeRegions(markdown string) string {
|
|
lines := strings.Split(markdown, "\n")
|
|
inFence := false
|
|
var fenceMarker string
|
|
for i, line := range lines {
|
|
if inFence {
|
|
if isCodeFenceClose(line, fenceMarker) {
|
|
inFence = false
|
|
fenceMarker = ""
|
|
}
|
|
lines[i] = ""
|
|
continue
|
|
}
|
|
if marker := codeFenceOpenMarker(line); marker != "" {
|
|
inFence = true
|
|
fenceMarker = marker
|
|
lines[i] = ""
|
|
continue
|
|
}
|
|
lines[i] = maskInlineCodeSpans(line)
|
|
}
|
|
return strings.Join(lines, "\n")
|
|
}
|
|
|
|
// maskInlineCodeSpans replaces the byte ranges of any inline code spans in
|
|
// line with space characters of equal length. Uses scanInlineCodeSpans from
|
|
// markdown_fix.go, which implements the CommonMark §6.1 matching-backtick-run
|
|
// rule (so “ `a`b` “ is a single span).
|
|
func maskInlineCodeSpans(line string) string {
|
|
spans := scanInlineCodeSpans(line)
|
|
if len(spans) == 0 {
|
|
return line
|
|
}
|
|
var sb strings.Builder
|
|
pos := 0
|
|
for _, loc := range spans {
|
|
sb.WriteString(line[pos:loc[0]])
|
|
sb.WriteString(strings.Repeat(" ", loc[1]-loc[0]))
|
|
pos = loc[1]
|
|
}
|
|
sb.WriteString(line[pos:])
|
|
return sb.String()
|
|
}
|
|
|
|
// stripEscapedEmphasisMarkers removes backslash-escaped '*' and '_' so the
|
|
// bold/italic regexes don't treat literal sequences like `\***text***` as
|
|
// real combined emphasis. CommonMark renders "\*" as a literal "*" with no
|
|
// emphasis semantics; dropping the escape + its target from the detection
|
|
// input keeps the heuristic aligned with what the renderer actually does.
|
|
//
|
|
// Known limitation: a doubled backslash escape ("\\" followed by a real
|
|
// emphasis marker, e.g. `\\***text***`) renders as a literal backslash
|
|
// followed by genuine combined emphasis, but this strip is not a proper
|
|
// parser and will instead consume the second backslash as the opener for
|
|
// another escape. That hides the real emphasis from the check, producing
|
|
// a false negative. Practical impact is small (this shape is rare in the
|
|
// kind of AI-Agent prompts we target) and the alternative — a full
|
|
// CommonMark escape parser — is not worth the code surface here.
|
|
func stripEscapedEmphasisMarkers(s string) string {
|
|
s = strings.ReplaceAll(s, `\*`, "")
|
|
s = strings.ReplaceAll(s, `\_`, "")
|
|
return s
|
|
}
|
|
|
|
// codeFenceOpenMarker returns the fence marker (e.g. "```" or "~~~~") if
|
|
// line opens a fenced code block, otherwise "". Applies CommonMark §4.5
|
|
// rules: up to 3 leading spaces are tolerated; 4+ leading spaces (or any
|
|
// leading tab, which expands to 4 columns) make the line an indented code
|
|
// block rather than a fence.
|
|
func codeFenceOpenMarker(line string) string {
|
|
body, ok := fenceIndentOK(line)
|
|
if !ok {
|
|
return ""
|
|
}
|
|
switch {
|
|
case strings.HasPrefix(body, "```"):
|
|
return leadingRun(body, '`')
|
|
case strings.HasPrefix(body, "~~~"):
|
|
return leadingRun(body, '~')
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// isCodeFenceClose reports whether line closes a fence opened with marker.
|
|
// Per CommonMark §4.5 the closer must use the same fence character, be at
|
|
// least as long as the opener, sit within 0..3 leading spaces, and carry
|
|
// no info-string text.
|
|
func isCodeFenceClose(line, marker string) bool {
|
|
if marker == "" {
|
|
return false
|
|
}
|
|
body, ok := fenceIndentOK(line)
|
|
if !ok {
|
|
return false
|
|
}
|
|
fenceChar := marker[0]
|
|
run := leadingRun(body, fenceChar)
|
|
if len(run) < len(marker) {
|
|
return false
|
|
}
|
|
return strings.TrimSpace(body[len(run):]) == ""
|
|
}
|
|
|
|
// fenceIndentOK returns (bodyWithoutLeadingSpaces, true) when line has
|
|
// 0..3 leading spaces and no leading tab — i.e. the indentation is
|
|
// permissible for a CommonMark fence. Returns ("", false) otherwise
|
|
// (4+ leading spaces or any tab), meaning the line must be treated as
|
|
// indented code block content rather than a fence boundary.
|
|
func fenceIndentOK(line string) (string, bool) {
|
|
for i := 0; i < len(line) && i < 4; i++ {
|
|
switch line[i] {
|
|
case ' ':
|
|
continue
|
|
case '\t':
|
|
return "", false
|
|
default:
|
|
return line[i:], true
|
|
}
|
|
}
|
|
// Reached index 4 without hitting a non-space character: too indented.
|
|
if len(line) >= 4 {
|
|
return "", false
|
|
}
|
|
// Line shorter than 4 chars and all spaces — still valid (empty content).
|
|
return "", true
|
|
}
|
|
|
|
// leadingRun returns the longest prefix of s made up of the byte c.
|
|
func leadingRun(s string, c byte) string {
|
|
i := 0
|
|
for i < len(s) && s[i] == c {
|
|
i++
|
|
}
|
|
return s[:i]
|
|
}
|