| 1 | import { ensureTrailingSlash, shellExpand } from "./resolve"; |
| 2 | |
| 3 | export interface FilepathsOptions { |
| 4 | /** |
| 5 | * Show suggestions with any of these extensions. Do not include the leading dot. |
| 6 | */ |
| 7 | extensions?: string[]; |
| 8 | /** |
| 9 | * Show suggestions where the name exactly matches one of these strings |
| 10 | */ |
| 11 | equals?: string | string[]; |
| 12 | /** |
| 13 | * Show suggestions where the name matches this expression |
| 14 | */ |
| 15 | matches?: RegExp; |
| 16 | /** |
| 17 | * Will treat folders like files, filtering based on the name. |
| 18 | */ |
| 19 | filterFolders?: boolean; |
| 20 | /** |
| 21 | * Set properties of suggestions of type "file". |
| 22 | */ |
| 23 | editFileSuggestions?: Omit<Fig.Suggestion, "name" | "type">; |
| 24 | /** |
| 25 | * Set properties of suggestions of type "folder". |
| 26 | */ |
| 27 | editFolderSuggestions?: Omit<Fig.Suggestion, "name" | "type">; |
| 28 | /** |
| 29 | * Start to suggest filepaths and folders from this directory. |
| 30 | */ |
| 31 | rootDirectory?: string; |
| 32 | /** |
| 33 | * Set how the generator should display folders: |
| 34 | * - **Default:** `always` will always suggest folders. |
| 35 | * - `never`: will never suggest folders. |
| 36 | * - `only`: will show only folders and no files. |
| 37 | */ |
| 38 | showFolders?: "always" | "never" | "only"; |
| 39 | } |
| 40 | |
| 41 | export function sortFilesAlphabetically(array: string[], skip: string[] = []): string[] { |
| 42 | const skipLower = skip.map((str) => str.toLowerCase()); |
| 43 | const results = array.filter((x) => !skipLower.includes(x.toLowerCase())); |
| 44 | |
| 45 | // Put all files beginning with . after all those that don't, sort alphabetically within each. |
| 46 | return [ |
| 47 | ...results.filter((x) => !x.startsWith(".")).sort((a, b) => a.localeCompare(b)), |
| 48 | ...results.filter((x) => x.startsWith(".")).sort((a, b) => a.localeCompare(b)), |
| 49 | "../", |
| 50 | ]; |
| 51 | } |
| 52 | |
| 53 | /** |
| 54 | * @param cwd - The current working directory when the user started typing the new path |
| 55 | * @param searchTerm - The path inserted by the user, it can be relative to cwd or absolute |
| 56 | * @returns The directory the user inserted, taking into account the cwd. |
| 57 | */ |
| 58 | export const getCurrentInsertedDirectory = ( |
| 59 | cwd: string | null, |
| 60 | searchTerm: string, |
| 61 | context: Fig.ShellContext |
| 62 | ): string => { |
| 63 | if (cwd === null) return "/"; |
| 64 | |
| 65 | const resolvedPath = shellExpand(searchTerm, context); |
| 66 | |
| 67 | const dirname = resolvedPath.slice(0, resolvedPath.lastIndexOf("/") + 1); |
| 68 | |
| 69 | if (dirname === "") { |
| 70 | return ensureTrailingSlash(cwd); |
| 71 | } |
| 72 | |
| 73 | return dirname.startsWith("/") ? dirname : `${ensureTrailingSlash(cwd)}${dirname}`; |
| 74 | }; |
| 75 | |
| 76 | /** |
| 77 | * Sugar over using the `filepaths` template with `filterTemplateSuggestions`. If any of the |
| 78 | * conditions match, the suggestion will be accepted. |
| 79 | * |
| 80 | * Basic filepath filters can be replaced with this generator. |
| 81 | * |
| 82 | * @example |
| 83 | * ``` |
| 84 | * // inside a `Fig.Arg`... |
| 85 | * generators: filepaths({ extensions: ["mjs", "js", "json"] }); |
| 86 | * ``` |
| 87 | */ |
| 88 | function filepathsFn(options: FilepathsOptions = {}): Fig.Generator { |
| 89 | const { |
| 90 | extensions = [], |
| 91 | equals = [], |
| 92 | matches, |
| 93 | filterFolders = false, |
| 94 | editFileSuggestions, |
| 95 | editFolderSuggestions, |
| 96 | rootDirectory, |
| 97 | showFolders = "always", |
| 98 | } = options; |
| 99 | // TODO: automatically remove eventual leading dots |
| 100 | const extensionsSet = new Set(extensions); |
| 101 | const equalsSet = new Set(equals); |
| 102 | |
| 103 | // NOTE: If no filter is provided we should not run the filterSuggestions fn. |
| 104 | // !! When new filtering parameters are added we should increase this function |
| 105 | const shouldFilterSuggestions = () => extensions.length > 0 || equals.length > 0 || matches; |
| 106 | |
| 107 | const filterSuggestions = ( |
| 108 | suggestions: Fig.TemplateSuggestion[] = [] |
| 109 | ): Fig.TemplateSuggestion[] => { |
| 110 | if (!shouldFilterSuggestions()) return suggestions; |
| 111 | |
| 112 | return suggestions.filter(({ name = "", type }) => { |
| 113 | if (!filterFolders && type === "folder") return true; |
| 114 | |
| 115 | if (equalsSet.has(name)) return true; |
| 116 | if (matches && !!name.match(matches)) return true; |
| 117 | // handle extensions |
| 118 | const [, ...suggestionExtensions] = name.split("."); |
| 119 | if (suggestionExtensions.length >= 1) { |
| 120 | let i = suggestionExtensions.length - 1; |
| 121 | let stackedExtensions = suggestionExtensions[i]; |
| 122 | do { |
| 123 | if (extensionsSet.has(stackedExtensions)) { |
| 124 | return true; |
| 125 | } |
| 126 | i -= 1; |
| 127 | // `i` may become -1 which is not a valid index, but the extensionSet check at the beginning is not run in that case, |
| 128 | // so the wrong extension is not evaluated |
| 129 | stackedExtensions = [suggestionExtensions[i], stackedExtensions].join("."); |
| 130 | } while (i >= 0); |
| 131 | } |
| 132 | return false; |
| 133 | }); |
| 134 | }; |
| 135 | |
| 136 | const postProcessSuggestions = ( |
| 137 | suggestions: Fig.TemplateSuggestion[] = [] |
| 138 | ): Fig.TemplateSuggestion[] => { |
| 139 | if (!editFileSuggestions && !editFolderSuggestions) return suggestions; |
| 140 | |
| 141 | return suggestions.map((suggestion) => ({ |
| 142 | ...suggestion, |
| 143 | ...((suggestion.type === "file" ? editFileSuggestions : editFolderSuggestions) || {}), |
| 144 | })); |
| 145 | }; |
| 146 | |
| 147 | return { |
| 148 | trigger: (oldToken, newToken) => { |
| 149 | const oldLastSlashIndex = oldToken.lastIndexOf("/"); |
| 150 | const newLastSlashIndex = newToken.lastIndexOf("/"); |
| 151 | // If the final path segment has changed, trigger new suggestions |
| 152 | if (oldLastSlashIndex !== newLastSlashIndex) { |
| 153 | return true; |
| 154 | } |
| 155 | // Here, there could either be no slashes, or something before the |
| 156 | // final slash has changed. In the case where there are no slashes, |
| 157 | // we don't want to trigger on each keystroke, so explicitly return false. |
| 158 | if (oldLastSlashIndex === -1 && newLastSlashIndex === -1) { |
| 159 | return false; |
| 160 | } |
| 161 | // We know there's at least one slash in the string thanks to the case |
| 162 | // above, so trigger if anything before the final slash has changed. |
| 163 | return oldToken.slice(0, oldLastSlashIndex) !== newToken.slice(0, newLastSlashIndex); |
| 164 | }, |
| 165 | getQueryTerm: (token) => token.slice(token.lastIndexOf("/") + 1), |
| 166 | |
| 167 | custom: async (_, executeCommand, generatorContext) => { |
| 168 | const { isDangerous, currentWorkingDirectory, searchTerm } = generatorContext; |
| 169 | const currentInsertedDirectory = |
| 170 | getCurrentInsertedDirectory( |
| 171 | rootDirectory ?? currentWorkingDirectory, |
| 172 | searchTerm, |
| 173 | generatorContext |
| 174 | ) ?? "/"; |
| 175 | |
| 176 | try { |
| 177 | const data = await executeCommand({ |
| 178 | command: "ls", |
| 179 | args: ["-1ApL"], |
| 180 | cwd: currentInsertedDirectory, |
| 181 | }); |
| 182 | const sortedFiles = sortFilesAlphabetically(data.stdout.split("\n"), [".DS_Store"]); |
| 183 | |
| 184 | const generatorOutputArray: Fig.TemplateSuggestion[] = []; |
| 185 | // Then loop through them and add them to the generatorOutputArray |
| 186 | // depending on the template type |
| 187 | for (const name of sortedFiles) { |
| 188 | if (name) { |
| 189 | const templateType = name.endsWith("/") ? "folders" : "filepaths"; |
| 190 | if ( |
| 191 | (templateType === "filepaths" && showFolders !== "only") || |
| 192 | (templateType === "folders" && showFolders !== "never") |
| 193 | ) { |
| 194 | generatorOutputArray.push({ |
| 195 | type: templateType === "filepaths" ? "file" : "folder", |
| 196 | name, |
| 197 | insertValue: name, |
| 198 | isDangerous, |
| 199 | context: { templateType }, |
| 200 | }); |
| 201 | } |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | // Filter suggestions. This takes in the array of suggestions, filters it, |
| 206 | // and outputs an array of suggestions |
| 207 | return postProcessSuggestions(filterSuggestions(generatorOutputArray)); |
| 208 | } catch (err) { |
| 209 | return []; |
| 210 | } |
| 211 | }, |
| 212 | }; |
| 213 | } |
| 214 | |
| 215 | export const folders = Object.assign( |
| 216 | () => filepathsFn({ showFolders: "only" }), |
| 217 | Object.freeze(filepathsFn({ showFolders: "only" })) |
| 218 | ); |
| 219 | export const filepaths = Object.assign(filepathsFn, Object.freeze(filepathsFn())); |