You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

commandline.go 1.4 kB

2 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package cmdline
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "github.com/spf13/cobra"
  7. "gitlink.org.cn/cloudream/common/pkgs/cmdtrie"
  8. "gitlink.org.cn/cloudream/storage/client/internal/services"
  9. )
  10. type CommandContext struct {
  11. Cmdline *Commandline
  12. }
  13. // TODO 逐步使用cobra代替cmdtrie
  14. var commands cmdtrie.CommandTrie[CommandContext, error] = cmdtrie.NewCommandTrie[CommandContext, error]()
  15. var rootCmd = cobra.Command{}
  16. type Commandline struct {
  17. Svc *services.Service
  18. }
  19. func NewCommandline(svc *services.Service) (*Commandline, error) {
  20. return &Commandline{
  21. Svc: svc,
  22. }, nil
  23. }
  24. func (c *Commandline) DispatchCommand(allArgs []string) {
  25. cmdCtx := CommandContext{
  26. Cmdline: c,
  27. }
  28. cmdErr, err := commands.Execute(cmdCtx, allArgs, cmdtrie.ExecuteOption{ReplaceEmptyArrayWithNil: true})
  29. if err != nil {
  30. if err == cmdtrie.ErrCommandNotFound {
  31. ctx := context.WithValue(context.Background(), "cmdCtx", &cmdCtx)
  32. err = rootCmd.ExecuteContext(ctx)
  33. if err != nil {
  34. fmt.Println(err)
  35. os.Exit(1)
  36. }
  37. return
  38. }
  39. fmt.Printf("execute command failed, err: %s", err.Error())
  40. os.Exit(1)
  41. }
  42. if cmdErr != nil {
  43. fmt.Printf("execute command failed, err: %s", cmdErr.Error())
  44. os.Exit(1)
  45. }
  46. }
  47. func MustAddCmd(fn any, prefixWords ...string) any {
  48. commands.MustAdd(fn, prefixWords...)
  49. return nil
  50. }
  51. func GetCmdCtx(cmd *cobra.Command) *CommandContext {
  52. return cmd.Context().Value("cmdCtx").(*CommandContext)
  53. }

本项目旨在将云际存储公共基础设施化,使个人及企业可低门槛使用高效的云际存储服务(安装开箱即用云际存储客户端即可,无需关注其他组件的部署),同时支持用户灵活便捷定制云际存储的功能细节。