aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRyan <fauxpark@gmail.com>2021-07-31 06:57:40 +1000
committerGitHub <noreply@github.com>2021-07-30 21:57:40 +0100
commitb021c2f2c5890df5335d3dd163167c6fe6213e0d (patch)
tree3d1f645190a819f13d7789a11c55b0706e1d9853
parent770a52542592919e504603152f3a2950875150c9 (diff)
downloadqmk_firmware-b021c2f2c5890df5335d3dd163167c6fe6213e0d.tar.gz
qmk_firmware-b021c2f2c5890df5335d3dd163167c6fe6213e0d.zip
Port new_keyboard.sh to CLI (#13706)
Co-authored-by: Erovia <Erovia@users.noreply.github.com>
-rw-r--r--docs/cli_commands.md4
-rw-r--r--docs/es/hardware_avr.md38
-rw-r--r--docs/hardware_avr.md38
-rw-r--r--docs/ja/hardware_avr.md38
-rw-r--r--lib/python/qmk/cli/new/keyboard.py141
-rw-r--r--lib/python/qmk/commands.py9
-rwxr-xr-xutil/new_keyboard.sh6
7 files changed, 213 insertions, 61 deletions
diff --git a/docs/cli_commands.md b/docs/cli_commands.md
index 314e7448d..c7468eb5e 100644
--- a/docs/cli_commands.md
+++ b/docs/cli_commands.md
@@ -280,12 +280,12 @@ qmk list-keymaps -kb planck/ez
280 280
281This command creates a new keyboard based on available templates. 281This command creates a new keyboard based on available templates.
282 282
283This command will prompt for input to guide you though the generation process. 283Any 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.
284 284
285**Usage**: 285**Usage**:
286 286
287``` 287```
288qmk new-keyboard 288qmk new-keyboard [-kb KEYBOARD] [-t {avr,ps2avrgb}] -u USERNAME
289``` 289```
290 290
291## `qmk new-keymap` 291## `qmk new-keymap`
diff --git a/docs/es/hardware_avr.md b/docs/es/hardware_avr.md
index f8c426381..ac6a71565 100644
--- a/docs/es/hardware_avr.md
+++ b/docs/es/hardware_avr.md
@@ -6,26 +6,28 @@ Si aún no lo has hecho, debes leer las [Pautas de teclados](hardware_keyboard_g
6 6
7## Añadir tu Teclado AVR a QMK 7## Añadir tu Teclado AVR a QMK
8 8
9QMK 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`: 9QMK 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`:
10 10
11``` 11```
12$ ./util/new_keyboard.sh 12$ qmk new-keyboard
13Generating a new QMK keyboard directory 13Ψ Generating a new QMK keyboard directory
14 14
15Keyboard Name: mycoolkb 15Keyboard Name: mycoolkeeb
16Keyboard Type [avr]: 16Keyboard Type:
17Your Name [John Smith]: 17 1. avr
18 18 2. ps2avrgb
19Copying base template files... done 19Please enter your choice: [1]
20Copying avr template files... done 20Your Name: [John Smith]
21Renaming keyboard files... done 21Ψ Copying base template files...
22Replacing %KEYBOARD% with mycoolkb... done 22Ψ Copying avr template files...
23Replacing %YOUR_NAME% with John Smith... done 23Ψ Renaming keyboard.[ch] to mycoolkeeb.[ch]...
24 24Ψ Replacing %YEAR% with 2021...
25Created a new keyboard called mycoolkb. 25Ψ Replacing %KEYBOARD% with mycoolkeeb...
26 26Ψ Replacing %YOUR_NAME% with John Smith...
27To start working on things, cd into keyboards/mycoolkb, 27
28or open the directory in your favourite text editor. 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.
29``` 31```
30 32
31Esto 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. 33Esto 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.
diff --git a/docs/hardware_avr.md b/docs/hardware_avr.md
index eb536ca96..3d58cdc05 100644
--- a/docs/hardware_avr.md
+++ b/docs/hardware_avr.md
@@ -6,26 +6,28 @@ If you have not yet you should read the [Keyboard Guidelines](hardware_keyboard_
6 6
7## Adding Your AVR Keyboard to QMK 7## Adding Your AVR Keyboard to QMK
8 8
9QMK 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: 9QMK 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`:
10 10
11``` 11```
12$ ./util/new_keyboard.sh 12$ qmk new-keyboard
13Generating a new QMK keyboard directory 13Ψ Generating a new QMK keyboard directory
14 14
15Keyboard Name: mycoolkb 15Keyboard Name: mycoolkeeb
16Keyboard Type [avr]: 16Keyboard Type:
17Your Name [John Smith]: 17 1. avr
18 18 2. ps2avrgb
19Copying base template files... done 19Please enter your choice: [1]
20Copying avr template files... done 20Your Name: [John Smith]
21Renaming keyboard files... done 21Ψ Copying base template files...
22Replacing %KEYBOARD% with mycoolkb... done 22Ψ Copying avr template files...
23Replacing %YOUR_NAME% with John Smith... done 23Ψ Renaming keyboard.[ch] to mycoolkeeb.[ch]...
24 24Ψ Replacing %YEAR% with 2021...
25Created a new keyboard called mycoolkb. 25Ψ Replacing %KEYBOARD% with mycoolkeeb...
26 26Ψ Replacing %YOUR_NAME% with John Smith...
27To start working on things, cd into keyboards/mycoolkb, 27
28or open the directory in your favourite text editor. 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.
29``` 31```
30 32
31This 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. 33This 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.
diff --git a/docs/ja/hardware_avr.md b/docs/ja/hardware_avr.md
index 66be2f71c..cdc5f8cb8 100644
--- a/docs/ja/hardware_avr.md
+++ b/docs/ja/hardware_avr.md
@@ -12,26 +12,28 @@
12 12
13## AVR を使用したキーボードを QMK に追加する 13## AVR を使用したキーボードを QMK に追加する
14 14
15QMK には AVR を使ったキーボードでの作業を簡略化するための機能が多数あります。大体のキーボードでは1行もコードを書く必要がありません。まずはじめに、`util/new_keyboard.sh` スクリプトを実行します。 15QMK には AVR を使ったキーボードでの作業を簡略化するための機能が多数あります。大体のキーボードでは1行もコードを書く必要がありません。まずはじめに、`qmk new-keyboard` を実行します。
16 16
17``` 17```
18$ ./util/new_keyboard.sh 18$ qmk new-keyboard
19Generating a new QMK keyboard directory 19Ψ Generating a new QMK keyboard directory
20 20
21Keyboard Name: mycoolkb 21Keyboard Name: mycoolkeeb
22Keyboard Type [avr]: 22Keyboard Type:
23Your Name [John Smith]: 23 1. avr
24 24 2. ps2avrgb
25Copying base template files... done 25Please enter your choice: [1]
26Copying avr template files... done 26Your Name: [John Smith]
27Renaming keyboard files... done 27Ψ Copying base template files...
28Replacing %KEYBOARD% with mycoolkb... done 28Ψ Copying avr template files...
29Replacing %YOUR_NAME% with John Smith... done 29Ψ Renaming keyboard.[ch] to mycoolkeeb.[ch]...
30 30Ψ Replacing %YEAR% with 2021...
31Created a new keyboard called mycoolkb. 31Ψ Replacing %KEYBOARD% with mycoolkeeb...
32 32Ψ Replacing %YOUR_NAME% with John Smith...
33To start working on things, cd into keyboards/mycoolkb, 33
34or open the directory in your favourite text editor. 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.
35``` 37```
36 38
37これにより、新しいキーボードをサポートするために必要なすべてのファイルが作成され、デフォルト値で設定が入力されます。あとはあなたのキーボード用にカスタマイズするだけです。 39これにより、新しいキーボードをサポートするために必要なすべてのファイルが作成され、デフォルト値で設定が入力されます。あとはあなたのキーボード用にカスタマイズするだけです。
diff --git a/lib/python/qmk/cli/new/keyboard.py b/lib/python/qmk/cli/new/keyboard.py
index ae4445ca4..9e4232679 100644
--- a/lib/python/qmk/cli/new/keyboard.py
+++ b/lib/python/qmk/cli/new/keyboard.py
@@ -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.
2""" 2"""
3from datetime import date
4import fileinput
5from pathlib import Path
6import re
7import shutil
8
9from qmk.commands import git_get_username
10import qmk.path
3from milc import cli 11from milc import cli
12from milc.questions import choice, question
13
14KEYBOARD_TYPES = ['avr', 'ps2avrgb']
15
16
17def keyboard_name(name):
18 """Callable for argparse validation.
19 """
20 if not validate_keyboard_name(name):
21 raise ValueError
22 return name
4 23
5 24
6@cli.subcommand('Creates a new keyboard') 25def 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')
7def new_keyboard(cli): 36def new_keyboard(cli):
8 """Creates a new keyboard 37 """Creates a new keyboard.
9 """ 38 """
10 # TODO: replace this bodge to the existing script 39 cli.log.info('{style_bright}Generating a new QMK keyboard directory{style_normal}')
11 cli.run(['util/new_keyboard.sh'], stdin=None, capture_output=False) 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
108def 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
117def 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
134def 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='')
diff --git a/lib/python/qmk/commands.py b/lib/python/qmk/commands.py
index 8ff8501bf..8c66228b2 100644
--- a/lib/python/qmk/commands.py
+++ b/lib/python/qmk/commands.py
@@ -240,6 +240,15 @@ def parse_configurator_json(configurator_file):
240 return user_keymap 240 return user_keymap
241 241
242 242
243def 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
243def git_check_repo(): 252def git_check_repo():
244 """Checks that the .git directory exists inside QMK_HOME. 253 """Checks that the .git directory exists inside QMK_HOME.
245 254
diff --git a/util/new_keyboard.sh b/util/new_keyboard.sh
index d0db23bb4..87b7cde0c 100755
--- a/util/new_keyboard.sh
+++ b/util/new_keyboard.sh
@@ -129,6 +129,12 @@ if [ ! -d "quantum" ]; then
129 exit 1 129 exit 1
130fi 130fi
131 131
132echo_bold "########################################"
133echo_bold "# NOTICE #"
134echo_bold "# This script has been deprecated. #"
135echo_bold "# Please use qmk new-keyboard instead. #"
136echo_bold "########################################"
137echo
132echo_bold "Generating a new QMK keyboard directory" 138echo_bold "Generating a new QMK keyboard directory"
133echo 139echo
134 140