path.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. """Functions that help us work with files and folders.
  2. """
  3. import logging
  4. import os
  5. import argparse
  6. from functools import lru_cache
  7. from pathlib import Path
  8. from qmk.constants import MAX_KEYBOARD_SUBFOLDERS, QMK_FIRMWARE
  9. from qmk.errors import NoSuchKeyboardError
  10. @lru_cache(maxsize=0)
  11. def is_keyboard(keyboard_name):
  12. """Returns True if `keyboard_name` is a keyboard we can compile.
  13. """
  14. if keyboard_name:
  15. keyboard_path = QMK_FIRMWARE / 'keyboards' / keyboard_name
  16. rules_mk = keyboard_path / 'rules.mk'
  17. return rules_mk.exists()
  18. @lru_cache(maxsize=0)
  19. def under_qmk_firmware():
  20. """Returns a Path object representing the relative path under qmk_firmware, or None.
  21. """
  22. cwd = Path(os.environ['ORIG_CWD'])
  23. try:
  24. return cwd.relative_to(QMK_FIRMWARE)
  25. except ValueError:
  26. return None
  27. @lru_cache(maxsize=0)
  28. def keyboard(keyboard_name):
  29. """Returns the path to a keyboard's directory relative to the qmk root.
  30. """
  31. return Path('keyboards') / keyboard_name
  32. @lru_cache(maxsize=0)
  33. def keymap(keyboard_name):
  34. """Locate the correct directory for storing a keymap.
  35. Args:
  36. keyboard_name
  37. The name of the keyboard. Example: clueboard/66/rev3
  38. """
  39. keyboard_folder = keyboard(keyboard_name)
  40. for i in range(MAX_KEYBOARD_SUBFOLDERS):
  41. if (keyboard_folder / 'keymaps').exists():
  42. return (keyboard_folder / 'keymaps').resolve()
  43. keyboard_folder = keyboard_folder.parent
  44. logging.error('Could not find the keymaps directory!')
  45. raise NoSuchKeyboardError('Could not find keymaps directory for: %s' % keyboard_name)
  46. @lru_cache(maxsize=0)
  47. def normpath(path):
  48. """Returns a `pathlib.Path()` object for a given path.
  49. 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.
  50. """
  51. path = Path(path)
  52. if path.is_absolute():
  53. return path
  54. return Path(os.environ['ORIG_CWD']) / path
  55. class FileType(argparse.FileType):
  56. def __call__(self, string):
  57. """normalize and check exists
  58. otherwise magic strings like '-' for stdin resolve to bad paths
  59. """
  60. norm = normpath(string)
  61. return super().__call__(norm if norm.exists() else string)