Skip to content

Commit b021c2f

Browse files
fauxparkErovia
andauthored
Port new_keyboard.sh to CLI (#13706)
Co-authored-by: Erovia <Erovia@users.noreply.github.com>
1 parent 770a525 commit b021c2f

File tree

7 files changed

+213
-61
lines changed

7 files changed

+213
-61
lines changed

docs/cli_commands.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -280,12 +280,12 @@ qmk list-keymaps -kb planck/ez
280280

281281
This command creates a new keyboard based on available templates.
282282

283-
This command will prompt for input to guide you though the generation process.
283+
Any arguments that are not provided will prompt for input. If `-u` is not passed and `user.name` is set in .gitconfig, it will be used as the default username in the prompt.
284284

285285
**Usage**:
286286

287287
```
288-
qmk new-keyboard
288+
qmk new-keyboard [-kb KEYBOARD] [-t {avr,ps2avrgb}] -u USERNAME
289289
```
290290

291291
## `qmk new-keymap`

docs/es/hardware_avr.md

+20-18
Original file line numberDiff line numberDiff line change
@@ -6,26 +6,28 @@ Si aún no lo has hecho, debes leer las [Pautas de teclados](hardware_keyboard_g
66

77
## Añadir tu Teclado AVR a QMK
88

9-
QMK tiene varias características para simplificar el trabajo con teclados AVR. Para la mayoría de los teclados no tienes que escribir ni una sola línea de código. Para empezar, ejecuta el archivo `util/new_keyboard.sh`:
9+
QMK tiene varias características para simplificar el trabajo con teclados AVR. Para la mayoría de los teclados no tienes que escribir ni una sola línea de código. Para empezar, ejecuta `qmk new-keyboard`:
1010

1111
```
12-
$ ./util/new_keyboard.sh
13-
Generating a new QMK keyboard directory
14-
15-
Keyboard Name: mycoolkb
16-
Keyboard Type [avr]:
17-
Your Name [John Smith]:
18-
19-
Copying base template files... done
20-
Copying avr template files... done
21-
Renaming keyboard files... done
22-
Replacing %KEYBOARD% with mycoolkb... done
23-
Replacing %YOUR_NAME% with John Smith... done
24-
25-
Created a new keyboard called mycoolkb.
26-
27-
To start working on things, cd into keyboards/mycoolkb,
28-
or open the directory in your favourite text editor.
12+
$ qmk new-keyboard
13+
Ψ Generating a new QMK keyboard directory
14+
15+
Keyboard Name: mycoolkeeb
16+
Keyboard Type:
17+
1. avr
18+
2. ps2avrgb
19+
Please enter your choice: [1]
20+
Your Name: [John Smith]
21+
Ψ Copying base template files...
22+
Ψ Copying avr template files...
23+
Ψ Renaming keyboard.[ch] to mycoolkeeb.[ch]...
24+
Ψ Replacing %YEAR% with 2021...
25+
Ψ Replacing %KEYBOARD% with mycoolkeeb...
26+
Ψ Replacing %YOUR_NAME% with John Smith...
27+
28+
Ψ Created a new keyboard called mycoolkeeb.
29+
Ψ To start working on things, `cd` into keyboards/mycoolkeeb,
30+
Ψ or open the directory in your preferred text editor.
2931
```
3032

3133
Esto creará todos los archivos necesarios para tu nuevo teclado, y rellenará la configuración con valores predeterminados. Ahora sólo tienes que personalizarlo para tu teclado.

docs/hardware_avr.md

+20-18
Original file line numberDiff line numberDiff line change
@@ -6,26 +6,28 @@ If you have not yet you should read the [Keyboard Guidelines](hardware_keyboard_
66

77
## Adding Your AVR Keyboard to QMK
88

9-
QMK has a number of features to simplify working with AVR keyboards. For most keyboards you don't have to write a single line of code. To get started, run the `util/new_keyboard.sh` script:
9+
QMK has a number of features to simplify working with AVR keyboards. For most keyboards you don't have to write a single line of code. To get started, run `qmk new-keyboard`:
1010

1111
```
12-
$ ./util/new_keyboard.sh
13-
Generating a new QMK keyboard directory
14-
15-
Keyboard Name: mycoolkb
16-
Keyboard Type [avr]:
17-
Your Name [John Smith]:
18-
19-
Copying base template files... done
20-
Copying avr template files... done
21-
Renaming keyboard files... done
22-
Replacing %KEYBOARD% with mycoolkb... done
23-
Replacing %YOUR_NAME% with John Smith... done
24-
25-
Created a new keyboard called mycoolkb.
26-
27-
To start working on things, cd into keyboards/mycoolkb,
28-
or open the directory in your favourite text editor.
12+
$ qmk new-keyboard
13+
Ψ Generating a new QMK keyboard directory
14+
15+
Keyboard Name: mycoolkeeb
16+
Keyboard Type:
17+
1. avr
18+
2. ps2avrgb
19+
Please enter your choice: [1]
20+
Your Name: [John Smith]
21+
Ψ Copying base template files...
22+
Ψ Copying avr template files...
23+
Ψ Renaming keyboard.[ch] to mycoolkeeb.[ch]...
24+
Ψ Replacing %YEAR% with 2021...
25+
Ψ Replacing %KEYBOARD% with mycoolkeeb...
26+
Ψ Replacing %YOUR_NAME% with John Smith...
27+
28+
Ψ Created a new keyboard called mycoolkeeb.
29+
Ψ To start working on things, `cd` into keyboards/mycoolkeeb,
30+
Ψ or open the directory in your preferred text editor.
2931
```
3032

3133
This will create all the files needed to support your new keyboard, and populate the settings with default values. Now you just need to customize it for your keyboard.

docs/ja/hardware_avr.md

+20-18
Original file line numberDiff line numberDiff line change
@@ -12,26 +12,28 @@
1212

1313
## AVR を使用したキーボードを QMK に追加する
1414

15-
QMK には AVR を使ったキーボードでの作業を簡略化するための機能が多数あります。大体のキーボードでは1行もコードを書く必要がありません。まずはじめに、`util/new_keyboard.sh` スクリプトを実行します
15+
QMK には AVR を使ったキーボードでの作業を簡略化するための機能が多数あります。大体のキーボードでは1行もコードを書く必要がありません。まずはじめに、`qmk new-keyboard` を実行します
1616

1717
```
18-
$ ./util/new_keyboard.sh
19-
Generating a new QMK keyboard directory
20-
21-
Keyboard Name: mycoolkb
22-
Keyboard Type [avr]:
23-
Your Name [John Smith]:
24-
25-
Copying base template files... done
26-
Copying avr template files... done
27-
Renaming keyboard files... done
28-
Replacing %KEYBOARD% with mycoolkb... done
29-
Replacing %YOUR_NAME% with John Smith... done
30-
31-
Created a new keyboard called mycoolkb.
32-
33-
To start working on things, cd into keyboards/mycoolkb,
34-
or open the directory in your favourite text editor.
18+
$ qmk new-keyboard
19+
Ψ Generating a new QMK keyboard directory
20+
21+
Keyboard Name: mycoolkeeb
22+
Keyboard Type:
23+
1. avr
24+
2. ps2avrgb
25+
Please enter your choice: [1]
26+
Your Name: [John Smith]
27+
Ψ Copying base template files...
28+
Ψ Copying avr template files...
29+
Ψ Renaming keyboard.[ch] to mycoolkeeb.[ch]...
30+
Ψ Replacing %YEAR% with 2021...
31+
Ψ Replacing %KEYBOARD% with mycoolkeeb...
32+
Ψ Replacing %YOUR_NAME% with John Smith...
33+
34+
Ψ Created a new keyboard called mycoolkeeb.
35+
Ψ To start working on things, `cd` into keyboards/mycoolkeeb,
36+
Ψ or open the directory in your preferred text editor.
3537
```
3638

3739
これにより、新しいキーボードをサポートするために必要なすべてのファイルが作成され、デフォルト値で設定が入力されます。あとはあなたのキーボード用にカスタマイズするだけです。

lib/python/qmk/cli/new/keyboard.py

+136-5
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,142 @@
1-
"""This script automates the creation of keyboards.
1+
"""This script automates the creation of new keyboard directories using a starter template.
22
"""
3+
from datetime import date
4+
import fileinput
5+
from pathlib import Path
6+
import re
7+
import shutil
8+
9+
from qmk.commands import git_get_username
10+
import qmk.path
311
from milc import cli
12+
from milc.questions import choice, question
13+
14+
KEYBOARD_TYPES = ['avr', 'ps2avrgb']
15+
16+
17+
def keyboard_name(name):
18+
"""Callable for argparse validation.
19+
"""
20+
if not validate_keyboard_name(name):
21+
raise ValueError
22+
return name
423

524

6-
@cli.subcommand('Creates a new keyboard')
25+
def validate_keyboard_name(name):
26+
"""Returns True if the given keyboard name contains only lowercase a-z, 0-9 and underscore characters.
27+
"""
28+
regex = re.compile(r'^[a-z0-9][a-z0-9/_]+$')
29+
return bool(regex.match(name))
30+
31+
32+
@cli.argument('-kb', '--keyboard', help='Specify the name for the new keyboard directory', arg_only=True, type=keyboard_name)
33+
@cli.argument('-t', '--type', help='Specify the keyboard type', arg_only=True, choices=KEYBOARD_TYPES)
34+
@cli.argument('-u', '--username', help='Specify your username (default from Git config)', arg_only=True)
35+
@cli.subcommand('Creates a new keyboard directory')
736
def new_keyboard(cli):
8-
"""Creates a new keyboard
37+
"""Creates a new keyboard.
938
"""
10-
# TODO: replace this bodge to the existing script
11-
cli.run(['util/new_keyboard.sh'], stdin=None, capture_output=False)
39+
cli.log.info('{style_bright}Generating a new QMK keyboard directory{style_normal}')
40+
cli.echo('')
41+
42+
# Get keyboard name
43+
new_keyboard_name = None
44+
while not new_keyboard_name:
45+
new_keyboard_name = cli.args.keyboard if cli.args.keyboard else question('Keyboard Name:')
46+
if not validate_keyboard_name(new_keyboard_name):
47+
cli.log.error('Keyboard names must contain only {fg_cyan}lowercase a-z{fg_reset}, {fg_cyan}0-9{fg_reset}, and {fg_cyan}_{fg_reset}! Please choose a different name.')
48+
49+
# Exit if passed by arg
50+
if cli.args.keyboard:
51+
return False
52+
53+
new_keyboard_name = None
54+
continue
55+
56+
keyboard_path = qmk.path.keyboard(new_keyboard_name)
57+
if keyboard_path.exists():
58+
cli.log.error(f'Keyboard {{fg_cyan}}{new_keyboard_name}{{fg_reset}} already exists! Please choose a different name.')
59+
60+
# Exit if passed by arg
61+
if cli.args.keyboard:
62+
return False
63+
64+
new_keyboard_name = None
65+
66+
# Get keyboard type
67+
keyboard_type = cli.args.type if cli.args.type else choice('Keyboard Type:', KEYBOARD_TYPES, default=0)
68+
69+
# Get username
70+
user_name = None
71+
while not user_name:
72+
user_name = question('Your Name:', default=find_user_name())
73+
74+
if not user_name:
75+
cli.log.error('You didn\'t provide a username, and we couldn\'t find one set in your QMK or Git configs. Please try again.')
76+
77+
# Exit if passed by arg
78+
if cli.args.username:
79+
return False
80+
81+
# Copy all the files
82+
copy_templates(keyboard_type, keyboard_path)
83+
84+
# Replace all the placeholders
85+
keyboard_basename = keyboard_path.name
86+
replacements = [
87+
('%YEAR%', str(date.today().year)),
88+
('%KEYBOARD%', keyboard_basename),
89+
('%YOUR_NAME%', user_name),
90+
]
91+
filenames = [
92+
keyboard_path / 'config.h',
93+
keyboard_path / 'info.json',
94+
keyboard_path / 'readme.md',
95+
keyboard_path / f'{keyboard_basename}.c',
96+
keyboard_path / f'{keyboard_basename}.h',
97+
keyboard_path / 'keymaps/default/readme.md',
98+
keyboard_path / 'keymaps/default/keymap.c',
99+
]
100+
replace_placeholders(replacements, filenames)
101+
102+
cli.echo('')
103+
cli.log.info(f'{{fg_green}}Created a new keyboard called {{fg_cyan}}{new_keyboard_name}{{fg_green}}.{{fg_reset}}')
104+
cli.log.info(f'To start working on things, `cd` into {{fg_cyan}}{keyboard_path}{{fg_reset}},')
105+
cli.log.info('or open the directory in your preferred text editor.')
106+
107+
108+
def find_user_name():
109+
if cli.args.username:
110+
return cli.args.username
111+
elif cli.config.user.name:
112+
return cli.config.user.name
113+
else:
114+
return git_get_username()
115+
116+
117+
def copy_templates(keyboard_type, keyboard_path):
118+
"""Copies the template files from quantum/template to the new keyboard directory.
119+
"""
120+
template_base_path = Path('quantum/template')
121+
keyboard_basename = keyboard_path.name
122+
123+
cli.log.info('Copying base template files...')
124+
shutil.copytree(template_base_path / 'base', keyboard_path)
125+
126+
cli.log.info(f'Copying {{fg_cyan}}{keyboard_type}{{fg_reset}} template files...')
127+
shutil.copytree(template_base_path / keyboard_type, keyboard_path, dirs_exist_ok=True)
128+
129+
cli.log.info(f'Renaming {{fg_cyan}}keyboard.[ch]{{fg_reset}} to {{fg_cyan}}{keyboard_basename}.[ch]{{fg_reset}}...')
130+
shutil.move(keyboard_path / 'keyboard.c', keyboard_path / f'{keyboard_basename}.c')
131+
shutil.move(keyboard_path / 'keyboard.h', keyboard_path / f'{keyboard_basename}.h')
132+
133+
134+
def replace_placeholders(replacements, filenames):
135+
"""Replaces the given placeholders in each template file.
136+
"""
137+
for replacement in replacements:
138+
cli.log.info(f'Replacing {{fg_cyan}}{replacement[0]}{{fg_reset}} with {{fg_cyan}}{replacement[1]}{{fg_reset}}...')
139+
140+
with fileinput.input(files=filenames, inplace=True) as file:
141+
for line in file:
142+
print(line.replace(replacement[0], replacement[1]), end='')

lib/python/qmk/commands.py

+9
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,15 @@ def parse_configurator_json(configurator_file):
240240
return user_keymap
241241

242242

243+
def git_get_username():
244+
"""Retrieves user's username from Git config, if set.
245+
"""
246+
git_username = cli.run(['git', 'config', '--get', 'user.name'])
247+
248+
if git_username.returncode == 0 and git_username.stdout:
249+
return git_username.stdout.strip()
250+
251+
243252
def git_check_repo():
244253
"""Checks that the .git directory exists inside QMK_HOME.
245254

util/new_keyboard.sh

+6
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,12 @@ if [ ! -d "quantum" ]; then
129129
exit 1
130130
fi
131131

132+
echo_bold "########################################"
133+
echo_bold "# NOTICE #"
134+
echo_bold "# This script has been deprecated. #"
135+
echo_bold "# Please use qmk new-keyboard instead. #"
136+
echo_bold "########################################"
137+
echo
132138
echo_bold "Generating a new QMK keyboard directory"
133139
echo
134140

0 commit comments

Comments
 (0)