forked from WordPress/wordpress-playground
-
Notifications
You must be signed in to change notification settings - Fork 0
/
install-asset.ts
96 lines (79 loc) · 2.06 KB
/
install-asset.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
import type { UniversalPHP } from '@php-wasm/universal';
import { writeFile } from './client-methods';
import { unzip } from './import-export';
export interface InstallAssetOptions {
/**
* The zip file to install.
*/
zipFile: File;
/**
* Target path to extract the main folder.
* @example
*
* <code>
* const targetPath = `${await playground.documentRoot}/wp-content/plugins`;
* </code>
*/
targetPath: string;
}
/**
* Install asset: Extract folder from zip file and move it to target
*/
export async function installAsset(
playground: UniversalPHP,
{ targetPath, zipFile }: InstallAssetOptions
): Promise<{
assetFolderPath: string;
assetFolderName: string;
}> {
// Extract to temporary folder so we can find asset folder name
const zipFileName = zipFile.name;
const tmpFolder = `/tmp/assets`;
const tmpZipPath = `/tmp/${zipFileName}`;
const removeTmpFolder = () =>
playground.rmdir(tmpFolder, {
recursive: true,
});
if (await playground.fileExists(tmpFolder)) {
await removeTmpFolder();
}
await writeFile(playground, {
path: tmpZipPath,
data: zipFile,
});
const cleanup = () =>
Promise.all([removeTmpFolder, () => playground.unlink(tmpZipPath)]);
try {
await unzip(playground, {
zipPath: tmpZipPath,
extractToPath: tmpFolder,
});
// Find extracted asset folder name
const files = await playground.listFiles(tmpFolder);
let assetFolderName;
let tmpAssetPath = '';
for (const file of files) {
tmpAssetPath = `${tmpFolder}/${file}`;
if (await playground.isDir(tmpAssetPath)) {
assetFolderName = file;
break;
}
}
if (!assetFolderName) {
throw new Error(
`The zip file should contain a single folder with files inside, but the provided zip file (${zipFileName}) does not contain such a folder.`
);
}
// Move asset folder to target path
const assetFolderPath = `${targetPath}/${assetFolderName}`;
await playground.mv(tmpAssetPath, assetFolderPath);
await cleanup();
return {
assetFolderPath,
assetFolderName,
};
} catch (error) {
await cleanup();
throw error;
}
}