Skip to content

Commit

Permalink
feat: add command to add service
Browse files Browse the repository at this point in the history
  • Loading branch information
mukezhz committed Jan 8, 2024
1 parent a0126c8 commit afa07f9
Show file tree
Hide file tree
Showing 7 changed files with 184 additions and 16 deletions.
23 changes: 21 additions & 2 deletions cmd/add_infrastructure.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,14 @@ import (
)

var addInfrastructureCmd = &cobra.Command{
Use: "add infra [name]",
Use: "infra add [name]",
Short: "Add a new infrastructure",
Args: cobra.MaximumNArgs(2),
Run: addInfrastructureHandler,
}

func addInfrastructureHandler(_ *cobra.Command, args []string) {
if len(args) > 0 && !strings.Contains(args[0], "infra") {
if len(args) > 0 && !strings.Contains(args[0], "add") {
color.Redln("Error: invalid command")
return
}
Expand Down Expand Up @@ -89,6 +89,7 @@ func addInfrastructure(
updatedCode := utility.AddListOfProvideInFxOptions(infrastructureModulePath, functions)
utility.WriteContentToPath(infrastructureModulePath, updatedCode)

var servicesTmpl []string
for _, i := range items {
templatePath := filepath.Join(".", "templates", "wesionary", "infrastructure", infrasTmpl[i])
var targetRoot string
Expand All @@ -97,7 +98,25 @@ func addInfrastructure(
} else {
targetRoot = filepath.Join(".", "pkg", "infrastructure", strings.Replace(infrasTmpl[i], ".tmpl", ".go", 1))
}

fileName := strings.Replace(infrasTmpl[i], ".tmpl", "", 1)
serviceTemplatePath := filepath.Join(".", "templates", "wesionary", "service")
for _, file := range utility.ListDirectory(templatesFS, serviceTemplatePath) {
if strings.Contains(file, fileName) {
servicesTmpl = append(servicesTmpl, file)
}
}
utility.GenerateFromEmbeddedTemplate(templatesFS, templatePath, targetRoot, data)

// add service too
var serviceModulePath string
if isNewProject {
serviceModulePath = filepath.Join(data.PackageName, "pkg", "services", "module.go")
} else {
serviceModulePath = filepath.Join(".", "pkg", "services", "module.go")
}

addService(questions, servicesTmpl, serviceModulePath, data, true, templatesFS)
}
return items
}
121 changes: 121 additions & 0 deletions cmd/add_service.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
package cmd

import (
"embed"
"os"
"path/filepath"
"strings"

"github.com/gookit/color"
"github.com/mukezhz/geng/pkg/constant"
"github.com/mukezhz/geng/pkg/model"
"github.com/mukezhz/geng/pkg/terminal"
"github.com/mukezhz/geng/pkg/utility"
"github.com/spf13/cobra"
)

var addServiceCmd = &cobra.Command{
Use: "service add [name]",
Short: "Add a new Service",
Args: cobra.MaximumNArgs(2),
Run: addServiceHandler,
}

func addServiceHandler(_ *cobra.Command, args []string) {
if len(args) > 0 && !strings.Contains(args[0], "add") {
color.Redln("Error: invalid command")
return
}
projectModule, err := utility.GetModuleNameFromGoModFile()
if err != nil {
color.Redln("Error finding Module name from go.mod:", err)
return
}
data := utility.GetModuleDataFromModuleName("", projectModule.Module, projectModule.GoVersion)
currentDir, err := os.Getwd()
if err != nil {
color.Redln("Error getting current directory:", err)
panic(err)
}
projectPath, err := utility.FindGitRoot(currentDir)
if err != nil {
color.Redln("Error finding Git root:", err)
return
}
serviceModulePath := filepath.Join(projectPath, "pkg", "services", "module.go")
templateInfraPath := filepath.Join(".", "templates", "wesionary", "service")
servicesTmpl := utility.ListDirectory(templatesFS, templateInfraPath)
services := utility.Map[string, string](servicesTmpl, func(q string) string {
return strings.Replace(q, ".tmpl", "", 1)
})

questions := []terminal.ProjectQuestion{
terminal.NewCheckboxQuestion(constant.ServiceNameKEY, "Select the Service? [<space> to select]", services),
}

terminal.StartInteractiveTerminal(questions)

items := addService(questions, servicesTmpl, serviceModulePath, data, false, templatesFS)
if len(items) == 0 {
color.Red.Println("No Service selected")
return
}

utility.PrintColorizeServiceDetail(data, services)
}

func addService(
questions []terminal.ProjectQuestion,
servicesTmpl []string,
serviceModulePath string,
data model.ModuleData,
isNewProject bool,
templatesFS embed.FS) []int {
var functions []string
var items []int
for _, q := range questions {
switch q.Key {
case constant.ServiceNameKEY:
selected := q.Input.Selected()
for s := range selected {
funcs := utility.GetFunctionDeclarations(filepath.Join(".", "templates", "wesionary", "service", servicesTmpl[s]), templatesFS)
filteredServices := utility.Filter[string](funcs, func(q string) bool {
return strings.Contains(q, "New")
})
functions = append(functions,
filteredServices...,
)
items = append(items, s)
}
case constant.InfrastructureNameKEY:
for i, s := range servicesTmpl {
funcs := utility.GetFunctionDeclarations(filepath.Join(".", "templates", "wesionary", "service", s), templatesFS)
filteredServices := utility.Filter[string](funcs, func(q string) bool {
return strings.Contains(q, "New")
})
functions = append(functions,
filteredServices...,
)
items = append(items, i)
}

}
}
if len(items) == 0 {
return items
}
updatedCode := utility.AddListOfProvideInFxOptions(serviceModulePath, functions)
utility.WriteContentToPath(serviceModulePath, updatedCode)

for _, i := range items {
templatePath := filepath.Join(".", "templates", "wesionary", "service", servicesTmpl[i])
var targetRoot string
if isNewProject {
targetRoot = filepath.Join(data.PackageName, "pkg", "services", strings.Replace(servicesTmpl[i], ".tmpl", ".go", 1))
} else {
targetRoot = filepath.Join(".", "pkg", "services", strings.Replace(servicesTmpl[i], ".tmpl", ".go", 1))
}
utility.GenerateFromEmbeddedTemplate(templatesFS, templatePath, targetRoot, data)
}
return items
}
1 change: 1 addition & 0 deletions cmd/run_project.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,5 @@ func init() {
rootCmd.AddCommand(newProjectCmd)
rootCmd.AddCommand(runProjectCmd)
rootCmd.AddCommand(addInfrastructureCmd)
rootCmd.AddCommand(addServiceCmd)
}
2 changes: 2 additions & 0 deletions pkg/constant/constant.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const (
DirectoryKEY = "directory"
ModueleNameKEY = "moduleName"
InfrastructureNameKEY = "infrastructureName"
ServiceNameKEY = "serviceName"
)

const (
Expand All @@ -20,4 +21,5 @@ const (
Directory = "Project Directory"
ModuleName = "Module Name"
InfrastructureName = "Infrastructures"
ServiceName = "Services"
)
38 changes: 38 additions & 0 deletions pkg/utility/print.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,44 @@ func PrintFinalStepAfterInfrastructureAddition(data model.ModuleData) {
color.Yellowf(output)
}

func PrintColorizeServiceDetail(data model.ModuleData, infras []string) {
color.Cyanln(`
GENG: GENERATE GOLANG INFRASTRUCTURE
██████╗ ███████╗███╗ ██╗ ██████╗
██╔════╝ ██╔════╝████╗ ██║ ██╔════╝
██║ ███╗█████╗ ██╔██╗ ██║█████╗██║ ███╗
██║ ██║██╔══╝ ██║╚██╗██║╚════╝██║ ██║
╚██████╔╝███████╗██║ ╚████║ ╚██████╔╝
╚═════╝ ╚══════╝╚═╝ ╚═══╝ ╚═════╝
`)
color.Greenln("\tThe information you have provided:\n")
color.Cyanf("\t%-20s💻: %-15s\n", constant.ModuleName, data.PackageName)
color.Cyanf("\t%-20s📂: %-15s\n", constant.ProjectModuleName, data.ProjectModuleName)
color.Cyanf("\t%-20s🆚: %-15s\n", constant.GoVersion, data.GoVersion)
color.Cyanf("\t%-20s🆚: %-15s\n", "Selected", constant.InfrastructureName)
for _, infra := range infras {
color.Cyanf("\t%-20s: [x]%-15s\n", "", infra)
}
PrintFinalStepAfterServiceAddition(data)
color.Redln("\n\tThank You For using 🙏🇳🇵🙏:\n")
}

func PrintFinalStepAfterServiceAddition(data model.ModuleData) {
output := fmt.Sprintf(`
🎉 Successfully added service %v
↪️ Restart the server to see the changes:
🌐 Check the following path:
%v
`, data.ModuleName, "pkg/services/")
color.Yellowf(output)
}

func PrintFinalStepAfterProjectInitialization(data model.ModuleData) {
output := fmt.Sprintf(`
💻 Change directory to project:
Expand Down
4 changes: 1 addition & 3 deletions templates/wesionary/project/pkg/services/module.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,5 @@ import (
// Module exports services present
var Module = fx.Module(
"services",
fx.Options(
fx.Provide(),
),
fx.Options(),
)
11 changes: 0 additions & 11 deletions templates/wesionary/service/module.tmpl

This file was deleted.

0 comments on commit afa07f9

Please sign in to comment.