ssh.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package ssh
  2. import (
  3. fs "io/ioutil"
  4. "os"
  5. "path/filepath"
  6. "github.com/jsmartx/giter/util"
  7. "github.com/kevinburke/ssh_config"
  8. )
  9. type Config struct {
  10. cfg *ssh_config.Config
  11. }
  12. func loadConfig() *ssh_config.Config {
  13. p, err := util.JoinPath("~/.ssh/", "config")
  14. if err != nil {
  15. return nil
  16. }
  17. f, err := os.Open(p)
  18. if err != nil {
  19. return nil
  20. }
  21. defer f.Close()
  22. cfg, err := ssh_config.Decode(f)
  23. if err != nil {
  24. return nil
  25. }
  26. return cfg
  27. }
  28. func saveConfig(cfg *ssh_config.Config) error {
  29. root, err := util.Mkdir("~/.ssh/")
  30. if err != nil {
  31. return err
  32. }
  33. b, err := cfg.MarshalText()
  34. if err != nil {
  35. return err
  36. }
  37. cfgPath := filepath.Join(root, "config")
  38. // write marshaled data to the file
  39. return fs.WriteFile(cfgPath, b, 0755)
  40. }
  41. func New() *Config {
  42. cfg := loadConfig()
  43. if cfg != nil {
  44. return &Config{cfg: cfg}
  45. }
  46. cfg = &ssh_config.Config{
  47. Hosts: make([]*ssh_config.Host, 0),
  48. }
  49. if err := saveConfig(cfg); err != nil {
  50. panic(err)
  51. }
  52. return &Config{cfg: cfg}
  53. }
  54. type Host struct {
  55. Key string
  56. Hostname string
  57. Port string
  58. IdentityFile string
  59. }
  60. func (h *Host) Transform() (*ssh_config.Host, error) {
  61. pattern, err := ssh_config.NewPattern(h.Key)
  62. if err != nil {
  63. return nil, err
  64. }
  65. nodes := make([]ssh_config.Node, 0)
  66. if h.Hostname != "" {
  67. nodes = append(nodes, &ssh_config.KV{Key: " HostName", Value: h.Hostname})
  68. }
  69. if h.Port != "" {
  70. nodes = append(nodes, &ssh_config.KV{Key: " Port", Value: h.Port})
  71. }
  72. if h.IdentityFile != "" {
  73. nodes = append(nodes, &ssh_config.KV{Key: " IdentityFile", Value: h.IdentityFile})
  74. }
  75. nodes = append(nodes, &ssh_config.Empty{})
  76. return &ssh_config.Host{
  77. Patterns: []*ssh_config.Pattern{pattern},
  78. Nodes: nodes,
  79. EOLComment: " -- added by giter",
  80. }, nil
  81. }
  82. func (c *Config) SetHost(h *Host) error {
  83. host, err := h.Transform()
  84. if err != nil {
  85. return err
  86. }
  87. for i, v := range c.cfg.Hosts {
  88. for _, pattern := range v.Patterns {
  89. if pattern.String() == h.Key {
  90. c.cfg.Hosts[i] = host
  91. return saveConfig(c.cfg)
  92. }
  93. }
  94. }
  95. c.cfg.Hosts = append(c.cfg.Hosts, host)
  96. return saveConfig(c.cfg)
  97. }