refactor to decouple commands form entrypoint for reusability and centralizing commands.

Increase reusability and composition
This commit is contained in:
Robin Olsen
2026-02-22 19:46:55 +01:00
parent 118e67dbf4
commit 33c8c05ae3
28 changed files with 305 additions and 282 deletions

View File

@@ -4,17 +4,23 @@ package cli
import (
"context"
"github.com/LazyBachelor/LazyPM/internal/commands/issues"
"github.com/LazyBachelor/LazyPM/internal/service"
"github.com/LazyBachelor/LazyPM/pkg/cli/commands"
"github.com/charmbracelet/fang"
"github.com/spf13/cobra"
)
// Config is an alias for service.Config, used to configure the CLI.
type Config = service.Config
type CLI struct{}
type CLI struct {
RootCmd *cobra.Command
}
func NewCli() *CLI {
return &CLI{}
func NewCli(rootCmd *cobra.Command) *CLI {
return &CLI{
RootCmd: rootCmd,
}
}
// Run initializes the services and executes the CLI commands.
@@ -26,9 +32,10 @@ func (c *CLI) Run(ctx context.Context, config Config) error {
defer cleanup()
commands.SetApp(app)
issuesCmd.SetApp(app)
if err := commands.Execute(); err != nil {
if err := fang.Execute(ctx, c.RootCmd,
fang.WithColorSchemeFunc(fang.AnsiColorScheme)); err != nil {
return err
}
@@ -44,9 +51,9 @@ func (c *CLI) RunWithArgs(ctx context.Context, config Config, args []string) err
defer cleanup()
commands.SetApp(app)
issuesCmd.SetApp(app)
if err := commands.ExecuteArgs(args); err != nil {
if err := issuesCmd.ExecuteArgs(args); err != nil {
return err
}

View File

@@ -1,65 +0,0 @@
package commands
import (
"fmt"
"github.com/charmbracelet/huh"
"github.com/spf13/cobra"
)
// closeCmd represents the close command,
// which allows users to close an existing issue by its ID.
var closeCmd = &cobra.Command{
Use: "close [id]",
Short: "Close an existing issue",
Long: `Close an existing issue by its ID.`,
Example: `pm close pm-abc`,
Args: cobra.ExactArgs(1),
RunE: runCloseCmd,
ValidArgsFunction: completeIssues,
}
// runCloseCmd executes the close command logic,
// which closes an issue by its ID after confirming with the user.
func runCloseCmd(cmd *cobra.Command, args []string) error {
closeID := args[0]
if closeID == "" {
return fmt.Errorf("issue ID cannot be empty")
}
app := AppFromContext(cmd.Context())
// Fetch the issue to ensure it exists before closing.
issue, err := app.Issues.GetIssue(cmd.Context(), closeID)
if err != nil {
return fmt.Errorf("error fetching issue: %w", err)
}
if issue == nil {
return fmt.Errorf("issue with ID %s not found", closeID)
}
// Ask for closing reason
if err = huh.NewInput().Value(&issue.CloseReason).
Title("Reason for closing the issue?").WithTheme(huh.ThemeBase()).Run(); err != nil {
return fmt.Errorf("error getting close reason: %w", err)
}
// Close the issue.
err = app.Issues.CloseIssue(cmd.Context(), closeID, issue.CloseReason, "", "")
if err != nil {
return fmt.Errorf("error closing issue: %w", err)
}
cmd.Println("Closed issue with ID:", closeID)
return nil
}
// init function to set up the close command and its flags.
func init() {
rootCmd.AddCommand(closeCmd)
}

View File

@@ -1,57 +0,0 @@
package commands
import (
"context"
"strings"
"github.com/LazyBachelor/LazyPM/internal/models"
"github.com/spf13/cobra"
)
// Variables for completion options and functions.
var (
typeOptions = []string{"bug", "feature", "task"}
statusOptions = []string{"open", "closed", "in_progress"}
priorityRange = []string{"0", "1", "2", "3", "4"}
)
// completionFunc returns a function that provides shell completion for the given options.
func completionFunc(options []string) func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) {
return func(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
return options, cobra.ShellCompDirectiveDefault
}
}
// completeIssues provides shell completion for issue IDs and titles.
func completeIssues(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
issues, _ := GetIssueCompletions(cmd.Context(), toComplete)
var ids []string
for _, issue := range issues {
ids = append(ids, issue.ID)
}
return ids, cobra.ShellCompDirectiveNoFileComp
}
// GetIssueCompletions fetches issues matching the toComplete string for shell completion.
func GetIssueCompletions(ctx context.Context, toComplete string) ([]models.Issue, cobra.ShellCompDirective) {
app := AppFromContext(ctx)
if app == nil {
return nil, cobra.ShellCompDirectiveNoFileComp
}
issues, err := app.Issues.AllIssues(ctx)
if err != nil {
return nil, cobra.ShellCompDirectiveNoFileComp
}
var completions []models.Issue
for _, issue := range issues {
if strings.HasPrefix(issue.ID, toComplete) {
completions = append(completions, issue)
} else if strings.HasPrefix(issue.Title, toComplete) {
completions = append(completions, issue)
}
}
return completions, cobra.ShellCompDirectiveNoFileComp
}

View File

@@ -1,119 +0,0 @@
package commands
import (
"fmt"
"strings"
"github.com/LazyBachelor/LazyPM/internal/models"
"github.com/charmbracelet/huh"
"github.com/spf13/cobra"
)
// createFlags holds the flag values for the create command
var createFlags Flags
const (
createCmdExample = `pm create New issue -d "Description" -s open -t task -p 3
pm create Fix bug --desc "Bug description" --status in_progress --type bug --priority 5`
)
// createCmd represents the create command, which allows users to create a new issue with specified details.
var createCmd = &cobra.Command{
Use: "create [title]",
Short: "Create a new issue",
Long: `Create a new issue with the specified details.`,
Example: createCmdExample,
Args: cobra.MinimumNArgs(0),
Aliases: []string{"add"},
RunE: runCreateCmd,
}
// runCreateCmd executes the create command logic,
func runCreateCmd(cmd *cobra.Command, args []string) error {
createFlags.title = strings.Join(args, " ")
// Run interactive if flag is set
if createFlags.interactive {
if err := runCreateInteractive(); err != nil {
return err
}
}
if createFlags.title == "" {
return fmt.Errorf("issue title cannot be empty")
}
issue := &models.Issue{
Title: createFlags.title,
Description: createFlags.description,
Status: models.Status(createFlags.status),
IssueType: models.IssueType(createFlags.issueType),
Priority: createFlags.priority,
}
// Create the issue using the service layer.
app := AppFromContext(cmd.Context())
err := app.Issues.CreateIssue(cmd.Context(), issue, "test_actor")
if err != nil {
return fmt.Errorf("error creating issue: %w", err)
}
// Display the created issue details to the user.
cmd.Printf("Created issue:\n%s", models.IssueString(*issue))
return nil
}
// runCreateInteractive runs the interactive mode for creating issues,
// allowing users to input issue details through a form.
func runCreateInteractive() error {
form := huh.NewForm(
huh.NewGroup(
huh.NewInput().Value(&createFlags.title).Title("Title"),
huh.NewText().Value(&createFlags.description).Title("Description")),
huh.NewGroup(
huh.NewSelect[string]().Title("Status").
Options(
huh.NewOption("Open", "open"),
huh.NewOption("Closed", "closed"),
huh.NewOption("In Progress", "in_progress"),
).Value(&createFlags.status),
huh.NewSelect[string]().Title("Type").
Options(
huh.NewOption("Bug", "bug"),
huh.NewOption("Feature", "feature"),
huh.NewOption("Task", "task"),
).Value(&createFlags.issueType),
huh.NewSelect[int]().Title("Priority").
Options(
huh.NewOption("0", 0),
huh.NewOption("1", 1),
huh.NewOption("2", 2),
huh.NewOption("3", 3),
huh.NewOption("4", 4),
).Value(&createFlags.priority),
)).WithTheme(huh.ThemeBase16())
return form.Run()
}
// init function to set up the create command and its flags.
func init() {
createCmd.Flags().BoolVarP(&createFlags.interactive, "interactive", "i", false, "Create issue interactively")
createCmd.Flags().StringVarP(&createFlags.description, "desc", "d", "", "Issue description")
createCmd.Flags().StringVarP(&createFlags.status, "status", "s", "open", "Issue status(open, closed, in_progress)")
createCmd.Flags().StringVarP(&createFlags.issueType, "type", "t", "task", "Issue type(bug, feature, task)")
createCmd.Flags().IntVarP(&createFlags.priority, "priority", "p", 0, "Issue priority(0-4)")
createCmd.RegisterFlagCompletionFunc("type", completionFunc(typeOptions))
createCmd.RegisterFlagCompletionFunc("status", completionFunc(statusOptions))
createCmd.RegisterFlagCompletionFunc("priority", completionFunc(priorityRange))
rootCmd.AddCommand(createCmd)
}

View File

@@ -1,132 +0,0 @@
package commands
import (
"context"
"fmt"
"strings"
"github.com/LazyBachelor/LazyPM/internal/models"
"github.com/charmbracelet/huh"
"github.com/spf13/cobra"
)
// Variables for delete command flag.
var (
confirmDelete bool
deleteIDs []string
deleteInteractive bool
)
// deleteCmd represents the delete command.
var deleteCmd = &cobra.Command{
Use: "delete [id]",
Short: "Delete an existing issue",
Long: `Delete an existing issue by its ID.`,
Example: `pm delete pm-abc`,
ValidArgsFunction: completeIssues,
Aliases: []string{"del", "remove", "rm"},
RunE: runDeleteCmd,
}
// runDeleteCmd executes the delete command logic,
// which deletes an issue by its ID after confirming with the user.
func runDeleteCmd(cmd *cobra.Command, args []string) error {
deleteID := strings.Join(args, " ")
if deleteInteractive {
if err := runDeleteInteractive(cmd.Context()); err != nil {
return err
}
return nil
}
if deleteID == "" {
return fmt.Errorf("issue ID cannot be empty")
}
app := AppFromContext(cmd.Context())
// Fetch the issue to ensure it exists before deletion.
issue, err := app.Issues.GetIssue(cmd.Context(), deleteID)
if err != nil {
return fmt.Errorf("error fetching issue: %w", err)
}
if issue == nil {
return fmt.Errorf("issue with ID %s not found", deleteID)
}
// Prompt for confirmation if not already confirmed via flag.
if !cmd.Flags().Changed("yes") {
huh.NewConfirm().Value(&confirmDelete).
Title("You want to delete this issue?").
Inline(true).WithTheme(huh.ThemeBase()).Run()
}
// If user did not confirm, cancel deletion.
if !confirmDelete {
cmd.Println("Deletion cancelled.")
return nil
}
// Delete the issue.
err = app.Issues.DeleteIssue(cmd.Context(), deleteID)
if err != nil {
return fmt.Errorf("error deleting issue: %w", err)
}
cmd.Println("Deleted issue with ID:", deleteID)
return nil
}
// runDeleteInteractive runs the interactive mode for deleting issues,
// allowing users to select multiple issues for deletion.
func runDeleteInteractive(ctx context.Context) error {
app := AppFromContext(ctx)
options := []huh.Option[string]{}
issues, err := app.Issues.SearchIssues(ctx, "", models.IssueFilter{})
if err != nil {
return fmt.Errorf("error fetching issues: %w", err)
}
for _, issue := range issues {
desc := fmt.Sprintf("%s: %s", issue.ID, issue.Title)
options = append(options, huh.NewOption(desc, issue.ID))
}
form := huh.NewForm(
huh.NewGroup(
huh.NewMultiSelect[string]().
Options(options...).Value(&deleteIDs).
Title("Select issues to delete"))).WithTheme(huh.ThemeBase())
if err := form.Run(); err != nil {
return fmt.Errorf("error running interactive form: %w", err)
}
if len(deleteIDs) == 0 {
return fmt.Errorf("no issues selected for deletion")
}
for _, id := range deleteIDs {
err := app.Issues.DeleteIssue(ctx, id)
if err != nil {
return fmt.Errorf("error deleting issue with ID %s: %w", id, err)
}
fmt.Printf("Deleted issue with ID: %s\n", id)
}
return nil
}
// init function to set up the delete command and its flags.
func init() {
deleteCmd.Flags().BoolVarP(&deleteInteractive, "interactive", "i", false, "Delete issues interactively")
deleteCmd.Flags().BoolVarP(&confirmDelete, "yes", "y", true, "Confirm deletion without prompt")
rootCmd.AddCommand(deleteCmd)
}

View File

@@ -1,86 +0,0 @@
package commands
import (
"strings"
"github.com/LazyBachelor/LazyPM/internal/models"
"github.com/spf13/cobra"
)
// Variables for get-issues command flags.
var listFlags Flags
const (
lsExamples = `pm list [id|title|description]
pm list --status open --type bug
pm list --title "New feature" --desc "feature description"
pm list -p 1 -l 10`
)
// getIssuesCmd represents the get issues command.
var getIssuesCmd = &cobra.Command{
Use: "list [search query]",
Short: "List all issues",
Long: `List all issues in the project management system.`,
Example: lsExamples,
Aliases: []string{"ls", "search"},
Args: cobra.MinimumNArgs(0),
RunE: runGetIssuesCmd,
}
// runGetIssuesCmd executes the get issues command logic,
// which retrieves and displays a list of issues based on the provided search query and filters.
func runGetIssuesCmd(cmd *cobra.Command, args []string) error {
queryArg := strings.Join(args, " ")
filter := models.IssueFilter{
TitleSearch: listFlags.title,
DescriptionContains: listFlags.description,
Limit: listFlags.limit,
}
// Only set filter fields if the corresponding flags
// were explicitly provided by the user.
if cmd.Flags().Changed("status") {
s := models.Status(listFlags.status)
filter.Status = &s
}
if cmd.Flags().Changed("type") {
t := models.IssueType(listFlags.issueType)
filter.IssueType = &t
}
if cmd.Flags().Changed("priority") {
filter.Priority = &listFlags.priority
}
// Fetch issues based on the search query and filters.
app := AppFromContext(cmd.Context())
issuesPtr, err := app.Issues.SearchIssues(cmd.Context(), queryArg, filter)
if err != nil {
return err
}
// Convert the returned issue pointers to issue values and print them.
issues := models.IssuesPtrToIssues(issuesPtr)
models.PrintIssues(issues)
return nil
}
// init function to set up the get issues command and its flags.
func init() {
getIssuesCmd.Flags().StringVar(&listFlags.title, "title", "", "Filter issues by title")
getIssuesCmd.Flags().StringVarP(&listFlags.description, "desc", "d", "", "Filter issues by description")
getIssuesCmd.Flags().StringVarP(&listFlags.status, "status", "s", "", "Filter issues by status (open, closed, in_progress)")
getIssuesCmd.Flags().StringVarP(&listFlags.issueType, "type", "t", "", "Filter issues by type (bug, feature, task)")
getIssuesCmd.Flags().IntVarP(&listFlags.priority, "priority", "p", 0, "Filter issues by priority (0-4)")
getIssuesCmd.Flags().IntVarP(&listFlags.limit, "limit", "l", 25, "Limit the number of issues returned")
getIssuesCmd.RegisterFlagCompletionFunc("status", completionFunc(statusOptions))
getIssuesCmd.RegisterFlagCompletionFunc("type", completionFunc(typeOptions))
getIssuesCmd.RegisterFlagCompletionFunc("priority", completionFunc(priorityRange))
rootCmd.AddCommand(getIssuesCmd)
}

View File

@@ -1,48 +0,0 @@
package commands
import (
"github.com/LazyBachelor/LazyPM/internal/models"
"github.com/spf13/cobra"
)
// getIssueCmd represents the get issue command.
var getIssueCmd = &cobra.Command{
Use: "describe [issue ID]",
Short: "Get issue details",
Long: `Get issue details by ID`,
ValidArgsFunction: completeIssues,
Aliases: []string{"get", "read"},
Args: cobra.ExactArgs(1),
RunE: runGetCmd,
}
// runGetCmd executes the get issue command logic,
// which retrieves and displays issue details by its ID.
func runGetCmd(cmd *cobra.Command, args []string) error {
issueID := args[0]
// Fetch the issue details using the service layer.
app := AppFromContext(cmd.Context())
issuePtr, err := app.Issues.GetIssue(cmd.Context(), issueID)
if err != nil {
return err
}
// If the issue is not found, inform the user.
if issuePtr == nil {
cmd.Printf("Issue with ID %s not found\n", issueID)
return nil
}
// Display the issue details to the user.
cmd.Println(models.IssueString(*issuePtr))
return nil
}
// init function to set up the get issue command.
func init() {
rootCmd.AddCommand(getIssueCmd)
}

View File

@@ -1,93 +0,0 @@
package commands
import (
"bytes"
"context"
"github.com/LazyBachelor/LazyPM/internal/service"
"github.com/charmbracelet/fang"
"github.com/spf13/cobra"
)
type contextKey string
const appKey contextKey = "app"
// app is a package-level variable used during command setup
var app *service.App
// Flags struct to hold command-line flag values for issues.
type Flags struct {
interactive bool
limit int
title string
description string
status string
issueType string
priority int
}
// rootCmd is the base command for the CLI application.
var rootCmd = &cobra.Command{
Short: "Project Management CLI",
Long: `Project Management CLI for managing issues and tasks.`,
PersistentPreRun: func(cmd *cobra.Command, args []string) {
// Inject app into context for all commands
if app != nil {
cmd.SetContext(context.WithValue(cmd.Context(), appKey, app))
}
},
}
// SetApp sets the app variable for use in command execution.
// Must be called before executing any commands to ensure services are available.
func SetApp(application *service.App) {
app = application
rootCmd.Use = app.Config.RootCmd
}
// AppFromContext retrieves the App from the command context
func AppFromContext(ctx context.Context) *service.App {
if a, ok := ctx.Value(appKey).(*service.App); ok {
return a
}
// Fallback to package-level app (for testing or edge cases)
return app
}
// Execute executes the root command using the fang library.
func Execute() error {
return fang.Execute(context.Background(), rootCmd,
fang.WithColorSchemeFunc(fang.AnsiColorScheme))
}
// ExecuteArgs executes the command with the given arguments using the fang library.
func ExecuteArgs(args []string) error {
rootCmd.SetArgs(args)
return fang.Execute(context.Background(), rootCmd,
fang.WithColorSchemeFunc(fang.AnsiColorScheme))
}
// ExecuteArgsString executes the command with the given arguments and returns the output as a string.
// This is useful for testing command outputs and used in the REPL
func ExecuteArgsString(args []string) (string, error) {
buf := new(bytes.Buffer)
rootCmd.SetOut(buf)
rootCmd.SetErr(buf)
rootCmd.SetArgs(args)
err := rootCmd.Execute()
return buf.String(), err
}
// init function to set up the command hierarchy and options.
func init() {
rootCmd.CompletionOptions.DisableDefaultCmd = false
rootCmd.AddGroup(&cobra.Group{ID: "help", Title: "Helping Commands"})
rootCmd.SetCompletionCommandGroupID("help")
rootCmd.SetHelpCommandGroupID("help")
}

View File

@@ -1,46 +0,0 @@
package commands
import (
"github.com/LazyBachelor/LazyPM/pkg/task"
"github.com/spf13/cobra"
)
// replInstance holds a reference to the REPL for accessing validation feedback
var replInstance interface {
GetCurrentFeedback() task.ValidationFeedback
}
// SetRepl sets the REPL instance for use by commands
func SetRepl(repl interface {
GetCurrentFeedback() task.ValidationFeedback
}) {
replInstance = repl
}
// StatusCmd displays the current task validation status
var StatusCmd = &cobra.Command{
Use: "status",
Short: "Check task validation status",
Long: "Displays the current task validation status and feedback.",
RunE: runStatusCmd,
}
func runStatusCmd(cmd *cobra.Command, args []string) error {
if replInstance == nil {
cmd.Println("No task validation available")
return nil
}
feedback := replInstance.GetCurrentFeedback()
if feedback.Message == "" {
cmd.Println("No validation status available yet.")
return nil
}
cmd.Print(feedback.Message)
return nil
}
func init() {
rootCmd.AddCommand(StatusCmd)
}

View File

@@ -1,102 +0,0 @@
package commands
import (
"fmt"
"github.com/LazyBachelor/LazyPM/internal/models"
"github.com/spf13/cobra"
)
var updateFlags Flags
var updateCmd = &cobra.Command{
Use: "update [issue ID]",
Short: "Update an existing issue",
Long: `Update an existing issue by its ID with the specified details.`,
Example: `pm update pm-001 --title "New title" -d "Description" -s in_progress --type task -p 3`,
RunE: runUpdateCmd,
Aliases: []string{"edit"},
Args: cobra.ExactArgs(1),
ValidArgsFunction: completeIssues,
}
func runUpdateCmd(cmd *cobra.Command, args []string) error {
issueID := args[0]
app := AppFromContext(cmd.Context())
issue, err := app.Issues.GetIssue(cmd.Context(), issueID)
if err != nil {
return fmt.Errorf("error getting issue: %w", err)
}
if issue == nil {
return fmt.Errorf("issue with ID %s not found", issueID)
}
updates, err := getUpdateValues(cmd)
if err != nil {
return fmt.Errorf("error getting update values: %w", err)
}
err = app.Issues.UpdateIssue(cmd.Context(), issueID, updates, "test_actor")
if err != nil {
return fmt.Errorf("error updating issue: %w", err)
}
updatedIssue, err := app.Issues.GetIssue(cmd.Context(), issueID)
if err != nil {
return fmt.Errorf("error getting updated issue: %w", err)
}
cmd.Printf("Updated issue to:\n%s", models.IssueString(*updatedIssue))
return nil
}
func init() {
updateCmd.Flags().StringVar(&updateFlags.title, "title", "", "New issue title")
updateCmd.Flags().StringVarP(&updateFlags.description, "desc", "d", "", "New issue description")
updateCmd.Flags().StringVarP(&updateFlags.status, "status", "s", "", "New issue status(open, closed, in_progress)")
updateCmd.Flags().StringVarP(&updateFlags.issueType, "type", "t", "", "New issue type(bug, feature, task)")
updateCmd.Flags().IntVarP(&updateFlags.priority, "priority", "p", 0, "New issue priority(0-5)")
updateCmd.RegisterFlagCompletionFunc("type", completionFunc(typeOptions))
updateCmd.RegisterFlagCompletionFunc("status", completionFunc(statusOptions))
updateCmd.RegisterFlagCompletionFunc("priority", completionFunc(priorityRange))
rootCmd.AddCommand(updateCmd)
}
func getUpdateValues(cmd *cobra.Command) (map[string]interface{}, error) {
updates := make(map[string]interface{})
if cmd.Flags().Changed("title") {
if updateFlags.title == "" {
return updates, fmt.Errorf("issue title cannot be empty")
}
updates["title"] = updateFlags.title
}
if cmd.Flags().Changed("desc") {
updates["description"] = updateFlags.description
}
if cmd.Flags().Changed("status") {
updates["status"] = updateFlags.status
}
if cmd.Flags().Changed("type") {
updates["issue_type"] = updateFlags.issueType
}
if cmd.Flags().Changed("priority") {
updates["priority"] = updateFlags.priority
}
if len(updates) == 0 {
return updates, fmt.Errorf("no updates specified")
}
return updates, nil
}

View File

@@ -1,36 +0,0 @@
package repl
import (
"strings"
"github.com/c-bata/go-prompt"
)
// completer provides suggestions for the REPL input based on the current input text.
func completer(d prompt.Document) []prompt.Suggest {
text := d.TextBeforeCursor() // Gets the text before the cursor as a string.
words := strings.Fields(text) // Split the string into words as []string.
// If there are no words, return no suggestions.
if len(words) == 0 {
return nil
}
// If the first word is not "pm", only provide root-level suggestions.
if words[0] != "pm" {
return filterByPrefix(rootSuggestions, words[0])
}
// If the first word is "pm", provide command and flag suggestions based on the context.
pmWords := words[1:]
if len(words) == 1 || (len(pmWords) == 1 && !strings.HasSuffix(text, " ")) {
return commandSuggestions(pmWords)
}
// If the last word starts with a "-", provide flag suggestions for the current command.
if len(pmWords) >= 1 {
return flagSuggestions(pmWords[0], pmWords, text)
}
return nil
}

View File

@@ -1,55 +0,0 @@
package repl
import (
"os/exec"
"strings"
"github.com/LazyBachelor/LazyPM/pkg/cli/commands"
)
// execute processes the input command and returns the output
// or an error if it occurs. It handles what type of command is being executed,
// whether it's a PM command or a shell command, and routes it accordingly.
func execute(input string) (string, error) {
if input == "" {
return "", nil
}
if input == "help" {
return ReplHelp, nil
}
if input == "title" {
return ReplTitle, nil
}
if after, ok := strings.CutPrefix(input, "pm"); ok {
return executePMCommand(after)
}
return executeShellCommand(input)
}
// executeShellCommand executes a shell command
// and returns its output or an error if it occurs.
func executeShellCommand(input string) (string, error) {
parts := strings.Fields(input)
if len(parts) == 0 {
return "", nil
}
cmd := exec.Command(parts[0], parts[1:]...)
output, err := cmd.CombinedOutput()
return string(output), err
}
// executePMCommand executes a PM command using the commands package
// and returns its output or an error if it occurs.
func executePMCommand(input string) (string, error) {
parts := strings.Fields(input)
if len(parts) == 0 {
return "", nil
}
output, err := commands.ExecuteArgsString(parts)
return output, err
}

View File

@@ -1,22 +0,0 @@
package repl
import "github.com/c-bata/go-prompt"
const PromptPrefix = "> "
const OptionMaxSuggestions = 5
// promptOptions returns a slice of prompt.Option
// to configure the behavior and appearance of the REPL prompt.
func promptOptions(history []string) []prompt.Option {
return []prompt.Option{
prompt.OptionPrefixTextColor(prompt.Cyan),
prompt.OptionMaxSuggestion(OptionMaxSuggestions),
prompt.OptionSuggestionBGColor(prompt.DefaultColor),
prompt.OptionSelectedSuggestionBGColor(prompt.DefaultColor),
prompt.OptionDescriptionBGColor(prompt.DefaultColor),
prompt.OptionSelectedDescriptionBGColor(prompt.DefaultColor),
prompt.OptionPreviewSuggestionBGColor(prompt.DefaultColor),
prompt.OptionScrollbarBGColor(prompt.DefaultColor),
prompt.OptionHistory(history),
}
}

View File

@@ -1,139 +0,0 @@
// Package repl implements the Read-Eval-Print Loop (REPL) for the PM CLI.
package repl
import (
"context"
"fmt"
"os"
"strings"
"github.com/LazyBachelor/LazyPM/internal/service"
"github.com/LazyBachelor/LazyPM/pkg/cli"
"github.com/LazyBachelor/LazyPM/pkg/cli/commands"
"github.com/LazyBachelor/LazyPM/pkg/cli/styles"
"github.com/LazyBachelor/LazyPM/pkg/task"
"github.com/c-bata/go-prompt"
"golang.org/x/term"
)
const (
ReplHelp = `Type 'pm help' for available PM commands.
Type 'pm status' to check task progress.
You can also run shell commands directly. Type 'exit' or 'quit' to leave.`
ReplTitle = "Welcome to Project Management CLI! " + ReplHelp
)
type REPL struct {
feedbackChan chan task.ValidationFeedback
quitChan chan bool
currentFeedback task.ValidationFeedback
exitRequested bool
}
func NewRepl() *REPL {
return &REPL{}
}
// Run starts the interactive Read-Eval-Print Loop for the PM CLI.
func (r *REPL) Run(ctx context.Context, config cli.Config) error {
// Set terminal to raw mode to capture input properly in the REPL.
// This allows us to handle input character by character and provide a better user experience.
// We also ensure that the terminal state is restored when the REPL exits, even if an error occurs.
oldState, err := term.GetState(int(os.Stdin.Fd()))
if err != nil {
return fmt.Errorf("failed to get terminal state: %w", err)
}
defer term.Restore(int(os.Stdin.Fd()), oldState)
// Initialize services for beads, config and stats.
app, cleanup, err := service.NewServices(ctx, config)
if err != nil {
return fmt.Errorf("failed to initialize services: %w", err)
}
defer cleanup()
// Make sure to set app, to ensure they are available.
commands.SetApp(app)
// Set the REPL instance so status command can access it
commands.SetRepl(r)
fmt.Println(styles.TitleStyle.Render(ReplTitle)) // Print REPL title.
// Start goroutine to watch for validation feedback and quit signals
if r.feedbackChan != nil && r.quitChan != nil {
go r.watchValidation()
}
// history keeps track of command history.
// This enables navigating through previous commands.
var history []string
// Start the REPL loop, which continues until the user types "exit" or "quit" or task completes.
for !r.exitRequested {
// Check if we should exit before prompting (non-blocking check)
if r.exitRequested {
break
}
// Prompt the user for input, and provide suggestions.
input := prompt.Input(
PromptPrefix,
completer,
promptOptions(history)...,
)
// Check again after prompt returns (in case validation completed while waiting)
if r.exitRequested {
break
}
// Trim whitespace from the input to ensure consistent command processing.
input = strings.TrimSpace(input)
// If the user types "exit" or "quit", break the loop and exit the REPL.
if input == "exit" || input == "quit" {
fmt.Println("Goodbye!")
break
}
// Add the input to the history for future navigation.
history = append(history, input)
output, _ := execute(input) // Ignore errors for now, gives better ux
fmt.Println(styles.CommandStyle.Render(output)) // Print the output of the command in a styled format.
}
return nil
}
func (r *REPL) watchValidation() {
for {
select {
case feedback := <-r.feedbackChan:
r.currentFeedback = feedback
if feedback.Success {
fmt.Printf("\n%s\n", styles.TitleStyle.Render("Task completed successfully!"))
fmt.Println("Press Enter to exit...")
r.exitRequested = true
return
}
case <-r.quitChan:
r.exitRequested = true
return
}
}
}
// GetCurrentFeedback returns the current validation feedback for the status command
func (r *REPL) GetCurrentFeedback() task.ValidationFeedback {
return r.currentFeedback
}
// SetChannels sets the channels for receiving validation feedback and quit signals from the task interface
func (r *REPL) SetChannels(feedbackChan chan task.ValidationFeedback, quitChan chan bool) {
r.feedbackChan = feedbackChan
r.quitChan = quitChan
}

View File

@@ -1,201 +0,0 @@
package repl
import (
"context"
"strings"
"github.com/LazyBachelor/LazyPM/pkg/cli/commands"
"github.com/c-bata/go-prompt"
"github.com/muesli/reflow/truncate"
)
// rootSuggestions is a list of prompt suggestions for root-level commands.
var rootSuggestions = []prompt.Suggest{
{Text: "pm", Description: "Project Management System"},
{Text: "exit", Description: "Exit pm CLI"},
{Text: "help", Description: "Show help information"},
{Text: "title", Description: "Print the welcome title"},
{Text: "git", Description: "Version control system"},
}
// commandSuggestions is a list of prompt suggestions for PM commands.
var baseSuggestions = []prompt.Suggest{
{Text: "help", Description: "Show help information"},
{Text: "delete", Description: "Delete an issue by ID"},
{Text: "close", Description: "Close an issue by ID"},
{Text: "create", Description: "Create a new issue with title"},
{Text: "update", Description: "Update an existing issue by ID"},
{Text: "describe", Description: "Get issue details by ID"},
{Text: "list", Description: "List all issues"},
}
// createFlags is a list of prompt suggestions for the create command flags.
var createFlags = []prompt.Suggest{
{Text: "--interactive", Description: "Create issue interactively"},
{Text: "--desc", Description: "Issue description"},
{Text: "--status", Description: "Issue status (open, closed, in_progress)"},
{Text: "--type", Description: "Issue type (bug, feature, task)"},
{Text: "--priority", Description: "Issue priority (0-5)"},
}
// updateFlags is a list of prompt suggestions for the update command flags.
var updateFlags = []prompt.Suggest{
{Text: "--title", Description: "New issue title"},
{Text: "--desc", Description: "New issue description"},
{Text: "--status", Description: "New issue status (open, closed, in_progress)"},
{Text: "--type", Description: "New issue type (bug, feature, task)"},
{Text: "--priority", Description: "New issue priority (0-5)"},
}
// listFlags is a list of prompt suggestions for the list command flags.
var listFlags = []prompt.Suggest{
{Text: "--title", Description: "Filter by title"},
{Text: "--desc", Description: "Filter by description"},
{Text: "--status", Description: "Filter by status (open, closed, in_progress)"},
{Text: "--type", Description: "Filter by type (bug, feature, task)"},
{Text: "--priority", Description: "Filter by priority (0-5)"},
{Text: "--limit", Description: "Limit number of results"},
}
var deleteFlags = []prompt.Suggest{
{Text: "--yes", Description: "Confirm deletion without prompt"},
{Text: "--interactive", Description: "Select issues to delete interactively"},
}
// statusValues is a list of prompt suggestions for status types
var statusValues = []prompt.Suggest{
{Text: "open", Description: "Open status"},
{Text: "closed", Description: "Closed status"},
{Text: "in_progress", Description: "In progress status"},
}
// typeValues is a list of prompt suggestions for issue types
var typeValues = []prompt.Suggest{
{Text: "bug", Description: "Bug issue type"},
{Text: "feature", Description: "Feature issue type"},
{Text: "task", Description: "Task issue type"},
}
// priorityValues is a list of prompt suggestions for issue priority levels
var priorityValues = []prompt.Suggest{
{Text: "0", Description: "Lowest priority"},
{Text: "1", Description: "Low priority"},
{Text: "2", Description: "Medium-low priority"},
{Text: "3", Description: "Medium priority"},
{Text: "4", Description: "High priority"},
}
// isIDCommand maps command names to a boolean indicating whether they expect an issue ID as an argument.
var isIDCommand = map[string]bool{
"describe": true,
"delete": true,
"del": true,
"rm": true,
"remove": true,
"get": true,
"read": true,
"close": true,
"update": true,
"edit": true,
}
var commandFlags = map[string][]prompt.Suggest{
"create": createFlags,
"add": createFlags,
"update": updateFlags,
"edit": updateFlags,
"list": listFlags,
"ls": listFlags,
"search": listFlags,
"delete": deleteFlags,
"del": deleteFlags,
"rm": deleteFlags,
"remove": deleteFlags,
}
// commandSuggestions returns a list of prompt suggestions based on the current input words.
func commandSuggestions(words []string) []prompt.Suggest {
if len(words) == 0 {
return baseSuggestions
}
return filterByPrefix(baseSuggestions, words[0])
}
// flagSuggestions returns a list of prompt suggestions for command flags based on the current input.
func flagSuggestions(cmd string, words []string, text string) []prompt.Suggest {
lastWord, prevWord := parseWords(words, text)
if values := getFlagValues(prevWord); values != nil {
return filterByPrefix(values, lastWord)
}
flags := commandFlags[cmd]
if isIDCommand[cmd] {
if len(words) < 2 && !strings.HasPrefix(lastWord, "-") {
return issueIDSuggestions(lastWord, true)
}
return filterByPrefix(flags, lastWord)
}
return filterByPrefix(flags, lastWord)
}
// issueIDSuggestions returns a list of prompt suggestions for issue IDs based on the current partial input.
func issueIDSuggestions(partial string, hasCommand bool) []prompt.Suggest {
// Only show suggestions if we've typed the command already
if !hasCommand {
return nil
}
issues, _ := commands.GetIssueCompletions(context.Background(), partial)
var suggestions []prompt.Suggest
for _, issue := range issues {
suggestions = append(suggestions, prompt.Suggest{
Text: issue.ID,
Description: truncate.String(issue.Title, 20),
})
}
return suggestions
}
// parseWords extracts the last and previous words from the input for flag suggestion logic.
func parseWords(words []string, text string) (lastWord, prevWord string) {
if len(words) > 0 && !strings.HasSuffix(text, " ") {
lastWord = words[len(words)-1]
if len(words) >= 2 {
prevWord = words[len(words)-2]
}
} else if len(words) >= 1 {
prevWord = words[len(words)-1]
}
return
}
// getFlagValues returns a list of prompt suggestions for flag values based on the given flag.
func getFlagValues(flag string) []prompt.Suggest {
switch flag {
case "-s", "--status":
return statusValues
case "-t", "--type":
return typeValues
case "-p", "--priority":
return priorityValues
}
return nil
}
// filterByPrefix filters a list of prompt suggestions based on a given prefix.
func filterByPrefix(suggestions []prompt.Suggest, prefix string) []prompt.Suggest {
if prefix == "" {
return suggestions
}
var filtered []prompt.Suggest
for _, s := range suggestions {
if strings.HasPrefix(s.Text, prefix) {
filtered = append(filtered, s)
}
}
return filtered
}

View File

@@ -1,10 +0,0 @@
// Package styles defines the styling for the CLI output using the lipgloss library.
package styles
import "github.com/charmbracelet/lipgloss"
var (
TitleStyle = lipgloss.NewStyle().Bold(true).Padding(1)
CommandStyle = lipgloss.NewStyle().Padding(1)
)