use.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package cmd
  2. import (
  3. "errors"
  4. "fmt"
  5. "strconv"
  6. "github.com/jsmartx/giter/git"
  7. "github.com/jsmartx/giter/ssh"
  8. "github.com/jsmartx/giter/store"
  9. "github.com/jsmartx/giter/util"
  10. "github.com/urfave/cli"
  11. )
  12. func Use(c *cli.Context) error {
  13. g, err := git.New(".")
  14. if err != nil {
  15. return err
  16. }
  17. name := c.Args().First()
  18. if name == "" {
  19. defaultName := ""
  20. if u := g.GetUser(); u != nil {
  21. defaultName = u.Name
  22. }
  23. name = util.Prompt(&util.PromptConfig{
  24. Prompt: "user name: ",
  25. Default: defaultName,
  26. })
  27. }
  28. s := store.New()
  29. users := s.List(name, true)
  30. if len(users) == 0 {
  31. return errors.New("user not found")
  32. }
  33. u := users[0]
  34. if len(users) > 1 {
  35. fmt.Printf("There are %d users:\n", len(users))
  36. for i, item := range users {
  37. fmt.Printf("%4d) %s\n", i+1, item.String())
  38. }
  39. str := util.Prompt(&util.PromptConfig{
  40. Prompt: "Enter number to select user: ",
  41. })
  42. i, err := strconv.Atoi(str)
  43. if err != nil {
  44. return err
  45. }
  46. if i < 1 || i > len(users) {
  47. return errors.New("Out of range")
  48. }
  49. u = users[i-1]
  50. }
  51. if u.IsSSH() {
  52. keyPath, err := u.KeyPath()
  53. if err != nil {
  54. fmt.Println(err)
  55. }
  56. s := ssh.New()
  57. err = s.SetHost(&ssh.Host{
  58. Key: u.Host,
  59. Hostname: u.Host,
  60. Port: u.Port,
  61. IdentityFile: keyPath,
  62. })
  63. if err != nil {
  64. fmt.Println(err)
  65. }
  66. }
  67. return g.SetUser(u.Name, u.Email)
  68. }