/
ssh.go
73 lines (55 loc) · 1.45 KB
/
ssh.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package gogit
import (
"bufio"
"fmt"
"os"
"path/filepath"
)
func getSshConfigPath() (string) {
return filepath.Join(os.Getenv("HOME"), ".ssh", "config")
}
func MoveTempFile() {
currentPath := getSshConfigPath()
newPath := filepath.Join(os.Getenv("HOME"), ".ssh", "config.bak")
err := os.Rename(currentPath, newPath)
if err != nil {
fmt.Println("Failed to create backup of SSH config file, aborting...")
return
}
err = os.Rename("config.tmp", currentPath)
if err != nil {
fmt.Println("Failed to move new SSH config file, to .ssh directory. Manual movement is recommended")
return
}
fmt.Println("New ssh config enabled")
}
func SetActiveHost(remotename string, active string, desired string) {
f, err := os.Open(getSshConfigPath())
if err != nil {
fmt.Printf("%v", err)
return
}
fnew, err := os.Create("config.tmp")
if err != nil {
fmt.Printf("%v", err)
return
}
defer f.Close()
defer fnew.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
text := scanner.Text()
if text == fmt.Sprintf("Host %s-%s", remotename, desired) {
fnew.WriteString(fmt.Sprintf("Host %s\n", remotename))
} else if text == fmt.Sprintf("Host %s", remotename) {
fnew.WriteString(fmt.Sprintf("Host %s-%s\n", remotename, active))
} else {
fnew.WriteString(text + "\n")
}
}
if err := scanner.Err(); err != nil {
fmt.Printf("%v", err)
return
}
MoveTempFile()
}