123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- package main
-
- import (
- "os"
- "path"
- "regexp"
- "strings"
- )
-
- type Identity struct {
- Name string
- Path string
- }
-
- func newIdentity(config Config, name string) Identity {
- return Identity{
- Name: name,
- Path: "",
- }
- }
-
- var hostRegexps = map[string]*regexp.Regexp{
- "ssh": regexp.MustCompile("(?P<user>.*@)?(?P<host>.*)"),
- "scp": regexp.MustCompile("(?P<user>.*@)?(?P<host>.*):(?P<file>.*)"),
- }
-
- func extractHost(prog string, args []string) string {
- args = removeOptions(prog, args)
- switch prog {
- case "ssh":
- if len(args) == 0 {
- return ""
- }
- re := hostRegexps["ssh"]
- arg := args[0]
- p := matchParams(re, arg)
- return p["host"]
- case "scp":
- re := hostRegexps["scp"]
- for _, arg := range args {
- if p := matchParams(re, arg); p != nil {
- return p["host"]
- }
- }
- }
- return ""
- }
-
- func findIdentityName(config Config, prog string, args []string) string {
- name := os.Getenv("SSH_IDENTITY")
- if name != "" {
- return name
- }
- identities := config.Identities
- host := extractHost(prog, args)
- for match, name := range identities {
- if strings.Contains(host, match) {
- return name
- }
- }
-
- return config.DefaultIdentity
- }
-
- func FindIdentity(config Config, prog string, args []string) Identity {
- name := findIdentityName(config, prog, args)
- path := path.Join(config.IdentitiesDir, name)
- return Identity{
- Name: name,
- Path: path,
- }
- }
|