main.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "os"
  6. "strings"
  7. "github.com/spf13/cobra"
  8. "netdome.biz/paul/qmk-rgb/internal/device"
  9. )
  10. // version is set at build time via -ldflags.
  11. var version = "dev"
  12. // Group IDs for the root help. They name a group in the help output and say
  13. // nothing else: no behaviour hangs off them.
  14. const (
  15. groupLighting = "lighting"
  16. groupProfile = "profile"
  17. groupKeyboard = "keyboard"
  18. )
  19. var targetDevice string
  20. // zoneSelection is the rule every command that writes lighting carries in its own
  21. // help. It is repeated per command rather than left to the root help because a
  22. // subcommand's --help does not print the root's, and this is the one thing a user
  23. // has to know before running one of them.
  24. const zoneSelection = "The zone is a VIA lighting channel: backlight, rgblight, rgb_matrix, audio or\n" +
  25. "led_matrix, or the name this keyboard's definition gives it. Several are written\n" +
  26. "comma separated and the word all means every channel the keyboard reports."
  27. // writesLighting is the help of a command that writes to the keyboard: what the
  28. // command does, then the one rule they share.
  29. func writesLighting(long string) string {
  30. return long + "\n\n" + zoneSelection
  31. }
  32. func newRootCommand() *cobra.Command {
  33. cmd := &cobra.Command{
  34. Use: "qmk-rgb-tool",
  35. Short: "QMK RGB CLI — control QMK keyboard lighting",
  36. SilenceErrors: true,
  37. SilenceUsage: true,
  38. }
  39. // The commands are grouped because fifteen of them in one flat list is where
  40. // a user starts reading the help to find a command and gives up. A group says
  41. // what a command is for, and a command in none of them lands under
  42. // "Additional Commands" where the grouping says nothing.
  43. cmd.AddGroup(
  44. &cobra.Group{ID: groupLighting, Title: "Lighting Commands:"},
  45. &cobra.Group{ID: groupProfile, Title: "Profile Commands:"},
  46. &cobra.Group{ID: groupKeyboard, Title: "Keyboard Commands:"},
  47. )
  48. cmd.PersistentFlags().StringVar(&targetDevice, "device", "", "Keyboard number as printed by 'keyboard info', starting at 1")
  49. cmd.PersistentFlags().StringVar(&definitionFlag, "definition", "", "VIA definition file to read effect names from, instead of the one in the data directory")
  50. cmd.PersistentFlags().BoolVar(&jsonOutput, "json", false, "Print JSON instead of text")
  51. return cmd
  52. }
  53. var rootCmd = newRootCommand()
  54. func Execute() {
  55. if err := rootCmd.Execute(); err != nil {
  56. fmt.Fprintf(os.Stderr, "Error: %v\n", err)
  57. os.Exit(1)
  58. }
  59. }
  60. func main() {
  61. Execute()
  62. }
  63. // keyboardCmd is the namespace for everything that is about one board rather
  64. // than about its lighting: which boards are connected, and the definition file
  65. // whose effect names belong to a board. The definition prose lives here because
  66. // there is no `definition` command of its own any more.
  67. var keyboardCmd = &cobra.Command{
  68. Use: "keyboard",
  69. Short: "Keyboard management commands",
  70. GroupID: groupKeyboard,
  71. Long: "A keyboard's effect names come from a VIA definition file, the same one VIA\n" +
  72. "itself uses. `fetch` downloads the file for the connected keyboard into the\n" +
  73. "data directory; to use a file you already have, put it in that directory or\n" +
  74. "pass it with --definition.",
  75. }
  76. // inGroup places a command in one of the root help's groups.
  77. func inGroup(cmd *cobra.Command, group string) *cobra.Command {
  78. cmd.GroupID = group
  79. return cmd
  80. }
  81. // discoverAll is a seam for tests.
  82. var discoverAll = device.DiscoverAll
  83. // runKeyboardInfo writes the connected QMK keyboards, as text unless --json
  84. // asks otherwise. The 1-based index that --device accepts is in the "index"
  85. // field, so the machine shape emits no banner alongside it. Whether a keyboard
  86. // has effect names is reported per keyboard, because it differs: one board may
  87. // have a definition and the next may not.
  88. func runKeyboardInfo(out io.Writer) error {
  89. devices, err := discoverAll()
  90. if err != nil {
  91. return err
  92. }
  93. if devices == nil {
  94. devices = []device.Device{}
  95. }
  96. lines := describeDevices(devices)
  97. if !jsonOutput {
  98. return printKeyboardInfoText(out, lines)
  99. }
  100. type info struct {
  101. Devices []keyboardLine `json:"devices"`
  102. Total int `json:"total"`
  103. }
  104. return encodeJSON(out, info{Devices: lines, Total: len(lines)})
  105. }
  106. var keyboardInfoCmd = &cobra.Command{
  107. Use: "info",
  108. Short: "Discover connected QMK keyboards",
  109. Long: "Scan for connected QMK keyboards and print device info as JSON.\n" +
  110. "Each device carries the 1-based index that --device accepts.",
  111. Args: cobra.NoArgs,
  112. RunE: func(cmd *cobra.Command, args []string) error {
  113. return runKeyboardInfo(cmd.OutOrStdout())
  114. },
  115. }
  116. func init() {
  117. registerCommands(rootCmd)
  118. registerFlagCompletions(rootCmd)
  119. rootCmd.Version = version
  120. rootCmd.SetVersionTemplate(" qmk-rgb-tool {{.Version}}\n")
  121. }
  122. // registerCommands adds every command to the root, each in the group the help
  123. // output lists it under. It is a function of its own so that a test can build the
  124. // same tree the binary runs and check the grouping is real, rather than repeating
  125. // a list that could fall behind the one that ships.
  126. func registerCommands(root *cobra.Command) {
  127. keyboardCmd.AddCommand(
  128. keyboardInfoCmd,
  129. NewKeyboardFetchCmd(),
  130. NewKeyboardDefinitionsCmd(),
  131. )
  132. // The zone is a positional argument, not a flag. A flag every help lists told
  133. // `keyboard info` and `list` about a channel they have none of, and it was
  134. // ignored there rather than refused. A positional argument is spelled only
  135. // where it is read, so there is nothing to ignore.
  136. lighting := []*cobra.Command{
  137. inGroup(NewEnableCmd(), groupLighting),
  138. inGroup(NewDisableCmd(), groupLighting),
  139. inGroup(NewInfoCmd(), groupLighting),
  140. inGroup(NewEffectCmd(), groupLighting),
  141. inGroup(NewBrightnessCmd(), groupLighting),
  142. inGroup(NewSpeedCmd(), groupLighting),
  143. inGroup(NewColorCmd(), groupLighting),
  144. }
  145. profiles := []*cobra.Command{
  146. inGroup(NewProfileSaveCmd(), groupProfile),
  147. inGroup(NewProfileLoadCmd(), groupProfile),
  148. }
  149. rest := []*cobra.Command{
  150. inGroup(NewProfileListCmd(), groupProfile),
  151. inGroup(NewProfileDeleteCmd(), groupProfile),
  152. keyboardCmd,
  153. }
  154. commands := make([]*cobra.Command, 0, len(lighting)+len(profiles)+len(rest))
  155. commands = append(commands, lighting...)
  156. commands = append(commands, profiles...)
  157. commands = append(commands, rest...)
  158. root.AddCommand(commands...)
  159. }
  160. // zoneArgs is the argument count of a command that reads a zone, together with
  161. // the message a user gets when the count is wrong. Cobra's own "accepts 2 arg(s),
  162. // received 1" does not say what the argument should have been, and a command that
  163. // writes lighting now fails at its arity rather than at a choice of channel, so
  164. // the usage line is the only help there is.
  165. func zoneArgs(min, max int, what string) cobra.PositionalArgs {
  166. return func(cmd *cobra.Command, args []string) error {
  167. if len(args) < min || len(args) > max {
  168. // cmd.Use already starts with the command's own name, so the path is
  169. // the name and what follows it, not the name twice.
  170. return fmt.Errorf("%s takes %s\nusage: %s%s", cmd.Name(), what,
  171. cmd.CommandPath(), strings.TrimPrefix(cmd.Use, cmd.Name()))
  172. }
  173. return nil
  174. }
  175. }
  176. // withZoneArgs declares a command's zone argument count, its usage line and the
  177. // completion for it, in one call. A command that names a channel and does not
  178. // call this is a command the shell knows nothing about, so the three belong
  179. // together: the count is what makes the zone required, the usage line is where
  180. // the vocabulary is documented, and the completion is how a user finds the names
  181. // a board supplies.
  182. //
  183. // A command that takes a zone and something else first — `load` takes a profile
  184. // name — cannot use this, because the zone is not what its first argument is. It
  185. // declares the count and its own completion instead.
  186. func withZoneArgs(cmd *cobra.Command, min, max int, what string) *cobra.Command {
  187. cmd.Args = zoneArgs(min, max, what)
  188. cmd.ValidArgsFunction = completeZoneArgs
  189. return cmd
  190. }