path.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 QMK_FIRMWARE, MAX_KEYBOARD_SUBFOLDERS
  7. from qmk.errors import NoSuchKeyboardError
  8. def is_keymap_dir(keymap_path):
  9. """Returns True if `keymap_path` is a valid keymap directory.
  10. """
  11. keymap_path = Path(keymap_path)
  12. keymap_c = keymap_path / 'keymap.c'
  13. keymap_json = keymap_path / 'keymap.json'
  14. return any((keymap_c.exists(), keymap_json.exists()))
  15. def is_keyboard(keyboard_name):
  16. """Returns True if `keyboard_name` is a keyboard we can compile.
  17. """
  18. keyboard_path = QMK_FIRMWARE / 'keyboards' / keyboard_name
  19. rules_mk = keyboard_path / 'rules.mk'
  20. return rules_mk.exists()
  21. def under_qmk_firmware():
  22. """Returns a Path object representing the relative path under qmk_firmware, or None.
  23. """
  24. cwd = Path(os.environ['ORIG_CWD'])
  25. try:
  26. return cwd.relative_to(QMK_FIRMWARE)
  27. except ValueError:
  28. return None
  29. def keymap(keyboard):
  30. """Locate the correct directory for storing a keymap.
  31. Args:
  32. keyboard
  33. The name of the keyboard. Example: clueboard/66/rev3
  34. """
  35. keyboard_folder = Path('keyboards') / keyboard
  36. for i in range(MAX_KEYBOARD_SUBFOLDERS):
  37. if (keyboard_folder / 'keymaps').exists():
  38. return (keyboard_folder / 'keymaps').resolve()
  39. keyboard_folder = keyboard_folder.parent
  40. logging.error('Could not find the keymaps directory!')
  41. raise NoSuchKeyboardError('Could not find keymaps directory for: %s' % keyboard)
  42. def normpath(path):
  43. """Returns a `pathlib.Path()` object for a given path.
  44. 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.
  45. """
  46. path = Path(path)
  47. if path.is_absolute():
  48. return path
  49. return Path(os.environ['ORIG_CWD']) / path
  50. def c_source_files(dir_names):
  51. """Returns a list of all *.c, *.h, and *.cpp files for a given list of directories
  52. Args:
  53. dir_names
  54. List of directories, relative pathing starts at qmk's cwd
  55. """
  56. files = []
  57. for dir in dir_names:
  58. files.extend(file for file in Path(dir).glob('**/*') if file.suffix in ['.c', '.h', '.cpp'])
  59. return files