Skip to content

feat: packet - #89

Merged
nao1215 merged 1 commit into
mainfrom
feature/mermaid-packet
Feb 24, 2026
Merged

nao1215 merged 1 commit into
mainfrom
feature/mermaid-packet

Conversation

@nao1215

@nao1215 nao1215 commented Feb 24, 2026 •

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • New Features

    • Added Mermaid packet diagram support for visualizing network packet structures with bit-level field definitions
  • Documentation

    • Updated documentation in multiple languages (English, Spanish, French, Japanese, Korean, Russian, Chinese) with packet diagram syntax guides and usage examples

@coderabbitai

coderabbitai Bot commented Feb 24, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This PR adds Mermaid packet diagram support to the library through a new mermaid/packet package with diagram builder functionality, comprehensive tests, example documentation, and feature documentation across seven languages.

Changes

Cohort / File(s) Summary
Documentation Translations
README.md, doc/es/README.md, doc/fr/README.md, doc/ja/README.md, doc/ko/README.md, doc/ru/README.md, doc/zh-cn/README.md
Adds Mermaid packet diagram documentation and examples to the feature list and introduces a new "Mermaid Packet Syntax" section with Go code, plain text output, and Mermaid diagram output across all language variants.
Packet Diagram Core Implementation
mermaid/packet/config.go, mermaid/packet/packet.go
Introduces packet diagram builder with configuration support via Option pattern, Diagram type with chainable methods (Field, Bit, Next, LF), error handling for invalid inputs (newlines in titles/labels, invalid bit ranges), and Mermaid syntax generation.
Tests and Examples
mermaid/packet/packet_test.go, mermaid/packet/examples_test.go
Adds comprehensive unit tests covering diagram construction, field validation, error propagation, string escaping, and output formatting, plus an example test demonstrating UDP packet diagram generation.
Generated Documentation
doc/packet/main.go, doc/packet/generated.md
Includes a Go program (with Linux/macOS build constraint) that generates the Mermaid packet diagram documentation and the resulting generated markdown file displaying a UDP packet structure.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 Hop along to packets new!
Mermaid diagrams bright and true,
Seven languages, bit by bit,
Our fluffy builder feels quite legit! ✨

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 31.25% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'feat: packet' is vague and does not clearly convey what the packet feature entails or why it was added. Consider using a more descriptive title like 'feat: add Mermaid packet diagram support' to better communicate the scope and purpose of the changes.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/mermaid-packet

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions

Copy link
Copy Markdown

Code Metrics Report

main (f2aca2e) #89 (0cffbc9) +/-
Coverage 90.2% 90.4% +0.1%
Test Execution Time 4s 5s +1s
Details
  |                     | main (f2aca2e) | #89 (0cffbc9) |  +/-  |
  |---------------------|----------------|---------------|-------|
+ | Coverage            |          90.2% |         90.4% | +0.1% |
  |   Files             |             42 |            44 |    +2 |
  |   Lines             |           1808 |          1888 |   +80 |
+ |   Covered           |           1632 |          1707 |   +75 |
- | Test Execution Time |             4s |            5s |   +1s |

Code coverage of files in pull request scope (0.0% → 93.7%)

Files Coverage +/- Status
mermaid/packet/config.go 100.0% +100.0% added
mermaid/packet/packet.go 93.5% +93.5% added

Reported by octocov

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (2)
mermaid/packet/packet_test.go (2)

19-65: All want strings using "packet" as the opening keyword are downstream of the bug in packet.go — they'll need updating to "packet-beta" when the root cause is fixed. See the packet.go comment for details.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@mermaid/packet/packet_test.go` around lines 19 - 65, The tests in
TestNewDiagram use "packet" as the diagram opening keyword but the
implementation will be changed to "packet-beta"; update expected strings in
TestNewDiagram (the want fields in the test cases) to use "packet-beta" (and
corresponding multi-line expectations such as the title case) so they match
NewDiagram/diagram.String() output; verify the third case still expects an error
when title contains newline and leave wantErr unchanged.

