Skip to content

Instantly share code, notes, and snippets.

@hineybush
Last active May 1, 2023 12:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hineybush/1180669e3abc34be61ab2c8e115802b9 to your computer and use it in GitHub Desktop.
Save hineybush/1180669e3abc34be61ab2c8e115802b9 to your computer and use it in GitHub Desktop.
Multi firmware builder for QMK

Script to aid in building multiple QMK firmware files based on input args.

Run via command line/terminal from within the /qmk_firmware/ directory.

Examples

Basic

you@pc: ~/qmk_firmware$ python ../scripts/qmk_build.py -h

Compile all keyboard default keymaps within a keyboard directory or directories

you@pc: ~/qmk_firmware$ python ../scripts/qmk_build.py hineybush
you@pc: ~/qmk_firmware$ python ../scripts/qmk_build.py hineybush -kb all
you@pc: ~/qmk_firmware$ python ../scripts/qmk_build.py hineybush gh60

Compile all keyboards with specific keymap(s) within a keyboard directory

you@pc: ~/qmk_firmware$ python ../scripts/qmk_build.py hineybush -km via
you@pc: ~/qmk_firmware$ python ../scripts/qmk_build.py hineybush -km via default

Compile specific keyboards with/without specific keymaps within a keyboard directory or directories

you@pc: ~/qmk_firmware$ python ../scripts/qmk_build.py hineybush -kb h87a h88 -km via
you@pc: ~/qmk_firmware$ python ../scripts/qmk_build.py hineybush -kb h87a h88 h60
you@pc: ~/qmk_firmware$ python ../scripts/qmk_build.py hineybush gh60 -kb h87a h88 h60 satan

Compile and copy firmware files to specified folder

you@pc: ~/qmk_firmware$ python ../scripts/qmk_build.py hineybush -km via -o ../firmware-files

Test mode - only shows you which keyboard firmware files would have been compiled

you@pc: ~/qmk_firmware$ python ../scripts/qmk_build.py hineybush -km via -t

Example output

(base) josh@hiney:~/git_kb/qmk_firmware_hiney$ python ../scripts/qmk_build.py hineybush -kb h87a -km via -o ../hiney-kb-firmware/ 
-----
Found the following keyboards to compile in keyboards/hineybush: 
hineybush/h87a/via
-----
Compiling...
-----
Ψ Compiling keymap with make --jobs --output-sync=target hineybush/h87a:via
-----
Copying hineybush_h87a_via.hex to: ../hiney-kb-firmware/
-----
Done!

Other Info

Created using Python version 3.9.12

If this messes up your QMK install/branch/PC I am not liable, use at your own risk.

