You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
2.1 KiB

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