feat(cmd): set custom module name for command new

pull/2898/head
twacqwq 2 years ago
parent fcd3b18e83
commit 7934811009
  1. 19
      cmd/kratos/internal/base/mod.go
  2. 10
      cmd/kratos/internal/project/new.go
  3. 7
      cmd/kratos/internal/project/project.go

@ -60,3 +60,22 @@ func KratosMod() string {
// $GOPATH/src/github.com/go-kratos/kratos
return filepath.Join(gopath, "src", "github.com", "go-kratos", "kratos")
}
// ModuleName returns custom module name
func ModuleName(moduleFile, moduleName string) error {
modBytes, err := os.ReadFile(moduleFile)
if err != nil {
return err
}
goMod, err := modfile.Parse(moduleFile, modBytes, nil)
if err != nil {
return err
}
goMod.Module.Syntax.Token[1] = moduleName
modBytes, err = goMod.Format()
if err != nil {
return err
}
return os.WriteFile(moduleFile, modBytes, 0644)
}

@ -4,6 +4,7 @@ import (
"context"
"fmt"
"os"
"path"
"path/filepath"
"github.com/AlecAivazis/survey/v2"
@ -16,6 +17,7 @@ import (
type Project struct {
Name string
Path string
ModuleName string
}
// New new a project from remote repo.
@ -37,7 +39,7 @@ func (p *Project) New(ctx context.Context, dir string, layout string, branch str
}
os.RemoveAll(to)
}
fmt.Printf("🚀 Creating service %s, layout repo is %s, please wait a moment.\n\n", p.Name, layout)
fmt.Printf("🚀 Creating service %s, layout repo is %s, module name is %s, please wait a moment.\n\n", p.Name, layout, p.ModuleName)
repo := base.NewRepo(layout, branch)
if err := repo.CopyTo(ctx, to, p.Name, []string{".git", ".github"}); err != nil {
return err
@ -49,6 +51,12 @@ func (p *Project) New(ctx context.Context, dir string, layout string, branch str
if e != nil {
return e
}
if p.ModuleName != "" && p.ModuleName != p.Name {
e = base.ModuleName(path.Join(to, "go.mod"), p.ModuleName)
if e != nil {
return e
}
}
base.Tree(to, dir)
fmt.Printf("\n🍺 Project creation succeeded %s\n", color.GreenString(p.Name))

@ -28,6 +28,7 @@ var (
branch string
timeout string
nomod bool
moduleName string
)
func init() {
@ -39,6 +40,7 @@ func init() {
CmdNew.Flags().StringVarP(&branch, "branch", "b", branch, "repo branch")
CmdNew.Flags().StringVarP(&timeout, "timeout", "t", timeout, "time out")
CmdNew.Flags().BoolVarP(&nomod, "nomod", "", nomod, "retain go mod")
CmdNew.Flags().StringVarP(&moduleName, "module-name", "m", moduleName, "module name")
}
func run(_ *cobra.Command, args []string) {
@ -64,9 +66,12 @@ func run(_ *cobra.Command, args []string) {
}
} else {
name = args[0]
if moduleName == "" {
moduleName = name
}
}
projectName, workingDir := processProjectParams(name, wd)
p := &Project{Name: projectName}
p := &Project{Name: projectName, ModuleName: moduleName}
done := make(chan error, 1)
go func() {
if !nomod {

Loading…
Cancel
Save