├── .editorconfig ├── .github └── FUNDING.yml ├── .gitignore ├── CMakeLists.txt ├── LICENSE.md ├── README.md ├── command-not-found.cpp ├── generate-db.js └── package.json /.editorconfig: -------------------------------------------------------------------------------- 1 | [*] 2 | indent_style = space 3 | indent_size = 2 4 | trim_trailing_whitespace = true 5 | 6 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: termux 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry 13 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Python 2 | __pycache__ 3 | 4 | # CMake build directory 5 | /build* 6 | 7 | # Downloaded content 8 | /Contents* 9 | 10 | # Generated header files 11 | /commands-*.h 12 | 13 | ## Editor/IDE/Code Lens 14 | # Vim 15 | [._]*.s[a-w][a-z] 16 | [._]s[a-w][a-z] 17 | # VS Code 18 | /.vscode 19 | # ccls 20 | /.ccls-cache 21 | # Other 22 | /compile_commands.json 23 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.25) 2 | project (command-not-found) 3 | 4 | set(CMAKE_CXX_STANDARD 20) 5 | 6 | set(COMMAND_NOT_FOUND_VERSION "3.1") 7 | 8 | add_custom_target(generate-db COMMAND ./generate-db.js WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}) 9 | add_executable(command-not-found command-not-found.cpp) 10 | add_dependencies(command-not-found generate-db) 11 | target_compile_options(command-not-found PRIVATE -Wall -Wextra -Werror -pedantic) 12 | target_compile_definitions(command-not-found PRIVATE COMMAND_NOT_FOUND_VERSION="${COMMAND_NOT_FOUND_VERSION}") 13 | 14 | install(TARGETS command-not-found DESTINATION libexec/termux) 15 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Command-not-found for termux 2 | 3 | This repo contains sources for the command-not-found utility used in termux. 4 | Apart from the sources for the binary (`command-not-found.cpp`), it also 5 | contains a script to generate lists of commands for the various official 6 | repositories: 7 | 8 | - [main repo](https://github.com/termux/termux-packages/tree/master/packages) 9 | - [root repo](https://github.com/termux/termux-packages/tree/master/root-packages) 10 | - [x11 repo](https://github.com/termux/termux-packages/tree/master/x11-packages) 11 | 12 | ## Building command-not-found 13 | 14 | To build the package, `cmake` and a c++ compiler (for example `g++` or `clang++`) 15 | needs to be installed. 16 | Apart from `cmake` and a C++ compiler, `nodejs` is also needed in order to 17 | generate list of commands. 18 | To do an out of source build, run these commands from the command-not-found 19 | directory: 20 | 21 | ```sh 22 | mkdir build && cd build 23 | cmake .. 24 | make 25 | ``` 26 | 27 | This will generate command lists by running `./generate-db.js`, and create 28 | a command-not-found binary which can be tested directly. 29 | To then install the program, run: 30 | 31 | ```sh 32 | make install 33 | ``` 34 | 35 | This installs command-not-found to `CMAKE_INSTALL_PREFIX/libexec/termux`, which 36 | is where command-not-found resides in termux. 37 | 38 | ## Updating the command lists 39 | 40 | In order to update the command lists, just a rebuild of command-not-found 41 | is to be done by bumping the `TERMUX_PKG_REVISION` in build recipe of 42 | command-not-found. 43 | -------------------------------------------------------------------------------- /command-not-found.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed under the Apache License, Version 2.0 (the "License"); 3 | * you may not use this file except in compliance with the License. 4 | * You may obtain a copy of the License at 5 | * 6 | * http://www.apache.org/licenses/LICENSE-2.0 7 | * 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | 24 | #ifndef __TERMUX_PREFIX__ 25 | #error "__TERMUX_PREFIX__ not defined" 26 | #endif 27 | 28 | const std::list main_commands = { 29 | #ifdef __aarch64__ 30 | #include "commands-aarch64-termux-main.h" 31 | #elif defined __arm__ 32 | #include "commands-arm-termux-main.h" 33 | #elif defined __i686__ 34 | #include "commands-i686-termux-main.h" 35 | #elif defined __x86_64__ 36 | #include "commands-x86_64-termux-main.h" 37 | #else 38 | #error Failed to detect arch 39 | #endif 40 | }; 41 | 42 | const std::list root_commands = { 43 | #ifdef __aarch64__ 44 | #include "commands-aarch64-termux-root.h" 45 | #elif defined __arm__ 46 | #include "commands-arm-termux-root.h" 47 | #elif defined __i686__ 48 | #include "commands-i686-termux-root.h" 49 | #elif defined __x86_64__ 50 | #include "commands-x86_64-termux-root.h" 51 | #else 52 | #error Failed to detect arch 53 | #endif 54 | }; 55 | 56 | const std::list x11_commands = { 57 | #ifdef __aarch64__ 58 | #include "commands-aarch64-termux-x11.h" 59 | #elif defined __arm__ 60 | #include "commands-arm-termux-x11.h" 61 | #elif defined __i686__ 62 | #include "commands-i686-termux-x11.h" 63 | #elif defined __x86_64__ 64 | #include "commands-x86_64-termux-x11.h" 65 | #else 66 | #error Failed to detect arch 67 | #endif 68 | }; 69 | 70 | struct info { 71 | std::string binary, repository; 72 | }; 73 | 74 | inline int termux_min3(int a, int b, int c) { 75 | return (a < b ? (a < c ? a : c) : (b < c ? b : c)); 76 | } 77 | 78 | int termux_levenshtein_distance(char const *s1, char const *s2) { 79 | int s1len = strlen(s1); 80 | int s2len = strlen(s2); 81 | int x, y; 82 | int **matrix; 83 | int distance; 84 | matrix = (int **)malloc(sizeof *matrix * (s2len + 1)); 85 | 86 | if (!matrix) { 87 | std::cerr << "Memory allocation seem to have failed" << std::endl; 88 | return -2; 89 | } 90 | 91 | matrix[0] = (int *)malloc(sizeof *matrix[0] * (s1len + 1)); 92 | 93 | if (!matrix[0]) { 94 | std::cerr << "Memory allocation seem to have failed" << std::endl; 95 | return -3; 96 | } 97 | 98 | matrix[0][0] = 0; 99 | for (x = 1; x <= s2len; x++) { 100 | matrix[x] = (int *)malloc(sizeof *matrix[x] * (s1len + 1)); 101 | 102 | if (!matrix[x]) { 103 | std::cerr << "Memory allocation seem to have failed" << std::endl; 104 | return -4; 105 | } 106 | 107 | matrix[x][0] = matrix[x - 1][0] + 1; 108 | } 109 | for (y = 1; y <= s1len; y++) { 110 | matrix[0][y] = matrix[0][y - 1] + 1; 111 | } 112 | for (x = 1; x <= s2len; x++) { 113 | for (y = 1; y <= s1len; y++) { 114 | matrix[x][y] = 115 | termux_min3(matrix[x - 1][y] + 1, matrix[x][y - 1] + 1, 116 | matrix[x - 1][y - 1] + (s1[y - 1] == s2[x - 1] ? 0 : 1)); 117 | } 118 | } 119 | distance = matrix[s2len][s1len]; 120 | 121 | for (x = 0; x <= s2len; x++) { 122 | free(matrix[x]); 123 | } 124 | free(matrix); 125 | 126 | return distance; 127 | } 128 | 129 | int termux_look_for_packages(const char *command_not_found, 130 | const std::list &cmds, 131 | int *best_distance, 132 | std::map &pkg_map, 133 | const char repository[]) { 134 | std::string current_package; 135 | std::string current_binary; 136 | int distance; 137 | for (auto it = cmds.begin(); it != cmds.end(); ++it) { 138 | std::string_view current_line = *it; 139 | if (current_line[0] != ' ') { 140 | current_package = current_line; 141 | } else { 142 | current_binary = current_line.substr(1); 143 | distance = termux_levenshtein_distance(command_not_found, 144 | current_binary.c_str()); 145 | if (distance < -1) { 146 | // malloc failed, return the error code 147 | return -distance; 148 | } else if (*best_distance == distance) { 149 | // As good as our previously best match 150 | pkg_map.insert(std::pair( 151 | current_package, {current_binary, repository})); 152 | } else if (*best_distance == -1 || distance < *best_distance) { 153 | // New best match 154 | pkg_map.clear(); 155 | *best_distance = distance; 156 | pkg_map.insert(std::pair( 157 | current_package, {current_binary, repository})); 158 | } 159 | } 160 | } 161 | return 0; 162 | } 163 | 164 | int main(int argc, const char *argv[]) { 165 | if (argc != 2) { 166 | std::cerr << "command-not-found v" COMMAND_NOT_FOUND_VERSION << std::endl 167 | << "usage: command-not-found " << std::endl; 168 | return 1; 169 | } 170 | 171 | const char *command = argv[1]; 172 | int best_distance = -1; 173 | std::map package_map; 174 | std::map::iterator it; 175 | int res; 176 | std::string_view sources_prefix = 177 | __TERMUX_PREFIX__ "/etc/apt/sources.list.d/"; 178 | 179 | res = termux_look_for_packages(command, main_commands, &best_distance, 180 | package_map, ""); 181 | if (res != 0) { 182 | return res; 183 | } 184 | 185 | res = termux_look_for_packages(command, root_commands, &best_distance, 186 | package_map, "root"); 187 | if (res != 0) { 188 | return res; 189 | } 190 | 191 | res = termux_look_for_packages(command, x11_commands, &best_distance, 192 | package_map, "x11"); 193 | if (res != 0) { 194 | return res; 195 | } 196 | 197 | if (best_distance == -1 || best_distance > 3) { 198 | std::cerr << command << ": command not found" << std::endl; 199 | } else if (best_distance == 0) { 200 | std::cerr << "The program " << command 201 | << " is not installed. Install it by executing:" << std::endl; 202 | for (it = package_map.begin(); it != package_map.end(); ++it) { 203 | std::cerr << " pkg install " << it->first; 204 | if (it->second.repository != "" && 205 | !std::filesystem::exists(std::string(sources_prefix) + 206 | it->second.repository + ".list")) { 207 | std::cerr << ", after running pkg install " << it->second.repository 208 | << "-repo" << std::endl; 209 | } else { 210 | std::cerr << std::endl; 211 | } 212 | if (next(it) != package_map.end()) { 213 | std::cerr << "or" << std::endl; 214 | } 215 | } 216 | } else { 217 | std::cerr << "No command " << command 218 | << " found, did you mean:" << std::endl; 219 | for (it = package_map.begin(); it != package_map.end(); ++it) { 220 | std::cerr << " Command " << it->second.binary << " in package " 221 | << it->first; 222 | if (it->second.repository != "" && 223 | !std::filesystem::exists(std::string(sources_prefix) + 224 | it->second.repository + ".list")) { 225 | std::cerr << " from the " << it->second.repository << "-repo repository" 226 | << std::endl; 227 | } else { 228 | std::cerr << std::endl; 229 | } 230 | } 231 | } 232 | return 127; 233 | } 234 | -------------------------------------------------------------------------------- /generate-db.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | import { glob, readFile, writeFile } from "node:fs/promises"; 3 | import { gunzip } from "node:zlib"; 4 | import { join } from "node:path"; 5 | import { promisify } from "node:util"; 6 | 7 | const gunzipAsync = promisify(gunzip); 8 | 9 | const { TERMUX_SCRIPTDIR, TERMUX_PREFIX, TERMUX_ARCH } = process.env; 10 | 11 | if (!TERMUX_SCRIPTDIR) { 12 | throw new Error("TERMUX_PKG_CACHEDIR environment variable is not defined"); 13 | } 14 | 15 | if (!TERMUX_PREFIX) { 16 | throw new Error("TERMUX_PREFIX environment variable is not defined"); 17 | } 18 | 19 | if (!TERMUX_ARCH) { 20 | throw new Error("TERMUX_ARCH environment variable is not defined"); 21 | } 22 | 23 | const binPrefix = TERMUX_PREFIX.substring(1) + "/bin/"; 24 | const repos = JSON.parse( 25 | await readFile(join(TERMUX_SCRIPTDIR, "repo.json")), 26 | ); 27 | 28 | /** 29 | * Parses an alternative file and returns an array of alternative entries. 30 | * 31 | * The parsing isn't strict, and doesn't report errors. It may unintentionally throw errors if the file is malformed. 32 | * 33 | * Each entry contains: 34 | * - `name`: The name of the alternative. 35 | * - `link`: The link to the alternative. 36 | * - `alternative`: The alternative path. 37 | * - `dependents`: An array of dependents, each with `link`, `name`, and `path`. This is the list of slaves of the alternative. If there is no dependents, it'll be an empty array for consistency 38 | * - `priority`: The priority of the alternative. 39 | * 40 | * Note that both the name and path do not start with TERMUX_PREFIX, but instead start with the relative path from TERMUX_PREFIX. 41 | */ 42 | async function parseAlternativeFile(filePath) { 43 | const content = await readFile(filePath, "utf8"); 44 | let name = undefined; 45 | let link = undefined; 46 | let alternative = undefined; 47 | let dependents = undefined; 48 | let priority = undefined; 49 | let parsingDependents = false; 50 | 51 | const alternatives = []; 52 | 53 | for (let line of content.split("\n")) { 54 | // Remove trailing comment 55 | // Comment starts with a '#' and can be at the end of the line as well 56 | let match = line.match(/\s*#.*/); 57 | line = line.substring(0, match === null ? line.length : match.index); 58 | 59 | 60 | if (line.startsWith("Name: ")) { 61 | if (parsingDependents) { 62 | parsingDependents = false; 63 | } 64 | 65 | // We already had a alternative entry, so push what we have parsed so far as an alternative entry 66 | if (name !== undefined) { 67 | alternatives.push({ 68 | name: name, 69 | link: link, 70 | alternative: alternative, 71 | dependents: dependents === undefined ? [] : dependents, 72 | priority: parseInt(priority), 73 | }); 74 | name = undefined; 75 | link = undefined; 76 | alternative = undefined; 77 | dependents = undefined; 78 | priority = undefined; 79 | } 80 | name = line.substring("Name: ".length).trim(); 81 | } 82 | 83 | if (line.startsWith("Link: ")) { 84 | parsingDependents = false; 85 | link = line.substring("Link: ".length).trim(); 86 | } 87 | 88 | if (line.startsWith("Alternative: ")) { 89 | parsingDependents = false; 90 | alternative = line.substring("Alternative: ".length).trim(); 91 | } 92 | 93 | if (line.startsWith("Priority: ")) { 94 | parsingDependents = false; 95 | priority = line.substring("Priority: ".length).trim(); 96 | } 97 | 98 | if (line.startsWith("Dependents:")) { 99 | parsingDependents = true; 100 | } 101 | 102 | // Parse the dependents entry here 103 | if (parsingDependents) { 104 | line = line.trim(); 105 | // We have not parsed any dependents yet, so we initialize the dependents array 106 | if (dependents === undefined) { 107 | dependents = []; 108 | } 109 | // We trim the line to remove the leading indentation 110 | // The line should be in the format: "->link name path" 111 | // "->" is the leading indent 112 | // We use the regex \s+ to split the line into parts since the there can 113 | // be multiple spaces used for separating the parts for enhancing readibility 114 | const [dependentLink, dependentName, dependentPath] = line 115 | .trim() 116 | .split(/\s+/); 117 | if (dependentLink && dependentName && dependentPath) { 118 | dependents.push({ 119 | link: dependentLink, 120 | name: dependentName, 121 | path: dependentPath, 122 | }); 123 | } 124 | } 125 | } 126 | 127 | // After parsing the entire file, if we have a name, this means this is the 128 | // final entry. So push it as well 129 | if (name !== undefined) { 130 | alternatives.push({ 131 | name: name, 132 | link: link, 133 | alternative: alternative, 134 | dependents: dependents === undefined ? [] : dependents, 135 | priority: priority, 136 | }); 137 | } 138 | return alternatives; 139 | } 140 | 141 | async function processRepo(repo, repoPath, arch) { 142 | // Fetch the Contents.gz file for the given architecture from the apt mirror 143 | const url = `${repo.url}/dists/${repo.distribution}/Contents-${arch}.gz`; 144 | const response = await fetch(url); 145 | 146 | if (!response.ok) { 147 | throw new Error(`${url} returned ${response.status}`); 148 | } 149 | 150 | // Since we are using a gzip file, we need to decompress it 151 | const data = await gunzipAsync(await response.arrayBuffer()); 152 | // Convert to string and split by new lines 153 | // Each line is of the format: 154 | // "path/to/file package" 155 | // 156 | // Where `path/to/file` is the path to the file in the package, and `package` 157 | // is the name of the package that provides this file. 158 | const lines = data.toString().split("\n"); 159 | 160 | // Stores mappings of binary names to package names 161 | // The key is the binary name, and the value is an array of package names 162 | // that provide this binary 163 | const binMap = new Map(); 164 | 165 | // Stores mappings of file paths to package names 166 | // This is needed to resolve the package names for binaries that are setup 167 | // using the alternatives system 168 | const fileMap = new Map(); 169 | // Populate the fileMap 170 | lines.forEach((line) => { 171 | const [path, packageName] = line.split(" "); 172 | fileMap.set(path, packageName); 173 | }); 174 | 175 | // Now filter the entries from Contents.gz that have binaries, and store them 176 | // in binMap 177 | lines 178 | .filter((line) => line.startsWith(binPrefix)) 179 | .forEach((line) => { 180 | const [pathToBinary, packageNames] = line.split(" "); 181 | const binary = pathToBinary.substring(pathToBinary.lastIndexOf("/") + 1); 182 | const packages = packageNames.split(","); 183 | 184 | packages.forEach((packageName) => { 185 | if (!binMap.has(packageName)) { 186 | binMap.set(packageName, []); 187 | } 188 | binMap.get(packageName).push(binary); 189 | }); 190 | }); 191 | 192 | // Now go through all the *.alternatives files in the repository and parse 193 | // them to find the alternatives and their dependents 194 | repoPath = join(TERMUX_SCRIPTDIR, repoPath); 195 | for await (const file of glob(`${repoPath}/*/*.alternatives`, { 196 | nodir: true, 197 | })) { 198 | const alternatives = await parseAlternativeFile(file); 199 | 200 | alternatives.forEach((alternativeEntry) => { 201 | let packageName = file.substring(repoPath.length + 1); 202 | packageName = packageName.substring(0, packageName.indexOf("/")); 203 | if (alternativeEntry.link.startsWith("bin/")) { 204 | const path = alternativeEntry.alternative; 205 | const binary = alternativeEntry.link.substring( 206 | alternativeEntry.link.lastIndexOf("/") + 1, 207 | ); 208 | 209 | const packageName = fileMap.get(join(TERMUX_PREFIX.substring(1), path)); 210 | if (packageName === undefined) { 211 | console.error(`Package name not found for path: ${path}`); 212 | process.exit(1); 213 | } 214 | if (!binMap.has(packageName)) { 215 | binMap.set(packageName, []); 216 | } 217 | binMap.get(packageName).push(binary); 218 | alternativeEntry.dependents.forEach(({ link, name: _, path }) => { 219 | if (link.startsWith("bin/")) { 220 | const depPackageName = fileMap.get( 221 | join(TERMUX_PREFIX.substring(1), path), 222 | ); 223 | const depBinary = link.substring(link.lastIndexOf("/") + 1); 224 | if (!binMap.has(depPackageName)) { 225 | binMap.set(depPackageName, []); 226 | } 227 | binMap.get(depPackageName).push(depBinary); 228 | } 229 | // Register the link in the fileMap for the package 230 | // This is used by vim.alternatives where bin/vim is a link with alternative libexec/vim/vim 231 | // and bin/editor is a link with alternative bin/vim 232 | fileMap.set(join(TERMUX_PREFIX.substring(1), link), packageName); 233 | if (!binMap.has(packageName)) { 234 | binMap.set(packageName, []); 235 | } 236 | binMap.get(packageName).push(binary); 237 | }); 238 | } 239 | // Register the link in the fileMap for the package 240 | // This is used by vim.alternatives where bin/vim is a link with alternative libexec/vim/vim 241 | // and bin/editor is a link with alternative bin/vim 242 | fileMap.set( 243 | join(TERMUX_PREFIX.substring(1), alternativeEntry.link), 244 | packageName, 245 | ); 246 | }); 247 | } 248 | 249 | const headerFile = `commands-${arch}-${repo.name}.h`; 250 | const header = Array.from(binMap.keys()) 251 | .sort() 252 | .map((packageName) => { 253 | const binaries = binMap 254 | .get(packageName) 255 | .sort() 256 | .map((bin) => `" ${bin}",`); 257 | return `"${packageName}",\n${binaries.join("\n")}`; 258 | }) 259 | .join("\n"); 260 | 261 | await writeFile(headerFile, header); 262 | } 263 | 264 | const promises = []; 265 | 266 | for (const path in repos) { 267 | if (path === "pkg_format") continue; 268 | const repo = repos[path]; 269 | promises.push(processRepo(repo, path, TERMUX_ARCH)); 270 | } 271 | 272 | await Promise.all(promises); 273 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "module", 3 | "private": true 4 | } 5 | --------------------------------------------------------------------------------