|
|
3 mesi fa | |
|---|---|---|
| .idea | 3 mesi fa | |
| cmd | 3 mesi fa | |
| examples | 3 mesi fa | |
| output | 3 mesi fa | |
| pkg | 3 mesi fa | |
| testdata | 3 mesi fa | |
| tests | 3 mesi fa | |
| ANALYSIS.md | 3 mesi fa | |
| EXPORT_GUIDE.md | 3 mesi fa | |
| IMPLEMENTATION_SUMMARY.md | 3 mesi fa | |
| README.md | 3 mesi fa | |
| go.mod | 3 mesi fa | |
| go.sum | 3 mesi fa | |
| test_diagram.mmd | 3 mesi fa |
A high-performance Go implementation of Mermaid diagram parsing and rendering, providing near-complete compatibility with Mermaid.js syntax.
Mermaid-Go aims to provide a native Go alternative to Mermaid.js with:
go get github.com/your-org/mermaid-go
package main
import (
"fmt"
"log"
"mermaid-go/pkg/ast"
"mermaid-go/pkg/detector"
"mermaid-go/pkg/parser"
"mermaid-go/pkg/renderer"
)
func main() {
// Auto-detect and parse any Mermaid diagram type
input := `sequenceDiagram
participant U as User
participant S as Server
U -> S : request
S --> U : response`
// Create main parser with auto-detection
mermaidParser := parser.NewMermaidParser()
// Detect diagram type
diagramType := mermaidParser.GetDiagramType(input)
fmt.Printf("Detected diagram type: %s\n", diagramType)
// Parse the diagram
diagram, err := mermaidParser.Parse(input)
if err != nil {
log.Fatal(err)
}
// Render back to Mermaid syntax
switch d := diagram.(type) {
case *ast.SequenceDiagram:
renderer := renderer.NewSequenceRenderer()
output, _ := renderer.Render(d)
fmt.Println(output)
case *ast.StateDiagram:
renderer := renderer.NewStateRenderer()
output, _ := renderer.Render(d)
fmt.Println(output)
// ... handle other diagram types
}
}
// Parse a complex sequence diagram with loops, alternatives, and parallel sections
input := `
sequenceDiagram
participant U as User
participant W as WebApp
participant S as Server
participant D as Database
U -> W : login request
activate W
loop Authentication
W -> S : validate credentials
S -> D : query user
D --> S : user data
end
alt Valid credentials
S --> W : success
W --> U : login complete
else Invalid credentials
S --> W : failure
W --> U : login failed
end
par User actions
U -> W : browse content
and Background tasks
S -> D : cleanup sessions
end
deactivate W
`
parser := parser.NewSequenceParser()
diagram, err := parser.Parse(input)
// ... rest of the code
// Parse a state diagram with guards, actions, and notes
input := `
stateDiagram-v2
[*] --> Idle
Idle --> Processing : start [hasData] / processData
Processing --> Idle : complete [success] / cleanup
Processing --> Error : fail [error] / logError
note right of Processing : Main processing state
note left of Error : Error handling
`
parser := parser.NewStateParser()
diagram, err := parser.Parse(input)
// ... rest of the code
stateDiagram-v2 before stateDiagram)mermaid-go fully supports Unicode characters including Chinese, Japanese, and Korean:
// Chinese pie chart
input := `pie showData
title 2024年市场份额分析
"阿里巴巴" : 35
"腾讯" : 30
"百度" : 20
"字节跳动" : 15`
// Chinese sequence diagram
input := `sequenceDiagram
participant 用户 as 用户端
participant 系统 as 后端系统
用户 ->> 系统: 登录请求
系统 -->> 用户: 登录响应`
# Parse and validate a Mermaid file
go run main.go parse diagram.mmd
# Convert between formats
go run main.go convert input.mmd output.mmd
flowchart TD
A[Start] --> B[Process]
B --> C{Decision}
C -->|Yes| D[Success]
C -->|No| E[Failure]
flowchart LR
subgraph "User Actions"
A([Login]) --> B{Authenticated?}
end
subgraph "System Process"
C[Process Request] --> D[Generate Response]
end
B -->|Yes| C
B -->|No| A
%% Styling
classDef userClass fill:#e1f5fe,stroke:#01579b,stroke-width:2px
class A,B userClass
%% Interactive elements
click A "https://example.com/login" "_blank"
click C callback
flowchart TB
A([Start/End]) --> B[Rectangle]
B --> C(Rounded)
C --> D{Diamond}
D --> E[/Parallelogram/]
E --> F[\Alt Parallelogram\]
F --> G>Flag]
G --> H[[Subroutine]]
H --> I((Circle))
classDiagram
class Animal {
+String name
+int age
+makeSound() void
-validateAge(int age) boolean
}
classDiagram
%% Interface definition
class Shape {
<<interface>>
+area() double
+perimeter() double
}
%% Abstract class
class AbstractShape {
<<abstract>>
+String color
+getColor() String
+setColor(String color) void
+area()* double
}
%% Relationships
Shape <|-- AbstractShape
AbstractShape <|-- Circle
AbstractShape <|-- Rectangle
%% Notes
note "This is a shape hierarchy example"
note for Shape "Defines the basic shape interface"
classDiagram
class Calculator {
+add(int a, int b) int
+subtract(double x, double y) double
+multiply(float[] numbers) float
-validateInput(Object input) boolean
}
mermaid-go/
├── pkg/
│ ├── ast/ # Abstract Syntax Tree definitions
│ │ ├── flowchart.go
│ │ ├── class.go
│ │ └── ...
│ ├── lexer/ # Tokenization
│ │ └── lexer.go
│ ├── parser/ # Syntax analysis
│ │ ├── mermaid.go
│ │ ├── flowchart.go
│ │ ├── class.go
│ │ └── ...
│ └── renderer/ # Output generation
│ ├── mermaid.go
│ ├── flowchart.go
│ └── class.go
├── cmd/ # CLI applications
├── examples/ # Usage examples
└── tests/ # Test diagrams
go test ./...
# Test flowcharts
go run test_flowchart_advanced.go
# Test class diagrams
go run test_class_advanced.go
# Test round-trip parsing
echo 'flowchart TD; A --> B' | go run main.go validate
flowchart TD
A[Button] --> B[Action]
click A "https://example.com" "_blank"
click B callback
flowchart LR
A --> B --> C
classDef default fill:#f9f9f9,stroke:#333,stroke-width:2px
classDef highlight fill:#ff6b6b,stroke:#c92a2a,stroke-width:3px
class B highlight
flowchart TB
subgraph Frontend ["Frontend Layer"]
direction LR
A[React App] --> B[API Client]
end
subgraph Backend ["Backend Services"]
direction TB
C[REST API] --> D[Database]
end
Frontend --> Backend
parser := parser.NewMermaidParser()
parser.SetStrictMode(true) // Enable strict syntax validation
parser.SetDebugMode(true) // Enable detailed error messages
renderer := renderer.NewMermaidRenderer()
renderer.SetIndentation(" ") // Set custom indentation
renderer.SetCompactMode(false) // Pretty-print output
We welcome contributions! Here's how to get started:
git checkout -b feature/new-diagram-typego test ./...pkg/ast/pkg/parser/pkg/renderer/flowchart TD
subgraph "Client Tier"
A[Web Browser] --> B[Mobile App]
end
subgraph "Application Tier"
C[Load Balancer] --> D[API Gateway]
D --> E[Microservice 1]
D --> F[Microservice 2]
end
subgraph "Data Tier"
G[(Primary DB)] --> H[(Replica DB)]
I[Cache Layer]
end
A --> C
B --> C
E --> G
F --> G
E --> I
F --> I
classDiagram
class Vehicle {
<<abstract>>
+String brand
+int year
+start() void
+stop() void
+getInfo()* String
}
class Car {
+int doors
+String fuelType
+getInfo() String
+openTrunk() void
}
class Motorcycle {
+boolean hasSidecar
+getInfo() String
+popWheelie() void
}
Vehicle <|-- Car
Vehicle <|-- Motorcycle
note for Vehicle "Base class for all vehicles"
该项目的设计严格遵循 mermaid.js 的内部架构:
| mermaid.js | mermaid-go |
|---|---|
flow.jison |
pkg/lexer/lexer.go + pkg/parser/flowchart.go |
flowDb.ts |
pkg/parser/flowchart.go (FlowDB) |
classDiagram.jison |
pkg/parser/class.go |
types.ts |
pkg/ast/flowchart.go, pkg/ast/class.go |
flowRenderer.ts |
pkg/renderer/flowchart.go |
由 gytmtc 创建,基于 mermaid.js 的架构设计,现已扩展支持多种图表类型和高级特性。
This project is licensed under the MIT License - see the LICENSE file for details.
Current Version: 0.8.0 (Alpha) Mermaid.js Compatibility: ~82% of core features Status: Active Development