Add template support for issue creation (bd-164b)

- Built-in templates: epic, bug, feature (embedded in binary)
- Custom templates in .beads/templates/ (override built-ins)
- Commands: bd template list/show/create
- Flag: bd create --from-template <name> "Title"
- Template fields: description, type, priority, labels, design, acceptance
- Security: sanitize template names to prevent path traversal
- Flag precedence: explicit flags override template defaults
- Tests: template loading, security, flag precedence
- Docs: commands/template.md and README.md updated

Closes bd-164b

Amp-Thread-ID: https://ampcode.com/threads/T-118fe54f-b112-4f99-a3d9-b7df53fb7284
Co-authored-by: Amp <amp@ampcode.com>
This commit is contained in:
Steve Yegge
2025-11-03 20:31:11 -08:00
parent d2328f23bf
commit eb434dd08c
19 changed files with 1192 additions and 327 deletions

View File

@@ -19,6 +19,7 @@ var createCmd = &cobra.Command{
Args: cobra.MinimumNArgs(0), // Changed to allow no args when using -f
Run: func(cmd *cobra.Command, args []string) {
file, _ := cmd.Flags().GetString("file")
fromTemplate, _ := cmd.Flags().GetString("from-template")
// If file flag is provided, parse markdown and create multiple issues
if file != "" {
@@ -52,13 +53,51 @@ var createCmd = &cobra.Command{
fmt.Fprintf(os.Stderr, "Error: title required (or use --file to create from markdown)\n")
os.Exit(1)
}
// Load template if specified
var tmpl *Template
if fromTemplate != "" {
var err error
tmpl, err = loadTemplate(fromTemplate)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
// Get field values, preferring explicit flags over template defaults
description, _ := cmd.Flags().GetString("description")
if description == "" && tmpl != nil {
description = tmpl.Description
}
design, _ := cmd.Flags().GetString("design")
if design == "" && tmpl != nil {
design = tmpl.Design
}
acceptance, _ := cmd.Flags().GetString("acceptance")
if acceptance == "" && tmpl != nil {
acceptance = tmpl.AcceptanceCriteria
}
priority, _ := cmd.Flags().GetInt("priority")
if cmd.Flags().Changed("priority") == false && tmpl != nil {
priority = tmpl.Priority
}
issueType, _ := cmd.Flags().GetString("type")
if !cmd.Flags().Changed("type") && tmpl != nil && tmpl.Type != "" {
// Flag not explicitly set and template has a type, use template
issueType = tmpl.Type
}
assignee, _ := cmd.Flags().GetString("assignee")
labels, _ := cmd.Flags().GetStringSlice("labels")
if len(labels) == 0 && tmpl != nil && len(tmpl.Labels) > 0 {
labels = tmpl.Labels
}
explicitID, _ := cmd.Flags().GetString("id")
parentID, _ := cmd.Flags().GetString("parent")
externalRef, _ := cmd.Flags().GetString("external-ref")
@@ -259,6 +298,7 @@ var createCmd = &cobra.Command{
func init() {
createCmd.Flags().StringP("file", "f", "", "Create multiple issues from markdown file")
createCmd.Flags().String("from-template", "", "Create issue from template (e.g., 'epic', 'bug', 'feature')")
createCmd.Flags().String("title", "", "Issue title (alternative to positional argument)")
createCmd.Flags().StringP("description", "d", "", "Issue description")
createCmd.Flags().String("design", "", "Design notes")

View File

@@ -17,11 +17,20 @@ var readyCmd = &cobra.Command{
limit, _ := cmd.Flags().GetInt("limit")
assignee, _ := cmd.Flags().GetString("assignee")
sortPolicy, _ := cmd.Flags().GetString("sort")
labels, _ := cmd.Flags().GetStringSlice("label")
labelsAny, _ := cmd.Flags().GetStringSlice("label-any")
// Use global jsonOutput set by PersistentPreRun (respects config.yaml + env vars)
// Normalize labels: trim, dedupe, remove empty
labels = normalizeLabels(labels)
labelsAny = normalizeLabels(labelsAny)
filter := types.WorkFilter{
// Leave Status empty to get both 'open' and 'in_progress' (bd-165)
Limit: limit,
SortPolicy: types.SortPolicy(sortPolicy),
Labels: labels,
LabelsAny: labelsAny,
}
// Use Changed() to properly handle P0 (priority=0)
if cmd.Flags().Changed("priority") {
@@ -42,6 +51,8 @@ var readyCmd = &cobra.Command{
Assignee: assignee,
Limit: limit,
SortPolicy: sortPolicy,
Labels: labels,
LabelsAny: labelsAny,
}
if cmd.Flags().Changed("priority") {
priority, _ := cmd.Flags().GetInt("priority")
@@ -261,6 +272,8 @@ func init() {
readyCmd.Flags().IntP("priority", "p", 0, "Filter by priority")
readyCmd.Flags().StringP("assignee", "a", "", "Filter by assignee")
readyCmd.Flags().StringP("sort", "s", "hybrid", "Sort policy: hybrid (default), priority, oldest")
readyCmd.Flags().StringSliceP("label", "l", []string{}, "Filter by labels (AND: must have ALL). Can combine with --label-any")
readyCmd.Flags().StringSlice("label-any", []string{}, "Filter by labels (OR: must have AT LEAST ONE). Can combine with --label")
rootCmd.AddCommand(readyCmd)
rootCmd.AddCommand(blockedCmd)
rootCmd.AddCommand(statsCmd)

310
cmd/bd/template.go Normal file
View File

@@ -0,0 +1,310 @@
package main
import (
"embed"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/fatih/color"
"github.com/spf13/cobra"
"gopkg.in/yaml.v3"
)
//go:embed templates/*.yaml
var builtinTemplates embed.FS
// Template represents an issue template
type Template struct {
Name string `yaml:"name" json:"name"`
Description string `yaml:"description" json:"description"`
Type string `yaml:"type" json:"type"`
Priority int `yaml:"priority" json:"priority"`
Labels []string `yaml:"labels" json:"labels"`
Design string `yaml:"design" json:"design"`
AcceptanceCriteria string `yaml:"acceptance_criteria" json:"acceptance_criteria"`
}
var templateCmd = &cobra.Command{
Use: "template",
Short: "Manage issue templates",
Long: `Manage issue templates for streamlined issue creation.
Templates can be built-in (epic, bug, feature) or custom templates
stored in .beads/templates/ directory.`,
}
var templateListCmd = &cobra.Command{
Use: "list",
Short: "List available templates",
Run: func(cmd *cobra.Command, args []string) {
templates, err := loadAllTemplates()
if err != nil {
fmt.Fprintf(os.Stderr, "Error loading templates: %v\n", err)
os.Exit(1)
}
if jsonOutput {
outputJSON(templates)
return
}
// Group by source
builtins := []Template{}
customs := []Template{}
for _, tmpl := range templates {
if isBuiltinTemplate(tmpl.Name) {
builtins = append(builtins, tmpl)
} else {
customs = append(customs, tmpl)
}
}
green := color.New(color.FgGreen).SprintFunc()
blue := color.New(color.FgBlue).SprintFunc()
if len(builtins) > 0 {
fmt.Printf("%s\n", green("Built-in Templates:"))
for _, tmpl := range builtins {
fmt.Printf(" %s\n", blue(tmpl.Name))
fmt.Printf(" Type: %s, Priority: P%d\n", tmpl.Type, tmpl.Priority)
if len(tmpl.Labels) > 0 {
fmt.Printf(" Labels: %s\n", strings.Join(tmpl.Labels, ", "))
}
}
fmt.Println()
}
if len(customs) > 0 {
fmt.Printf("%s\n", green("Custom Templates:"))
for _, tmpl := range customs {
fmt.Printf(" %s\n", blue(tmpl.Name))
fmt.Printf(" Type: %s, Priority: P%d\n", tmpl.Type, tmpl.Priority)
if len(tmpl.Labels) > 0 {
fmt.Printf(" Labels: %s\n", strings.Join(tmpl.Labels, ", "))
}
}
fmt.Println()
}
if len(templates) == 0 {
fmt.Println("No templates available")
}
},
}
var templateShowCmd = &cobra.Command{
Use: "show <template-name>",
Short: "Show template details",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
templateName := args[0]
tmpl, err := loadTemplate(templateName)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
if jsonOutput {
outputJSON(tmpl)
return
}
green := color.New(color.FgGreen).SprintFunc()
blue := color.New(color.FgBlue).SprintFunc()
fmt.Printf("%s %s\n", green("Template:"), blue(tmpl.Name))
fmt.Printf("Type: %s\n", tmpl.Type)
fmt.Printf("Priority: P%d\n", tmpl.Priority)
if len(tmpl.Labels) > 0 {
fmt.Printf("Labels: %s\n", strings.Join(tmpl.Labels, ", "))
}
fmt.Printf("\n%s\n%s\n", green("Description:"), tmpl.Description)
if tmpl.Design != "" {
fmt.Printf("\n%s\n%s\n", green("Design:"), tmpl.Design)
}
if tmpl.AcceptanceCriteria != "" {
fmt.Printf("\n%s\n%s\n", green("Acceptance Criteria:"), tmpl.AcceptanceCriteria)
}
},
}
var templateCreateCmd = &cobra.Command{
Use: "create <template-name>",
Short: "Create a custom template",
Long: `Create a custom template in .beads/templates/ directory.
This will create a template file that you can edit to customize
the default values for your common issue types.`,
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
templateName := args[0]
// Sanitize template name
if err := sanitizeTemplateName(templateName); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
// Ensure .beads/templates directory exists
templatesDir := filepath.Join(".beads", "templates")
if err := os.MkdirAll(templatesDir, 0755); err != nil {
fmt.Fprintf(os.Stderr, "Error creating templates directory: %v\n", err)
os.Exit(1)
}
// Create template file
templatePath := filepath.Join(templatesDir, templateName+".yaml")
if _, err := os.Stat(templatePath); err == nil {
fmt.Fprintf(os.Stderr, "Error: template '%s' already exists\n", templateName)
os.Exit(1)
}
// Default template structure
tmpl := Template{
Name: templateName,
Description: "[Describe the issue]\n\n## Additional Context\n\n[Add relevant details]",
Type: "task",
Priority: 2,
Labels: []string{},
Design: "[Design notes]",
AcceptanceCriteria: "- [ ] Acceptance criterion 1\n- [ ] Acceptance criterion 2",
}
// Marshal to YAML
data, err := yaml.Marshal(tmpl)
if err != nil {
fmt.Fprintf(os.Stderr, "Error creating template: %v\n", err)
os.Exit(1)
}
// Write template file
if err := os.WriteFile(templatePath, data, 0644); err != nil {
fmt.Fprintf(os.Stderr, "Error writing template: %v\n", err)
os.Exit(1)
}
green := color.New(color.FgGreen).SprintFunc()
fmt.Printf("%s Created template: %s\n", green("✓"), templatePath)
fmt.Printf("Edit the file to customize your template.\n")
},
}
func init() {
templateCmd.AddCommand(templateListCmd)
templateCmd.AddCommand(templateShowCmd)
templateCmd.AddCommand(templateCreateCmd)
rootCmd.AddCommand(templateCmd)
}
// loadAllTemplates loads both built-in and custom templates
func loadAllTemplates() ([]Template, error) {
templates := []Template{}
// Load built-in templates
builtins := []string{"epic", "bug", "feature"}
for _, name := range builtins {
tmpl, err := loadBuiltinTemplate(name)
if err != nil {
// Skip if not found (shouldn't happen with built-ins)
continue
}
templates = append(templates, *tmpl)
}
// Load custom templates from .beads/templates/
templatesDir := filepath.Join(".beads", "templates")
if _, err := os.Stat(templatesDir); err == nil {
entries, err := os.ReadDir(templatesDir)
if err != nil {
return nil, fmt.Errorf("reading templates directory: %w", err)
}
for _, entry := range entries {
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".yaml") {
continue
}
name := strings.TrimSuffix(entry.Name(), ".yaml")
tmpl, err := loadCustomTemplate(name)
if err != nil {
// Skip invalid templates
continue
}
templates = append(templates, *tmpl)
}
}
return templates, nil
}
// sanitizeTemplateName validates template name to prevent path traversal
func sanitizeTemplateName(name string) error {
if name != filepath.Base(name) {
return fmt.Errorf("invalid template name '%s' (no path separators allowed)", name)
}
if strings.Contains(name, "..") {
return fmt.Errorf("invalid template name '%s' (no .. allowed)", name)
}
return nil
}
// loadTemplate loads a template by name (checks custom first, then built-in)
func loadTemplate(name string) (*Template, error) {
if err := sanitizeTemplateName(name); err != nil {
return nil, err
}
// Try custom templates first
tmpl, err := loadCustomTemplate(name)
if err == nil {
return tmpl, nil
}
// Fall back to built-in templates
return loadBuiltinTemplate(name)
}
// loadBuiltinTemplate loads a built-in template
func loadBuiltinTemplate(name string) (*Template, error) {
path := fmt.Sprintf("templates/%s.yaml", name)
data, err := builtinTemplates.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("template '%s' not found", name)
}
var tmpl Template
if err := yaml.Unmarshal(data, &tmpl); err != nil {
return nil, fmt.Errorf("parsing template: %w", err)
}
return &tmpl, nil
}
// loadCustomTemplate loads a custom template from .beads/templates/
func loadCustomTemplate(name string) (*Template, error) {
path := filepath.Join(".beads", "templates", name+".yaml")
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("template '%s' not found", name)
}
var tmpl Template
if err := yaml.Unmarshal(data, &tmpl); err != nil {
return nil, fmt.Errorf("parsing template: %w", err)
}
return &tmpl, nil
}
// isBuiltinTemplate checks if a template name is a built-in template
func isBuiltinTemplate(name string) bool {
builtins := map[string]bool{
"epic": true,
"bug": true,
"feature": true,
}
return builtins[name]
}

View File

@@ -0,0 +1,44 @@
package main
import (
"testing"
)
func TestSanitizeTemplateName(t *testing.T) {
tests := []struct {
name string
input string
wantError bool
}{
{"valid simple name", "epic", false},
{"valid with dash", "my-template", false},
{"valid with underscore", "my_template", false},
{"path traversal with ../", "../etc/passwd", true},
{"path traversal with ..", "..", true},
{"absolute path", "/etc/passwd", true},
{"relative path", "foo/bar", true},
{"hidden file", ".hidden", false}, // Hidden files are okay
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := sanitizeTemplateName(tt.input)
if (err != nil) != tt.wantError {
t.Errorf("sanitizeTemplateName(%q) error = %v, wantError %v", tt.input, err, tt.wantError)
}
})
}
}
func TestLoadTemplatePathTraversal(t *testing.T) {
// Try to load a template with path traversal
_, err := loadTemplate("../../../etc/passwd")
if err == nil {
t.Error("Expected error for path traversal, got nil")
}
_, err = loadTemplate("foo/bar")
if err == nil {
t.Error("Expected error for path with separator, got nil")
}
}

193
cmd/bd/template_test.go Normal file
View File

@@ -0,0 +1,193 @@
package main
import (
"os"
"path/filepath"
"testing"
)
func TestLoadBuiltinTemplate(t *testing.T) {
tests := []struct {
name string
templateName string
wantType string
wantPriority int
wantHasLabels bool
}{
{
name: "epic template",
templateName: "epic",
wantType: "epic",
wantPriority: 1,
wantHasLabels: true,
},
{
name: "bug template",
templateName: "bug",
wantType: "bug",
wantPriority: 1,
wantHasLabels: true,
},
{
name: "feature template",
templateName: "feature",
wantType: "feature",
wantPriority: 2,
wantHasLabels: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tmpl, err := loadBuiltinTemplate(tt.templateName)
if err != nil {
t.Fatalf("loadBuiltinTemplate() error = %v", err)
}
if tmpl.Type != tt.wantType {
t.Errorf("Type = %v, want %v", tmpl.Type, tt.wantType)
}
if tmpl.Priority != tt.wantPriority {
t.Errorf("Priority = %v, want %v", tmpl.Priority, tt.wantPriority)
}
if tt.wantHasLabels && len(tmpl.Labels) == 0 {
t.Errorf("Expected labels but got none")
}
if tmpl.Description == "" {
t.Errorf("Expected description but got empty string")
}
if tmpl.AcceptanceCriteria == "" {
t.Errorf("Expected acceptance criteria but got empty string")
}
})
}
}
func TestLoadBuiltinTemplateNotFound(t *testing.T) {
_, err := loadBuiltinTemplate("nonexistent")
if err == nil {
t.Errorf("Expected error for nonexistent template, got nil")
}
}
func TestLoadCustomTemplate(t *testing.T) {
// Create temporary directory for test
tmpDir := t.TempDir()
oldWd, _ := os.Getwd()
defer os.Chdir(oldWd)
os.Chdir(tmpDir)
// Create .beads/templates directory
templatesDir := filepath.Join(".beads", "templates")
if err := os.MkdirAll(templatesDir, 0755); err != nil {
t.Fatalf("Failed to create templates directory: %v", err)
}
// Create a custom template
customTemplate := `name: custom-test
description: Test custom template
type: chore
priority: 3
labels:
- test
- custom
design: Test design
acceptance_criteria: Test acceptance
`
templatePath := filepath.Join(templatesDir, "custom-test.yaml")
if err := os.WriteFile(templatePath, []byte(customTemplate), 0644); err != nil {
t.Fatalf("Failed to write template: %v", err)
}
// Load the custom template
tmpl, err := loadCustomTemplate("custom-test")
if err != nil {
t.Fatalf("loadCustomTemplate() error = %v", err)
}
if tmpl.Name != "custom-test" {
t.Errorf("Name = %v, want custom-test", tmpl.Name)
}
if tmpl.Type != "chore" {
t.Errorf("Type = %v, want chore", tmpl.Type)
}
if tmpl.Priority != 3 {
t.Errorf("Priority = %v, want 3", tmpl.Priority)
}
if len(tmpl.Labels) != 2 {
t.Errorf("Expected 2 labels, got %d", len(tmpl.Labels))
}
}
func TestLoadTemplate_PreferCustomOverBuiltin(t *testing.T) {
// Create temporary directory for test
tmpDir := t.TempDir()
oldWd, _ := os.Getwd()
defer os.Chdir(oldWd)
os.Chdir(tmpDir)
// Create .beads/templates directory
templatesDir := filepath.Join(".beads", "templates")
if err := os.MkdirAll(templatesDir, 0755); err != nil {
t.Fatalf("Failed to create templates directory: %v", err)
}
// Create a custom template with same name as builtin
customTemplate := `name: epic
description: Custom epic override
type: epic
priority: 0
labels:
- custom-epic
design: Custom design
acceptance_criteria: Custom acceptance
`
templatePath := filepath.Join(templatesDir, "epic.yaml")
if err := os.WriteFile(templatePath, []byte(customTemplate), 0644); err != nil {
t.Fatalf("Failed to write template: %v", err)
}
// loadTemplate should prefer custom over builtin
tmpl, err := loadTemplate("epic")
if err != nil {
t.Fatalf("loadTemplate() error = %v", err)
}
// Should get custom template (priority 0) not builtin (priority 1)
if tmpl.Priority != 0 {
t.Errorf("Priority = %v, want 0 (custom template)", tmpl.Priority)
}
if len(tmpl.Labels) != 1 || tmpl.Labels[0] != "custom-epic" {
t.Errorf("Expected custom-epic label, got %v", tmpl.Labels)
}
}
func TestIsBuiltinTemplate(t *testing.T) {
tests := []struct {
name string
template string
want bool
}{
{"epic is builtin", "epic", true},
{"bug is builtin", "bug", true},
{"feature is builtin", "feature", true},
{"custom is not builtin", "custom", false},
{"random is not builtin", "random", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := isBuiltinTemplate(tt.template); got != tt.want {
t.Errorf("isBuiltinTemplate(%v) = %v, want %v", tt.template, got, tt.want)
}
})
}
}

56
cmd/bd/templates/bug.yaml Normal file
View File

@@ -0,0 +1,56 @@
# Built-in template for bug reports
name: bug
description: |
## Summary
[Brief description of the bug]
## Steps to Reproduce
1. Step 1
2. Step 2
3. Step 3
## Expected Behavior
[What should happen]
## Actual Behavior
[What actually happens]
## Environment
- OS: [e.g., macOS 15.7.1]
- Version: [e.g., bd 0.20.1]
- Additional context: [any relevant details]
## Additional Context
[Screenshots, logs, or other relevant information]
type: bug
priority: 1
labels:
- bug
design: |
## Root Cause Analysis
[Describe the underlying cause once identified]
## Proposed Fix
[Outline the solution approach]
## Impact Assessment
- Affected features: [list]
- Breaking changes: [yes/no and details]
- Migration needed: [yes/no and details]
acceptance_criteria: |
- [ ] Bug no longer reproduces with original steps
- [ ] Regression tests added
- [ ] Related edge cases tested
- [ ] Documentation updated if behavior changed

View File

@@ -0,0 +1,51 @@
# Built-in template for creating epics
name: epic
description: |
## Overview
[Describe the high-level goal and scope of this epic]
## Success Criteria
- [ ] Criteria 1
- [ ] Criteria 2
- [ ] Criteria 3
## Background
[Provide context and motivation]
## Scope
**In Scope:**
- Item 1
- Item 2
**Out of Scope:**
- Item 1
- Item 2
type: epic
priority: 1
labels:
- epic
design: |
## Architecture
[Describe the overall architecture and approach]
## Components
- Component 1: [description]
- Component 2: [description]
## Dependencies
[List external dependencies or constraints]
acceptance_criteria: |
- [ ] All child issues are completed
- [ ] Integration tests pass
- [ ] Documentation is updated
- [ ] Code review completed

View File

@@ -0,0 +1,60 @@
# Built-in template for feature requests
name: feature
description: |
## Feature Request
[Describe the desired feature]
## Motivation
[Why is this feature needed? What problem does it solve?]
## Use Cases
1. **Use Case 1**: [description]
2. **Use Case 2**: [description]
## Proposed Solution
[High-level approach to implementing this feature]
## Alternatives Considered
- **Alternative 1**: [description and why not chosen]
- **Alternative 2**: [description and why not chosen]
type: feature
priority: 2
labels:
- feature
design: |
## Technical Design
[Detailed technical approach]
## API Changes
[New commands, flags, or APIs]
## Data Model Changes
[Database schema changes if any]
## Implementation Notes
- Note 1
- Note 2
## Testing Strategy
- Unit tests: [scope]
- Integration tests: [scope]
- Manual testing: [steps]
acceptance_criteria: |
- [ ] Feature implements all described use cases
- [ ] All tests pass
- [ ] Documentation updated (README, commands)
- [ ] Examples added if applicable
- [ ] No performance regressions