Skip to content

Commit

Permalink
Automatically configure userspace at runtime
Browse files Browse the repository at this point in the history
  • Loading branch information
zvecr committed Dec 30, 2023
1 parent 753136a commit 3e9d726
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 2 deletions.
47 changes: 46 additions & 1 deletion qmk_cli/helpers.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
"""Useful helper functions.
"""
import os
import json
from functools import lru_cache
from importlib.util import find_spec
from pathlib import Path

from milc import cli
Expand Down Expand Up @@ -58,3 +58,48 @@ def in_qmk_firmware():
# Move up a directory before the next iteration
cur_dir = cur_dir / '..'
cur_dir = cur_dir.resolve()


def is_qmk_userspace(qmk_userspace):
"""Returns True if the given Path() is a qmk_userspace clone.
"""
path = qmk_userspace / 'qmk.json'
if not path.exists():
return False

try:
return 'userspace_version' in json.loads(path.read_text(encoding="UTF-8"))
except json.decoder.JSONDecodeError as e:
return False


@lru_cache(maxsize=2)
def find_qmk_userspace():
"""Look for qmk_userspace in the usual places.
"""
if in_qmk_userspace():
return in_qmk_userspace()

if cli.config.user.overlay_dir:
return Path(cli.config.user.overlay_dir).expanduser().resolve()

if 'QMK_USERSPACE' in os.environ:
path = Path(os.environ['QMK_USERSPACE']).expanduser()
if path.exists():
return path.resolve()
return path

return Path.home() / 'qmk_userspace'


def in_qmk_userspace():
"""Returns the path to the qmk_userspace we are currently in, or None if we are not inside qmk_userspace.
"""
cur_dir = Path.cwd()
while len(cur_dir.parents) > 0:
if is_qmk_userspace(cur_dir):
return cur_dir

# Move up a directory before the next iteration
cur_dir = cur_dir / '..'
cur_dir = cur_dir.resolve()
4 changes: 3 additions & 1 deletion qmk_cli/script_qmk.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
import milc

from . import __version__
from .helpers import find_qmk_firmware, is_qmk_firmware
from .helpers import find_qmk_firmware, is_qmk_firmware, find_qmk_userspace, is_qmk_userspace

milc.set_metadata(version=__version__)
milc.EMOJI_LOGLEVELS['INFO'] = '{fg_blue}Ψ{style_reset_all}'
Expand Down Expand Up @@ -60,7 +60,9 @@ def main():
exit(1)

# Environment setup
qmk_userspace = find_qmk_userspace()
qmk_firmware = find_qmk_firmware()
os.environ['QMK_USERSPACE'] = str(qmk_userspace)
os.environ['QMK_HOME'] = str(qmk_firmware)
os.environ['ORIG_CWD'] = os.getcwd()

Expand Down

0 comments on commit 3e9d726

Please sign in to comment.