-
Notifications
You must be signed in to change notification settings - Fork 5
/
bin-get.ts
executable file
·248 lines (225 loc) · 6.37 KB
/
bin-get.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
#!/usr/bin/env -S deno run --allow-write=/usr/bin/,/tmp --allow-env --allow-read
import { red } from "https://deno.land/x/[email protected]/mod.ts";
import { tgz } from "https://deno.land/x/[email protected]/mod.ts";
import {
copy,
readerFromStreamReader,
} from "https://deno.land/[email protected]/streams/conversion.ts";
import { exists } from "https://deno.land/[email protected]/fs/mod.ts";
import yargs from "https://deno.land/x/[email protected]/deno.ts";
import { Arguments } from "https://deno.land/x/[email protected]/deno-types.ts";
import { YargsInstance } from "https://deno.land/x/[email protected]/build/lib/yargs-factory.js";
import { emptyDir, walkSync } from "https://deno.land/[email protected]/fs/mod.ts";
type ApiResult = {
message: string | undefined;
body: string | undefined;
assets: Array<Asset> | undefined;
};
type Asset = {
browser_download_url: string;
name: string;
type: "tgz" | "binary";
};
async function install(
githubPackageName: string,
version: string,
installDirectory: string,
force: boolean,
) {
if (!githubPackageName) {
console.log(red("Please provide a package name as the second argument"));
Deno.exit(5);
}
let githubApiUrl =
`https://api.github.com/repos/${githubPackageName}/releases/latest`;
if (version) {
githubApiUrl =
`https://api.github.com/repos/${githubPackageName}/releases/tags/${version}`;
}
const result = await (await api(githubApiUrl)).json() as ApiResult;
if (result.message) {
console.log(
red(
`${result.message} for package ${githubPackageName} at ${githubApiUrl}`,
),
);
Deno.exit(1);
}
if (result.assets) {
appendAssetsFromBody(result);
result.assets = result.assets.filter(function (asset: Asset) {
return matchAssetToPlatform(asset);
});
if (result.assets.length === 0) {
console.log(red(`No downloadable asset found for ${githubPackageName}`));
Deno.exit(3);
}
// if (result.assets.length > 1) {
// console.log(red(`Multiple downloadable assets found for ${githubPackageName}`));
// console.log(result.assets.map((asset) => asset.browser_download_url));
// }
downloadAsset(result.assets[0], githubPackageName, installDirectory, force);
}
}
const systemArch = Deno.build.arch.toLowerCase();
const archMap: Record<string, string[]> = {
"x86_64": ["x86_64", "amd64"],
};
const os = Deno.build.os.toLowerCase();
function matchAssetToPlatform(asset: Asset): boolean {
const assetName = asset.name.toLowerCase();
let architectureMatch = false;
if (archMap[systemArch]) {
for (const arch of archMap[systemArch]) {
if (assetName.match(arch)) {
architectureMatch = true;
break;
}
}
}
if (!architectureMatch) {
return false;
}
if (!assetName.match(os)) {
return false;
}
if (assetName.match(/(tar\.gz|tgz)$/)) {
asset.type = "tgz";
}
if (assetName.match(/(\.asc|\.sha[0-9]+(sum)?|\.md5)$/)) {
return false;
}
if (!asset.type) {
asset.type = "binary";
}
return true;
}
function appendAssetsFromBody(result: ApiResult) {
const urls = result.body?.matchAll(/http[^)]+/g);
if (!urls) {
return;
}
for (const url of urls) {
result.assets?.push({
browser_download_url: url[0],
name: url[0],
} as Asset);
}
}
async function downloadAsset(
asset: Asset,
githubPackageName: string,
installDirectory: string,
force: boolean,
): Promise<boolean> {
verbose && console.log(asset);
const packageName = githubPackageName.split("/")[1];
const tempDir = await Deno.makeTempDir();
const tempResult = await Deno.makeTempFile();
let filePath: string | null = null;
const response = await api(asset.browser_download_url);
const rdr = response.body?.getReader();
if (rdr) {
const r = readerFromStreamReader(rdr);
const f = await Deno.open(tempResult, {
create: true,
write: true,
});
await copy(r, f);
f.close();
}
if (asset.type == "tgz") {
console.log(`uncompressing to ${tempDir}`);
await tgz.uncompress(tempResult, tempDir);
// now copy the binary to the tempResult binary
const files = Array.from(walkSync(tempDir, {
includeDirs: false,
includeFiles: true,
}));
for (const file of files) {
if (file.name == packageName) {
filePath = file.path;
break;
}
}
} else if (asset.type == "binary") {
filePath = tempResult;
}
try {
if (filePath) {
console.log("Installing...");
await Deno.chmod(filePath, 0o755);
await Deno.mkdir(installDirectory, {
recursive: true,
});
const installLocation: string = installDirectory + "/" + packageName;
// @todo add --force flag to override without asking
if (await exists(installLocation) && !force) {
const answer = prompt(
`File already exists at ${installLocation}, do you want to override? [y/N]`,
);
if (answer?.toLowerCase().trim() == "n") {
Deno.exit(0);
}
}
if (await exists(installLocation)) {
await Deno.remove(installLocation);
}
await Deno.copyFile(filePath, installLocation);
}
} finally {
await emptyDir(tempDir);
await Deno.remove(tempResult);
}
return true;
}
async function api(url: string) {
const headers: Record<string, string> = {};
if (url.match(/github/)) {
const credentials = githubCredentials();
if (credentials) {
headers["Authorization"] = "Basic " + credentials.join(":");
}
}
return await fetch(url, {
headers: headers,
});
}
function githubCredentials() {
const token = Deno.env.get("GITHUB_TOKEN");
const user = Deno.env.get("GITHUB_USER");
if (token && user) {
return [
user,
token,
];
}
return null;
}
let verbose = false;
await yargs(Deno.args)
.scriptName("bin-get")
.command(
"install <package> [package-version] [--yes] [--force] [--verbose] [--directory]",
"install a package",
(yargs: YargsInstance) => {
return yargs.positional("package-version", {
describe: "Github repo name (helm/helm for example)",
});
},
(argv: Arguments) => {
verbose = argv.verbose;
if (!argv.directory) {
argv.directory = "/usr/bin";
}
install(
argv.package,
argv["package-version"],
argv.directory,
argv.force,
);
},
)
.strictCommands()
.demandCommand(1)
.parse();