67-95: Same downstream keyword issue — packet in want should be packet-beta.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@mermaid/packet/packet_test.go` around lines 67 - 95, The test
TestDiagram_Build expects the old top-level keyword; update the expected output
in the want string to use "packet-beta" instead of "packet". Locate the want
variable in TestDiagram_Build (within packet_test.go) and replace the leading
line `packet` with `packet-beta` so the expected output matches what
NewDiagram/Build now emits.
🧹 Nitpick comments (2)
mermaid/packet/packet.go (1)

180-194: normalizeQuoted calls strings.TrimSpace redundantly in the validated call path.

quote is only ever called from Field and Next, both of which first pass the label through validateLabel — which already trims whitespace. The TrimSpace inside normalizeQuoted is a no-op at runtime for those callers (and the test that calls quote directly passes a non-whitespace-padded value). The outer-quote detection logic is still useful; only the redundant trim is worth noting.

♻️ Optional refactor
 func normalizeQuoted(value string) string {
-	trimmed := strings.TrimSpace(value)
-	if len(trimmed) >= 2 && strings.HasPrefix(trimmed, `"`) && strings.HasSuffix(trimmed, `"`) {
-		return trimmed[1 : len(trimmed)-1]
+	if len(value) >= 2 && strings.HasPrefix(value, `"`) && strings.HasSuffix(value, `"`) {
+		return value[1 : len(value)-1]
 	}
-	return trimmed
+	return value
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@mermaid/packet/packet.go` around lines 180 - 194, normalizeQuoted currently
calls strings.TrimSpace redundantly because callers (Field and Next via
validateLabel) already trim labels; remove the TrimSpace to avoid
double-trimming but keep the outer-quote stripping logic intact. In practice,
change normalizeQuoted to operate on the raw value (no TrimSpace) and only strip
surrounding double quotes if present, and ensure quote still calls
normalizeQuoted; verify callers relying on validateLabel still trim input.
mermaid/packet/packet_test.go (1)

233-248: errors.Is(d.Error(), err) — sound, but slightly over-specified.

Build() stores the error in d.err and then returns it, so d.Error() and err are the same pointer; d.Error() == err would suffice. errors.Is works here (it trivially matches identical pointers) and is more future-proof if the implementation ever wraps, so this is fine as-is.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@mermaid/packet/packet_test.go` around lines 233 - 248, The test
TestDiagram_BuildStoresError over-specifies the comparison by using
errors.Is(d.Error(), err); change it to a direct pointer equality check
(d.Error() == err) since Build() stores the same error in d.err and returns it;
update the assertion in TestDiagram_BuildStoresError to use == to reflect that
Error() and the returned err are identical (referencing NewDiagram, Build, and
Error methods).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@doc/packet/main.go`:
- Around line 29-35: The chained call to
packet.NewDiagram(...).Next(...).Field(...).String() hides any error state set
during Next/Field; split the chain into a named variable (e.g., diag :=
packet.NewDiagram(...).Next(...).Field(...)), then call the terminal method and
check its error return (e.g., s, err := diag.String(); if err != nil {
processLogger.Error(...); os.Exit(1) }) before writing to generated.md so
malformed diagrams are not silently emitted; reference the constructors/mutators
NewDiagram, Next, Field and the terminal String in your changes.

---

Duplicate comments:
In `@mermaid/packet/packet_test.go`:
- Around line 19-65: The tests in TestNewDiagram use "packet" as the diagram
opening keyword but the implementation will be changed to "packet-beta"; update
expected strings in TestNewDiagram (the want fields in the test cases) to use
"packet-beta" (and corresponding multi-line expectations such as the title case)
so they match NewDiagram/diagram.String() output; verify the third case still
expects an error when title contains newline and leave wantErr unchanged.
- Around line 67-95: The test TestDiagram_Build expects the old top-level
keyword; update the expected output in the want string to use "packet-beta"
instead of "packet". Locate the want variable in TestDiagram_Build (within
packet_test.go) and replace the leading line `packet` with `packet-beta` so the
expected output matches what NewDiagram/Build now emits.

---

Nitpick comments:
In `@mermaid/packet/packet_test.go`:
- Around line 233-248: The test TestDiagram_BuildStoresError over-specifies the
comparison by using errors.Is(d.Error(), err); change it to a direct pointer
equality check (d.Error() == err) since Build() stores the same error in d.err
and returns it; update the assertion in TestDiagram_BuildStoresError to use ==
to reflect that Error() and the returned err are identical (referencing
NewDiagram, Build, and Error methods).

