Skip to content

Commit

Permalink
refactor: change the directory of command to cmd dir
Browse files Browse the repository at this point in the history
  • Loading branch information
mukezhz committed Jan 3, 2024
1 parent 3b73701 commit 4f9e1d9
Show file tree
Hide file tree
Showing 7 changed files with 355 additions and 200 deletions.
92 changes: 92 additions & 0 deletions cmd/create_project.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package cmd

import (
"fmt"
"path/filepath"

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

var newProjectCmd = &cobra.Command{
Use: "new [project name]",
Short: "Create a new project",
Args: cobra.MaximumNArgs(1),
Run: createProject,
}

func createProject(cmd *cobra.Command, args []string) {
var projectName string
var projectModuleName string
var goVersion string
var projectDescription string
var author string
var directory string

if len(args) == 0 {
questions := []terminal.ProjectQuestion{
terminal.NewShortQuestion(constant.ProjectNameKEY, constant.ProjectName+" *", "Enter Project Name:"),
terminal.NewShortQuestion(constant.ProjectModuleNameKEY, constant.ProjectModuleName+" *", "Enter Module Name:"),
terminal.NewShortQuestion(constant.AuthorKEY, constant.Author+" [Optional]", "Enter Author Detail[Mukesh Chaudhary <[email protected]>] [Optional]"),
terminal.NewLongQuestion(constant.ProjectDescriptionKEY, constant.ProjectDescription+" [Optional]", "Enter Project Description [Optional]"),
terminal.NewShortQuestion(constant.GoVersionKEY, constant.GoVersion+" [Optional]", "Enter Go Version (Default: 1.20) [Optional]"),
terminal.NewShortQuestion(constant.DirectoryKEY, constant.Directory+" [Optional]", "Enter Project Directory (Default: package_name) [Optional]"),
}
terminal.StartInteractiveTerminal(questions)

for _, q := range questions {
switch q.Key {
case constant.ProjectNameKEY:
projectName = q.Answer
case constant.ProjectDescriptionKEY:
projectDescription = q.Answer
case constant.AuthorKEY:
author = q.Answer
case constant.ProjectModuleNameKEY:
projectModuleName = q.Answer
case constant.GoVersionKEY:
goVersion = q.Answer
case constant.DirectoryKEY:
directory = q.Answer
}
}
} else {
projectName = args[0]
projectModuleName, _ = cmd.Flags().GetString("mod")
goVersion, _ = cmd.Flags().GetString("version")
directory, _ = cmd.Flags().GetString("dir")
}

goVersion = utility.CheckVersion(goVersion)
if projectName == "" {
color.Redln("Error: project name is required")
return
}
if projectModuleName == "" {
color.Redln("Error: module name is required")
return
}

data := utility.GetModuleDataFromModuleName(projectName, projectModuleName, goVersion)
data.ProjectDescription = projectDescription
data.Author = author

data.Directory = directory
if data.Directory == "" {
data.Directory = filepath.Join(data.Directory, data.PackageName)
}
targetRoot := data.Directory

templatePath := filepath.Join("templates", "wesionary", "project")
err := utility.GenerateFiles(templatesFS, templatePath, targetRoot, data)
if err != nil {
color.Redln("Error generate file", err)
return
}

utility.PrintColorizeProjectDetail(data)
fmt.Println("")
}
79 changes: 79 additions & 0 deletions cmd/new_module.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package cmd

import (
"fmt"
"os"
"path/filepath"

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

var newModuleCmd = &cobra.Command{
Use: "gen features [name]",
Short: "Create a new features",
Args: cobra.MaximumNArgs(2),
Run: createModule,
}

func createModule(_ *cobra.Command, args []string) {
projectModule, err := utility.GetModuleNameFromGoModFile()
if err != nil {
fmt.Println("Error finding Module name from go.mod:", err)
return
}
currentDir, err := os.Getwd()
if err != nil {
color.Redln("Error getting current directory:", err)
panic(err)
}
projectPath, err := utility.FindGitRoot(currentDir)
if err != nil {
fmt.Println("Error finding Git root:", err)
return
}
mainModulePath := filepath.Join(projectPath, "domain", "features", "module.go")
if err != nil {
panic(err)
}
var moduleName string
if len(args) == 1 {
questions := []terminal.ProjectQuestion{
terminal.NewShortQuestion(constant.ModueleNameKEY, constant.ModueleNameKEY+" *", "Enter Module Name:"),
}
terminal.StartInteractiveTerminal(questions)

for _, q := range questions {
switch q.Key {
case constant.ModueleNameKEY:
moduleName = q.Answer
}
}
} else {
moduleName = args[1]
}
if !utility.CheckGolangIdentifier(moduleName) {
color.Redln("Error: module name is invalid")
return
}
data := utility.GetModuleDataFromModuleName(moduleName, projectModule.Module, projectModule.GoVersion)

// Define the directory structure
targetRoot := filepath.Join(".", "domain", "features", data.PackageName)
templatePath := filepath.Join(".", "templates", "wesionary", "module")

err = utility.GenerateFiles(templatesFS, templatePath, targetRoot, data)
if err != nil {
color.Redln("Error: generate file", err)
return
}

updatedCode := utility.AddAnotherFxOptionsInModule(mainModulePath, data.PackageName, data.ProjectModuleName)
utility.WriteContentToPath(mainModulePath, updatedCode)

utility.PrintColorizeModuleDetail(data)

}
62 changes: 62 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package cmd

import (
"embed"
"errors"
"fmt"
"os"

"github.com/spf13/cobra"
"github.com/spf13/viper"
)

var (
// Used for flags.
cfgFile string
userLicense string

rootCmd = &cobra.Command{
Use: "cobra-cli",
Short: "A generator for Cobra based Applications",
Long: `Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
}
templatesFS embed.FS
)

func initConfig() {
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
// Find home directory.
home, err := os.UserHomeDir()
cobra.CheckErr(err)

// Search config in home directory with name ".cobra" (without extension).
viper.AddConfigPath(home)
viper.SetConfigType("yaml")
viper.SetConfigName(".cobra")
}

viper.AutomaticEnv()

err := viper.ReadInConfig()

notFound := &viper.ConfigFileNotFoundError{}
switch {
case err != nil && !errors.As(err, notFound):
cobra.CheckErr(err)
case err != nil && errors.As(err, notFound):
// The config file is optional, we shouldn't exit when the config is not found
break
default:
fmt.Fprintln(os.Stderr, "Using config file:", viper.ConfigFileUsed())
}
}

func Execute(fs embed.FS) error {
templatesFS = fs
return rootCmd.Execute()
}
41 changes: 41 additions & 0 deletions cmd/run_project.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package cmd

import (
"github.com/mukezhz/geng/pkg/utility"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)

var runProjectCmd = &cobra.Command{
Use: "run [project name]",
Short: "Run the project",
Args: cobra.MaximumNArgs(1),
Run: runProject,
}

func runProject(cmd *cobra.Command, args []string) {
runGo := "go"
// execute command from golang
err := utility.ExecuteCommand(runGo, args...)
if err != nil {
return
}
}

func init() {
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")
rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution")
rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project")
rootCmd.PersistentFlags().Bool("viper", false, "use Viper for configuration")
cobra.CheckErr(viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")))
cobra.CheckErr(viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper")))
viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")
viper.SetDefault("license", "none")
newProjectCmd.Flags().StringP("mod", "m", "", "features name")
newProjectCmd.Flags().StringP("dir", "d", "", "target directory")
newProjectCmd.Flags().StringP("version", "v", "", "version support")
rootCmd.AddCommand(newModuleCmd)
rootCmd.AddCommand(newProjectCmd)
rootCmd.AddCommand(runProjectCmd)
}
23 changes: 19 additions & 4 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ require (
github.com/charmbracelet/lipgloss v0.7.1
github.com/gookit/color v1.5.4
github.com/spf13/cobra v1.8.0
github.com/spf13/viper v1.18.2
go.uber.org/fx v1.20.1
golang.org/x/text v0.14.0
)
Expand All @@ -16,23 +17,37 @@ require (
github.com/atotto/clipboard v0.1.4 // indirect
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81 // indirect
github.com/fsnotify/fsnotify v1.7.0 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
github.com/magiconair/properties v1.8.7 // indirect
github.com/mattn/go-isatty v0.0.19 // indirect
github.com/mattn/go-localereader v0.0.1 // indirect
github.com/mattn/go-runewidth v0.0.14 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect
github.com/muesli/cancelreader v0.2.2 // indirect
github.com/muesli/reflow v0.3.0 // indirect
github.com/muesli/termenv v0.15.2 // indirect
github.com/pelletier/go-toml/v2 v2.1.0 // indirect
github.com/rivo/uniseg v0.4.4 // indirect
github.com/sagikazarmark/locafero v0.4.0 // indirect
github.com/sagikazarmark/slog-shim v0.1.0 // indirect
github.com/sourcegraph/conc v0.3.0 // indirect
github.com/spf13/afero v1.11.0 // indirect
github.com/spf13/cast v1.6.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778 // indirect
go.uber.org/atomic v1.7.0 // indirect
go.uber.org/atomic v1.9.0 // indirect
go.uber.org/dig v1.17.0 // indirect
go.uber.org/multierr v1.6.0 // indirect
go.uber.org/multierr v1.9.0 // indirect
go.uber.org/zap v1.23.0 // indirect
golang.org/x/sync v0.3.0 // indirect
golang.org/x/sys v0.12.0 // indirect
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect
golang.org/x/sync v0.5.0 // indirect
golang.org/x/sys v0.15.0 // indirect
golang.org/x/term v0.12.0 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
Loading

0 comments on commit 4f9e1d9

Please sign in to comment.