keyboard stuff
at master 227 lines 11 kB view raw view rendered
1# QMK CLI Development 2 3This document has useful information for developers wishing to write new `qmk` subcommands. 4 5# Overview 6 7The QMK CLI operates using the subcommand pattern made famous by git. The main `qmk` script is simply there to setup the environment and pick the correct entrypoint to run. Each subcommand is a self-contained module with an entrypoint (decorated by `@cli.subcommand()`) that performs some action and returns a shell returncode, or None. 8 9## Developer mode: 10 11If you intend to maintain keyboards and/or contribute to QMK, you can enable the CLI's "Developer" mode: 12 13`qmk config user.developer=True` 14 15This will allow you to see all available subcommands. 16**Note:** You will have to install additional requirements: 17``` 18python3 -m pip install -r requirements-dev.txt 19``` 20 21# Subcommands 22 23[MILC](https://github.com/clueboard/milc) is the CLI framework `qmk` uses to handle argument parsing, configuration, logging, and many other features. It lets you focus on writing your tool without wasting your time writing glue code. 24 25Subcommands in the local CLI are always found in `qmk_firmware/lib/python/qmk/cli`. 26 27Let's start by looking at an example subcommand. This is `lib/python/qmk/cli/hello.py`: 28 29```python 30"""QMK Python Hello World 31 32This is an example QMK CLI script. 33""" 34from milc import cli 35 36 37@cli.argument('-n', '--name', default='World', help='Name to greet.') 38@cli.subcommand('QMK Hello World.') 39def hello(cli): 40 """Log a friendly greeting. 41 """ 42 cli.log.info('Hello, %s!', cli.config.hello.name) 43``` 44 45First we import the `cli` object from `milc`. This is how we interact with the user and control the script's behavior. We use `@cli.argument()` to define a command line flag, `--name`. This also creates a configuration variable named `hello.name` (and the corresponding `user.name`) which the user can set so they don't have to specify the argument. The `cli.subcommand()` decorator designates this function as a subcommand. The name of the subcommand will be taken from the name of the function. 46 47Once inside our function we find a typical "Hello, World!" program. We use `cli.log` to access the underlying [Logger Object](https://docs.python.org/3.9/library/logging.html#logger-objects), whose behavior is user controllable. We also access the value for name supplied by the user as `cli.config.hello.name`. The value for `cli.config.hello.name` will be determined by looking at the `--name` argument supplied by the user, if not provided it will use the value in the `qmk.ini` config file, and if neither of those is provided it will fall back to the default supplied in the `cli.argument()` decorator. 48 49# User Interaction 50 51MILC and the QMK CLI have several nice tools for interacting with the user. Using these standard tools will allow you to colorize your text for easier interactions, and allow the user to control when and how that information is displayed and stored. 52 53## Printing Text 54 55There are two main methods for outputting text in a subcommand- `cli.log` and `cli.echo()`. They operate in similar ways but you should prefer to use `cli.log.info()` for most general purpose printing. 56 57You can use special tokens to colorize your text, to make it easier to understand the output of your program. See [Colorizing Text](#colorizing-text) below. 58 59Both of these methods support built-in string formatting using python's [printf style string format operations](https://docs.python.org/3.9/library/stdtypes.html#old-string-formatting). You can use tokens such as `%s` and `%d` within your text strings then pass the values as arguments. See our Hello, World program above for an example. 60 61You should never use the format operator (`%`) directly, always pass values as arguments. 62 63### Logging (`cli.log`) 64 65The `cli.log` object gives you access to a [Logger Object](https://docs.python.org/3.9/library/logging.html#logger-objects). We have configured our log output to show the user a nice emoji for each log level (or the log level name if their terminal does not support unicode.) This way the user can tell at a glance which messages are most important when something goes wrong. 66 67The default log level is `INFO`. If the user runs `qmk -v <subcommand>` the default log level will be set to `DEBUG`. 68 69| Function | Emoji | 70|----------|-------| 71| cli.log.critical | `{bg_red}{fg_white}¬_¬{style_reset_all}` | 72| cli.log.error | `{fg_red}☒{style_reset_all}` | 73| cli.log.warning | `{fg_yellow}⚠{style_reset_all}` | 74| cli.log.info | `{fg_blue}Ψ{style_reset_all}` | 75| cli.log.debug | `{fg_cyan}☐{style_reset_all}` | 76| cli.log.notset | `{style_reset_all}¯\\_(o_o)_/¯` | 77 78### Printing (`cli.echo`) 79 80Sometimes you simply need to print text outside of the log system. This is appropriate if you are outputting fixed data or writing out something that should never be logged. Most of the time you should prefer `cli.log.info()` over `cli.echo`. 81 82### Colorizing Text 83 84You can colorize the output of your text by including color tokens within text. Use color to highlight, not to convey information. Remember that the user can disable color, and your subcommand should still be usable if they do. 85 86You should generally avoid setting the background color, unless it's integral to what you are doing. Remember that users have a lot of preferences when it comes to their terminal color, so you should pick colors that work well against both black and white backgrounds. 87 88Colors prefixed with 'fg' will affect the foreground (text) color. Colors prefixed with 'bg' will affect the background color. 89 90| Color | Background | Extended Background | Foreground | Extended Foreground| 91|-------|------------|---------------------|------------|--------------------| 92| Black | {bg_black} | {bg_lightblack_ex} | {fg_black} | {fg_lightblack_ex} | 93| Blue | {bg_blue} | {bg_lightblue_ex} | {fg_blue} | {fg_lightblue_ex} | 94| Cyan | {bg_cyan} | {bg_lightcyan_ex} | {fg_cyan} | {fg_lightcyan_ex} | 95| Green | {bg_green} | {bg_lightgreen_ex} | {fg_green} | {fg_lightgreen_ex} | 96| Magenta | {bg_magenta} | {bg_lightmagenta_ex} | {fg_magenta} | {fg_lightmagenta_ex} | 97| Red | {bg_red} | {bg_lightred_ex} | {fg_red} | {fg_lightred_ex} | 98| White | {bg_white} | {bg_lightwhite_ex} | {fg_white} | {fg_lightwhite_ex} | 99| Yellow | {bg_yellow} | {bg_lightyellow_ex} | {fg_yellow} | {fg_lightyellow_ex} | 100 101There are also control sequences that can be used to change the behavior of 102ANSI output: 103 104| Control Sequences | Description | 105|-------------------|-------------| 106| {style_bright} | Make the text brighter | 107| {style_dim} | Make the text dimmer | 108| {style_normal} | Make the text normal (neither `{style_bright}` nor `{style_dim}`) | 109| {style_reset_all} | Reset all text attributes to default. (This is automatically added to the end of every string.) | 110| {bg_reset} | Reset the background color to the user's default | 111| {fg_reset} | Reset the foreground color to the user's default | 112 113# Arguments and Configuration 114 115QMK handles the details of argument parsing and configuration for you. When you add a new argument it is automatically incorporated into the config tree based on your subcommand's name and the long name of the argument. You can access this configuration in `cli.config`, using either attribute-style access (`cli.config.<subcommand>.<argument>`) or dictionary-style access (`cli.config['<subcommand>']['<argument>']`). 116 117Under the hood QMK uses [ConfigParser](https://docs.python.org/3/library/configparser.html) to store configurations. This gives us an easy and straightforward way to represent the configuration in a human-editable way. We have wrapped access to this configuration to provide some nicities that ConfigParser does not normally have. 118 119## Reading Configuration Values 120 121You can interact with `cli.config` in all the ways you'd normally expect. For example the `qmk compile` command gets the keyboard name from `cli.config.compile.keyboard`. It does not need to know whether that value came from the command line, an environment variable, or the configuration file. 122 123Iteration is also supported: 124 125``` 126for section in cli.config: 127 for key in cli.config[section]: 128 cli.log.info('%s.%s: %s', section, key, cli.config[section][key]) 129``` 130 131## Setting Configuration Values 132 133You can set configuration values in the usual ways. 134 135Dictionary style: 136 137``` 138cli.config['<section>']['<key>'] = <value> 139``` 140 141Attribute style: 142 143``` 144cli.config.<section>.<key> = <value> 145``` 146 147## Deleting Configuration Values 148 149You can delete configuration values in the usual ways. 150 151Dictionary style: 152 153``` 154del(cli.config['<section>']['<key>']) 155``` 156 157Attribute style: 158 159``` 160del(cli.config.<section>.<key>) 161``` 162 163## Writing The Configuration File 164 165The configuration is not written out when it is changed. Most commands do not need to do this. We prefer to have the user change their configuration deliberately using `qmk config`. 166 167You can use `cli.save_config()` to write out the configuration. 168 169## Excluding Arguments From Configuration 170 171Some arguments should not be propagated to the configuration file. These can be excluded by adding `arg_only=True` when creating the argument. 172 173Example: 174 175``` 176@cli.argument('-o', '--output', arg_only=True, help='File to write to') 177@cli.argument('filename', arg_only=True, help='Configurator JSON file') 178@cli.subcommand('Create a keymap.c from a QMK Configurator export.') 179def json_keymap(cli): 180 pass 181``` 182 183You will only be able to access these arguments using `cli.args`. For example: 184 185``` 186cli.log.info('Reading from %s and writing to %s', cli.args.filename, cli.args.output) 187``` 188 189# Testing, and Linting, and Formatting (oh my!) 190 191We use nose2, flake8, and yapf to test, lint, and format code. You can use the `pytest` and `format-python` subcommands to run these tests: 192 193### Testing and Linting 194 195``` 196qmk pytest 197``` 198 199### Formatting 200 201``` 202qmk format-python 203``` 204 205## Formatting Details 206 207We use [yapf](https://github.com/google/yapf) to automatically format code. Our configuration is in the `[yapf]` section of `setup.cfg`. 208 209::: tip 210Many editors can use yapf as a plugin to automatically format code as you type. 211::: 212 213## Testing Details 214 215Our tests can be found in `lib/python/qmk/tests/`. You will find both unit and integration tests in this directory. We hope you will write both unit and integration tests for your code, but if you do not please favor integration tests. 216 217If your PR does not include a comprehensive set of tests please add comments like this to your code so that other people know where they can help: 218 219```python 220# TODO(unassigned/<your_github_username>): Write <unit|integration> tests 221``` 222 223We use [nose2](https://nose2.readthedocs.io/en/latest/getting_started.html) to run our tests. You can refer to the nose2 documentation for more details on what you can do in your test functions. 224 225## Linting Details 226 227We use flake8 to lint our code. Your code should pass flake8 before you open a PR. This will be checked when you run `qmk pytest` and by CI when you submit a PR.