path.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. """Functions that help us work with files and folders.
  2. """
  3. import logging
  4. import os
  5. from pathlib import Path
  6. from qmk.constants import MAX_KEYBOARD_SUBFOLDERS, QMK_FIRMWARE
  7. from qmk.errors import NoSuchKeyboardError
  8. def is_keyboard(keyboard_name):
  9. """Returns True if `keyboard_name` is a keyboard we can compile.
  10. """
  11. if keyboard_name:
  12. keyboard_path = QMK_FIRMWARE / 'keyboards' / keyboard_name
  13. rules_mk = keyboard_path / 'rules.mk'
  14. return rules_mk.exists()
  15. def under_qmk_firmware():
  16. """Returns a Path object representing the relative path under qmk_firmware, or None.
  17. """
  18. cwd = Path(os.environ['ORIG_CWD'])
  19. try:
  20. return cwd.relative_to(QMK_FIRMWARE)
  21. except ValueError:
  22. return None
  23. def keyboard(keyboard_name):
  24. """Returns the path to a keyboard's directory relative to the qmk root.
  25. """
  26. return Path('keyboards') / keyboard_name
  27. def keymap(keyboard_name):
  28. """Locate the correct directory for storing a keymap.
  29. Args:
  30. keyboard_name
  31. The name of the keyboard. Example: clueboard/66/rev3
  32. """
  33. keyboard_folder = keyboard(keyboard_name)
  34. for i in range(MAX_KEYBOARD_SUBFOLDERS):
  35. if (keyboard_folder / 'keymaps').exists():
  36. return (keyboard_folder / 'keymaps').resolve()
  37. keyboard_folder = keyboard_folder.parent
  38. logging.error('Could not find the keymaps directory!')
  39. raise NoSuchKeyboardError('Could not find keymaps directory for: %s' % keyboard_name)
  40. def normpath(path):
  41. """Returns a `pathlib.Path()` object for a given path.
  42. This will use the path to a file as seen from the directory the script was called from. You should use this to normalize filenames supplied from the command line.
  43. """
  44. path = Path(path)
  45. if path.is_absolute():
  46. return path
  47. return Path(os.environ['ORIG_CWD']) / path