haunt/cmd/run.go

96 lines
2.1 KiB
Go
Raw Normal View History

package cmd
import (
"fmt"
"log"
"os"
"strings"
"github.com/abs3ntdev/haunt/src/haunt"
"github.com/spf13/cobra"
)
2023-03-08 21:46:44 +00:00
var startCmd = &cobra.Command{
Use: "start",
Aliases: []string{"s", "run"},
Short: "run haunt, optionally provide the name of projects to only run those otherwise will run all configured projects",
Args: cobra.MatchAll(cobra.OnlyValidArgs),
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return getProjectNamesToRun(toComplete), cobra.ShellCompDirectiveNoFileComp
},
2023-03-08 21:46:44 +00:00
RunE: start,
}
func init() {
2023-03-08 21:46:44 +00:00
rootCmd.AddCommand(startCmd)
}
func getProjectNamesToRun(input string) []string {
2023-03-06 07:39:01 +00:00
h := haunt.NewHaunt()
// read a config if exist
2023-03-06 07:39:01 +00:00
err := h.Settings.Read(&h)
if err != nil {
return []string{}
}
names := []string{}
2023-03-06 07:39:01 +00:00
for _, project := range h.Projects {
if strings.HasPrefix(project.Name, input) {
names = append(names, project.Name)
}
}
return names
}
// haunt workflow
2023-03-08 21:46:44 +00:00
func start(cmd *cobra.Command, args []string) (err error) {
2023-03-06 07:39:01 +00:00
h := haunt.NewHaunt()
// read a config if exist
2023-03-06 07:39:01 +00:00
err = h.Settings.Read(&h)
if err != nil {
if os.IsNotExist(err) {
log.Println(h.Prefix("No config file found, initializing one for you"))
err = defaultConfig(cmd, args)
if err != nil {
log.Println(h.Prefix("Failed to generate default config: " + err.Error()))
}
err = h.Settings.Read(&h)
if err != nil {
return fmt.Errorf(h.Prefix("Failed to read config file: " + err.Error()))
}
} else {
return err
}
}
if len(args) >= 1 {
// filter by name flag if exist
2023-03-06 07:39:01 +00:00
h.Projects = h.Filter(args)
if len(h.Projects) == 0 {
log.Println(h.Prefix("No valid project found, exiting. Check your config file or run haunt add"))
return
}
}
// increase file limit
2023-03-06 07:39:01 +00:00
if h.Settings.FileLimit != 0 {
if err = h.Settings.Flimit(); err != nil {
return err
}
}
// web server
2023-03-06 07:39:01 +00:00
if h.Server.Status {
h.Server.Parent = h
err = h.Server.Start()
if err != nil {
return err
}
2023-03-06 07:39:01 +00:00
err = h.Server.OpenURL()
if err != nil {
return err
}
}
2023-03-08 21:46:44 +00:00
// start workflow
return h.Start()
}