Files
router/tools/ipadm/interactive.go
T
mike 1a39f54858 ipadm: translate to English, fix help alignment
- All ipadm-internal messages (usage, prompts, errors) are now English
- Usage text is built programmatically from a (left, desc) row list with
  computed column width instead of hand-aligned spaces, so it can't drift
  out of alignment again when rows are added/changed
- README's literal usage block updated to match; rest of the repo docs
  stay German
2026-08-18 11:49:47 +02:00

93 lines
2.1 KiB
Go

package main
import (
"bufio"
"fmt"
"os"
"strings"
)
var stdinReader = bufio.NewReader(os.Stdin)
// prompt shows label with a "[current]" hint, reads one line, and returns
// current unchanged if the user just presses enter.
func prompt(label, current string) string {
if current != "" {
fmt.Printf("%s [%s]: ", label, current)
} else {
fmt.Printf("%s: ", label)
}
line, _ := stdinReader.ReadString('\n')
line = strings.TrimSpace(line)
if line == "" {
return current
}
return line
}
// interactiveEdit implements the bare `ipadm <hostname>` form: add the host
// if it doesn't exist yet, otherwise edit it in place. Returns the updated
// host list, or an error if validation fails.
func interactiveEdit(hosts []Host, name string, cfg netConfig) ([]Host, error) {
if err := validateHostname(name); err != nil {
return nil, err
}
idx := findHost(hosts, name)
var cur Host
if idx >= 0 {
cur = hosts[idx]
fmt.Printf("Editing existing host %q (press enter to keep a value)\n", name)
} else {
cur = Host{Name: name}
fmt.Printf("New host %q (press enter to leave MAC/comment empty)\n", name)
}
for {
ip := prompt("IP address", cur.IP)
if err := validateIP(ip, cfg.lanCIDR, cfg.poolStart, cfg.poolEnd); err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
continue
}
cur.IP = ip
break
}
for {
mac := prompt("MAC address (optional, '-' to clear)", macOrDash(cur.MAC))
if mac == "-" {
mac = ""
}
norm, err := normalizeMAC(mac)
if err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
continue
}
cur.MAC = norm
break
}
cur.Comment = prompt("Comment", cur.Comment)
if other := findByIP(hosts, cur.IP, idx); other >= 0 {
return nil, fmt.Errorf("IP %s is already assigned to host %q", cur.IP, hosts[other].Name)
}
if other := findByMAC(hosts, cur.MAC, idx); other >= 0 {
return nil, fmt.Errorf("MAC %s is already assigned to host %q", cur.MAC, hosts[other].Name)
}
if idx >= 0 {
hosts[idx] = cur
} else {
hosts = append(hosts, cur)
}
return hosts, nil
}
func macOrDash(mac string) string {
if mac == "" {
return ""
}
return mac
}