-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy path_unpack.js
More file actions
185 lines (174 loc) · 5.05 KB
/
_unpack.js
File metadata and controls
185 lines (174 loc) · 5.05 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
import { dirname, join } from "node:path";
import { createWriteStream } from "node:fs";
import { pipeline } from "node:stream/promises";
import fs from "fs-extra";
import micromatch from "micromatch";
import * as tar from "tar";
import unzipper from "unzipper";
import { blue, bold, green, yellow } from "colorette";
import { isFile, isDirectory, chmodOwnerPlusX, relativeToCwd } from "./_util.js";
/**
* @param {{
* sourceFile: string,
* globs?: string[],
* targetDirectory: string
* }} args
*/
export async function unpackTarGz({ sourceFile, globs = ["**/*"], targetDirectory }) {
if (!(await isFile(sourceFile))) {
throw new Error(`Source file does not exist: ${sourceFile}`);
}
if (!(await isDirectory(targetDirectory))) {
throw new Error(`Destination path does not exist: ${targetDirectory}`);
}
const meta = {
fileSetDirectory: relativeToCwd(targetDirectory),
fileSet: [],
};
const matcher = micromatch.matcher(globs);
try {
await tar.extract({
f: sourceFile,
z: true,
cwd: targetDirectory,
filter: (path) => {
const isMatch = matcher(path);
if (isMatch) {
meta.fileSet.push(path);
}
return isMatch;
},
});
} catch (err) {
throw new Error(`Could not unpack ${sourceFile}`, { cause: err });
}
return meta;
}
/**
* @param {{
* sourceFile: string,
* context?: string,
* globs?: string[],
* targetDirectory: string
* }} args
*/
export async function unpackZip({ sourceFile, context, globs = ["**/*"], targetDirectory }) {
if (!(await isFile(sourceFile))) {
throw new Error(`Source file does not exist: ${sourceFile}`);
}
if (!(await isDirectory(targetDirectory))) {
throw new Error(`Destination path does not exist: ${targetDirectory}`);
}
const meta = {
context,
fileSetDirectory: relativeToCwd(targetDirectory),
fileSet: [],
};
try {
const matcher = micromatch.matcher(globs);
const directory = await unzipper.Open.file(sourceFile);
const files = directory.files.filter((file) =>
context
? file.path.startsWith(context) && matcher(file.path.substring(context.length))
: matcher(file.path),
);
for (const file of files) {
// See: https://github.com/ZJONSSON/node-unzipper/blob/d19c3fb9c1bbdce6e6bcb701ac65ddb071e1eb31/lib/extract.js#L18-L40
const contextFilePath = context ? file.path.substring(context.length) : file.path;
const extractPath = join(targetDirectory, contextFilePath.replace(/\\/g, "/"));
if (extractPath.indexOf(targetDirectory) !== 0) {
continue;
}
if (file.type === "Directory") {
await fs.ensureDir(extractPath);
} else {
await fs.ensureDir(dirname(extractPath));
await pipeline(file.stream(), createWriteStream(extractPath));
}
meta.fileSet.push(file.path);
}
} catch (err) {
throw new Error(`Could not unpack ${sourceFile}`, { cause: err });
}
return meta;
}
/**
* @param {{
* sourceFile: string,
* context?: string,
* globs?: string[],
* targetDirectory: string,
* chmod: boolean,
* }} args
*/
export async function unpackAsset({ sourceFile, context, globs, targetDirectory, chmod }) {
let meta = {};
console.group(bold("Unpacking:"), yellow(sourceFile));
console.log("Destination:", targetDirectory);
try {
// Detect archive type based on file extension
if (sourceFile.endsWith(".tar.gz") || sourceFile.endsWith(".tgz")) {
meta = await unpackTarGz({ sourceFile, globs, targetDirectory });
} else {
meta = await unpackZip({ sourceFile, context, globs, targetDirectory });
}
console.log(`Extracted ${green(meta.fileSet.length)} items`);
if (meta.fileSet.length === 0) {
throw new Error(`No files matched globs ${JSON.stringify(globs)} in archive ${sourceFile}`);
}
if (chmod) {
const extractedFiles = await fs.readdir(targetDirectory);
for (const file of extractedFiles) {
console.log(`chmod o+x ${blue(file)}`);
chmodOwnerPlusX(join(targetDirectory, file));
}
}
} finally {
console.groupEnd();
}
return meta;
}
/**
* @param {{
* sourceDirectory: string,
* context?: string,
* globs?: string[],
* targetDirectory: function,
* assets: [{*}]
* }} args
*/
export async function unpackAssets({
title,
sourceDirectory,
context,
globs,
targetDirectory,
assets,
}) {
if (!(await isDirectory(sourceDirectory))) {
throw new Error(`Source directory does not exist: ${sourceDirectory}`);
}
const meta = { assets: [] };
console.group(`${title} - Unpacking ${assets.length} assets:`);
try {
for (const asset of assets) {
const source = join(sourceDirectory, asset.name);
const target = targetDirectory(asset);
await fs.ensureDir(target);
const assetMeta = await unpackAsset({
sourceFile: source,
targetDirectory: target,
context,
globs,
chmod: asset.chmod,
});
meta.assets.push({
...asset,
...assetMeta,
});
}
} finally {
console.groupEnd();
}
return meta;
}