at master 5.8 kB view raw
1"""Functions that help us work with files and folders. 2""" 3import logging 4import os 5import argparse 6from pathlib import Path, PureWindowsPath, PurePosixPath 7 8from qmk.constants import MAX_KEYBOARD_SUBFOLDERS, QMK_FIRMWARE, QMK_USERSPACE, HAS_QMK_USERSPACE 9from qmk.errors import NoSuchKeyboardError 10 11 12def is_keyboard(keyboard_name): 13 """Returns True if `keyboard_name` is a keyboard we can compile. 14 """ 15 if not keyboard_name: 16 return False 17 18 # keyboard_name values of 'c:/something' or '/something' trigger append issues 19 # due to "If the argument is an absolute path, the previous path is ignored" 20 # however it should always be a folder located under qmk_firmware/keyboards 21 if Path(keyboard_name).is_absolute(): 22 return False 23 24 keyboard_json = QMK_FIRMWARE / 'keyboards' / keyboard_name / 'keyboard.json' 25 26 return keyboard_json.exists() 27 28 29def under_qmk_firmware(path=Path(os.environ['ORIG_CWD'])): 30 """Returns a Path object representing the relative path under qmk_firmware, or None. 31 """ 32 try: 33 return path.relative_to(QMK_FIRMWARE) 34 except ValueError: 35 return None 36 37 38def under_qmk_userspace(path=Path(os.environ['ORIG_CWD'])): 39 """Returns a Path object representing the relative path under $QMK_USERSPACE, or None. 40 """ 41 try: 42 if HAS_QMK_USERSPACE: 43 return path.relative_to(QMK_USERSPACE) 44 except ValueError: 45 pass 46 return None 47 48 49def is_under_qmk_firmware(path=Path(os.environ['ORIG_CWD'])): 50 """Returns a boolean if the input path is a child under qmk_firmware. 51 """ 52 if path is None: 53 return False 54 try: 55 return Path(os.path.commonpath([Path(path), QMK_FIRMWARE])) == QMK_FIRMWARE 56 except ValueError: 57 return False 58 59 60def is_under_qmk_userspace(path=Path(os.environ['ORIG_CWD'])): 61 """Returns a boolean if the input path is a child under $QMK_USERSPACE. 62 """ 63 if path is None: 64 return False 65 try: 66 if HAS_QMK_USERSPACE: 67 return Path(os.path.commonpath([Path(path), QMK_USERSPACE])) == QMK_USERSPACE 68 except ValueError: 69 return False 70 71 72def keyboard(keyboard_name): 73 """Returns the path to a keyboard's directory relative to the qmk root. 74 """ 75 return Path('keyboards') / keyboard_name 76 77 78def keymaps(keyboard_name): 79 """Returns all of the `keymaps/` directories for a given keyboard. 80 81 Args: 82 83 keyboard_name 84 The name of the keyboard. Example: clueboard/66/rev3 85 """ 86 keyboard_folder = keyboard(keyboard_name) 87 found_dirs = [] 88 89 if HAS_QMK_USERSPACE: 90 this_keyboard_folder = Path(QMK_USERSPACE) / keyboard_folder 91 for _ in range(MAX_KEYBOARD_SUBFOLDERS): 92 if (this_keyboard_folder / 'keymaps').exists(): 93 found_dirs.append((this_keyboard_folder / 'keymaps').resolve()) 94 95 this_keyboard_folder = this_keyboard_folder.parent 96 if this_keyboard_folder.resolve() == QMK_USERSPACE.resolve(): 97 break 98 99 # We don't have any relevant keymap directories in userspace, so we'll use the fully-qualified path instead. 100 if len(found_dirs) == 0: 101 found_dirs.append((QMK_USERSPACE / keyboard_folder / 'keymaps').resolve()) 102 103 this_keyboard_folder = QMK_FIRMWARE / keyboard_folder 104 for _ in range(MAX_KEYBOARD_SUBFOLDERS): 105 if (this_keyboard_folder / 'keymaps').exists(): 106 found_dirs.append((this_keyboard_folder / 'keymaps').resolve()) 107 108 this_keyboard_folder = this_keyboard_folder.parent 109 if this_keyboard_folder.resolve() == QMK_FIRMWARE.resolve(): 110 break 111 112 if len(found_dirs) > 0: 113 return found_dirs 114 115 logging.error('Could not find the keymaps directory!') 116 raise NoSuchKeyboardError('Could not find keymaps directory for: %s' % keyboard_name) 117 118 119def keymap(keyboard_name, keymap_name): 120 """Locate the directory of a given keymap. 121 122 Args: 123 124 keyboard_name 125 The name of the keyboard. Example: clueboard/66/rev3 126 keymap_name 127 The name of the keymap. Example: default 128 """ 129 for keymap_dir in keymaps(keyboard_name): 130 if (keymap_dir / keymap_name).exists(): 131 return (keymap_dir / keymap_name).resolve() 132 133 134def normpath(path): 135 """Returns a `pathlib.Path()` object for a given path. 136 137 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. 138 """ 139 path = Path(path) 140 141 if path.is_absolute(): 142 return path 143 144 return Path(os.environ['ORIG_CWD']) / path 145 146 147def unix_style_path(path): 148 """Converts a Windows-style path with drive letter to a Unix path. 149 150 Path().as_posix() normally returns the path with drive letter and forward slashes, so is inappropriate for `Makefile` paths. 151 152 Passes through unadulterated if the path is not a Windows-style path. 153 154 Args: 155 156 path 157 The path to convert. 158 159 Returns: 160 The input path converted to Unix format. 161 """ 162 if isinstance(path, PureWindowsPath): 163 p = list(path.parts) 164 p[0] = f'/{p[0][0].lower()}' # convert from `X:/` to `/x` 165 path = PurePosixPath(*p) 166 return path 167 168 169class FileType(argparse.FileType): 170 def __init__(self, *args, **kwargs): 171 # Use UTF8 by default for stdin 172 if 'encoding' not in kwargs: 173 kwargs['encoding'] = 'UTF-8' 174 return super().__init__(*args, **kwargs) 175 176 def __call__(self, string): 177 """normalize and check exists 178 otherwise magic strings like '-' for stdin resolve to bad paths 179 """ 180 norm = normpath(string) 181 return norm if norm.exists() else super().__call__(string)