Compare commits

..

4 Commits

Author SHA1 Message Date
6add048755 更新readme 2024-08-09 15:11:53 +08:00
ee3309164b 更新readme 2024-08-09 15:03:09 +08:00
d2bf98a710 实现更新功能 2024-08-09 14:57:41 +08:00
576ef0d31e 优化命令参数提示 2024-08-08 21:44:39 +08:00
7 changed files with 82 additions and 48 deletions

View File

@ -2,7 +2,7 @@
以golib.gaore.com/GaoreGo/hertz_demo为模板的hertz框架脚手架 以golib.gaore.com/GaoreGo/hertz_demo为模板的hertz框架脚手架
#### 安装: #### 安装:
go install golib.gaore.com/GaoreGo/hertz_scaffold go install golib.gaore.com/GaoreGo/hertz_scaffold@latest
#### 命令行参数: #### 命令行参数:
@ -17,12 +17,13 @@
Flags: Flags:
-h, --help help for create -h, --help help for create
-p, --project string 项目名称 -p, --project string 项目名称
-t, --tag string 指定tag (不指定默认拉取master)
#### 创建项目: #### 创建项目:
hertz_scaffold create -p hertz.gaore.com hertz_scaffold create -p hertz.gaore.com
#### 更新项目: #### 更新项目(注意,更新项目会覆盖本地项目,请谨慎操作)
hertz_scaffold update -p hertz.gaore.com (还没实现) hertz_scaffold update -p hertz.gaore.com -t 1.0.0

View File

