-
Notifications
You must be signed in to change notification settings - Fork 432
Expand file tree
/
Copy pathzip.ts
More file actions
116 lines (110 loc) · 2.76 KB
/
zip.ts
File metadata and controls
116 lines (110 loc) · 2.76 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
/*
* zip.ts
*
* Copyright (C) 2020-2022 Posit Software, PBC
*/
import { dirname } from "../deno_ral/path.ts";
import { existsSync } from "../deno_ral/fs.ts";
import { isWindows } from "../deno_ral/platform.ts";
import { execProcess } from "./process.ts";
import { safeWindowsExec } from "./windows.ts";
export function unzip(file: string, dir?: string) {
if (!dir) dir = dirname(file);
if (file.endsWith(".exe")) {
// Self-extracting 7z archive (e.g., TinyTeX-windows.exe)
return safeWindowsExec(
file,
["-y"],
(cmd: string[]) => {
return execProcess({
cmd: cmd[0],
args: cmd.slice(1),
cwd: dir,
stdout: "piped",
});
},
);
} else if (file.endsWith("zip")) {
// It's a zip file
if (isWindows) {
const args = [
"-Command",
`"& { Add-Type -A 'System.IO.Compression.FileSystem'; [IO.Compression.ZipFile]::ExtractToDirectory('${file}', '${dir}'); }"`,
];
return safeWindowsExec(
"powershell",
args,
(cmd: string[]) => {
return execProcess(
{
cmd: cmd[0],
args: cmd.slice(1),
stdout: "piped",
},
);
},
);
} else {
// Use the built in unzip command
return execProcess(
{ cmd: "unzip", args: ["-o", file], cwd: dir, stdout: "piped" },
);
}
} else {
// use the tar command to untar this
// On Windows, prefer System32 tar to avoid Git Bash tar path issues
let tarCmd = "tar";
if (isWindows) {
const systemRoot = Deno.env.get("SystemRoot") || "C:\\Windows";
const system32Tar = `${systemRoot}\\System32\\tar.exe`;
if (existsSync(system32Tar)) {
tarCmd = system32Tar;
}
// Otherwise fall back to "tar" in PATH
}
return execProcess(
{ cmd: tarCmd, args: ["xf", file], cwd: dir, stdout: "piped" },
);
}
}
export function zip(
files: string | string[],
archive: string,
options?: {
overwrite?: boolean;
cwd?: string;
},
) {
if (options?.overwrite === false && existsSync(archive)) {
throw new Error(`An archive already exits at ${archive}`);
}
const filesArr = Array.isArray(files) ? files : [files];
const zipCmd = () => {
if (isWindows) {
return [
"PowerShell",
"Compress-Archive",
"-Path",
filesArr.map((x) => `"${x}"`).join(", "),
"-DestinationPath",
archive,
"-Force",
];
} else {
return [
"zip",
"-r",
archive,
...filesArr,
];
}
};
const cmd = zipCmd();
return execProcess({
cmd: cmd[0],
args: cmd.slice(1),
cwd: options?.cwd,
stdout: "piped",
stderr: "piped",
});
}