use.go 1.2 KB

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