| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- package main
- import (
- "fmt"
- "strconv"
- "strings"
- intdevice "netdome.biz/paul/qmk-rgb/internal/device"
- )
- // selectDevice resolves the --device selector against the discovered
- // keyboards. An empty selector picks the only keyboard when exactly one is
- // connected and fails otherwise, so commands never silently target the wrong
- // keyboard.
- func selectDevice(devices []intdevice.Device, selector string) (intdevice.Device, error) {
- if len(devices) == 0 {
- return intdevice.Device{}, fmt.Errorf("no QMK keyboard found")
- }
- if selector == "" {
- if len(devices) > 1 {
- return intdevice.Device{}, fmt.Errorf(
- "multiple QMK keyboards found, use --device to select:\n%s",
- formatDeviceList(devices))
- }
- return devices[0], nil
- }
- invalid := fmt.Errorf("invalid --device %q: expected a keyboard number\n%s",
- selector, formatDeviceList(devices))
- index, err := strconv.Atoi(selector)
- if err != nil {
- return intdevice.Device{}, invalid
- }
- if index < 1 || index > len(devices) {
- return intdevice.Device{}, invalid
- }
- return devices[index-1], nil
- }
- // formatDeviceList renders the selectable keyboards with the numbers that
- // --device accepts.
- func formatDeviceList(devices []intdevice.Device) string {
- var b strings.Builder
- for _, d := range devices {
- name := d.Name
- if name == "" {
- name = "Unknown QMK keyboard"
- }
- fmt.Fprintf(&b, " %d %s VID=0x%04x PID=0x%04x %s\n",
- d.Index, name, d.VendorID, d.ProductID, d.Path)
- }
- return b.String()
- }
|