├── .github └── workflows │ ├── cd.yml │ └── ci.yml ├── .vscode └── settings.json ├── LICENSE.txt ├── README.md ├── pkgm.ts ├── pkgx.yaml └── tea.yaml /.github/workflows/cd.yml: -------------------------------------------------------------------------------- 1 | name: cd 2 | 3 | on: 4 | release: 5 | types: 6 | - published 7 | 8 | concurrency: 9 | group: cd/${{ github.event.release.tag_name }} 10 | cancel-in-progress: true 11 | 12 | jobs: 13 | retag: 14 | permissions: 15 | contents: write 16 | runs-on: ubuntu-latest 17 | steps: 18 | - uses: actions/checkout@v4 19 | - uses: fischerscode/tagger@v0 20 | with: 21 | prefix: v 22 | - run: | 23 | git tag -f latest 24 | git push origin latest --force 25 | 26 | publish: 27 | permissions: 28 | pages: write 29 | id-token: write 30 | contents: write 31 | runs-on: ubuntu-latest 32 | steps: 33 | - uses: actions/checkout@v4 34 | 35 | - name: gather prefix-less version string 36 | run: | 37 | V=${{ github.event.release.tag_name }} 38 | V=${V:1} 39 | echo "V=$V" >> $GITHUB_ENV 40 | 41 | - run: | 42 | sed -i -E "s/\"pkgm 0\\.0\\.0\\+dev\"/\"pkgm $V\"/g" pkgm.ts 43 | mv pkgm.ts pkgm 44 | tar czf pkgm-$V.tgz pkgm 45 | 46 | - uses: pkgxdev/setup@v4 47 | 48 | - name: verify `pkgm --version` 49 | run: test "$(./pkgm --version)" = "pkgm $V" 50 | 51 | - run: 52 | gh release upload --clobber ${{ github.event.release.tag_name }} pkgm-$V.tgz 53 | env: 54 | GITHUB_TOKEN: ${{ github.token }} 55 | 56 | - run: | 57 | mkdir out 58 | mv pkgm out/pkgm.ts 59 | echo $V > out/version.txt 60 | 61 | - uses: actions/configure-pages@v4 62 | - uses: actions/upload-pages-artifact@v3 63 | with: 64 | path: out/ 65 | - uses: actions/deploy-pages@v4 66 | 67 | - uses: aurelien-baudet/workflow-dispatch@v4 68 | with: 69 | workflow: bump.yml 70 | repo: pkgxdev/homebrew-made 71 | ref: main 72 | token: ${{secrets.GH_TOKEN}} 73 | inputs: '{ "formula": "pkgm" }' 74 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: ci 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | 9 | concurrency: 10 | group: ${{ github.ref }} 11 | cancel-in-progress: true 12 | 13 | jobs: 14 | lint: 15 | runs-on: ubuntu-latest 16 | steps: 17 | - uses: actions/checkout@v4 18 | - uses: denolib/setup-deno@v2 19 | with: 20 | deno-version: v2.x 21 | - run: deno fmt --check . 22 | - run: deno lint . 23 | - run: deno check ./pkgm.ts 24 | 25 | #TODO test on linux! we are currently broken due to rpath issues 26 | # https://github.com/pkgxdev/pkgm/pull/30#issuecomment-2678957666 27 | test: 28 | continue-on-error: true 29 | strategy: 30 | matrix: 31 | os: 32 | - macos-latest 33 | - ubuntu-latest 34 | runs-on: ${{ matrix.os }} 35 | steps: 36 | - uses: actions/checkout@v4 37 | - uses: pkgxdev/setup@v4 38 | 39 | - run: ./pkgm.ts i git 40 | - run: ~/.local/bin/git --version 41 | - run: "! test -f /usr/local/bin/git" 42 | - run: ./pkgm.ts ls | grep .local/pkgs/git-scm.org 43 | - run: ./pkgm.ts rm git 44 | - run: test ! -f ~/.local/bin/git 45 | 46 | - run: ./pkgm.ts i pkgx.sh/brewkit 47 | - run: ~/.local/bin/bk --help 48 | 49 | # check repeats work 50 | - run: rm ~/.local/bin/bk 51 | - run: test ! -f /usr/local/bin/bk 52 | - run: ./pkgm.ts i pkgx.sh/brewkit 53 | - run: ~/.local/bin/bk --help 54 | 55 | - run: ./pkgm.ts i gum 56 | - run: ~/.local/bin/gum --version 57 | 58 | # test a thing with deps 59 | # https://github.com/pkgxdev/pkgm/issues/24 60 | - run: ./pkgm.ts i curl 61 | - run: ~/.local/bin/curl -L pkgx.sh 62 | 63 | - run: ./pkgm.ts shim semverator 64 | - run: ~/.local/bin/semverator validate 1.0.0 65 | 66 | # tests shims do not shim deps 67 | - run: ./pkgm.ts shim node@20 68 | - run: test ! -d ~/.local/bin/openssl 69 | - run: if [[ $(~/.local/bin/node --version) != v20* ]]; then false; fi 70 | 71 | - run: ./pkgm.ts i hyperfine@1.18 72 | - run: ./pkgm.ts outdated | grep hyperfine 73 | - run: if pkgx semverator satisfies '>=1.19' "$(hyperfine --version | cut -f 2 -d ' ')"; then false; fi 74 | - run: ./pkgm.ts update 75 | - run: pkgx semverator satisfies '>=1.19' "$(hyperfine --version | cut -f 2 -d ' ')" 76 | 77 | # TODO pending: https://github.com/pkgxdev/pantry/issues/8487 78 | # - run: ./pkgm.ts i xpra.org # https://github.com/pkgxdev/pkgm/issues/13 79 | # - run: ls -la /usr/local/pkgs/xpra.org/v6.2.3/venv/bin 80 | # - run: xpra --version 81 | 82 | # verifies that libpkgx is creating the pantry at the right place 83 | # Refs: https://github.com/pkgxdev/pkgm/issues/59 84 | - run: | 85 | ./pkgm.ts i semverator 86 | if test -d /tmp/foo/pkgx; then 87 | test $(uname) = Linux 88 | else 89 | test $(uname) = Darwin 90 | fi 91 | env: 92 | XDG_DATA_HOME: /tmp/foo 93 | 94 | - run: | 95 | set -x 96 | sudo ./pkgm.ts i node@22 dev 97 | [[ $(node --version) = v22* ]] || exit 2 98 | mkdir foo 99 | cd foo 100 | echo "dependencies: node@20" > pkgx.yaml 101 | mkdir -p /tmp/bar/pkgx/dev$PWD/ 102 | touch /tmp/bar/pkgx/dev$PWD/dev.pkgx.activated # `dev .` doesn’t work in CI (fix in dev^2) 103 | [[ $(node --version) = v20* ]] || exit 3 104 | env: 105 | XDG_DATA_HOME: /tmp/bar 106 | 107 | # https://github.com/pkgxdev/pkgm/issues/62 108 | - run: | 109 | ./pkgm.ts i spotify_player 110 | spotify_player --version 111 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "deno.enable": true 3 | } 4 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2022–23 pkgx inc. 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # `pkgm` 2 | 3 | Install `pkgx` packages to `/usr/local`. 4 | 5 | > [!CAUTION] 6 | > 7 | > `pkgm` is new software. Please report any issues you encounter and try it out 8 | > in parallel with your current package manager. 9 | 10 | ## Usage 11 | 12 | ```sh 13 | $ pkgm install node 14 | # ^^ installs latest node to ~/.local. ie. you get ~/.local/bin/node 15 | 16 | $ pkgm install node@20.1 17 | # ^^ installs node^20.1 or switches out the installed node to 20.1 18 | 19 | $ pkgm uninstall node 20 | 21 | $ sudo pkgm install node 22 | # ^^ installs node to /usr/local. ie. you get /usr/local/bin/node 23 | 24 | $ pkgm shim node 25 | # ^^ creates a shim for node at ~/.local/bin/node 26 | # see the docs below for details about shims 27 | 28 | $ pkgm list 29 | # ^^ lists what’s installed 30 | 31 | $ pkgm outdated 32 | # ^^ lists outdated installations 33 | 34 | $ pkgm update 35 | # ^^ updates ~/.local packages to latest versions 36 | 37 | $ sudo pkgm update 38 | # ^^ updates /usr/local packages to latest versions 39 | ``` 40 | 41 | > [!TIP] 42 | > 43 | > - `pkgm i` is an alias for `pkgm install` 44 | > - `pkgm rm` is an alias for `pkgm uninstall` 45 | > - `pkgm ls` is an alias for `pkgm list` 46 | > - `pkgm up` is an alias for `pkgm update` 47 | 48 | > [!WARNING] 49 | > 50 | > You should probably `sudo pkgm install` rather than install to `~/.local`. 51 | > This is because many other tools will not look in `~/.local` for packages 52 | > _even_ if it’s in `PATH`. Having said this—by all means—see how it goes! 53 | 54 | > ### Shims 55 | > 56 | > Shims are files with a single line, eg `#!/usr/bin/env -S pkgx -q! node@22`. 57 | > 58 | > Thus using the shell to invoke the program via `pkgx`. You get all the 59 | > benefits of an installed package—but only installed on-demand. Useful for 60 | > self-healing setups, devops, containers and plenty more one-off or ephemeral 61 | > tasks. 62 | > 63 | > Shims are pretty great—but have caveats. Some software might be surprised that 64 | > a package is not fully “installed” which can lead to unexpected errors. In 65 | > practice we have seen issues only rarely and for more complex package 66 | > combinations. 67 | 68 | ## Installation 69 | 70 | ```sh 71 | brew install pkgxdev/made/pkgm || curl https://pkgx.sh | sh 72 | ``` 73 | 74 | ## Uninstallation 75 | 76 | ```sh 77 | brew rm pkgm || sudo rm /usr/local/bin/pkgm 78 | ``` 79 | 80 | # Intricacies 81 | 82 | 1. Packages are installed via `pkgx` to `~/.pkgx` 83 | 2. We then `sudo` hard-link them to `/usr/local/pkgs` 84 | 3. We then symlink the hard-links to `/usr/local` 85 | 86 | # Advantages Over Homebrew 87 | 88 | - Blazingly fast 89 | - Install specific versions of any pkg 90 | - You install by executable name—thus you _don’t have to do a search first_ 91 | - Installed packages can be installed as `root` 92 | - `dev`-aware installations 93 | - Optional self-healing shims 94 | -------------------------------------------------------------------------------- /pkgm.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env -S pkgx --quiet deno^2.1 run --ext=ts --allow-sys=uid --allow-run --allow-env --allow-read --allow-write --allow-ffi --allow-net=dist.pkgx.dev 2 | import { 3 | hooks, 4 | Installation, 5 | Path, 6 | plumbing, 7 | SemVer, 8 | semver, 9 | utils, 10 | } from "https://deno.land/x/libpkgx@v0.21.0/mod.ts"; 11 | import { dirname, join } from "jsr:@std/path@^1"; 12 | import { ensureDir, existsSync, walk } from "jsr:@std/fs@^1"; 13 | import { parseArgs } from "jsr:@std/cli@^1"; 14 | const { hydrate } = plumbing; 15 | 16 | function standardPath() { 17 | let path = "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"; 18 | 19 | // for pkgx installed via homebrew 20 | let homebrewPrefix = ""; 21 | switch (Deno.build.os) { 22 | case "darwin": 23 | homebrewPrefix = "/opt/homebrew"; // /usr/local is already in the path 24 | break; 25 | case "linux": 26 | homebrewPrefix = `/home/linuxbrew/.linuxbrew:${ 27 | Deno.env.get("HOME") 28 | }/.linuxbrew`; 29 | break; 30 | } 31 | if (homebrewPrefix) { 32 | homebrewPrefix = Deno.env.get("HOMEBREW_PREFIX") ?? homebrewPrefix; 33 | path = `${homebrewPrefix}/bin:${path}`; 34 | } 35 | 36 | return path; 37 | } 38 | 39 | const parsedArgs = parseArgs(Deno.args, { 40 | alias: { 41 | v: "version", 42 | h: "help", 43 | p: "pin", 44 | }, 45 | boolean: ["help", "version", "pin"], 46 | }); 47 | 48 | if (parsedArgs.help || parsedArgs._[0] == "help") { 49 | const { code } = await new Deno.Command("pkgx", { 50 | args: [ 51 | "glow", 52 | "https://raw.githubusercontent.com/pkgxdev/pkgm/refs/heads/main/README.md", 53 | ], 54 | }).spawn().status; 55 | Deno.exit(code); 56 | } else if (parsedArgs.version) { 57 | console.log("pkgm 0.0.0+dev"); 58 | } else { 59 | const args = parsedArgs._.map((x) => `${x}`).slice(1); 60 | 61 | switch (parsedArgs._[0]) { 62 | case "install": 63 | case "i": 64 | { 65 | const rv = await install(args, install_prefix().string); 66 | console.log(rv.join("\n")); 67 | } 68 | break; 69 | case "local-install": 70 | case "li": 71 | if (install_prefix().string != "/usr/local") { 72 | await install(args, Path.home().join(".local").string); 73 | } else { 74 | console.error("deprecated: use `pkgm install` without `sudo` instead"); 75 | } 76 | break; 77 | case "stub": 78 | case "shim": 79 | // equivalent to `pkgx^1 install` 80 | // shims often work just fine, but sometimes don’t. 81 | // when they don’t it is usually because the consuming tool makes assumptions about 82 | // where files for the package in question reside. 83 | await shim(args, install_prefix().string); 84 | break; 85 | case "uninstall": 86 | case "rm": 87 | { 88 | let all_success = true; 89 | for (const arg of args) { 90 | if (!await uninstall(arg)) { 91 | all_success = false; 92 | } 93 | } 94 | Deno.exit(all_success ? 0 : 1); 95 | } 96 | break; 97 | case "list": 98 | case "ls": 99 | for await (const path of ls()) { 100 | console.log(path); 101 | } 102 | break; 103 | case "up": 104 | case "update": 105 | case "upgrade": 106 | await update(); 107 | break; 108 | 109 | case "pin": 110 | console.error("%cU EARLY! soz, not implemented", "color:red"); 111 | Deno.exit(1); 112 | break; 113 | case "outdated": 114 | await outdated(); 115 | break; 116 | default: 117 | if (Deno.args.length === 0) { 118 | console.error("https://github.com/pkgxdev/pkgm"); 119 | } else { 120 | console.error("invalid usage"); 121 | } 122 | Deno.exit(2); 123 | } 124 | } 125 | 126 | async function install(args: string[], basePath: string) { 127 | if (args.length === 0) { 128 | console.error("no packages specified"); 129 | Deno.exit(1); 130 | } 131 | 132 | const pkgx = get_pkgx(); 133 | 134 | const [json] = await query_pkgx(pkgx, args); 135 | const pkg_prefixes = json.pkgs.map((x) => 136 | `${x.pkg.project}/v${x.pkg.version}` 137 | ); 138 | 139 | // get the pkgx_dir this way as it is a) more reliable and b) the only way if 140 | // we are running as sudo on linux since it doesn’t give us a good way to get 141 | // the home directory of the pre-sudo user 142 | const pkgx_dir = (() => { 143 | const { path, pkg } = json.pkgs[0]!; 144 | const remove = pkg.project + "/v" + pkg.version; 145 | return path.string.slice(0, -remove.length - 1); 146 | })(); 147 | 148 | const runtime_env = expand_runtime_env(json, basePath); 149 | 150 | const dst = basePath; 151 | for (const pkg_prefix of pkg_prefixes) { 152 | // create ${dst}/pkgs/${prefix} 153 | await mirror_directory(join(dst, "pkgs"), pkgx_dir, pkg_prefix); 154 | // symlink ${dst}/pkgs/${prefix} to ${dst} 155 | if (!pkg_prefix.startsWith("pkgx.sh/v")) { 156 | // ^^ don’t overwrite ourselves 157 | // ^^ * https://github.com/pkgxdev/pkgm/issues/14 158 | // ^^ * https://github.com/pkgxdev/pkgm/issues/17 159 | await symlink(join(dst, "pkgs", pkg_prefix), dst); 160 | } 161 | // create v1, etc. symlinks 162 | await create_v_symlinks(join(dst, "pkgs", pkg_prefix)); 163 | } 164 | 165 | const rv = []; 166 | 167 | for (const [project, env] of Object.entries(runtime_env)) { 168 | if (project == "pkgx.sh") continue; 169 | 170 | const pkg_prefix = pkg_prefixes.find((x) => x.startsWith(project))!; 171 | 172 | if (!pkg_prefix) continue; //FIXME wtf? 173 | 174 | for (const bin of ["bin", "sbin"]) { 175 | const bin_prefix = join(`${dst}/pkgs`, pkg_prefix, bin); 176 | 177 | if (!existsSync(bin_prefix)) continue; 178 | 179 | for await (const entry of Deno.readDir(bin_prefix)) { 180 | if (!entry.isFile) continue; 181 | 182 | const to_stub = join(dst, bin, entry.name); 183 | 184 | let sh = `#!/bin/sh\n`; 185 | for (const [key, value] of Object.entries(env)) { 186 | sh += `export ${key}="${value}"\n`; 187 | } 188 | 189 | sh += "\n"; 190 | //TODO should be specific with the project 191 | sh += dev_stub_text(to_stub, bin_prefix, entry.name); 192 | 193 | await Deno.remove(to_stub); //FIXME inefficient to symlink for no reason 194 | await Deno.writeTextFile(to_stub, sh.trim() + "\n"); 195 | await Deno.chmod(to_stub, 0o755); 196 | 197 | rv.push(to_stub); 198 | } 199 | } 200 | } 201 | 202 | if ( 203 | !Deno.env.get("PATH")?.split(":")?.includes( 204 | new Path(basePath).join("bin").string, 205 | ) 206 | ) { 207 | console.error( 208 | "%c! warning:", 209 | "color:yellow", 210 | `${new Path(basePath).join("bin")} not in $PATH`, 211 | ); 212 | } 213 | 214 | return rv; 215 | } 216 | 217 | async function shim(args: string[], basePath: string) { 218 | const pkgx = get_pkgx(); 219 | 220 | await ensureDir(join(basePath, "bin")); 221 | 222 | const json = (await query_pkgx(pkgx, args))[0]; 223 | 224 | const args_pkgs: Record = {}; 225 | const projects_we_care_about: string[] = []; 226 | for (const arg of args) { 227 | const pkgs = await hooks.usePantry().find(arg); 228 | if (pkgs.length == 0) throw new Error(`no such pkg: ${arg}`); 229 | if (pkgs.length > 1) throw new Error(`ambiguous pkg: ${arg}`); 230 | args_pkgs[pkgs[0].project] = utils.pkg.parse(arg).constraint; 231 | projects_we_care_about.push(pkgs[0].project); 232 | const companions = await hooks.usePantry().project(pkgs[0]).companions(); 233 | projects_we_care_about.push(...companions.map((x) => x.project)); 234 | } 235 | 236 | for (const pkg of json.pkgs) { 237 | if (!projects_we_care_about.includes(pkg.pkg.project)) continue; 238 | 239 | for (const bin of ["bin", "sbin"]) { 240 | const bin_prefix = pkg.path.join(bin); 241 | if (!bin_prefix.exists()) continue; 242 | for await (const entry of Deno.readDir(bin_prefix.string)) { 243 | if (!entry.isFile && !entry.isSymlink) continue; 244 | const name = entry.name; 245 | const quick_shim = Deno.build.os == "darwin" && 246 | pkgx == "/usr/local/bin/pkgx"; 247 | const interpreter = quick_shim 248 | ? "/usr/local/bin/pkgx" 249 | : "/usr/bin/env -S pkgx"; 250 | 251 | const range = args_pkgs[pkg.pkg.project]; 252 | const arg = `${pkg.pkg.project}${`${range}` == "*" ? "" : `${range}`}`; 253 | 254 | const shim = `#!${interpreter} --shebang --quiet +${arg} -- ${name}`; 255 | 256 | if (existsSync(join(basePath, "bin", name))) { 257 | await Deno.remove(join(basePath, "bin", name)); 258 | } 259 | 260 | // without the newline zsh on macOS fails to invoke the interpreter with a bad interpreter error 261 | await Deno.writeTextFile(join(basePath, "bin", name), shim + "\n", { 262 | mode: 0o755, 263 | }); 264 | 265 | console.error(join(basePath, "bin", name)); 266 | } 267 | } 268 | } 269 | } 270 | 271 | interface JsonResponse { 272 | runtime_env: Record>; 273 | pkgs: Installation[]; 274 | env: Record>; 275 | pkg: Installation; 276 | } 277 | 278 | async function query_pkgx( 279 | pkgx: string, 280 | args: string[], 281 | ): Promise<[JsonResponse, Record]> { 282 | args = args.map((x) => `+${x}`); 283 | 284 | const env: Record = { 285 | "PATH": standardPath(), 286 | }; 287 | const set = (key: string) => { 288 | const x = Deno.env.get(key); 289 | if (x) env[key] = x; 290 | }; 291 | set("HOME"); 292 | set("PKGX_DIR"); 293 | set("PKGX_PANTRY_DIR"); 294 | set("PKGX_DIST_URL"); 295 | set("XDG_DATA_HOME"); 296 | 297 | const needs_sudo_backwards = install_prefix().string == "/usr/local"; 298 | let cmd = needs_sudo_backwards ? "/usr/bin/sudo" : pkgx; 299 | if (needs_sudo_backwards) { 300 | if (!Deno.env.get("SUDO_USER")) { 301 | if (Deno.uid() == 0) { 302 | console.error( 303 | "%cwarning", 304 | "color:yellow", 305 | "installing as root; installing via `sudo` is preferred", 306 | ); 307 | } 308 | cmd = pkgx; 309 | } else { 310 | args.unshift("-u", Deno.env.get("SUDO_USER")!, pkgx); 311 | } 312 | } 313 | 314 | const proc = new Deno.Command(cmd, { 315 | args: [...args, "--json=v1"], 316 | stdout: "piped", 317 | env, 318 | clearEnv: true, 319 | }) 320 | .spawn(); 321 | 322 | const status = await proc.status; 323 | 324 | if (!status.success) { 325 | Deno.exit(status.code); 326 | } 327 | 328 | const out = await proc.output(); 329 | const json = JSON.parse(new TextDecoder().decode(out.stdout)); 330 | 331 | const pkgs = 332 | (json.pkgs as { path: string; project: string; version: string }[]).map( 333 | (x) => { 334 | return { 335 | path: new Path(x.path), 336 | pkg: { project: x.project, version: new SemVer(x.version) }, 337 | }; 338 | }, 339 | ); 340 | const pkg = pkgs.find((x) => `+${x.pkg.project}` == args[0])!; 341 | return [{ 342 | pkg, 343 | pkgs, 344 | env: json.env, 345 | runtime_env: json.runtime_env, 346 | }, env]; 347 | } 348 | 349 | async function mirror_directory(dst: string, src: string, prefix: string) { 350 | await processEntry(join(src, prefix), join(dst, prefix)); 351 | 352 | async function processEntry(sourcePath: string, targetPath: string) { 353 | const fileInfo = await Deno.lstat(sourcePath); 354 | 355 | if (fileInfo.isDirectory) { 356 | // Create the target directory 357 | await ensureDir(targetPath); 358 | 359 | // Recursively process the contents of the directory 360 | for await (const entry of Deno.readDir(sourcePath)) { 361 | const entrySourcePath = join(sourcePath, entry.name); 362 | const entryTargetPath = join(targetPath, entry.name); 363 | await processEntry(entrySourcePath, entryTargetPath); 364 | } 365 | } else if (fileInfo.isFile) { 366 | // Remove the target file if it exists 367 | if (existsSync(targetPath)) { 368 | await Deno.remove(targetPath); 369 | } 370 | // Create a hard link for files 371 | await Deno.link(sourcePath, targetPath); 372 | } else if (fileInfo.isSymlink) { 373 | // Recreate symlink in the target directory 374 | const linkTarget = await Deno.readLink(sourcePath); 375 | symlink_with_overwrite(linkTarget, targetPath); 376 | } else { 377 | throw new Error(`unsupported file type at: ${sourcePath}`); 378 | } 379 | } 380 | } 381 | 382 | async function symlink(src: string, dst: string) { 383 | for ( 384 | const base of [ 385 | "bin", 386 | "sbin", 387 | "share", 388 | "lib", 389 | "libexec", 390 | "var", 391 | "etc", 392 | "ssl", // FIXME for ca-certs 393 | ] 394 | ) { 395 | const foo = join(src, base); 396 | if (existsSync(foo)) { 397 | await processEntry(foo, join(dst, base)); 398 | } 399 | } 400 | 401 | async function processEntry(sourcePath: string, targetPath: string) { 402 | const fileInfo = await Deno.lstat(sourcePath); 403 | 404 | if (fileInfo.isDirectory) { 405 | // Create the target directory 406 | await ensureDir(targetPath); 407 | 408 | // Recursively process the contents of the directory 409 | for await (const entry of Deno.readDir(sourcePath)) { 410 | const entrySourcePath = join(sourcePath, entry.name); 411 | const entryTargetPath = join(targetPath, entry.name); 412 | await processEntry(entrySourcePath, entryTargetPath); 413 | } 414 | } else { 415 | // resinstall 416 | if (existsSync(targetPath)) { 417 | await Deno.remove(targetPath); 418 | } 419 | symlink_with_overwrite(sourcePath, targetPath); 420 | } 421 | } 422 | } 423 | 424 | //FIXME we only do major as that's typically all pkgs need, but like we should do better 425 | async function create_v_symlinks(prefix: string) { 426 | const shelf = dirname(prefix); 427 | 428 | const versions = []; 429 | for await (const { name, isDirectory, isSymlink } of Deno.readDir(shelf)) { 430 | if (isSymlink) continue; 431 | if (!isDirectory) continue; 432 | if (name == "var") continue; 433 | if (!name.startsWith("v")) continue; 434 | if (/^v\d+$/.test(name)) continue; // pcre.org/v2 435 | const version = semver.parse(name); 436 | if (version) { 437 | versions.push(version); 438 | } 439 | } 440 | 441 | // collect an Record of versions per major version 442 | const major_versions: Record = {}; 443 | for (const version of versions) { 444 | if ( 445 | major_versions[version.major] === undefined || 446 | version.gt(major_versions[version.major]) 447 | ) { 448 | major_versions[version.major] = version; 449 | } 450 | } 451 | 452 | for (const [key, semver] of Object.entries(major_versions)) { 453 | symlink_with_overwrite(`v${semver}`, join(shelf, `v${key}`)); 454 | } 455 | } 456 | 457 | function expand_runtime_env( 458 | json: JsonResponse, 459 | basePath: string, 460 | ) { 461 | const { runtime_env, pkgs } = json; 462 | 463 | //FIXME this combines all runtime env which is strictly overkill 464 | // for transitive deps that may not need it 465 | 466 | const expanded: Record> = {}; 467 | for (const [_project, env] of Object.entries(runtime_env)) { 468 | for (const [key, value] of Object.entries(env)) { 469 | const pkg = pkgs.find((x) => x.pkg.project == _project)!.pkg; 470 | const mm = hooks.useMoustaches().tokenize.all(pkg, json.pkgs); 471 | const new_value = hooks.useMoustaches().apply(value, mm); 472 | expanded[key] ??= new Set(); 473 | expanded[key].add(new_value); 474 | } 475 | } 476 | 477 | // fix https://github.com/pkgxdev/pkgm/pull/30#issuecomment-2678957666 478 | if (Deno.build.os == "linux") { 479 | expanded["LD_LIBRARY_PATH"] ??= new Set(); 480 | expanded["LD_LIBRARY_PATH"].add(`${basePath}/lib`); 481 | } 482 | 483 | const rv: Record = {}; 484 | for (const [key, set] of Object.entries(expanded)) { 485 | rv[key] = [...set].join(":"); 486 | } 487 | 488 | // DUMB but easiest way to fix a bug 489 | const rv2: Record> = {}; 490 | for (const { pkg: { project } } of json.pkgs) { 491 | rv2[project] = rv; 492 | } 493 | 494 | return rv2; 495 | } 496 | 497 | function symlink_with_overwrite(src: string, dst: string) { 498 | if (existsSync(dst) && Deno.lstatSync(dst).isSymlink) { 499 | Deno.removeSync(dst); 500 | } 501 | Deno.symlinkSync(src, dst); 502 | } 503 | 504 | function get_pkgx() { 505 | for (const path of Deno.env.get("PATH")!.split(":")) { 506 | const pkgx = join(path, "pkgx"); 507 | if (existsSync(pkgx)) { 508 | const out = new Deno.Command(pkgx, { args: ["--version"] }).outputSync(); 509 | const stdout = new TextDecoder().decode(out.stdout); 510 | const match = stdout.match(/^pkgx (\d+.\d+)/); 511 | if (!match || parseFloat(match[1]) < 2.4) { 512 | Deno.exit(1); 513 | } 514 | return pkgx; 515 | } 516 | } 517 | throw new Error("no `pkgx` found in `$PATH`"); 518 | } 519 | 520 | async function* ls() { 521 | for ( 522 | const path of [new Path("/usr/local/pkgs"), Path.home().join(".local/pkgs")] 523 | ) { 524 | if (!path.isDirectory()) continue; 525 | const dirs = [path]; 526 | let dir: Path | undefined; 527 | while ((dir = dirs.pop()) != undefined) { 528 | for await (const [path, { name, isDirectory, isSymlink }] of dir.ls()) { 529 | if (!isDirectory || isSymlink) continue; 530 | if (/^v\d+\./.test(name)) { 531 | yield path; 532 | } else { 533 | dirs.push(path); 534 | } 535 | } 536 | } 537 | } 538 | } 539 | 540 | async function uninstall(arg: string) { 541 | let found: { project: string } | undefined = 542 | (await hooks.usePantry().find(arg))?.[0]; 543 | if (!found) { 544 | found = await plumbing.which(arg); 545 | } 546 | if (!found) { 547 | console.error(`no such pkg: ${arg}`); 548 | return false; 549 | } 550 | 551 | const set = new Set(); 552 | const files: Path[] = []; 553 | let dirs: Path[] = []; 554 | const pkg_dirs: Path[] = []; 555 | const root = install_prefix(); 556 | const dir = root.join("pkgs", found.project); 557 | if (!dir.isDirectory()) { 558 | console.error(`not installed: ${dir}`); 559 | if ( 560 | root.string == "/usr/local" && 561 | Path.home().join(".local/pkgs", found.project).isDirectory() 562 | ) { 563 | console.error( 564 | `%c! rerun without \`sudo\` to uninstall ~/.local/pkgs/${found.project}`, 565 | "color:yellow", 566 | ); 567 | } else if (new Path("/usr/local/pkgs").join(found.project).isDirectory()) { 568 | console.error( 569 | `%c! rerun as \`sudo\` to uninstall /usr/local/pkgs/${found.project}`, 570 | "color:yellow", 571 | ); 572 | } 573 | return false; 574 | } 575 | 576 | console.error("%cuninstalling", "color:red", dir); 577 | 578 | pkg_dirs.push(dir); 579 | for await (const [pkgdir, { isDirectory }] of dir.ls()) { 580 | if (!isDirectory) continue; 581 | for await (const { path, isDirectory } of walk(pkgdir.string)) { 582 | const leaf = new Path(path).relative({ to: pkgdir }); 583 | const resolved_path = root.join(leaf); 584 | if (set.has(resolved_path.string)) continue; 585 | if (!resolved_path.exists()) continue; 586 | if (isDirectory) { 587 | dirs.push(resolved_path); 588 | } else { 589 | files.push(resolved_path); 590 | } 591 | } 592 | } 593 | 594 | // we need to delete this in a heirachical fashion or they don’t delete 595 | dirs = dirs.sort().reverse(); 596 | 597 | if (files.length == 0) { 598 | console.error("unexpectedly not installed"); 599 | Deno.exit(1); 600 | } 601 | for (const path of files) { 602 | if (!path.isDirectory()) { 603 | Deno.removeSync(path.string); 604 | } 605 | } 606 | for (const path of dirs) { 607 | if (path.isDirectory()) { 608 | try { 609 | Deno.removeSync(path.string); 610 | } catch { 611 | // some dirs will not be removable 612 | } 613 | } 614 | } 615 | for (const path of pkg_dirs) { 616 | Deno.removeSync(path.string, { recursive: true }); 617 | } 618 | 619 | return true; 620 | } 621 | 622 | function writable(path: string) { 623 | try { 624 | //FIXME this is pretty gross 625 | Deno.mkdirSync(join(path, ".writable_test"), { recursive: true }); 626 | Deno.remove(join(path, ".writable_test")); 627 | return true; 628 | } catch { 629 | return false; 630 | } 631 | } 632 | 633 | async function outdated() { 634 | const pkgs: Installation[] = []; 635 | for await (const pkg of walk_pkgs(new Path("/usr/local/pkgs"))) { 636 | pkgs.push(pkg); 637 | } 638 | for await (const pkg of walk_pkgs(Path.home().join(".local/pkgs"))) { 639 | pkgs.push(pkg); 640 | } 641 | 642 | const { pkgs: raw_graph } = await hydrate( 643 | pkgs.map((x) => ({ 644 | project: x.pkg.project, 645 | constraint: new semver.Range(`^${x.pkg.version}`), 646 | })), 647 | ); 648 | const graph: Record = {}; 649 | for (const { project, constraint } of raw_graph) { 650 | graph[project] = constraint; 651 | } 652 | 653 | for (const { path, pkg } of pkgs) { 654 | const versions = await hooks.useInventory().get(pkg); 655 | // console.log(pkg, graph[pkg.project]); 656 | const constrained_versions = versions.filter((x) => 657 | graph[pkg.project].satisfies(x) && x.gt(pkg.version) 658 | ); 659 | if (constrained_versions.length) { 660 | console.log( 661 | pkg.project, 662 | "is outdated", 663 | pkg.version, 664 | "<", 665 | constrained_versions.slice(-1)[0], 666 | `\x1b[2m${path}\x1b[22m`, 667 | ); 668 | } 669 | } 670 | } 671 | 672 | async function* walk_pkgs(root: Path) { 673 | const dirs = [root]; 674 | let dir: Path | undefined; 675 | while ((dir = dirs.pop()) !== undefined) { 676 | if (!dir.isDirectory()) continue; 677 | for await (const [path, { name, isSymlink, isDirectory }] of dir.ls()) { 678 | if (isSymlink || !isDirectory) continue; 679 | if (semver.parse(name)) { 680 | const project = path.parent().relative({ to: root }); 681 | const version = new SemVer(path.basename()); 682 | yield { path, pkg: { project, version } }; 683 | } else { 684 | dirs.push(path); 685 | } 686 | } 687 | } 688 | } 689 | 690 | async function update() { 691 | const pkgs: Installation[] = []; 692 | for await (const pkg of walk_pkgs(install_prefix().join("pkgs"))) { 693 | pkgs.push(pkg); 694 | } 695 | 696 | const { pkgs: raw_graph } = await hydrate( 697 | pkgs.map((x) => ({ 698 | project: x.pkg.project, 699 | constraint: new semver.Range(`^${x.pkg.version}`), 700 | })), 701 | ); 702 | const graph: Record = {}; 703 | for (const { project, constraint } of raw_graph) { 704 | graph[project] = constraint; 705 | } 706 | 707 | const update_list = []; 708 | 709 | for (const { pkg } of pkgs) { 710 | const versions = await hooks.useInventory().get(pkg); 711 | const constrained_versions = versions.filter((x) => 712 | graph[pkg.project].satisfies(x) && x.gt(pkg.version) 713 | ); 714 | 715 | if (constrained_versions.length) { 716 | const pkgspec = `${pkg.project}=${constrained_versions.slice(-1)[0]}`; 717 | update_list.push(pkgspec); 718 | } 719 | } 720 | 721 | for (const pkgspec of update_list) { 722 | const pkg = utils.pkg.parse(pkgspec); 723 | console.log( 724 | "updating:", 725 | new Path("/usr/local/pkgs").join(pkg.project), 726 | "to", 727 | pkg.constraint.single(), 728 | ); 729 | } 730 | 731 | await install(update_list, install_prefix().string); 732 | } 733 | 734 | function install_prefix() { 735 | // if /usr/local is writable, use that 736 | if (writable("/usr/local")) { 737 | return new Path("/usr/local"); 738 | } else { 739 | return Path.home().join(".local"); 740 | } 741 | } 742 | 743 | function dev_stub_text(selfpath: string, bin_prefix: string, name: string) { 744 | if (selfpath.startsWith("/usr/local") && selfpath != "/usr/local/bin/dev") { 745 | return ` 746 | dev_check() { 747 | [ -x /usr/local/bin/dev ] || return 1 748 | local d="$PWD" 749 | until [ "$d" = / ]; do 750 | if [ -f "${datadir()}/pkgx/dev/$d/dev.pkgx.activated" ]; then 751 | echo $d 752 | return 0 753 | fi 754 | d="$(dirname "$d")" 755 | done 756 | return 1 757 | } 758 | 759 | if d="$(dev_check)"; then 760 | eval "$(/usr/local/bin/dev "$d" 2>/dev/null)" 761 | [ "$(command -v ${name} 2>/dev/null)" != "${selfpath}" ] && exec ${name} "$@" 762 | fi 763 | 764 | exec ${bin_prefix}/${name} "$@" 765 | `.trim(); 766 | } else { 767 | return `exec ${bin_prefix}/${name} "$@"`; 768 | } 769 | } 770 | 771 | function datadir() { 772 | const default_data_home = Deno.build.os == "darwin" 773 | ? "/Library/Application Support" 774 | : "/.local/share"; 775 | return `\${XDG_DATA_HOME:-$HOME${default_data_home}}`; 776 | } 777 | -------------------------------------------------------------------------------- /pkgx.yaml: -------------------------------------------------------------------------------- 1 | dependencies: deno^2 2 | -------------------------------------------------------------------------------- /tea.yaml: -------------------------------------------------------------------------------- 1 | # https://tea.xyz/what-is-this-file 2 | # 3 | # DO NOT REMOVE OR EDIT THIS WARNING: 4 | # 5 | # This file is auto-generated by the TEA app. It is intended to validate ownership of your repository. 6 | # DO NOT commit this file or accept any PR if you don't know what this is. 7 | # We are aware that spammers will try to use this file to try to profit off others' work. 8 | # We take this very seriously and will take action against any malicious actors. 9 | # 10 | # If you are not the owner of this repository, and someone maliciously opens a commit with this file 11 | # please report it to us at support@tea.xyz. 12 | # 13 | # A constitution without this header is invalid. 14 | --- 15 | version: 2.0.0 16 | codeOwners: 17 | - '0x060F08FE34282a3783D2544A1f0804d9FEaAb283' 18 | quorum: 1 19 | --------------------------------------------------------------------------------