diff --git a/config.go b/config.go index f49236f..5a74741 100644 --- a/config.go +++ b/config.go @@ -4,12 +4,14 @@ import ( "encoding/json" "fmt" "io/ioutil" + "math" neturl "net/url" "os" "os/exec" "path/filepath" "runtime" - "strings" + + "github.com/agext/levenshtein" ) type Config struct { @@ -83,15 +85,14 @@ func (cfg *Config) LoadFile(file string) error { } func (cfg *Config) GetEnv(url string) (env Env, err error) { - u, err := neturl.Parse(url) - if err != nil { - return - } + u1, _ := neturl.Parse(url) for _, service := range cfg.Services { - if strings.Contains(service.URL, u.Host) { + u2, _ := neturl.Parse(service.URL) + if u1.Host == u2.Host { return service.Env, nil } } + err = fmt.Errorf("%s: no such host in config file", u1.Host) return } @@ -121,3 +122,19 @@ func (cfg *Config) Edit() error { cmd.Stdin = os.Stdin return cmd.Run() } + +func (cfg *Config) SimilarURLs(url string) (urls []string) { + u1, _ := neturl.Parse(url) + for _, service := range cfg.Services { + u2, _ := neturl.Parse(service.URL) + degree := round(levenshtein.Similarity(u1.Host, u2.Host, nil) * 100) + if degree > 50 { + urls = append(urls, service.URL) + } + } + return +} + +func round(f float64) float64 { + return math.Floor(f + .5) +} diff --git a/main.go b/main.go index 0cfe4de..65dabbf 100644 --- a/main.go +++ b/main.go @@ -48,6 +48,7 @@ func main() { } func run(args []string) int { + var url string if len(args) > 0 { switch args[0] { case "-h", "--help": @@ -63,11 +64,16 @@ func run(args []string) int { } fmt.Fprintf(os.Stderr, "Error: %s\n", err.Error()) return 1 + default: + url = args[0] } - env, err := cfg.GetEnv(args[0]) + env, err := cfg.GetEnv(url) if err != nil { fmt.Fprintf(os.Stderr, "Error: %s\n", err.Error()) + for _, url := range cfg.SimilarURLs(url) { + } + fmt.Fprintf(os.Stderr, " similar urls found %q\n") return 1 } if credentials == "" {