path.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 keymap(keyboard):
  24. """Locate the correct directory for storing a keymap.
  25. Args:
  26. keyboard
  27. The name of the keyboard. Example: clueboard/66/rev3
  28. """
  29. keyboard_folder = Path('keyboards') / keyboard
  30. for i in range(MAX_KEYBOARD_SUBFOLDERS):
  31. if (keyboard_folder / 'keymaps').exists():
  32. return (keyboard_folder / 'keymaps').resolve()
  33. keyboard_folder = keyboard_folder.parent
  34. logging.error('Could not find the keymaps directory!')
  35. raise NoSuchKeyboardError('Could not find keymaps directory for: %s' % keyboard)
  36. def normpath(path):
  37. """Returns a `pathlib.Path()` object for a given path.
  38. 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.
  39. """
  40. path = Path(path)
  41. if path.is_absolute():
  42. return path
  43. return Path(os.environ['ORIG_CWD']) / path