How moul/protoc-gen-gotemplate works
Project Type and Purpose
• This is an open‑source code generation tool / protoc plugin (“protoc‑gen‑gotemplate”).
• It plugs into the protoc compiler, reads .proto files, constructs an AST (via protoc-gen-go helpers), and then applies user‑supplied Go text‑templates to generate code, scripts, or data files.
• It also ships an optional Web Editor (in cmd/web-editor) that lets you play with .proto + template pairs in your browser.
Key Architectural Components
A. External Tools and Inputs
• protoc (Google’s Protobuf compiler) – invokes the plugin
• .proto source files & user templates directory
B. Plugin CLI (main.go, helpers/, vendor/)
1. CLI Entrypoint (root main.go + Makefile + Dockerfile)
• Parses plugin‑specific flags (template_dir, destination_dir, debug, single‑package‑mode, etc.)
• Invoked by protoc --gotemplate_out=…
2. AST Builder
• Leverages protoc-gen-go helper functions to transform .proto descriptors into an internal AST
3. Template Engine
• Loads every *.tmpl in the template directory (preserving subfolders)
• Constructs a funcmap: combines Sprig helpers + custom helpers in helpers/ (e.g., goType, camelCase, httpPath, etc.)
• For each AST + template, executes text/template to emit output files
4. Output Writer
• Maps the template sub‑path to the target file path (drops the .tmpl extension) under destination_dir
C. Web Editor (cmd/web-editor/)
• A small HTTP server serving static/index.html
• Loads the same plugin core as a library to process user input in real time
• Provides a browser UI for live generation demos
D. Containerization & CI
• Dockerfile / GitHub Actions workflows build / test / release the plugin image on Docker Hub
• Makefile and .releaserc.js automate versioning and publishing
Relationships and Data Flows
• Directional flow:
[protoc] ──> [protoc‑gen‑gotemplate CLI] ──> (parses flags, loads .proto)
└─> [AST Builder] ──> [Template Engine (+ FuncMap)] ──> [Output Writer] ──> generated files
• Web Editor path:
[Browser] ↔ HTTP ↔ [Web‑Editor Server] ↔ Plugin Core → on‑the‑fly generation
• Docker wraps the CLI entrypoint, mounting the project directory and invoking the plugin inside a container.
Architectural Patterns & Design Principles
• Plugin Architecture: conforms to the protoc plugin interface
• Modular Layers: CLI → AST → Template Engine → I/O
• Separation of Concerns: core generator is decoupled from the Web UI
• Extensibility: user‑supplied templates + funcmap enable custom output formats
• protoc ➔ plugin CLI ➔ AST Builder ➔ Template Engine ➔ File System
• Browser ↔ HTTP Server ↔ plugin core
• External dependencies (green)
• Core modules (blue)
• Data stores / file I/O (gray)
• Network layer (orange for HTTP)
• Annotations for key technologies: Go, text/template, Sprig, protoc-gen-go, Docker