feat: add helper functions for file and db ops and integrate them in

commands
This commit is contained in:
2025-09-24 11:52:25 +05:30
parent 452fded733
commit a7b55fc080
4 changed files with 118 additions and 84 deletions

View File

@@ -1,19 +1,11 @@
/*
Copyright © 2025 NAME HERE <EMAIL ADDRESS>
*/
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
@@ -21,62 +13,43 @@ 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())
envy, err := utils.GetEnvy()
if err != nil {
utils.ErrPrint(err.Error())
return
}
_, err = os.Stat(path.Join(cwd, ".envy"))
project := envy.Get("envy.project").(string)
pinned := envy.Get("envy.env").(string)
// 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
}
if project == "" {
utils.ErrPrint("Project name is empty. .envy file might have been modified.")
return
}
project := tree.Get("envy.project").(string)
pinned := tree.Get("envy.env").(string)
if pinned == "" {
utils.ErrPrint("Pinned environment is empty. .envy file might have been modified.")
return
}
if project == "" {
utils.ErrPrint("Project name is empty. .envy file might have been modified.")
return
}
dbProject, err := utils.GetProject(project)
if err != nil {
utils.ErrPrint(err.Error())
return
}
if pinned == "" {
utils.ErrPrint("Pinned environment is empty. .envy file might have been modified.")
return
}
envs, err := utils.GetEnvironments(dbProject.ID)
if err != nil {
utils.ErrPrint(err.Error())
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(" * " + en.Name + pinStyle.Render(" [pinned]"))
} else {
fmt.Println(" * " + en.Name)
}
pinStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("#0FF"))
for _, en := range envs {
if en.Name == pinned {
fmt.Println(" * " + en.Name + pinStyle.Render(" [pinned]"))
} else {
fmt.Println(" * " + en.Name)
}
}
},