| name | code-style |
| description | Apply Go code style best practices for openstack-k8s-operators operators based on gopls modernize and openstack-k8s-operators conventions |
| argument-hint | [file.go] |
| user-invocable | true |
| allowed-tools | ["Bash","Read","Grep","Glob","Edit","MultiEdit"] |
| context | fork |
Code Style for openstack-k8s-operators Operators
This skill applies and enforces Go code style best practices for openstack-k8s-operators operators, following openstack-k8s-operators conventions and gopls modernize recommendations.
Code Style Guidelines
1. Modern Go Syntax
Based on gopls modernize and lib-common patterns:
Slice Declaration
var items []string = []string{}
var items []string
Map Declaration
var configs map[string]interface{} = make(map[string]interface{})
var configs = make(map[string]interface{})
String Building
result := ""
for _, item := range items {
result += item + "\n"
}
var builder strings.Builder
for _, item := range items {
builder.WriteString(item)
builder.WriteString("\n")
}
result := builder.String()
2. Controller-Runtime Patterns
Error Handling
if err := r.Get(ctx, req.NamespacedName, &instance); err != nil {
if errors.IsNotFound(err) {
return ctrl.Result{}, nil
}
return ctrl.Result{}, fmt.Errorf("failed to get instance: %w", err)
}
Logging
log := ctrl.LoggerFrom(ctx).WithValues("instance", instance.Name)
log.Info("Starting reconciliation")
Status Updates
meta.SetStatusCondition(&instance.Status.Conditions, metav1.Condition{
Type: "Ready",
Status: metav1.ConditionTrue,
Reason: "ReconciliationSuccessful",
Message: "Instance successfully reconciled",
})
3. Error Handling
return fmt.Errorf("Failed to create configmap")
return fmt.Errorf("failed to create configmap: %w", err)
if err != nil {
return err
} else {
doSomething()
}
if err != nil {
return err
}
doSomething()
result, _ := someFunction()
result, err := someFunction()
if err != nil {
return fmt.Errorf("failed to do something: %w", err)
}
4. Naming Conventions
MAX_RETRIES := 3
func GetOwner() string {}
appId := "123"
maxRetries := 3
func Owner() string {}
appID := "123"
func (reconciler *GlanceReconciler) Reconcile(...) {}
func (this *GlanceReconciler) Reconcile(...) {}
func (r *GlanceReconciler) Reconcile(...) {}
package util
package common
package helpers
package glance
package endpoint
package condition
5. Interface Design
type Storage interface {
Get(key string) ([]byte, error)
Set(key string, value []byte) error
Delete(key string) error
List(prefix string) ([]string, error)
Watch(prefix string) <-chan Event
}
type Reader interface {
Get(key string) ([]byte, error)
}
func NewStore() StoreInterface { return &store{} }
func NewStore() *Store { return &store{} }
6. Context and Concurrency
type Server struct {
ctx context.Context
}
func (s *Server) Process(ctx context.Context, req Request) error {}
go func() {
for {
doWork()
}
}()
go func() {
for {
select {
case <-ctx.Done():
return
case item := <-ch:
process(item)
}
}
}()
7. openstack-k8s-operators Operator Conventions
Finalizer Handling
const FinalizerName = "operator.openstack.org/finalizer"
if instance.DeletionTimestamp != nil {
return r.handleDeletion(ctx, &instance)
}
if !controllerutil.ContainsFinalizer(&instance, FinalizerName) {
controllerutil.AddFinalizer(&instance, FinalizerName)
return ctrl.Result{}, r.Update(ctx, &instance)
}
Resource Management
if err := ctrl.SetControllerReference(&instance, resource, r.Scheme); err != nil {
return fmt.Errorf("failed to set owner reference: %w", err)
}
8. Testing Patterns
Ginkgo Best Practices
var _ = Describe("Nova Controller", func() {
Context("When creating a Nova instance", func() {
BeforeEach(func() {
})
It("Should create required resources", func() {
})
})
})
Mock Usage
type ServiceInterface interface {
CreateService(ctx context.Context, svc *corev1.Service) error
}
Automated Style Fixes
The skill provides automated fixes for:
1. Modernization
- Convert old slice/map declarations
- Update string concatenation to use strings.Builder
- Fix inefficient loops and patterns
- Apply gopls modernize suggestions
2. Imports
- Organize imports according to Go conventions
- Remove unused imports
- Group standard, third-party, and local imports
3. Variable Naming
- Apply Go naming conventions
- Fix exported vs unexported naming
- Ensure consistent abbreviations
4. Function Signatures
- Add context parameters where missing
- Proper error return patterns
- Consistent receiver naming
Style Enforcement Tools
Built-in Analyzers
gopls check <file>
gopls fix -a fillstruct,unusedparam <file>
golangci-lint run --enable-all
Custom Rules
- openstack-k8s-operators-specific patterns
- Controller-runtime best practices
- OpenStack operator conventions
- lib-common integration patterns
Integration with Development Workflow
Pre-commit Hooks
repos:
- repo: local
hooks:
- id: go-style-check
name: Go Style Check
entry: ./scripts/style-check.sh
language: script
files: '\.go$'
IDE Configuration
{
"go.lintTool": "golangci-lint",
"go.lintFlags": ["--config", ".golangci.yml"],
"gopls": {
"experimentalPostfixCompletions": true,
"analyses": {
"unusedparams": true,
"shadow": true
}
}
}
Usage
Invoke /code-style to:
- Analyze Current Code: Scan for style issues and improvement opportunities
- Apply Automated Fixes: Fix common patterns and modernize syntax
- Generate Style Report: Detailed analysis with specific recommendations
- Create Action Items: Use TodoWrite to track style improvements
Examples
/code-style analyze-project
/code-style fix-file controllers/nova_controller.go
/code-style check-libcommon
/code-style modernize
Reference