-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpkgm.ts
executable file
·280 lines (245 loc) · 8.07 KB
/
pkgm.ts
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
#!/usr/bin/env -S pkgx deno^2.1 run --ext=ts --allow-sys=uid --allow-run=pkgx,/usr/bin/sudo --allow-env=PKGX_DIR,HOME --allow-read=/usr/local/pkgs
import { dirname, fromFileUrl, join } from "jsr:@std/path@^1";
import { ensureDir, existsSync } from "jsr:@std/fs@^1";
import { parse as parse_args } from "jsr:@std/flags@0.224.0";
import * as semver from "jsr:@std/semver@^1";
const parsedArgs = parse_args(Deno.args, {
alias: {
v: "version",
h: "help",
p: "pin",
},
boolean: ["help", "version", "pin"],
});
if (parsedArgs.help) {
const status = await new Deno.Command("pkgx", {
args: ["gh", "repo", "view", "pkgxdev/pkgm"],
clearEnv: true,
env: {
"PATH": "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin",
"HOME": Deno.env.get("HOME")!,
},
}).spawn().status;
Deno.exit(status.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":
await install(args);
break;
case "uninstall":
case "rm":
case "list":
case "ls":
case "up":
case "update":
case "pin":
case "outdated":
case "stub":
console.error("%cunimplemented. soz. U EARLY.", "color: red");
Deno.exit(1);
break;
case "sudo-install": {
const [pkgx_dir, runtime_env, ...paths] = args;
const parsed_runtime_env = JSON.parse(runtime_env) as Record<
string,
Record<string, string>
>;
await sudo_install(pkgx_dir, paths, parsed_runtime_env);
break;
}
default:
console.error("invalid usage");
Deno.exit(2);
}
}
async function install(args: string[]) {
if (args.length === 0) {
console.error("no packages specified");
Deno.exit(1);
}
args = args.map((x) => `+${x}`);
const env: Record<string, string> = {
"PATH": "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin",
};
const set = (key: string) => {
const x = Deno.env.get(key);
if (x) env[key] = x;
};
set("HOME");
set("PKGX_DIR");
const proc = new Deno.Command("pkgx", {
args: [...args, "--json"],
stdout: "piped",
env,
clearEnv: true,
})
.spawn();
let 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));
// deno-lint-ignore no-explicit-any
const pkg_prefixes = json.pkgs.map((x: any) => `${x.project}/v${x.version}`);
const to_install = [];
for (const prefix of pkg_prefixes) {
if (!existsSync(join("/usr/local/pkgs", prefix))) {
to_install.push(prefix);
}
}
if (to_install.length === 0) {
console.error("pkgs already installed");
Deno.exit(0);
}
const self = fromFileUrl(import.meta.url);
const pkgx_dir = Deno.env.get("PKGX_DIR") || `${Deno.env.get("HOME")}/.pkgx`;
const needs_sudo = Deno.uid() != 0;
const runtime_env = expand_runtime_env(json.runtime_env);
args = [
"pkgx",
"deno^2.1",
"run",
"--ext=ts",
"--allow-write", // cannot be qualified ∵ `Deno.link()` requires full access for some reason
"--allow-read", // same ^^ 😕
self,
"sudo-install",
pkgx_dir,
runtime_env,
...to_install,
];
const cmd = needs_sudo ? "/usr/bin/sudo" : args.shift()!;
status = await new Deno.Command(cmd, { args, env, clearEnv: true })
.spawn().status;
Deno.exit(status.code);
}
async function sudo_install(
pkgx_dir: string,
pkg_prefixes: string[],
runtime_env: Record<string, Record<string, string>>,
) {
const dst = "/usr/local";
for (const pkg_prefix of pkg_prefixes) {
// create /usr/local/pkgs/${prefix}
await mirror_directory("/usr/local/pkgs", pkgx_dir, pkg_prefix);
// symlink /usr/local/pkgs/${prefix} to /usr/local
await symlink(join("/usr/local/pkgs", pkg_prefix), dst);
// create v1, etc. symlinks
await create_v_symlinks(join("/usr/local/pkgs", pkg_prefix));
}
for (const [project, env] of Object.entries(runtime_env)) {
const pkg_prefix = pkg_prefixes.find((x) => x.startsWith(project))!;
for (const bin of ["bin", "sbin"]) {
const bin_prefix = join("/usr/local/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("/usr/local", bin, entry.name);
let sh = `#!/bin/sh\n`;
for (const [key, value] of Object.entries(env)) {
sh += `export ${key}="${value}"\n`;
}
sh += `exec "${bin_prefix}/${entry.name}" "$@"\n`;
await Deno.remove(to_stub); //FIXME inefficient to symlink for no reason
await Deno.writeTextFile(to_stub, sh);
await Deno.chmod(to_stub, 0o755);
}
}
}
}
async function mirror_directory(dst: string, src: string, prefix: string) {
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) {
// Create a hard link for files
await Deno.link(sourcePath, targetPath);
} else if (fileInfo.isSymlink) {
// Recreate symlink in the target directory
const linkTarget = await Deno.readLink(sourcePath);
await Deno.symlink(linkTarget, targetPath);
} else {
throw new Error(`unsupported file type at: ${sourcePath}`);
}
}
}
async function symlink(src: string, dst: string) {
await processEntry(src, dst);
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);
}
await Deno.symlink(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 entry of Deno.readDir(shelf)) {
if (
entry.isDirectory && !entry.isSymlink && entry.name.startsWith("v") &&
entry.name != "var"
) {
try {
versions.push(semver.parse(entry.name));
} catch {
//ignore
}
}
}
// collect an Record of versions per major version
const major_versions: Record<number, semver.SemVer> = {};
for (const version of versions) {
if (
major_versions[version.major] === undefined ||
semver.greaterThan(version, major_versions[version.major])
) {
major_versions[version.major] = version;
}
}
for (const [key, value] of Object.entries(major_versions)) {
await Deno.symlink(`v${semver.format(value)}`, join(shelf, `v${key}`));
}
}
function expand_runtime_env(
runtime_env: Record<string, Record<string, string>>,
) {
const expanded: Record<string, Record<string, string>> = {};
for (const [project, env] of Object.entries(runtime_env)) {
const expanded_env: Record<string, string> = {};
for (const [key, value] of Object.entries(env)) {
const new_value = value.replaceAll(/\$?{{.*prefix}}/g, "/usr/local");
expanded_env[key] = new_value;
}
expanded[project] = expanded_env;
}
return JSON.stringify(expanded);
}