Skip to content
quarry Artifact [27ec7bf4e9]
Login

Artifact [27ec7bf4e9]

Artifact 27ec7bf4e97204f48f7a2aa01a5a0c859d10c538a9e60387ec8c85474c4b4404:


package api

import (
	"strings"
)

// nameFold is a name as a person would read it as the same: case folded,
// the separators - _ . removed.
func nameFold(s string) string {
	return strings.Map(func(r rune) rune {
		if r == '-' || r == '_' || r == '.' {
			return -1
		}
		return r
	}, strings.ToLower(s))
}

// nameSkeleton is a name as the eye confuses it: folded, then the
// look-alike letters made one: rn as m, 0 as o, and 1, i, l as l.
func nameSkeleton(s string) string {
	s = strings.ReplaceAll(nameFold(s), "rn", "m")
	return strings.NewReplacer("0", "o", "1", "l", "i", "l").Replace(s)
}

// nameClash compares a name wanted for a new agent with the names that
// exist. same are those that fold to it (a collision: only the case or
// the separators differ); like are those that differ from it only by the
// look-alike letters (to be flagged, not refused). Each keeps the
// existing name as it is spelt.
func nameClash(name string, existing []string) (same, like []string) {
	fold, skel := nameFold(name), nameSkeleton(name)
	for _, e := range existing {
		switch {
		case nameFold(e) == fold:
			same = append(same, e)
		case nameSkeleton(e) == skel:
			like = append(like, e)
		}
	}
	return same, like
}

// accountNames is every live account's name, agents included.
func (d Deps) accountNames() []string {
	if d.Accounts == nil {
		return nil
	}
	accts, err := d.Accounts.Accounts()
	if err != nil {
		return nil
	}
	names := make([]string, 0, len(accts))
	for _, a := range accts {
		names = append(names, a.Name)
	}
	return names
}

// lookAlikes are the existing accounts a new agent's name could be
// mistaken for.
func (d Deps) lookAlikes(name string) []string {
	_, like := nameClash(name, d.accountNames())
	return like
}