@ -1,6 +1,7 @@
package cmd package cmd
import ( import (
"fmt"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"log" "log"
"os" "os"
@ -9,7 +10,7 @@ import (
var ( var (
template = "git@golib-ssh.gaore.com:GaoreGo/hertz_demo.git" template = "git@golib-ssh.gaore.com:GaoreGo/hertz_demo.git"
project string project string
branch = "master" branch string
) )
var rootCmd = &cobra.Command{ var rootCmd = &cobra.Command{
@ -17,6 +18,11 @@ var rootCmd = &cobra.Command{
Short: "hertz框架脚手架", Short: "hertz框架脚手架",
Long: `以golib.gaore.com/GaoreGo/hertz_demo为模板的脚手架`, Long: `以golib.gaore.com/GaoreGo/hertz_demo为模板的脚手架`,
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
if len(args) == 0 {
cmd.Help()
} else {
fmt.Println("Invalid command")
}
}, },
} }

View File

@ -16,11 +16,11 @@ var createCmd = &cobra.Command{
}, },
} }
func init() {
createCmd.Flags().StringVarP(&project, "project", "p", "", "项目名称")
}
func handleCreateCommand(args []string) { func handleCreateCommand(args []string) {
if projectExists(project) {
log.Printf("Project %s already exists, use update", project)
os.Exit(1)
}
err := handleRemoteTemplate(template, branch, project) err := handleRemoteTemplate(template, branch, project)
if err != nil { if err != nil {
log.Printf("Error creating project: %s\n", err) log.Printf("Error creating project: %s\n", err)
@ -29,3 +29,16 @@ func handleCreateCommand(args []string) {
fmt.Printf("Project %s created successfully!\n", project) fmt.Printf("Project %s created successfully!\n", project)
return return
} }
func init() {
initFlags(createCmd)
}
// projectExists 检查项目路径是否已经存在
func projectExists(projectPath string) bool {
info, err := os.Stat(projectPath)
if os.IsNotExist(err) {
return false
}
return info.IsDir()
}

View File

@ -1,7 +1,9 @@
package cmd package cmd
import ( import (
"bytes"
"fmt" "fmt"
"github.com/spf13/cobra"
"io" "io"
"io/fs" "io/fs"
"log" "log"
@ -38,12 +40,13 @@ func handleRemoteTemplate(templateRepo, branch, projectPath string) (err error)
defer os.RemoveAll(tempDir) defer os.RemoveAll(tempDir)
// 克隆模板仓库 // 克隆模板仓库
cloneCmd := exec.Command("git", "clone", "-b", branch, templateRepo, tempDir) cloneCmd := exec.Command("git", "clone", "--branch", branch, templateRepo, tempDir)
cloneCmd.Stdout = io.Discard cloneCmd.Stdout = io.Discard
cloneCmd.Stderr = os.Stderr var stderr bytes.Buffer
cloneCmd.Stderr = &stderr
if err = cloneCmd.Run(); err != nil { if err = cloneCmd.Run(); err != nil {
return fmt.Errorf("error cloning template repository: %s", err) return fmt.Errorf("error cloning template repository: %s\n%s", err, extractError(stderr.String()))
} }
return copyTemplate(tempDir, projectPath) return copyTemplate(tempDir, projectPath)
@ -117,3 +120,23 @@ func copyAndReplaceFile(src, dist string, mode os.FileMode, replacements map[str
_, err = targetFile.WriteString(newContent) _, err = targetFile.WriteString(newContent)
return return
} }
// extractError 解析并提取实际的错误信息
func extractError(stderr string) string {
lines := strings.Split(stderr, "\n")
var errorLines []string
for _, line := range lines {
// 过滤掉非错误信息
if strings.HasPrefix(line, "fatal:") || strings.Contains(line, "error:") {
errorLines = append(errorLines, line)
}
}
return strings.Join(errorLines, "\n")
}
// initFlags 初始化通用的命令行参数
func initFlags(cmd *cobra.Command) {
cmd.Flags().StringVarP(&project, "project", "p", "", "项目名称")
cmd.Flags().StringVarP(&branch, "tag", "t", "master", "指定tag")
cmd.MarkFlagRequired("project")
}

View File

@ -3,6 +3,8 @@ package cmd
import ( import (
"fmt" "fmt"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"log"
"os"
) )
var updateCmd = &cobra.Command{ var updateCmd = &cobra.Command{
@ -10,6 +12,20 @@ var updateCmd = &cobra.Command{
Short: "更新项目", Short: "更新项目",
Long: `Update the current project`, Long: `Update the current project`,
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
fmt.Println("还没做") handleUpdateCommand(args)
}, },
} }
func init() {
initFlags(updateCmd)
}
func handleUpdateCommand(args []string) {
err := handleRemoteTemplate(template, branch, project)
if err != nil {
log.Printf("Error update project: %s\n", err)
os.Exit(1)
}
fmt.Printf("Project %s update successfully!\n", project)
return
}

View File

@ -27,32 +27,23 @@ unaffected.
Define flags using flag.String(), Bool(), Int(), etc. Define flags using flag.String(), Bool(), Int(), etc.
This declares an integer flag, -flagname, stored in the pointer ip, with type *int. This declares an integer flag, -flagname, stored in the pointer ip, with type *int.
var ip = flag.Int("flagname", 1234, "help message for flagname") var ip = flag.Int("flagname", 1234, "help message for flagname")
If you like, you can bind the flag to a variable using the Var() functions. If you like, you can bind the flag to a variable using the Var() functions.
var flagvar int var flagvar int
func init() { func init() {
flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname") flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
} }
Or you can create custom flags that satisfy the Value interface (with Or you can create custom flags that satisfy the Value interface (with
pointer receivers) and couple them to flag parsing by pointer receivers) and couple them to flag parsing by
flag.Var(&flagVal, "name", "help message for flagname") flag.Var(&flagVal, "name", "help message for flagname")
For such flags, the default value is just the initial value of the variable. For such flags, the default value is just the initial value of the variable.
After all flags are defined, call After all flags are defined, call
flag.Parse() flag.Parse()
to parse the command line into the defined flags. to parse the command line into the defined flags.
Flags may then be used directly. If you're using the flags themselves, Flags may then be used directly. If you're using the flags themselves,
they are all pointers; if you bind to variables, they're values. they are all pointers; if you bind to variables, they're values.
fmt.Println("ip has value ", *ip) fmt.Println("ip has value ", *ip)
fmt.Println("flagvar has value ", flagvar) fmt.Println("flagvar has value ", flagvar)
@ -63,26 +54,22 @@ The arguments are indexed from 0 through flag.NArg()-1.
The pflag package also defines some new functions that are not in flag, The pflag package also defines some new functions that are not in flag,
that give one-letter shorthands for flags. You can use these by appending that give one-letter shorthands for flags. You can use these by appending
'P' to the name of any function that defines a flag. 'P' to the name of any function that defines a flag.
var ip = flag.IntP("flagname", "f", 1234, "help message") var ip = flag.IntP("flagname", "f", 1234, "help message")
var flagvar bool var flagvar bool
func init() { func init() {
flag.BoolVarP(&flagvar, "boolname", "b", true, "help message") flag.BoolVarP(&flagvar, "boolname", "b", true, "help message")
} }
flag.VarP(&flagval, "varname", "v", "help message") flag.VarP(&flagval, "varname", "v", "help message")
Shorthand letters can be used with single dashes on the command line. Shorthand letters can be used with single dashes on the command line.
Boolean shorthand flags can be combined with other shorthand flags. Boolean shorthand flags can be combined with other shorthand flags.
Command line flag syntax: Command line flag syntax:
--flag // boolean flags only --flag // boolean flags only
--flag=x --flag=x
Unlike the flag package, a single dash before an option means something Unlike the flag package, a single dash before an option means something
different than a double dash. Single dashes signify a series of shorthand different than a double dash. Single dashes signify a series of shorthand
letters for flags. All but the last shorthand letter must be boolean flags. letters for flags. All but the last shorthand letter must be boolean flags.
// boolean flags // boolean flags
-f -f
-abc -abc
@ -940,9 +927,9 @@ func (f *FlagSet) usage() {
} }
} }
// --unknown (args will be empty) //--unknown (args will be empty)
// --unknown --next-flag ... (args will be --next-flag ...) //--unknown --next-flag ... (args will be --next-flag ...)
// --unknown arg ... (args will be arg ...) //--unknown arg ... (args will be arg ...)
func stripUnknownFlagValue(args []string) []string { func stripUnknownFlagValue(args []string) []string {
if len(args) == 0 { if len(args) == 0 {
//--unknown //--unknown

View File

@ -98,12 +98,9 @@ func (f *FlagSet) GetStringSlice(name string) ([]string, error) {
// The argument p points to a []string variable in which to store the value of the flag. // The argument p points to a []string variable in which to store the value of the flag.
// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly. // Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly.
// For example: // For example:
// // --ss="v1,v2" --ss="v3"
// --ss="v1,v2" --ss="v3"
//
// will result in // will result in
// // []string{"v1", "v2", "v3"}
// []string{"v1", "v2", "v3"}
func (f *FlagSet) StringSliceVar(p *[]string, name string, value []string, usage string) { func (f *FlagSet) StringSliceVar(p *[]string, name string, value []string, usage string) {
f.VarP(newStringSliceValue(value, p), name, "", usage) f.VarP(newStringSliceValue(value, p), name, "", usage)
} }
@ -117,12 +114,9 @@ func (f *FlagSet) StringSliceVarP(p *[]string, name, shorthand string, value []s
// The argument p points to a []string variable in which to store the value of the flag. // The argument p points to a []string variable in which to store the value of the flag.
// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly. // Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly.
// For example: // For example:
// // --ss="v1,v2" --ss="v3"
// --ss="v1,v2" --ss="v3"
//
// will result in // will result in
// // []string{"v1", "v2", "v3"}
// []string{"v1", "v2", "v3"}
func StringSliceVar(p *[]string, name string, value []string, usage string) { func StringSliceVar(p *[]string, name string, value []string, usage string) {
CommandLine.VarP(newStringSliceValue(value, p), name, "", usage) CommandLine.VarP(newStringSliceValue(value, p), name, "", usage)
} }
@ -136,12 +130,9 @@ func StringSliceVarP(p *[]string, name, shorthand string, value []string, usage
// The return value is the address of a []string variable that stores the value of the flag. // The return value is the address of a []string variable that stores the value of the flag.
// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly. // Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly.
// For example: // For example:
// // --ss="v1,v2" --ss="v3"
// --ss="v1,v2" --ss="v3"
//
// will result in // will result in
// // []string{"v1", "v2", "v3"}
// []string{"v1", "v2", "v3"}
func (f *FlagSet) StringSlice(name string, value []string, usage string) *[]string { func (f *FlagSet) StringSlice(name string, value []string, usage string) *[]string {
p := []string{} p := []string{}
f.StringSliceVarP(&p, name, "", value, usage) f.StringSliceVarP(&p, name, "", value, usage)
@ -159,12 +150,9 @@ func (f *FlagSet) StringSliceP(name, shorthand string, value []string, usage str
// The return value is the address of a []string variable that stores the value of the flag. // The return value is the address of a []string variable that stores the value of the flag.
// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly. // Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly.
// For example: // For example:
// // --ss="v1,v2" --ss="v3"
// --ss="v1,v2" --ss="v3"
//
// will result in // will result in
// // []string{"v1", "v2", "v3"}
// []string{"v1", "v2", "v3"}
func StringSlice(name string, value []string, usage string) *[]string { func StringSlice(name string, value []string, usage string) *[]string {
return CommandLine.StringSliceP(name, "", value, usage) return CommandLine.StringSliceP(name, "", value, usage)
} }