refactor to decouple commands form entrypoint for reusability and centralizing commands.
Increase reusability and composition
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
)
|
||||
@@ -4,12 +4,10 @@ import (
|
||||
"os/exec"
|
||||
"strings"
|
||||
|
||||
"github.com/LazyBachelor/LazyPM/pkg/cli/commands"
|
||||
"github.com/LazyBachelor/LazyPM/internal/commands/issues"
|
||||
)
|
||||
|
||||
// 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
|
||||
@@ -29,8 +27,6 @@ func execute(input string) (string, error) {
|
||||
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 {
|
||||
@@ -42,14 +38,12 @@ func executeShellCommand(input string) (string, error) {
|
||||
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)
|
||||
output, err := issuesCmd.ExecuteArgsString(parts)
|
||||
return output, err
|
||||
}
|
||||
@@ -7,11 +7,13 @@ import (
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/LazyBachelor/LazyPM/internal/commands/issues"
|
||||
surveyCmd "github.com/LazyBachelor/LazyPM/internal/commands/survey"
|
||||
"github.com/LazyBachelor/LazyPM/internal/service"
|
||||
"github.com/LazyBachelor/LazyPM/internal/style"
|
||||
"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/LazyBachelor/LazyPM/pkg/tui/styles"
|
||||
"github.com/c-bata/go-prompt"
|
||||
"golang.org/x/term"
|
||||
)
|
||||
@@ -27,6 +29,7 @@ You can also run shell commands directly. Type 'exit' or 'quit' to leave.`
|
||||
type REPL struct {
|
||||
feedbackChan chan task.ValidationFeedback
|
||||
quitChan chan bool
|
||||
app *service.App
|
||||
|
||||
currentFeedback task.ValidationFeedback
|
||||
exitRequested bool
|
||||
@@ -55,12 +58,12 @@ func (r *REPL) Run(ctx context.Context, config cli.Config) error {
|
||||
defer cleanup()
|
||||
|
||||
// Make sure to set app, to ensure they are available.
|
||||
commands.SetApp(app)
|
||||
issuesCmd.SetApp(app)
|
||||
|
||||
// Set the REPL instance so status command can access it
|
||||
commands.SetRepl(r)
|
||||
// Store app reference for updating feedback
|
||||
r.app = app
|
||||
|
||||
fmt.Println(styles.TitleStyle.Render(ReplTitle)) // Print REPL title.
|
||||
fmt.Println(style.TitleStyle.Render(ReplTitle)) // Print REPL title.
|
||||
|
||||
// Start goroutine to watch for validation feedback and quit signals
|
||||
if r.feedbackChan != nil && r.quitChan != nil {
|
||||
@@ -102,8 +105,8 @@ func (r *REPL) Run(ctx context.Context, config cli.Config) error {
|
||||
// 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.
|
||||
output, _ := execute(input) // Ignore errors for now, gives better ux
|
||||
fmt.Println(style.TextStyle.Render(output)) // Print the output of the command in a styled format.
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -114,6 +117,13 @@ func (r *REPL) watchValidation() {
|
||||
select {
|
||||
case feedback := <-r.feedbackChan:
|
||||
r.currentFeedback = feedback
|
||||
// Update app's CurrentFeedback so status command can access it
|
||||
if r.app != nil {
|
||||
r.app.CurrentFeedback = &service.ValidationFeedback{
|
||||
Success: feedback.Success,
|
||||
Message: feedback.Message,
|
||||
}
|
||||
}
|
||||
if feedback.Success {
|
||||
fmt.Printf("\n%s\n", styles.TitleStyle.Render("Task completed successfully!"))
|
||||
fmt.Println("Press Enter to exit...")
|
||||
@@ -127,13 +137,18 @@ func (r *REPL) watchValidation() {
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
func init() {
|
||||
issuesCmd.RootCmd.AddCommand(issuesCmd.GetCmd)
|
||||
issuesCmd.RootCmd.AddCommand(issuesCmd.ListCmd)
|
||||
issuesCmd.RootCmd.AddCommand(issuesCmd.CloseCmd)
|
||||
issuesCmd.RootCmd.AddCommand(issuesCmd.CreateCmd)
|
||||
issuesCmd.RootCmd.AddCommand(issuesCmd.DeleteCmd)
|
||||
issuesCmd.RootCmd.AddCommand(issuesCmd.UpdateCmd)
|
||||
issuesCmd.RootCmd.AddCommand(surveyCmd.StatusCmd)
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/LazyBachelor/LazyPM/pkg/cli/commands"
|
||||
"github.com/LazyBachelor/LazyPM/internal/commands/issues"
|
||||
"github.com/c-bata/go-prompt"
|
||||
"github.com/muesli/reflow/truncate"
|
||||
)
|
||||
@@ -21,6 +21,7 @@ var rootSuggestions = []prompt.Suggest{
|
||||
// commandSuggestions is a list of prompt suggestions for PM commands.
|
||||
var baseSuggestions = []prompt.Suggest{
|
||||
{Text: "help", Description: "Show help information"},
|
||||
{Text: "status", Description: "Show task status"},
|
||||
{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"},
|
||||
@@ -148,7 +149,7 @@ func issueIDSuggestions(partial string, hasCommand bool) []prompt.Suggest {
|
||||
return nil
|
||||
}
|
||||
|
||||
issues, _ := commands.GetIssueCompletions(context.Background(), partial)
|
||||
issues, _ := issuesCmd.GetIssueCompletions(context.Background(), partial)
|
||||
|
||||
var suggestions []prompt.Suggest
|
||||
for _, issue := range issues {
|
||||
@@ -15,7 +15,7 @@ import (
|
||||
// 3. Run the interface
|
||||
// 4. Start validation loop in background
|
||||
// 5. Show questionnaire when done
|
||||
func RunTask(ctx context.Context, t Tasker, i Interface, ifaceType InterfaceType) error {
|
||||
func RunTask(ctx context.Context, t Tasker, i Interface, iType InterfaceType) error {
|
||||
doneChan := make(chan bool, 1)
|
||||
quitChan := make(chan bool, 1)
|
||||
feedbackChan := make(chan ValidationFeedback, 10)
|
||||
@@ -65,7 +65,7 @@ func RunTask(ctx context.Context, t Tasker, i Interface, ifaceType InterfaceType
|
||||
}
|
||||
|
||||
// Show questionnaire
|
||||
questions := t.Questions(ifaceType)
|
||||
questions := t.Questions(iType)
|
||||
questionare := taskui.NewQuestionnaireModel(questions)
|
||||
model, err = tea.NewProgram(questionare, tea.WithAltScreen()).Run()
|
||||
if err != nil {
|
||||
|
||||
Reference in New Issue
Block a user