-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathpkgm.ts
More file actions
executable file
·1003 lines (887 loc) · 29.4 KB
/
pkgm.ts
File metadata and controls
executable file
·1003 lines (887 loc) · 29.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/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
import {
hooks,
Installation,
Path,
plumbing,
SemVer,
semver,
utils,
} from "https://deno.land/x/libpkgx@v0.21.0/mod.ts";
import { dirname, join } from "jsr:@std/path@^1";
import { ensureDir, existsSync, walk } from "jsr:@std/fs@^1";
import { parseArgs } from "jsr:@std/cli@^1";
const { hydrate } = plumbing;
// Module-scope SemVer literal: must be defined before any function that
// reads it can be called from top-level code below. `const` declarations
// are hoisted in name only (TDZ), so placing this further down the file
// triggered "Cannot access 'PKGX_MIN_VERSION' before initialization" once
// install()/get_pkgx() ran at module-init time.
const PKGX_MIN_VERSION = new SemVer("2.4.0");
function standardPath() {
let path = "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin";
// for pkgx installed via homebrew
let homebrewPrefix = "";
switch (Deno.build.os) {
case "darwin":
homebrewPrefix = "/opt/homebrew"; // /usr/local is already in the path
break;
case "linux":
homebrewPrefix = `/home/linuxbrew/.linuxbrew:${
Deno.env.get(
"HOME",
)
}/.linuxbrew`;
break;
}
if (homebrewPrefix) {
homebrewPrefix = Deno.env.get("HOMEBREW_PREFIX") ?? homebrewPrefix;
path = `${homebrewPrefix}/bin:${path}`;
}
return path;
}
const parsedArgs = parseArgs(Deno.args, {
alias: {
v: "version",
h: "help",
p: "pin",
},
boolean: ["help", "version", "pin"],
});
if (parsedArgs.help || parsedArgs._[0] == "help") {
const { code } = await new Deno.Command("pkgx", {
args: [
"glow",
"https://raw.githubusercontent.com/pkgxdev/pkgm/refs/heads/main/README.md",
],
}).spawn().status;
Deno.exit(code);
} else if (parsedArgs.version) {
console.log("pkgm 0.0.0+dev");
} else {
const args = parsedArgs._.map((x) => `${x}`).slice(1);
switch (parsedArgs._[0]) {
case "install":
case "i":
{
const rv = await install(args, install_prefix().string);
console.log(rv.join("\n"));
}
break;
case "local-install":
case "li":
if (install_prefix().string != "/usr/local") {
await install(args, Path.home().join(".local").string);
} else {
console.error("deprecated: use `pkgm install` without `sudo` instead");
}
break;
case "stub":
case "shim":
// equivalent to `pkgx^1 install`
// shims often work just fine, but sometimes don’t.
// when they don’t it is usually because the consuming tool makes assumptions about
// where files for the package in question reside.
await shim(args, install_prefix().string);
break;
case "uninstall":
case "rm":
{
let all_success = true;
for (const arg of args) {
if (!(await uninstall(arg))) {
all_success = false;
}
}
Deno.exit(all_success ? 0 : 1);
}
break;
case "list":
case "ls":
for await (const path of ls()) {
console.log(path);
}
break;
case "up":
case "update":
case "upgrade":
await update();
break;
case "pin":
console.error("%cU EARLY! soz, not implemented", "color:red");
Deno.exit(1);
break;
case "outdated":
await outdated();
break;
default:
if (Deno.args.length === 0) {
console.error("https://github.com/pkgxdev/pkgm");
} else {
console.error("invalid usage");
}
Deno.exit(2);
}
}
async function install(args: string[], basePath: string) {
if (args.length === 0) {
console.error("no packages specified");
Deno.exit(1);
}
const pkgx = get_pkgx();
const [json] = await query_pkgx(pkgx, args);
const pkg_prefixes = json.pkgs.map(
(x) => `${x.pkg.project}/v${x.pkg.version}`,
);
// get the pkgx_dir this way as it is a) more reliable and b) the only way if
// we are running as sudo on linux since it doesn’t give us a good way to get
// the home directory of the pre-sudo user
const pkgx_dir = (() => {
const { path, pkg } = json.pkgs[0]!;
const remove = pkg.project + "/v" + pkg.version;
return path.string.slice(0, -remove.length - 1);
})();
const runtime_env = expand_runtime_env(json, basePath);
const dst = basePath;
for (const pkg_prefix of pkg_prefixes) {
// create ${dst}/pkgs/${prefix}
await mirror_directory(join(dst, "pkgs"), pkgx_dir, pkg_prefix);
// symlink ${dst}/pkgs/${prefix} to ${dst}
if (!pkg_prefix.startsWith("pkgx.sh/v")) {
// ^^ don’t overwrite ourselves
// ^^ * https://github.com/pkgxdev/pkgm/issues/14
// ^^ * https://github.com/pkgxdev/pkgm/issues/17
await symlink(join(dst, "pkgs", pkg_prefix), dst);
}
// create v1, etc. symlinks
await create_v_symlinks(join(dst, "pkgs", pkg_prefix));
}
const rv = [];
for (const [project, env] of Object.entries(runtime_env)) {
if (project == "pkgx.sh") continue;
const pkg_prefix = pkg_prefixes.find((x) => x.startsWith(project))!;
if (!pkg_prefix) continue; //FIXME wtf?
for (const bin of ["bin", "sbin"]) {
const bin_prefix = join(`${dst}/pkgs`, pkg_prefix, bin);
if (!existsSync(bin_prefix)) continue;
for await (const entry of Deno.readDir(bin_prefix)) {
if (!entry.isFile) continue;
const to_stub = join(dst, bin, entry.name);
let sh = `#!/bin/sh\n`;
for (const [key, value] of Object.entries(env)) {
sh += `export ${key}="${value}"\n`;
}
sh += "\n";
//TODO should be specific with the project
sh += dev_stub_text(to_stub, bin_prefix, entry.name);
await Deno.remove(to_stub); //FIXME inefficient to symlink for no reason
await Deno.writeTextFile(to_stub, sh.trim() + "\n");
await Deno.chmod(to_stub, 0o755);
rv.push(to_stub);
}
}
}
if (
!Deno.env
.get("PATH")
?.split(":")
?.includes(new Path(basePath).join("bin").string)
) {
console.error(
"%c! warning:",
"color:yellow",
`${new Path(basePath).join("bin")} not in $PATH`,
);
}
return rv;
}
async function shim(args: string[], basePath: string) {
const pkgx = get_pkgx();
await ensureDir(join(basePath, "bin"));
const json = (await query_pkgx(pkgx, args))[0];
const args_pkgs: Record<string, semver.Range> = {};
const projects_we_care_about: string[] = [];
for (const arg of args) {
const pkgs = await hooks.usePantry().find(arg);
if (pkgs.length == 0) throw new Error(`no such pkg: ${arg}`);
if (pkgs.length > 1) throw new Error(`ambiguous pkg: ${arg}`);
args_pkgs[pkgs[0].project] = utils.pkg.parse(arg).constraint;
projects_we_care_about.push(pkgs[0].project);
const companions = await hooks.usePantry().project(pkgs[0]).companions();
projects_we_care_about.push(...companions.map((x) => x.project));
}
for (const pkg of json.pkgs) {
if (!projects_we_care_about.includes(pkg.pkg.project)) continue;
for (const bin of ["bin", "sbin"]) {
const bin_prefix = pkg.path.join(bin);
if (!bin_prefix.exists()) continue;
for await (const entry of Deno.readDir(bin_prefix.string)) {
if (!entry.isFile && !entry.isSymlink) continue;
const name = entry.name;
const quick_shim = Deno.build.os == "darwin" &&
pkgx == "/usr/local/bin/pkgx";
const interpreter = quick_shim
? "/usr/local/bin/pkgx"
: "/usr/bin/env -S pkgx";
const range = args_pkgs[pkg.pkg.project];
const arg = `${pkg.pkg.project}${`${range}` == "*" ? "" : `${range}`}`;
const shim = `#!${interpreter} --shebang --quiet +${arg} -- ${name}`;
if (existsSync(join(basePath, "bin", name))) {
await Deno.remove(join(basePath, "bin", name));
}
// without the newline zsh on macOS fails to invoke the interpreter with a bad interpreter error
await Deno.writeTextFile(join(basePath, "bin", name), shim + "\n", {
mode: 0o755,
});
console.error(join(basePath, "bin", name));
}
}
}
}
interface JsonResponse {
runtime_env: Record<string, Record<string, string>>;
pkgs: Installation[];
env: Record<string, Record<string, string>>;
pkg: Installation;
}
async function query_pkgx(
pkgx: string,
args: string[],
): Promise<[JsonResponse, Record<string, string>]> {
args = args.map((x) => `+${x}`);
const env: Record<string, string> = {
PATH: standardPath(),
};
const set = (key: string) => {
const x = Deno.env.get(key);
if (x) env[key] = x;
};
set("HOME");
set("PKGX_DIR");
set("PKGX_PANTRY_DIR");
set("PKGX_DIST_URL");
set("XDG_DATA_HOME");
const isRoot = Deno.uid() == 0;
const sudoUser = Deno.env.get("SUDO_USER");
const prefix = install_prefix().string;
const isSystemPrefix = prefix == "/usr/local";
let cmd = pkgx;
let cmd_args = args;
if (isSystemPrefix) {
if (isRoot && sudoUser) {
const sudo_user_home = user_home(sudoUser);
// If sudo preserved HOME (typical macOS — sudoers keeps HOME in
// env_keep by default; most Linux distros reset it via env_reset),
// the shebang's outer `pkgx --quiet deno^2.1 run …` ran as root
// with HOME pointing at SUDO_USER's tree and its self-cache left
// root-owned dirs under $SUDO_USER/.pkgx. The privilege-dropped
// inner pkgx below would then EACCES on those dirs and abort the
// install. Reclaim ownership for $SUDO_USER so the install can
// proceed without forcing the user to remember `sudo -H`.
if (sudo_user_home && Deno.env.get("HOME") === sudo_user_home) {
reclaim_pkgx_cache_for(sudo_user_home, sudoUser);
}
// Drop privileges so pkgx writes its cache as the invoking user, not root.
// But only if pkgx is reachable from sudoUser — otherwise the inner sudo
// aborts with "unable to execute …: Permission denied" (pkgxdev/pkgm#68).
const reachable = pkgx_reachable_as(pkgx, sudoUser);
if (reachable) {
cmd = "/usr/bin/sudo";
cmd_args = ["-u", sudoUser, "--", reachable, ...args];
// Override HOME, or pkgx will cache back under /root/ where sudoUser
// can't reach it on the next invocation.
if (sudo_user_home) env.HOME = sudo_user_home;
} else if (Deno.env.get("PKGM_DEBUG")) {
console.error(
`pkgm: \`pkgx\` at ${pkgx} is not reachable as ${sudoUser}; running it as root`,
);
}
} else if (isRoot) {
console.error(
"%cwarning",
"color:yellow",
"installing as root; installing via `sudo` is preferred",
);
}
}
const proc = new Deno.Command(cmd, {
args: [...cmd_args, "--json=v1"],
stdout: "piped",
env,
clearEnv: true,
}).spawn();
const status = await proc.status;
if (!status.success) {
Deno.exit(status.code);
}
const out = await proc.output();
const json = JSON.parse(new TextDecoder().decode(out.stdout));
const pkgs = (
json.pkgs as { path: string; project: string; version: string }[]
).map((x) => {
return {
path: new Path(x.path),
pkg: { project: x.project, version: new SemVer(x.version) },
};
});
const pkg = pkgs.find((x) => `+${x.pkg.project}` == args[0])!;
return [
{
pkg,
pkgs,
env: json.env,
runtime_env: json.runtime_env,
},
env,
];
}
async function mirror_directory(dst: string, src: string, prefix: string) {
let warned_copy_fallback = false;
await processEntry(join(src, prefix), join(dst, prefix));
async function processEntry(sourcePath: string, targetPath: string) {
const fileInfo = await Deno.lstat(sourcePath);
if (fileInfo.isDirectory) {
// Create the target directory
await ensureDir(targetPath);
// Recursively process the contents of the directory
for await (const entry of Deno.readDir(sourcePath)) {
const entrySourcePath = join(sourcePath, entry.name);
const entryTargetPath = join(targetPath, entry.name);
await processEntry(entrySourcePath, entryTargetPath);
}
} else if (fileInfo.isFile) {
// Remove the target file if it exists
if (existsSync(targetPath)) {
await Deno.remove(targetPath);
}
try {
await Deno.link(sourcePath, targetPath);
} catch {
if (!warned_copy_fallback) {
console.warn(
"%c! hardlinking failed (possibly cross-device?), falling back to file copy",
"color:yellow",
);
warned_copy_fallback = true;
}
await Deno.copyFile(sourcePath, targetPath);
}
} else if (fileInfo.isSymlink) {
// Recreate symlink in the target directory
const linkTarget = await Deno.readLink(sourcePath);
symlink_with_overwrite(linkTarget, targetPath);
} else {
throw new Error(`unsupported file type at: ${sourcePath}`);
}
}
}
async function symlink(src: string, dst: string) {
for (
const base of [
"bin",
"sbin",
"share",
"lib",
"libexec",
"var",
"etc",
"ssl", // FIXME for ca-certs
]
) {
const foo = join(src, base);
if (existsSync(foo)) {
await processEntry(foo, join(dst, base));
}
}
async function processEntry(sourcePath: string, targetPath: string) {
const fileInfo = await Deno.lstat(sourcePath);
if (fileInfo.isDirectory) {
// Create the target directory
await ensureDir(targetPath);
// Recursively process the contents of the directory
for await (const entry of Deno.readDir(sourcePath)) {
const entrySourcePath = join(sourcePath, entry.name);
const entryTargetPath = join(targetPath, entry.name);
await processEntry(entrySourcePath, entryTargetPath);
}
} else {
// resinstall
if (existsSync(targetPath)) {
await Deno.remove(targetPath);
}
symlink_with_overwrite(sourcePath, targetPath);
}
}
}
//FIXME we only do major as that's typically all pkgs need, but like we should do better
async function create_v_symlinks(prefix: string) {
const shelf = dirname(prefix);
const versions = [];
for await (const { name, isDirectory, isSymlink } of Deno.readDir(shelf)) {
if (isSymlink) continue;
if (!isDirectory) continue;
if (name == "var") continue;
if (!name.startsWith("v")) continue;
if (/^v\d+$/.test(name)) continue; // pcre.org/v2
const version = semver.parse(name);
if (version) {
versions.push(version);
}
}
// collect an Record of versions per major version
const major_versions: Record<number, SemVer> = {};
for (const version of versions) {
if (
major_versions[version.major] === undefined ||
version.gt(major_versions[version.major])
) {
major_versions[version.major] = version;
}
}
for (const [key, semver] of Object.entries(major_versions)) {
symlink_with_overwrite(`v${semver}`, join(shelf, `v${key}`));
}
}
function expand_runtime_env(json: JsonResponse, basePath: string) {
const { runtime_env, pkgs } = json;
//FIXME this combines all runtime env which is strictly overkill
// for transitive deps that may not need it
const expanded: Record<string, Set<string>> = {};
for (const [_project, env] of Object.entries(runtime_env)) {
for (const [key, value] of Object.entries(env)) {
const pkg = pkgs.find((x) => x.pkg.project == _project)!.pkg;
const mm = hooks.useMoustaches().tokenize.all(pkg, json.pkgs);
const new_value = hooks.useMoustaches().apply(value, mm);
expanded[key] ??= new Set<string>();
expanded[key].add(new_value);
}
}
// fix https://github.com/pkgxdev/pkgm/pull/30#issuecomment-2678957666
if (Deno.build.os == "linux") {
expanded["LD_LIBRARY_PATH"] ??= new Set<string>();
expanded["LD_LIBRARY_PATH"].add(`${basePath}/lib`);
}
const rv: Record<string, string> = {};
for (const [key, set] of Object.entries(expanded)) {
rv[key] = [...set].join(":");
}
// DUMB but easiest way to fix a bug
const rv2: Record<string, Record<string, string>> = {};
for (
const {
pkg: { project },
} of json.pkgs
) {
rv2[project] = rv;
}
return rv2;
}
function symlink_with_overwrite(src: string, dst: string) {
if (existsSync(dst) && Deno.lstatSync(dst).isSymlink) {
Deno.removeSync(dst);
}
Deno.symlinkSync(src, dst);
}
function pkgx_meets_minimum(path: string): boolean {
try {
const out = new Deno.Command(path, { args: ["--version"] }).outputSync();
if (!out.success) return false;
const match = new TextDecoder().decode(out.stdout).match(
/^pkgx (\d+\.\d+\.\d+)/,
);
if (!match) return false;
return new SemVer(match[1]).gte(PKGX_MIN_VERSION);
} catch {
return false;
}
}
function get_pkgx() {
for (const path of Deno.env.get("PATH")!.split(":")) {
const pkgx = join(path, "pkgx");
if (!existsSync(pkgx)) continue;
if (!pkgx_meets_minimum(pkgx)) Deno.exit(1);
return pkgx;
}
throw new Error("no `pkgx` found in `$PATH`");
}
async function* ls() {
for (
const path of [
new Path("/usr/local/pkgs"),
Path.home().join(".local/pkgs"),
]
) {
if (!path.isDirectory()) continue;
const dirs = [path];
let dir: Path | undefined;
while ((dir = dirs.pop()) != undefined) {
for await (const [path, { name, isDirectory, isSymlink }] of dir.ls()) {
if (!isDirectory || isSymlink) continue;
if (/^v\d+\./.test(name)) {
yield path;
} else {
dirs.push(path);
}
}
}
}
}
async function uninstall(arg: string) {
let found: { project: string } | undefined;
try {
found = (await hooks.usePantry().find(arg))?.[0];
} catch {
console.error(
"%c pantry not found, trying to find package another way",
"color:blue",
);
}
if (!found) {
found = await plumbing.which(arg);
}
if (!found) {
console.error(`no such pkg: ${arg}`);
return false;
}
const set = new Set<string>();
const files: Path[] = [];
let dirs: Path[] = [];
const pkg_dirs: Path[] = [];
const root = install_prefix();
const dir = root.join("pkgs", found.project);
if (!dir.isDirectory()) {
console.error(`not installed: ${dir}`);
if (
root.string == "/usr/local" &&
Path.home().join(".local/pkgs", found.project).isDirectory()
) {
console.error(
`%c! rerun without \`sudo\` to uninstall ~/.local/pkgs/${found.project}`,
"color:yellow",
);
} else if (new Path("/usr/local/pkgs").join(found.project).isDirectory()) {
console.error(
`%c! rerun as \`sudo\` to uninstall /usr/local/pkgs/${found.project}`,
"color:yellow",
);
}
return false;
}
console.error("%cuninstalling", "color:red", dir);
pkg_dirs.push(dir);
for await (const [pkgdir, { isDirectory }] of dir.ls()) {
if (!isDirectory) continue;
for await (const { path, isDirectory } of walk(pkgdir.string)) {
const leaf = new Path(path).relative({ to: pkgdir });
const resolved_path = root.join(leaf);
if (set.has(resolved_path.string)) continue;
if (!resolved_path.exists()) continue;
if (isDirectory) {
dirs.push(resolved_path);
} else {
files.push(resolved_path);
}
}
}
// we need to delete this in a heirachical fashion or they don’t delete
dirs = dirs.sort().reverse();
if (files.length == 0) {
console.error("unexpectedly not installed");
Deno.exit(1);
}
for (const path of files) {
if (!path.isDirectory()) {
Deno.removeSync(path.string);
}
}
for (const path of dirs) {
if (path.isDirectory()) {
try {
Deno.removeSync(path.string);
} catch {
// some dirs will not be removable
}
}
}
for (const path of pkg_dirs) {
Deno.removeSync(path.string, { recursive: true });
}
return true;
}
function writable(path: string) {
try {
//FIXME this is pretty gross
Deno.mkdirSync(join(path, ".writable_test"), { recursive: true });
Deno.remove(join(path, ".writable_test"));
return true;
} catch {
return false;
}
}
async function outdated() {
const pkgs: Installation[] = [];
for await (const pkg of walk_pkgs(new Path("/usr/local/pkgs"))) {
pkgs.push(pkg);
}
for await (const pkg of walk_pkgs(Path.home().join(".local/pkgs"))) {
pkgs.push(pkg);
}
const { pkgs: raw_graph } = await hydrate(
pkgs.map((x) => ({
project: x.pkg.project,
constraint: new semver.Range(`^${x.pkg.version}`),
})),
);
const graph: Record<string, semver.Range> = {};
for (const { project, constraint } of raw_graph) {
graph[project] = constraint;
}
for (const { path, pkg } of pkgs) {
const versions = await hooks.useInventory().get(pkg);
// console.log(pkg, graph[pkg.project]);
const constrained_versions = versions.filter(
(x) => graph[pkg.project].satisfies(x) && x.gt(pkg.version),
);
if (constrained_versions.length) {
console.log(
pkg.project,
"is outdated",
pkg.version,
"<",
constrained_versions.slice(-1)[0],
`\x1b[2m${path}\x1b[22m`,
);
}
}
}
async function* walk_pkgs(root: Path) {
const dirs = [root];
let dir: Path | undefined;
while ((dir = dirs.pop()) !== undefined) {
if (!dir.isDirectory()) continue;
for await (const [path, { name, isSymlink, isDirectory }] of dir.ls()) {
if (isSymlink || !isDirectory) continue;
if (semver.parse(name)) {
const project = path.parent().relative({ to: root });
const version = new SemVer(path.basename());
yield { path, pkg: { project, version } };
} else {
dirs.push(path);
}
}
}
}
async function update() {
const pkgs: Installation[] = [];
for await (const pkg of walk_pkgs(install_prefix().join("pkgs"))) {
pkgs.push(pkg);
}
const { pkgs: raw_graph } = await hydrate(
pkgs.map((x) => ({
project: x.pkg.project,
constraint: new semver.Range(`^${x.pkg.version}`),
})),
);
const graph: Record<string, semver.Range> = {};
for (const { project, constraint } of raw_graph) {
graph[project] = constraint;
}
const update_list = [];
for (const { pkg } of pkgs) {
const versions = await hooks.useInventory().get(pkg);
const constrained_versions = versions.filter(
(x) => graph[pkg.project].satisfies(x) && x.gt(pkg.version),
);
if (constrained_versions.length) {
const pkgspec = `${pkg.project}=${constrained_versions.slice(-1)[0]}`;
update_list.push(pkgspec);
}
}
for (const pkgspec of update_list) {
const pkg = utils.pkg.parse(pkgspec);
console.log(
"updating:",
new Path("/usr/local/pkgs").join(pkg.project),
"to",
pkg.constraint.single(),
);
}
await install(update_list, install_prefix().string);
}
function install_prefix() {
// if /usr/local is writable, use that
if (writable("/usr/local")) {
return new Path("/usr/local");
} else {
return Path.home().join(".local");
}
}
function user_home_from_passwd(user: string): string | undefined {
try {
const passwd = Deno.readTextFileSync("/etc/passwd");
for (const line of passwd.split("\n")) {
if (!line || line.startsWith("#")) continue;
const fields = line.split(":");
if (fields[0] === user) return fields[5] || undefined;
}
} catch {
// Ignore unreadable or absent passwd database and fall back to other lookups.
}
return undefined;
}
function user_home_from_dscl(user: string): string | undefined {
if (!existsSync("/usr/bin/dscl")) return undefined;
try {
const out = new Deno.Command("/usr/bin/dscl", {
args: [".", "-read", `/Users/${user}`, "NFSHomeDirectory"],
}).outputSync();
if (!out.success) return undefined;
const line = new TextDecoder().decode(out.stdout).trim();
const prefix = "NFSHomeDirectory:";
if (!line.startsWith(prefix)) return undefined;
const home = line.slice(prefix.length).trim();
return home || undefined;
} catch {
return undefined;
}
}
function user_home(user: string): string | undefined {
// Prefer getent where available, but fall back to passwd parsing and macOS
// dscl so HOME can still be resolved when dropping privileges on systems
// without getent.
const getent = existsSync("/usr/bin/getent")
? "/usr/bin/getent"
: existsSync("/bin/getent")
? "/bin/getent"
: undefined;
if (getent) {
try {
const out = new Deno.Command(getent, {
args: ["passwd", user],
}).outputSync();
if (out.success) {
const fields = new TextDecoder().decode(out.stdout).trim().split(":");
if (fields[5]) return fields[5];
}
} catch {
// Ignore getent lookup failures and try portable fallbacks below.
}
}
return user_home_from_passwd(user) ?? user_home_from_dscl(user);
}
function reclaim_pkgx_cache_for(home: string, user: string): void {
// Targeted chown: only files currently owned by root, not user-owned
// entries the caller may have placed under .pkgx for their own reasons.
// Best-effort — if find/chown aren't reachable the inner pkgx may still
// EACCES, but most invocations succeed.
const cache = join(home, ".pkgx");
if (!existsSync(cache)) return;
const find = existsSync("/usr/bin/find") ? "/usr/bin/find" : "/bin/find";
try {
new Deno.Command(find, {
args: [cache, "-uid", "0", "-exec", "chown", user, "{}", "+"],
stdout: "null",
stderr: "null",
}).outputSync();
} catch {
// best-effort
}
}
function pkgx_reachable_as(current: string, user: string): string | undefined {
// The caller has already enforced PKGX_MIN_VERSION for `current` via
// get_pkgx(); fallback candidates have not, so each return path below
// re-checks with pkgx_meets_minimum() to avoid handing back an
// unsupported binary (per #86 review).
if (reachable_as(current, user)) return current;
const home = user_home(user);
if (home) {
// Versioned pkgx.sh layout: ~/.pkgx/pkgx.sh/v<x.y.z>/bin/pkgx — pick the
// highest version that meets the minimum.
const root = join(home, ".pkgx/pkgx.sh");
if (existsSync(root)) {
let best: { v: SemVer; path: string } | undefined;
try {
if (Deno.statSync(root).isDirectory) {
for (const entry of Deno.readDirSync(root)) {
if (!entry.isDirectory || !entry.name.startsWith("v")) continue;
try {
const v = new SemVer(entry.name.slice(1));
if (v.lt(PKGX_MIN_VERSION)) continue;
const path = join(root, entry.name, "bin/pkgx");
if (!existsSync(path)) continue;
// Directory-name version is a cheap pre-filter; verify the
// actual binary too, matching the other fallback paths so a
// stale or non-executable `v*/bin/pkgx` can't be returned
// (per #86 review).
if (!pkgx_meets_minimum(path)) continue;
if (!best || v.gt(best.v)) best = { v, path };
} catch {
// skip malformed version dir
}
}
}
} catch {
// Ignore unreadable/non-directory pkgx.sh roots and fall back to other locations.
}
if (best) return best.path;
}
const local = join(home, ".local/bin/pkgx");
if (existsSync(local) && pkgx_meets_minimum(local)) return local;
}
if (
existsSync("/usr/local/bin/pkgx") &&
pkgx_meets_minimum("/usr/local/bin/pkgx")
) {
return "/usr/local/bin/pkgx";
}
return undefined;
}
function reachable_as(p: string, user: string): boolean {
// Conservative heuristic: private home dirs are typically mode 700, so a
// path under another user's home is unreachable. System paths and the
// user's own home are assumed reachable.
const home = user_home(user);
if (home && (p === home || p.startsWith(`${home}/`))) return true;
// Shared Linuxbrew prefix lives under /home but is world-traversable and
// is treated as a system pkgx location by standardPath(). Without this
// exemption a pkgx installed via Linuxbrew would force the root-execution
// fallback, recreating the root-owned cache problem this code avoids
// (per #86 review). Honour $HOMEBREW_PREFIX in case it's elsewhere.
const brew = Deno.env.get("HOMEBREW_PREFIX") ?? "/home/linuxbrew/.linuxbrew";
if (p === brew || p.startsWith(`${brew}/`)) return true;
if (p === "/root" || p.startsWith("/root/")) return false;
if (p === "/var/root" || p.startsWith("/var/root/")) return false;
if (p.match(/^\/(home|Users)\/([^/]+)(?:\/|$)/)) return false;
return true;
}
function dev_stub_text(selfpath: string, bin_prefix: string, name: string) {
if (selfpath.startsWith("/usr/local") && selfpath != "/usr/local/bin/dev") {
return `
dev_check() {
[ -x /usr/local/bin/dev ] || return 1
local d="$PWD"
until [ "$d" = / ]; do
if [ -f "${datadir()}/pkgx/dev/$d/dev.pkgx.activated" ]; then
echo $d
return 0
fi
d="$(dirname "$d")"
done
return 1
}
if d="$(dev_check)"; then
eval "$(/usr/local/bin/dev "$d" 2>/dev/null)"
[ "$(command -v ${name} 2>/dev/null)" != "${selfpath}" ] && exec ${name} "$@"
fi
exec ${bin_prefix}/${name} "$@"
`.trim();
} else {
return `exec ${bin_prefix}/${name} "$@"`;
}
}
function datadir() {
const default_data_home = Deno.build.os == "darwin"
? "/Library/Application Support"