MIT License
Copyright (c) Josh Hinnebusch 2022
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Compile QMK firmware for multiple keyboards at once.
# babby's first real python code
# this should be ran from within the qmk_firmware directory - where ever it is.
from distutils.command.build import build
import subprocess
import os
import argparse
import shutil
from datetime import datetime
from argparse import RawDescriptionHelpFormatter
helpString = """Script to aid in building multiple QMK firmware files based on input args.
Run from within the /qmk_firmware/ directory.
---Examples---
Basic
you@pc: ~/qmk_firmware$ python ../scripts/qmk_build.py -h
Compile all keyboard default keymaps within a keyboard directory
you@pc: ~/qmk_firmware$ python ../scripts/qmk_build.py hineybush
you@pc: ~/qmk_firmware$ python ../scripts/qmk_build.py hineybush gh60
Compile all keyboards with specific keymap(s) within a keyboard directory
you@pc: ~/qmk_firmware$ python ../scripts/qmk_build.py hineybush -km via
you@pc: ~/qmk_firmware$ python ../scripts/qmk_build.py hineybush -km via default
Compile specific keyboards with/without specific keymaps within a keyboard directory
you@pc: ~/qmk_firmware$ python ../scripts/qmk_build.py hineybush -kb h87a h88 -km via
you@pc: ~/qmk_firmware$ python ../scripts/qmk_build.py hineybush -kb h87a h88 h60
Compile and copy firmware files to specified folder
you@pc: ~/qmk_firmware$ python ../scripts/qmk_build.py hineybush -km via -o ../firmware-files
Test mode - only shows you which keyboard firmware files would have been compiled
you@pc: ~/qmk_firmware$ python ../scripts/qmk_build.py hineybush -km via -t
"""
# input argument parser
inputParser = argparse.ArgumentParser(
description=helpString, formatter_class=RawDescriptionHelpFormatter)
inputParser.add_argument('path', type=str, nargs='+',
help="Directory of keyboard(s) to build. ex. \'hineybush\', \'gh60\'. Can run multiple keyboard directories at once")
inputParser.add_argument('-km', '--keymap', type=str, nargs='*',
help="Which keymap(s) to build. ex. \'default\', \'via\'. default = \'default\'", default=["default"])
inputParser.add_argument('-kb', '--keyboards', nargs="*", type=str,
help="List of specific keyboards within the directory to build. ex. \'h87a\'. Default (blank) will build all within the specified path", default=["all"])
inputParser.add_argument('-o', '--outputdir', type=str, default='.',
help="Directory to copy files to. ex. \'../firmware\'. Default will leave firmware files within the default QMK directory. Works for .hex and .bin', default='.'")
inputParser.add_argument('-t', '--test', default=False, action='store_true',
help="Enable test mode, will only show which keyboards would have been compiled")
inputParser.add_argument('--no-test', dest='test', action='store_false',
help="Normal operation mode, not needed")
inputArgs = inputParser.parse_args()
# board/user directory to look for
inputPath = getattr(inputArgs, 'path')
# keymap file(s) to build (default, via, etc)
inputKeymap = getattr(inputArgs, 'keymap')
# keyboards to build (blank or all, or specific ones)
inputBoardList = getattr(inputArgs, 'keyboards')
outputDir = getattr(inputArgs, 'outputdir')
testStatus = getattr(inputArgs, 'test')
buildList = [] # init empty list to fill with found keyboard files
extensionList = ['.hex', '.bin']
# function to build the buildlist
def listdirs(rootdir, kbPath):
for a in rootdir:
# get keyboard subdirectories from /keyboards/arg1
kbDir = os.path.join(kbPath, a)
if os.path.isdir(kbDir):
# go into each subdir, check for keymap files:
for b in os.listdir(kbDir):
dirInKbDir = os.path.join(kbDir, b)
for c in inputKeymap:
hopefulKeymapDir = f'{dirInKbDir}/{c}'
# check if needed keymap dir exists
if os.path.isdir(hopefulKeymapDir):
# get path of needed keymap
kbPathSplit = hopefulKeymapDir.split('/')
# pull out keyboard and keymap name from path, add to overall name list
buildList.append(
f"{kbPathSplit[1]}/{kbPathSplit[2]}/{kbPathSplit[4]}")
if buildList != []:
print(
f"-----\nFound the following keyboards to compile in {kbPath}: {os.linesep}{os.linesep.join(map(str, buildList))}")
else:
print(
f"-----\nWarning! Did not find any keyboards in {kbPath} with keyboard(s) {', '.join(map(str,inputBoardList))} or keymap(s) {', '.join(map(str,inputKeymap))}")
return buildList
# function to build the buildlist per keymap folder
def kmListDirs(rootdir):
kbPath = f"keyboards/{rootdir}"
if inputBoardList == ['all']:
q = os.listdir(kbPath)
else:
q = inputBoardList
listdirs(q, kbPath)
return buildList
# function to run qmk compile
def qmkBuild(buildlist):
for b in buildlist: # concat the qmk compile command with buildList info
kbDir = b.split('/')[0]
kb = b.split('/')[1]
km = b.split('/')[2]
fullCmd = f"qmk compile -j 0 -kb {kbDir}/{kb} -km {km}"
# run fullCmd in bash, quietly
subprocess.run(fullCmd, shell=True, check=True,
text=True, stdout=subprocess.DEVNULL)
# copies newly compiled firmware files to specified output folder
def copyToOutput(buildlist, outputDir):
filesToCopy = []
for b in buildlist: # concat the filenames with buildList info
kbDir = b.split('/')[0]
kb = b.split('/')[1]
km = b.split('/')[2]
for c in extensionList:
fwfilename = f"{kbDir}_{kb}_{km}{c}"
for d in os.listdir('.'):
if (os.path.isfile(fwfilename) and (d == fwfilename)):
filesToCopy.append(d)
for e in filesToCopy:
print(f"Copying {e} to: {outputDir}")
shutil.copy(e, outputDir)
def mainCycle(input):
for a in input:
# empty buildlist from previous runs, if any (needed for multi keyboard/dir use)
buildList = []
kmListDirs(a)
return buildList
# main code
# get time of exec start (unused tbh)
exectime = datetime.now()
dt_string = exectime.strftime("%d/%m/%Y %H:%M:%S")
if testStatus == False:
mainCycle(inputPath)
print("-----")
qmkBuild(buildList)
if outputDir != '.':
copyToOutput(buildList, outputDir)
else:
print("Firmware files saved in default QMK directory.")
else:
mainCycle(inputPath)
print("-----\nTest run only, did not compile!")
if outputDir != '.':
print(f"Output firmware files would have been copied to {outputDir}")
else:
print(f"Output firmware files would have been copied to default QMK directory")
print("-----\nDone!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment