Repository navigation
fix(markdown)!: preserve underscore contexts - #149
Merged
Merged
Conversation
- Preserve underscores in code, links, and HTTP URLs - Escape rendered messages without mutating template fields - Cover formatting boundaries, templates, and error paths BREAKING CHANGE: Custom tpl underscores are now escaped in ordinary Markdown text, and template helpers receive raw fields. Use HTML formatting for intentional italics and update helpers that relied on pre-escaped fields. Related to appleboy/telegram-action#30
There was a problem hiding this comment.
🟡 Changes recommended
URL preservation fails for mixed-case schemes and bracketed IPv6 hosts, while backslash handling breaks inline-code delimiter pairing and introduces visible escapes.
3 open issues
What changed in this PR
This PR updates shared Markdown message preparation for Drone and GitHub Actions notifications to preserve underscores in code, links, and bare HTTP(S) URLs while retaining ordinary-text escaping.
Changes:
- Adds context-aware underscore handling after template rendering, without mutating source fields.
- Adds regression coverage for formatting contexts, templates, message sources, and errors.
- Documents compatibility changes and pending Telegram rendering verification.
| File | Description |
|---|---|
| README.md | Explains Markdown escaping, template compatibility, and the HTML alternative. |
| plugin.go | Adds context scanning and centralizes render-before-escape message preparation. |
| plugin_test.go | Adds context, rendering, source-preservation, and error regression tests. |
| plan.md | Records the behavior contract, verification evidence, and release follow-ups. |
Review effort: Balanced
Comment on lines
+163
to
+166
| case 'h': | ||
| if strings.HasPrefix(str[i:], "https://") || strings.HasPrefix(str[i:], "http://") { | ||
| end = markdownURLEnd(str, i) | ||
| } |
Comment on lines
+198
to
+199
| case '\\': | ||
| i++ |
| i := start | ||
| for i < len(str) { | ||
| r, size := utf8.DecodeRuneInString(str[i:]) | ||
| if unicode.IsSpace(r) || unicode.IsControl(r) || strings.ContainsRune("`<>[]", r) { |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.

Summary
Messages containing code such as
_siteor links with underscores were globally rewritten with backslashes, producing visible backslashes or damaged links. Preserve underscores inside complete inline/fenced code, link labels and destinations, and bare HTTP(S) URLs. Keep existing underscore escaping for ordinary text.Render templates before applying context-aware escaping, so a field can appear in both ordinary text and code without mutating the original field. Add regression coverage and document compatibility behavior.
Compatibility change: custom
tplvalues now receive ordinary-text underscore escaping, including_italic_; template helpers receive raw fields instead of pre-escaped fields. Use HTML markup for intentional italics and adjust helpers that relied on pre-escaped input. This is not a MarkdownV2 migration or a complete Markdown validator.Related issues
Architecture / flow
flowchart TD Input["Exec: message, file or default message"] --> Render["renderMessages: template.RenderTrim with raw fields"] Render --> Decode["html.UnescapeString"] Render -->|error| Err["Return error without partial messages"] Decode --> Mode{"Format == Markdown?"} Mode -->|yes| Escape["escapeMarkdownOne: delimiter index and context scan"] Mode -->|no| Ready["renderedMessages"] Escape --> Ready Ready --> Send["Existing NewMessage / ParseMode / Send"] style Render fill:#dff0d8,stroke:#3c763d style Escape fill:#dff0d8,stroke:#3c763dAI authorship
plugin.go,plugin_test.go,README.md,plan.md.Change classification
Plan reference
See plan.md for the approved scope, behavior contract, implementation evidence, rollback, and release follow-ups. No CLI, dependency, transport, media, Docker, or workflow changes.
Verification
Setup
Check out
fix/30-markdown-escapinginappleboy/drone-telegramand run commands from the repository root. Tested locally with Go 1.26.10 on macOS/arm64, golangci-lint 2.15.0, and standalone gofumpt 0.8.0. CI uses golangci-lint 2.12 and the repository's Linux/Go matrix; remote results remain separate from local evidence.The automated checks below need no Telegram credentials. Empty
TELEGRAM_TOKENandTELEGRAM_TOkeep credential-gated integration tests skipped. Formake fmt-check, ensuregofumptis on PATH; the local run used a temporary installation:GOBIN=/tmp/drone-telegram-tools go install mvdan.cc/gofumpt@v0.8.0 PATH="/tmp/drone-telegram-tools:$PATH" make fmt-checkAutomated checks
All commands run from the repository root; observed commands were invoked through the local
rtkwrapper.env TELEGRAM_TOKEN= TELEGRAM_TO= go test ./...env TELEGRAM_TOKEN= TELEGRAM_TO= go test -race ./...go vet ./...golangci-lint run ./...extra-rulesdeprecation warnings onlyPATH="/tmp/drone-telegram-tools:$PATH" make fmt-checkgo build -o /tmp/drone-telegram-tools/drone-telegram .git diff --checkBehavioral scenarios
go test -run '^TestEscapeMarkdown' -count=1 -v .. Inline code containing_Some text, fenced code,[_Some text](https://example.com/some_path), and a bare URL must remain unchanged;user_nameoutside these contexts must becomeuser\_name. The initial five regression cases all failed with extra backslashes before the fix and passed afterward. Expanded cases cover escaped delimiters, balanced URL parentheses, Unicode, existing escapes, and unmatched syntax. The large unmatched-delimiter case must complete without truncation or panic.go test -run '^TestRenderMessages' -count=1 -v .. Afeature_onefield must be escaped in ordinary text but preserved in code and a link label, without mutating its source. File/default messages must follow the same rules; HTML and other formats must retain their previous output. The invalid-template case must return an error and no partial messages; a missing message file must retain its load error. Temporary test files are cleaned up byt.TempDir().PLUGIN_TOKENandPLUGIN_TOsecurely for that chat and save only the three message-content lines from the README Markdown example (without the YAML keys) to/tmp/telegram-markdown-example.txt, then run/tmp/drone-telegram-tools/drone-telegram --format Markdown --message.file /tmp/telegram-markdown-example.txt. Expected: code displays_sitewithout an added backslash, ordinaryrelease_namedisplays literally, and the link destination remainshttps://example.com/_site. Inspect the URL without needing a successful response from the example website. This sends a real message; delete the test message and unset test credentials afterward. No real messages were sent during this work.Cleanup
Automated fixtures use temporary directories. The formatter/binary artifacts are under
/tmp/drone-telegram-tools; no generated build files or credentials are included in the PR.Security check
Risk and rollback
tplitalics need review.Reviewer guide
escapeMarkdownOne,markdownDelimiters,markdownURLEnd, andrenderMessagescarefully: delimiter pairing, backslash parity, URL boundaries, malformed-input fallback, and rendering order are the main risks.