From 1c9582fbf9150446102e2c29fe73d44243328dba Mon Sep 17 00:00:00 2001 From: Suraj B M Date: Tue, 23 Sep 2025 23:28:06 +0530 Subject: [PATCH] feat: implement list command --- cmd/list.go | 97 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 cmd/list.go diff --git a/cmd/list.go b/cmd/list.go new file mode 100644 index 0000000..99a8a5a --- /dev/null +++ b/cmd/list.go @@ -0,0 +1,97 @@ +/* +Copyright © 2025 NAME HERE +*/ +package cmd + +import ( + "envy/cmd/utils" + "errors" + "fmt" + "os" + "path" + + "github.com/charmbracelet/lipgloss" + "github.com/pelletier/go-toml" + "github.com/spf13/cobra" + "gorm.io/gorm" +) + +// listCmd represents the list command +var listCmd = &cobra.Command{ + Use: "list", + Short: "List all the environments in the current project", + Run: func(cmd *cobra.Command, args []string) { + cwd, err := os.Getwd() + if err != nil { + utils.ErrPrint("Not able to fetch working directory:", err.Error()) + return + } + + _, err = os.Stat(path.Join(cwd, ".envy")) + + // file exists + if err == nil { + tree, err := toml.LoadFile(path.Join(cwd, ".envy")) + if err != nil { + utils.ErrPrint("Failed to parse .envy file:", err.Error()) + return + } + + project := tree.Get("envy.project").(string) + pinned := tree.Get("envy.env").(string) + + if project == "" { + utils.ErrPrint("Project name is empty. .envy file might have been modified.") + return + } + + if pinned == "" { + utils.ErrPrint("Pinned environment is empty. .envy file might have been modified.") + return + } + + utils.InitDb() + + var dbProject utils.Project + result := utils.DB.Where("name = ?", project).First(&dbProject) + + if result.Error != nil { + if errors.Is(result.Error, gorm.ErrRecordNotFound) { + utils.ErrPrint("Project with the name", project, "not found in the database.") + return + } + } + + var envs []utils.Environment + result = utils.DB.Where("project_id = ?", dbProject.ID).Find(&envs) + + if result.Error != nil { + utils.ErrPrint("Error occured:", result.Error.Error()) + return + } + + pinStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("#0FF")) + for _, en := range envs { + if en.Name == pinned { + fmt.Println(" * " + pinStyle.Render(en.Name)) + } else { + fmt.Println(" * " + en.Name) + } + } + } + }, +} + +func init() { + rootCmd.AddCommand(listCmd) + + // Here you will define your flags and configuration settings. + + // Cobra supports Persistent Flags which will work for this command + // and all subcommands, e.g.: + // listCmd.PersistentFlags().String("foo", "", "A help for foo") + + // Cobra supports local flags which will only run when this command + // is called directly, e.g.: + // listCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") +}