github.com/echohead/hub@v2.2.1+incompatible/git/ssh_config.go (about) 1 package git 2 3 import ( 4 "bufio" 5 "os" 6 "path/filepath" 7 "regexp" 8 "strings" 9 ) 10 11 const ( 12 hostReStr = "(?i)^[ \t]*(host|hostname)[ \t]+(.+)$" 13 ) 14 15 type SSHConfig map[string]string 16 17 func newSSHConfigReader() *SSHConfigReader { 18 return &SSHConfigReader{ 19 Files: []string{ 20 filepath.Join(os.Getenv("HOME"), ".ssh/config"), 21 "/etc/ssh_config", 22 "/etc/ssh/ssh_config", 23 }, 24 } 25 } 26 27 type SSHConfigReader struct { 28 Files []string 29 } 30 31 func (r *SSHConfigReader) Read() SSHConfig { 32 config := make(SSHConfig) 33 hostRe := regexp.MustCompile(hostReStr) 34 35 for _, filename := range r.Files { 36 r.readFile(config, hostRe, filename) 37 } 38 39 return config 40 } 41 42 func (r *SSHConfigReader) readFile(c SSHConfig, re *regexp.Regexp, f string) error { 43 file, err := os.Open(f) 44 if err != nil { 45 return err 46 } 47 defer file.Close() 48 49 hosts := []string{"*"} 50 scanner := bufio.NewScanner(file) 51 for scanner.Scan() { 52 line := scanner.Text() 53 match := re.FindStringSubmatch(line) 54 if match == nil { 55 continue 56 } 57 58 names := strings.Fields(match[2]) 59 if strings.EqualFold(match[1], "host") { 60 hosts = names 61 } else { 62 for _, host := range hosts { 63 for _, name := range names { 64 c[host] = name 65 } 66 } 67 } 68 } 69 70 return scanner.Err() 71 }