path.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. keyboard_path = QMK_FIRMWARE / 'keyboards' / keyboard_name
  12. rules_mk = keyboard_path / 'rules.mk'
  13. return rules_mk.exists()
  14. def under_qmk_firmware():
  15. """Returns a Path object representing the relative path under qmk_firmware, or None.
  16. """
  17. cwd = Path(os.environ['ORIG_CWD'])
  18. try:
  19. return cwd.relative_to(QMK_FIRMWARE)
  20. except ValueError:
  21. return None
  22. def keymap(keyboard):
  23. """Locate the correct directory for storing a keymap.
  24. Args:
  25. keyboard
  26. The name of the keyboard. Example: clueboard/66/rev3
  27. """
  28. keyboard_folder = Path('keyboards') / keyboard
  29. for i in range(MAX_KEYBOARD_SUBFOLDERS):
  30. if (keyboard_folder / 'keymaps').exists():
  31. return (keyboard_folder / 'keymaps').resolve()
  32. keyboard_folder = keyboard_folder.parent
  33. logging.error('Could not find the keymaps directory!')
  34. raise NoSuchKeyboardError('Could not find keymaps directory for: %s' % keyboard)
  35. def normpath(path):
  36. """Returns a `pathlib.Path()` object for a given path.
  37. 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.
  38. """
  39. path = Path(path)
  40. if path.is_absolute():
  41. return path
  42. return Path(os.environ['ORIG_CWD']) / path