-
Notifications
You must be signed in to change notification settings - Fork 1.6k
📖 Add docs: custom markers for unsupported file extensions #5107
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
nerdeveloper
wants to merge
1
commit into
kubernetes-sigs:master
Choose a base branch
from
nerdeveloper:docs/custom-markers-issue-4829
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+171
−0
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,170 @@ | ||
# Creating Custom Markers | ||
|
||
## Overview | ||
|
||
When using Kubebuilder as a library, you may need to scaffold files with extensions that aren't natively supported by Kubebuilder's marker system. This guide shows you how to create custom marker support for any file extension. | ||
|
||
## When to Use Custom Markers | ||
|
||
Custom markers are useful when: | ||
|
||
- You're building an external plugin for languages not natively supported by Kubebuilder | ||
- You want to scaffold files with custom extensions (`.rs`, `.java`, `.py`, `.tpl`, etc.) | ||
- You need scaffolding markers in non-Go files for your own use cases | ||
- Your file extensions aren't (and shouldn't be) part of the core `commentsByExt` map | ||
|
||
## Understanding Markers | ||
|
||
Markers are special comments used by Kubebuilder for scaffolding purposes. They indicate where code can be inserted or modified. The core Kubebuilder marker system only supports `.go`, `.yaml`, and `.yml` files by default. | ||
|
||
Example of a marker in a Go file: | ||
```go | ||
// +kubebuilder:scaffold:imports | ||
``` | ||
|
||
## Implementation Example | ||
|
||
Here's how to implement custom markers for Rust files (`.rs`). This same pattern can be applied to any file extension. | ||
|
||
### Define Your Marker Type | ||
|
||
```go | ||
// pkg/markers/rust.go | ||
package markers | ||
|
||
import ( | ||
"fmt" | ||
"path/filepath" | ||
"strings" | ||
) | ||
|
||
const RustPluginPrefix = "+rust:scaffold:" | ||
|
||
type RustMarker struct { | ||
prefix string | ||
comment string | ||
value string | ||
} | ||
|
||
func NewRustMarker(path string, value string) (RustMarker, error) { | ||
ext := filepath.Ext(path) | ||
if ext != ".rs" { | ||
return RustMarker{}, fmt.Errorf("expected .rs file, got %s", ext) | ||
} | ||
|
||
return RustMarker{ | ||
prefix: formatPrefix(RustPluginPrefix), | ||
comment: "//", | ||
value: value, | ||
}, nil | ||
} | ||
|
||
func (m RustMarker) String() string { | ||
return m.comment + " " + m.prefix + m.value | ||
} | ||
|
||
func formatPrefix(prefix string) string { | ||
trimmed := strings.TrimSpace(prefix) | ||
var builder strings.Builder | ||
if !strings.HasPrefix(trimmed, "+") { | ||
builder.WriteString("+") | ||
} | ||
builder.WriteString(trimmed) | ||
if !strings.HasSuffix(trimmed, ":") { | ||
builder.WriteString(":") | ||
} | ||
return builder.String() | ||
} | ||
``` | ||
|
||
### Use in Template Files | ||
|
||
```go | ||
package templates | ||
|
||
import ( | ||
"fmt" | ||
"path/filepath" | ||
"sigs.k8s.io/kubebuilder/v4/pkg/machinery" | ||
"github.com/yourorg/yourplugin/pkg/markers" | ||
) | ||
|
||
type RustMainFile struct { | ||
machinery.TemplateMixin | ||
machinery.ProjectNameMixin | ||
} | ||
|
||
func (f *RustMainFile) SetTemplateDefaults() error { | ||
if f.Path == "" { | ||
f.Path = filepath.Join("src", "main.rs") | ||
} | ||
|
||
marker, err := markers.NewRustMarker(f.Path, "imports") | ||
if err != nil { | ||
return err | ||
} | ||
|
||
f.TemplateBody = fmt.Sprintf(`// Generated by Rust Plugin | ||
%s | ||
|
||
use std::error::Error; | ||
|
||
fn main() -> Result<(), Box<dyn Error>> { | ||
println!("Hello from %s!"); | ||
Ok(()) | ||
} | ||
`, marker.String(), f.ProjectName) | ||
|
||
return nil | ||
} | ||
``` | ||
|
||
### Integrate with External Plugin | ||
|
||
```go | ||
package main | ||
|
||
import ( | ||
"sigs.k8s.io/kubebuilder/v4/pkg/plugin" | ||
"sigs.k8s.io/kubebuilder/v4/pkg/plugin/external" | ||
"github.com/yourorg/yourplugin/pkg/templates" | ||
) | ||
|
||
func main() { | ||
p := &external.Plugin{ | ||
Name: "rust.kubebuilder.io", | ||
Version: plugin.Version{Number: 1, Stage: plugin.Alpha}, | ||
|
||
Init: func(req external.PluginRequest) external.PluginResponse { | ||
mainFile := &templates.RustMainFile{} | ||
|
||
return external.PluginResponse{ | ||
Universe: req.Universe, | ||
Files: []machinery.File{mainFile}, | ||
} | ||
}, | ||
} | ||
|
||
external.Run(p) | ||
} | ||
``` | ||
|
||
## Adapting for Other Languages | ||
|
||
To support other file extensions, modify the marker implementation by changing: | ||
|
||
- The comment syntax (e.g., `//` for Java, `#` for Python, `{{/* ... */}}` for templates) | ||
- The file extension check (e.g., `.java`, `.py`, `.tpl`) | ||
- The marker prefix (e.g., `+java:scaffold:`, `+python:scaffold:`) | ||
|
||
## Key Considerations | ||
|
||
1. **Unique Prefixes**: Choose a unique prefix for your plugin to avoid conflicts (e.g., `+rust:scaffold:`, `+java:scaffold:`) | ||
|
||
2. **Comment Syntax**: Different languages have different comment syntax. Ensure you map the correct comment style for each file extension | ||
|
||
3. **Error Handling**: Validate file extensions and return clear error messages for unsupported files | ||
|
||
4. **Testing**: Test your marker implementation with various scenarios to ensure reliability | ||
Comment on lines
+160
to
+168
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think all is great !!! |
||
|
||
For more information on creating external plugins, see [External Plugins](external-plugins.md). |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Did you test those examples?
Because when it was raised seems like it was missing externalise something.
Is that working properly?
If so, could you please share in the description the POC / tests made?