In `@mermaid/packet/packet.go`:
- Around line 180-194: normalizeQuoted currently calls strings.TrimSpace
redundantly because callers (Field and Next via validateLabel) already trim
labels; remove the TrimSpace to avoid double-trimming but keep the outer-quote
stripping logic intact. In practice, change normalizeQuoted to operate on the
raw value (no TrimSpace) and only strip surrounding double quotes if present,
and ensure quote still calls normalizeQuoted; verify callers relying on
validateLabel still trim input.

ℹ️ Review info

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f2aca2e and e2e5028.

📒 Files selected for processing (13)
  • README.md
  • doc/es/README.md
  • doc/fr/README.md
  • doc/ja/README.md
  • doc/ko/README.md
  • doc/packet/generated.md
  • doc/packet/main.go
  • doc/ru/README.md
  • doc/zh-cn/README.md
  • mermaid/packet/config.go
  • mermaid/packet/examples_test.go
  • mermaid/packet/packet.go
  • mermaid/packet/packet_test.go

Comment thread doc/packet/main.go
Comment on lines +29 to +35
diagram := packet.NewDiagram(io.Discard, packet.WithTitle("UDP Packet")).
Next(16, "Source Port"). //nolint:mnd
Next(16, "Destination Port"). //nolint:mnd
Field(32, 47, "Length"). //nolint:mnd
Field(48, 63, "Checksum"). //nolint:mnd
Field(64, 95, "Data (variable length)"). //nolint:mnd
String()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Diagram error state is silently discarded by chaining straight to .String().

If any field call in the chain sets an error (e.g., after a future refactor changes the hardcoded values), String() still returns a partial body with no indication of failure, and the malformed content gets written to generated.md without any warning.

Split the chain so the error can be checked:

🛡️ Proposed fix
-	diagram := packet.NewDiagram(io.Discard, packet.WithTitle("UDP Packet")).
-		Next(16, "Source Port").                 //nolint:mnd
-		Next(16, "Destination Port").            //nolint:mnd
-		Field(32, 47, "Length").                 //nolint:mnd
-		Field(48, 63, "Checksum").               //nolint:mnd
-		Field(64, 95, "Data (variable length)"). //nolint:mnd
-		String()
+	d := packet.NewDiagram(io.Discard, packet.WithTitle("UDP Packet")).
+		Next(16, "Source Port").                 //nolint:mnd
+		Next(16, "Destination Port").            //nolint:mnd
+		Field(32, 47, "Length").                 //nolint:mnd
+		Field(48, 63, "Checksum").               //nolint:mnd
+		Field(64, 95, "Data (variable length)")  //nolint:mnd
+	if d.Error() != nil {
+		panic(d.Error())
+	}
+	diagram := d.String()
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
diagram := packet.NewDiagram(io.Discard, packet.WithTitle("UDP Packet")).
Next(16, "Source Port"). //nolint:mnd
Next(16, "Destination Port"). //nolint:mnd
Field(32, 47, "Length"). //nolint:mnd
Field(48, 63, "Checksum"). //nolint:mnd
Field(64, 95, "Data (variable length)"). //nolint:mnd
String()
d := packet.NewDiagram(io.Discard, packet.WithTitle("UDP Packet")).
Next(16, "Source Port"). //nolint:mnd
Next(16, "Destination Port"). //nolint:mnd
Field(32, 47, "Length"). //nolint:mnd
Field(48, 63, "Checksum"). //nolint:mnd
Field(64, 95, "Data (variable length)") //nolint:mnd
if d.Error() != nil {
panic(d.Error())
}
diagram := d.String()
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@doc/packet/main.go` around lines 29 - 35, The chained call to
packet.NewDiagram(...).Next(...).Field(...).String() hides any error state set
during Next/Field; split the chain into a named variable (e.g., diag :=
packet.NewDiagram(...).Next(...).Field(...)), then call the terminal method and
check its error return (e.g., s, err := diag.String(); if err != nil {
processLogger.Error(...); os.Exit(1) }) before writing to generated.md so
malformed diagrams are not silently emitted; reference the constructors/mutators
NewDiagram, Next, Field and the terminal String in your changes.

@nao1215
nao1215 merged commit ff536a6 into main Feb 24, 2026
15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant