path.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  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, QMK_USERSPACE, HAS_QMK_USERSPACE
  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 not keyboard_name:
  13. return False
  14. # keyboard_name values of 'c:/something' or '/something' trigger append issues
  15. # due to "If the argument is an absolute path, the previous path is ignored"
  16. # however it should always be a folder located under qmk_firmware/keyboards
  17. if Path(keyboard_name).is_absolute():
  18. return False
  19. keyboard_path = QMK_FIRMWARE / 'keyboards' / keyboard_name
  20. rules_mk = keyboard_path / 'rules.mk'
  21. return rules_mk.exists()
  22. def under_qmk_firmware(path=Path(os.environ['ORIG_CWD'])):
  23. """Returns a Path object representing the relative path under qmk_firmware, or None.
  24. """
  25. try:
  26. return path.relative_to(QMK_FIRMWARE)
  27. except ValueError:
  28. return None
  29. def under_qmk_userspace(path=Path(os.environ['ORIG_CWD'])):
  30. """Returns a Path object representing the relative path under $QMK_USERSPACE, or None.
  31. """
  32. try:
  33. if HAS_QMK_USERSPACE:
  34. return path.relative_to(QMK_USERSPACE)
  35. except ValueError:
  36. pass
  37. return None
  38. def is_under_qmk_firmware(path=Path(os.environ['ORIG_CWD'])):
  39. """Returns a boolean if the input path is a child under qmk_firmware.
  40. """
  41. if path is None:
  42. return False
  43. try:
  44. return Path(os.path.commonpath([Path(path), QMK_FIRMWARE])) == QMK_FIRMWARE
  45. except ValueError:
  46. return False
  47. def is_under_qmk_userspace(path=Path(os.environ['ORIG_CWD'])):
  48. """Returns a boolean if the input path is a child under $QMK_USERSPACE.
  49. """
  50. if path is None:
  51. return False
  52. try:
  53. if HAS_QMK_USERSPACE:
  54. return Path(os.path.commonpath([Path(path), QMK_USERSPACE])) == QMK_USERSPACE
  55. except ValueError:
  56. return False
  57. def keyboard(keyboard_name):
  58. """Returns the path to a keyboard's directory relative to the qmk root.
  59. """
  60. return Path('keyboards') / keyboard_name
  61. def keymaps(keyboard_name):
  62. """Returns all of the `keymaps/` directories for a given keyboard.
  63. Args:
  64. keyboard_name
  65. The name of the keyboard. Example: clueboard/66/rev3
  66. """
  67. keyboard_folder = keyboard(keyboard_name)
  68. found_dirs = []
  69. if HAS_QMK_USERSPACE:
  70. this_keyboard_folder = Path(QMK_USERSPACE) / keyboard_folder
  71. for _ in range(MAX_KEYBOARD_SUBFOLDERS):
  72. if (this_keyboard_folder / 'keymaps').exists():
  73. found_dirs.append((this_keyboard_folder / 'keymaps').resolve())
  74. this_keyboard_folder = this_keyboard_folder.parent
  75. if this_keyboard_folder.resolve() == QMK_USERSPACE.resolve():
  76. break
  77. # We don't have any relevant keymap directories in userspace, so we'll use the fully-qualified path instead.
  78. if len(found_dirs) == 0:
  79. found_dirs.append((QMK_USERSPACE / keyboard_folder / 'keymaps').resolve())
  80. this_keyboard_folder = QMK_FIRMWARE / keyboard_folder
  81. for _ in range(MAX_KEYBOARD_SUBFOLDERS):
  82. if (this_keyboard_folder / 'keymaps').exists():
  83. found_dirs.append((this_keyboard_folder / 'keymaps').resolve())
  84. this_keyboard_folder = this_keyboard_folder.parent
  85. if this_keyboard_folder.resolve() == QMK_FIRMWARE.resolve():
  86. break
  87. if len(found_dirs) > 0:
  88. return found_dirs
  89. logging.error('Could not find the keymaps directory!')
  90. raise NoSuchKeyboardError('Could not find keymaps directory for: %s' % keyboard_name)
  91. def keymap(keyboard_name, keymap_name):
  92. """Locate the directory of a given keymap.
  93. Args:
  94. keyboard_name
  95. The name of the keyboard. Example: clueboard/66/rev3
  96. keymap_name
  97. The name of the keymap. Example: default
  98. """
  99. for keymap_dir in keymaps(keyboard_name):
  100. if (keymap_dir / keymap_name).exists():
  101. return (keymap_dir / keymap_name).resolve()
  102. def normpath(path):
  103. """Returns a `pathlib.Path()` object for a given path.
  104. 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.
  105. """
  106. path = Path(path)
  107. if path.is_absolute():
  108. return path
  109. return Path(os.environ['ORIG_CWD']) / path
  110. class FileType(argparse.FileType):
  111. def __init__(self, *args, **kwargs):
  112. # Use UTF8 by default for stdin
  113. if 'encoding' not in kwargs:
  114. kwargs['encoding'] = 'UTF-8'
  115. return super().__init__(*args, **kwargs)
  116. def __call__(self, string):
  117. """normalize and check exists
  118. otherwise magic strings like '-' for stdin resolve to bad paths
  119. """
  120. norm = normpath(string)
  121. return norm if norm.exists() else super().__call__(string)