packages/hyprspace: select peers by name or ID prefix

This commit is contained in:
Max Headroom 2024-04-22 15:04:33 +02:00
parent aadc5f3e7b
commit 3e3eec0fb1
2 changed files with 29 additions and 14 deletions

View file

@ -162,6 +162,33 @@ func FindPeer(peers []Peer, needle peer.ID) (*Peer, bool) {
return nil, false return nil, false
} }
func FindPeerByName(peers []Peer, needle string) (*Peer, bool) {
for _, p := range peers {
if p.Name == needle {
return &p, true
}
}
return nil, false
}
func FindPeerByIDPrefix(peers []Peer, needle string) (*Peer, bool) {
for _, p := range peers {
if strings.HasPrefix(p.ID.String(), needle) {
return &p, true
}
}
return nil, false
}
func FindPeerByCLIRef(peers []Peer, needle string) (*Peer, bool) {
if strings.HasPrefix(needle, "@") {
name := strings.TrimPrefix(needle, "@")
return FindPeerByName(peers, name)
} else {
return FindPeerByIDPrefix(peers, needle)
}
}
func (cfg Config) FindRoute(needle net.IPNet) (*RouteTableEntry, bool) { func (cfg Config) FindRoute(needle net.IPNet) (*RouteTableEntry, bool) {
networks, err := cfg.PeerLookup.ByRoute.CoveredNetworks(needle) networks, err := cfg.PeerLookup.ByRoute.CoveredNetworks(needle)
if err != nil { if err != nil {

View file

@ -111,19 +111,7 @@ func (hsr *HyprspaceRPC) Route(args *RouteArgs, reply *RouteReply) error {
if err != nil { if err != nil {
return err return err
} }
peerId, err := peer.Decode(args.Args[1]) target, found := config.FindPeerByCLIRef(hsr.config.Peers, args.Args[1])
if err != nil {
return err
}
var target config.Peer
var found bool
for _, p := range hsr.config.Peers {
if p.ID == peerId {
target = p
found = true
break
}
}
if !found { if !found {
return errors.New("no such peer") return errors.New("no such peer")
} }
@ -134,7 +122,7 @@ func (hsr *HyprspaceRPC) Route(args *RouteArgs, reply *RouteReply) error {
hsr.config.PeerLookup.ByRoute.Insert(&config.RouteTableEntry{ hsr.config.PeerLookup.ByRoute.Insert(&config.RouteTableEntry{
Net: *network, Net: *network,
Target: target, Target: *target,
}) })
case Del: case Del:
if len(args.Args) != 1 { if len(args.Args) != 1 {