@reativ/wpbox 0.0.0-stage → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +288 -2
- package/bin/wpbox.js +12 -0
- package/dist/backup/dump-analysis.js +44 -0
- package/dist/backup/import-files.js +50 -0
- package/dist/backup/layout.js +89 -0
- package/dist/backup/readers/archive-reader.js +16 -0
- package/dist/backup/readers/index.js +14 -0
- package/dist/backup/readers/tar-reader.js +42 -0
- package/dist/backup/readers/wpress-reader.js +76 -0
- package/dist/backup/readers/zip-reader.js +51 -0
- package/dist/backup/stage.js +128 -0
- package/dist/cli.js +61 -0
- package/dist/commands/database.js +22 -0
- package/dist/commands/init/analyze.js +24 -0
- package/dist/commands/init/index.js +73 -0
- package/dist/commands/init/questions.js +42 -0
- package/dist/commands/project.js +12 -0
- package/dist/commands/site.js +58 -0
- package/dist/docker/compose-file.js +110 -0
- package/dist/docker/compose.js +41 -0
- package/dist/docker/environment.js +35 -0
- package/dist/project/config.js +60 -0
- package/dist/project/gitignore.js +15 -0
- package/dist/project/paths.js +22 -0
- package/dist/project/secrets.js +29 -0
- package/dist/project/site-url.js +27 -0
- package/dist/remote/connect.js +17 -0
- package/dist/remote/download.js +70 -0
- package/dist/remote/ftp-fs.js +56 -0
- package/dist/remote/mirror.js +72 -0
- package/dist/remote/remote-database.js +103 -0
- package/dist/remote/remote-fs.js +1 -0
- package/dist/remote/sftp-fs.js +54 -0
- package/dist/remote/wordpress-locator.js +58 -0
- package/dist/sources/backup-source.js +1 -0
- package/dist/sources/index.js +36 -0
- package/dist/sources/local-source.js +32 -0
- package/dist/sources/remote-questions.js +71 -0
- package/dist/sources/remote-source.js +119 -0
- package/dist/sources/url-source.js +32 -0
- package/dist/ui/output.js +24 -0
- package/dist/ui/prompts.js +80 -0
- package/dist/utils/errors.js +6 -0
- package/dist/utils/exec.js +45 -0
- package/dist/utils/format.js +22 -0
- package/dist/utils/fs.js +88 -0
- package/dist/utils/result.js +2 -0
- package/dist/utils/work-queue.js +30 -0
- package/dist/wordpress/content.js +74 -0
- package/dist/wordpress/database.js +78 -0
- package/dist/wordpress/summary.js +30 -0
- package/dist/wordpress/url-replacements.js +23 -0
- package/package.json +62 -4
- package/templates/Dockerfile +26 -0
- package/templates/exporter.php +129 -0
- package/templates/local-entrypoint.sh +9 -0
- package/templates/mailpit.php +17 -0
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { parseDbHost } from '../remote/remote-database.js';
|
|
3
|
+
import { log } from '../ui/output.js';
|
|
4
|
+
import { confirm, select, text } from '../ui/prompts.js';
|
|
5
|
+
const DEFAULT_PORTS = { ftp: 21, sftp: 22 };
|
|
6
|
+
export async function askConnection(protocol, previous) {
|
|
7
|
+
const host = await text('Host', { initial: previous?.host, placeholder: 'ftp.example.com' });
|
|
8
|
+
const port = Number(await text('Port', { initial: String(previous?.port ?? DEFAULT_PORTS[protocol]) }));
|
|
9
|
+
const user = await text('Username', { initial: previous?.user });
|
|
10
|
+
const privateKey = protocol === 'sftp' ? await askPrivateKey(previous?.privateKey) : undefined;
|
|
11
|
+
return { host, port, user, privateKey };
|
|
12
|
+
}
|
|
13
|
+
async function askPrivateKey(previous) {
|
|
14
|
+
const method = await select('Authentication', [
|
|
15
|
+
{ value: 'password', label: 'Password' },
|
|
16
|
+
{ value: 'key', label: 'SSH private key' },
|
|
17
|
+
], previous ? 'key' : 'password');
|
|
18
|
+
return method === 'key' ? text('Private key file', { initial: previous ?? '~/.ssh/id_ed25519' }) : undefined;
|
|
19
|
+
}
|
|
20
|
+
export async function chooseInstall(installs, previousRoot) {
|
|
21
|
+
if (installs.length === 1) {
|
|
22
|
+
log.success(`WordPress found in ${installs[0].root}`);
|
|
23
|
+
return installs[0];
|
|
24
|
+
}
|
|
25
|
+
if (installs.length > 1) {
|
|
26
|
+
return select('More than one WordPress found. Which one?', installs.map((install) => ({ value: install, label: install.root })), installs.find((install) => install.root === previousRoot) ?? installs[0]);
|
|
27
|
+
}
|
|
28
|
+
const root = await text('WordPress folder on the server (the one with wp-content)', { initial: previousRoot ?? '/public_html' });
|
|
29
|
+
return { root, wpConfigPath: path.posix.join(root, 'wp-config.php') };
|
|
30
|
+
}
|
|
31
|
+
export function askIncludeUploads(previous) {
|
|
32
|
+
return confirm('Download uploads (images, media)? It can be large.', previous ?? true);
|
|
33
|
+
}
|
|
34
|
+
export async function askDatabaseSource(connection, wpConfig, previous) {
|
|
35
|
+
const method = await select('How should wpbox get the database?', [
|
|
36
|
+
{
|
|
37
|
+
value: 'exporter',
|
|
38
|
+
label: 'Temporary export script',
|
|
39
|
+
hint: 'uploads a one-time PHP file, downloads the dump, deletes it. Works on most hosting',
|
|
40
|
+
},
|
|
41
|
+
{ value: 'mysql', label: 'Direct MySQL connection', hint: 'needs remote MySQL access, often blocked on shared hosting' },
|
|
42
|
+
{ value: 'file', label: 'A .sql file I put in import/' },
|
|
43
|
+
], previous?.method ?? 'exporter');
|
|
44
|
+
switch (method) {
|
|
45
|
+
case 'exporter':
|
|
46
|
+
return { method, siteUrl: await askPublicSiteUrl(connection, previous) };
|
|
47
|
+
case 'mysql':
|
|
48
|
+
return { method, ...(await askMysql(connection, wpConfig, previous)) };
|
|
49
|
+
case 'file':
|
|
50
|
+
return { method };
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
async function askPublicSiteUrl(connection, previous) {
|
|
54
|
+
const guess = `https://${connection.host.replace(/^(s?ftp|ssh)\./, '')}`;
|
|
55
|
+
return text('Public site URL', { initial: previous?.method === 'exporter' ? previous.siteUrl : guess });
|
|
56
|
+
}
|
|
57
|
+
async function askMysql(connection, wpConfig, previous) {
|
|
58
|
+
const saved = previous?.method === 'mysql' ? previous : undefined;
|
|
59
|
+
const guess = parseDbHost(wpConfig.dbHost, connection.host);
|
|
60
|
+
return {
|
|
61
|
+
host: await text('MySQL host', { initial: saved?.host ?? guess.host }),
|
|
62
|
+
port: Number(await text('MySQL port', { initial: String(saved?.port ?? guess.port) })),
|
|
63
|
+
name: await text('Database name', { initial: saved?.name ?? wpConfig.dbName }),
|
|
64
|
+
user: await text('Database user', { initial: saved?.user ?? wpConfig.dbUser }),
|
|
65
|
+
tablePrefix: await text('Table prefix', { initial: saved?.tablePrefix ?? wpConfig.tablePrefix ?? 'wp_' }),
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
export function previousRemoteConfig(source, protocol) {
|
|
69
|
+
const isRemote = source?.type === 'ftp' || source?.type === 'sftp';
|
|
70
|
+
return isRemote && source.type === protocol ? source : undefined;
|
|
71
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { EXCLUDED_CONTENT } from '../backup/layout.js';
|
|
4
|
+
import { scanImportFolder } from '../backup/import-files.js';
|
|
5
|
+
import { stageBackup } from '../backup/stage.js';
|
|
6
|
+
import { connect } from '../remote/connect.js';
|
|
7
|
+
import { mirror } from '../remote/mirror.js';
|
|
8
|
+
import { dumpRemoteMysql, exportWithTemporaryScript } from '../remote/remote-database.js';
|
|
9
|
+
import { findWordPressInstalls, parseWpConfig, readRemoteFile } from '../remote/wordpress-locator.js';
|
|
10
|
+
import { log, task } from '../ui/output.js';
|
|
11
|
+
import { confirm, password } from '../ui/prompts.js';
|
|
12
|
+
import { UserError } from '../utils/errors.js';
|
|
13
|
+
import { formatBytes } from '../utils/format.js';
|
|
14
|
+
import { askConnection, askDatabaseSource, askIncludeUploads, chooseInstall, previousRemoteConfig, } from './remote-questions.js';
|
|
15
|
+
export class RemoteSource {
|
|
16
|
+
protocol;
|
|
17
|
+
constructor(protocol) {
|
|
18
|
+
this.protocol = protocol;
|
|
19
|
+
}
|
|
20
|
+
async acquire(context) {
|
|
21
|
+
const previous = previousRemoteConfig(context.config.source, this.protocol);
|
|
22
|
+
const reuse = context.repeatLastRun && previous !== undefined;
|
|
23
|
+
const connection = reuse ? previous.connection : await askConnection(this.protocol, previous?.connection);
|
|
24
|
+
const secret = await this.secretFor(connection, context);
|
|
25
|
+
const options = { ...connection, protocol: this.protocol, password: secret };
|
|
26
|
+
const client = await task(`Connecting to ${connection.host}`, () => connect(options));
|
|
27
|
+
try {
|
|
28
|
+
if (!client.encrypted)
|
|
29
|
+
log.warn('The FTP server does not support TLS: the connection is not encrypted.');
|
|
30
|
+
const install = reuse
|
|
31
|
+
? { root: previous.wordpressRoot, wpConfigPath: previous.wpConfigPath }
|
|
32
|
+
: await chooseInstall(await task('Looking for WordPress', () => findWordPressInstalls(client)), previous?.wordpressRoot);
|
|
33
|
+
const wpConfig = parseWpConfig(await readRemoteFile(client, install.wpConfigPath).catch(() => ''));
|
|
34
|
+
const includeUploads = reuse ? previous.includeUploads : await askIncludeUploads(previous?.includeUploads);
|
|
35
|
+
await this.syncContent(options, client, install.root, includeUploads, context.paths);
|
|
36
|
+
const database = reuse ? previous.database : await askDatabaseSource(connection, wpConfig, previous?.database);
|
|
37
|
+
const dumpPath = await this.fetchDatabase(database, { client, install: install.root, wpConfig, context });
|
|
38
|
+
await this.offerToSaveSecret(connection, secret, context);
|
|
39
|
+
const source = {
|
|
40
|
+
type: this.protocol,
|
|
41
|
+
connection,
|
|
42
|
+
wordpressRoot: install.root,
|
|
43
|
+
wpConfigPath: install.wpConfigPath,
|
|
44
|
+
includeUploads,
|
|
45
|
+
database,
|
|
46
|
+
};
|
|
47
|
+
return {
|
|
48
|
+
contentDir: context.paths.mirror,
|
|
49
|
+
dumpPath,
|
|
50
|
+
disposable: false,
|
|
51
|
+
format: `${this.protocol.toUpperCase()} (${connection.host})`,
|
|
52
|
+
source,
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
finally {
|
|
56
|
+
await client.close();
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
async syncContent(connection, client, wordpressRoot, includeUploads, paths) {
|
|
60
|
+
const exclude = (relativePath) => {
|
|
61
|
+
const topLevel = relativePath.split('/')[0];
|
|
62
|
+
return EXCLUDED_CONTENT.has(topLevel) || (!includeUploads && topLevel === 'uploads');
|
|
63
|
+
};
|
|
64
|
+
const result = await task('Syncing wp-content', (report) => mirror({
|
|
65
|
+
connection,
|
|
66
|
+
client,
|
|
67
|
+
remoteRoot: path.posix.join(wordpressRoot, 'wp-content'),
|
|
68
|
+
localRoot: paths.mirror,
|
|
69
|
+
exclude,
|
|
70
|
+
onProgress: (progress) => report(describeMirrorProgress(progress)),
|
|
71
|
+
}));
|
|
72
|
+
log.success(`wp-content synced: ${result.files} files, ${result.downloaded} downloaded, ${result.removed} removed locally`);
|
|
73
|
+
}
|
|
74
|
+
async fetchDatabase(database, remote) {
|
|
75
|
+
const { paths } = remote.context;
|
|
76
|
+
fs.rmSync(paths.stage, { recursive: true, force: true });
|
|
77
|
+
switch (database.method) {
|
|
78
|
+
case 'exporter':
|
|
79
|
+
return task('Exporting the database through a temporary script', (report) => exportWithTemporaryScript(remote.client, remote.install, database.siteUrl, paths.stage, (bytes) => report(`Exporting the database… ${formatBytes(bytes)}`)));
|
|
80
|
+
case 'mysql': {
|
|
81
|
+
const secretKey = `mysql://${database.user}@${database.host}`;
|
|
82
|
+
const dbPassword = remote.context.secrets.get(secretKey) ??
|
|
83
|
+
remote.wpConfig.dbPassword ??
|
|
84
|
+
(await password('Database password', 'WPBOX_DB_PASSWORD'));
|
|
85
|
+
return task(`Dumping the database from ${database.host}`, () => dumpRemoteMysql({ ...database, password: dbPassword }, paths.stage));
|
|
86
|
+
}
|
|
87
|
+
case 'file': {
|
|
88
|
+
const staged = await stageBackup(scanImportFolder(paths.import), paths, { includeContent: false });
|
|
89
|
+
if (!staged.dumpPath)
|
|
90
|
+
throw new UserError('No .sql file found in import/.');
|
|
91
|
+
return staged.dumpPath;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
async secretFor(connection, context) {
|
|
96
|
+
const saved = context.secrets.get(secretKey(this.protocol, connection));
|
|
97
|
+
if (saved !== undefined)
|
|
98
|
+
return saved;
|
|
99
|
+
if (connection.privateKey)
|
|
100
|
+
return process.env.WPBOX_KEY_PASSPHRASE ?? '';
|
|
101
|
+
return password(`${this.protocol.toUpperCase()} password`, 'WPBOX_FTP_PASSWORD');
|
|
102
|
+
}
|
|
103
|
+
async offerToSaveSecret(connection, secret, context) {
|
|
104
|
+
const key = secretKey(this.protocol, connection);
|
|
105
|
+
if (!secret || context.repeatLastRun || context.secrets.has(key))
|
|
106
|
+
return;
|
|
107
|
+
if (await confirm('Save the password for `wpbox pull`? (stored in .wpbox/secrets.json)', false)) {
|
|
108
|
+
context.secrets.set(key, secret);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
function secretKey(protocol, connection) {
|
|
113
|
+
return `${protocol}://${connection.user}@${connection.host}`;
|
|
114
|
+
}
|
|
115
|
+
function describeMirrorProgress(progress) {
|
|
116
|
+
return progress.phase === 'scan'
|
|
117
|
+
? `Scanning remote files… ${progress.files} files in ${progress.folders} folders`
|
|
118
|
+
: `Downloading ${progress.done}/${progress.total} files (${formatBytes(progress.bytes)} / ${formatBytes(progress.totalBytes)})`;
|
|
119
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { onlyNamed, scanImportFolder } from '../backup/import-files.js';
|
|
3
|
+
import { download } from '../remote/download.js';
|
|
4
|
+
import { task } from '../ui/output.js';
|
|
5
|
+
import { confirm, text } from '../ui/prompts.js';
|
|
6
|
+
import { formatProgress } from '../utils/format.js';
|
|
7
|
+
import { LocalSource } from './local-source.js';
|
|
8
|
+
const validateUrl = (value) => (/^https?:\/\/.+/.test(value) ? undefined : 'Enter a http(s):// URL');
|
|
9
|
+
export class UrlSource {
|
|
10
|
+
async acquire(context) {
|
|
11
|
+
const urls = await this.resolveUrls(context);
|
|
12
|
+
const downloaded = [];
|
|
13
|
+
for (const url of urls) {
|
|
14
|
+
const file = await task(`Downloading from ${new URL(url).host}`, (report) => download(url, context.paths.import, (done, total, fileName) => report(`Downloading ${fileName} ${formatProgress(done, total)}`)));
|
|
15
|
+
downloaded.push(path.basename(file));
|
|
16
|
+
}
|
|
17
|
+
const files = onlyNamed(scanImportFolder(context.paths.import), downloaded);
|
|
18
|
+
const backup = await new LocalSource(files).acquire(context);
|
|
19
|
+
return { ...backup, source: { type: 'url', urls } };
|
|
20
|
+
}
|
|
21
|
+
async resolveUrls({ urls, config, repeatLastRun }) {
|
|
22
|
+
if (urls?.length)
|
|
23
|
+
return urls;
|
|
24
|
+
if (repeatLastRun && config.source?.type === 'url')
|
|
25
|
+
return config.source.urls;
|
|
26
|
+
const answers = [await text('Backup URL', { placeholder: 'https://example.com/backup.zip', validate: validateUrl })];
|
|
27
|
+
while (await confirm('Add another URL? (a separate .sql, or more UpdraftPlus parts)', false)) {
|
|
28
|
+
answers.push(await text('URL', { validate: validateUrl }));
|
|
29
|
+
}
|
|
30
|
+
return answers;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import * as clack from '@clack/prompts';
|
|
2
|
+
import pc from 'picocolors';
|
|
3
|
+
export { pc };
|
|
4
|
+
export const log = clack.log;
|
|
5
|
+
export const intro = clack.intro;
|
|
6
|
+
export const outro = clack.outro;
|
|
7
|
+
export const note = clack.note;
|
|
8
|
+
export async function task(title, work) {
|
|
9
|
+
if (!process.stdout.isTTY) {
|
|
10
|
+
clack.log.step(title);
|
|
11
|
+
return work(() => { });
|
|
12
|
+
}
|
|
13
|
+
const spinner = clack.spinner();
|
|
14
|
+
spinner.start(title);
|
|
15
|
+
try {
|
|
16
|
+
const result = await work((message) => spinner.message(message));
|
|
17
|
+
spinner.stop(title);
|
|
18
|
+
return result;
|
|
19
|
+
}
|
|
20
|
+
catch (error) {
|
|
21
|
+
spinner.error(title);
|
|
22
|
+
throw error;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import * as clack from '@clack/prompts';
|
|
2
|
+
import { UserError } from '../utils/errors.js';
|
|
3
|
+
let assumeDefaults = false;
|
|
4
|
+
export function useDefaultAnswers(enabled) {
|
|
5
|
+
assumeDefaults = enabled;
|
|
6
|
+
}
|
|
7
|
+
export function isInteractive() {
|
|
8
|
+
return !assumeDefaults && hasTerminal();
|
|
9
|
+
}
|
|
10
|
+
export async function text(message, options = {}) {
|
|
11
|
+
const { initial, placeholder, validate } = options;
|
|
12
|
+
if (!isInteractive()) {
|
|
13
|
+
if (!initial)
|
|
14
|
+
throw needsAnswer(message);
|
|
15
|
+
const error = validate?.(initial);
|
|
16
|
+
if (error)
|
|
17
|
+
throw new UserError(`${message}: ${error}`);
|
|
18
|
+
return initial;
|
|
19
|
+
}
|
|
20
|
+
const answer = await clack.text({
|
|
21
|
+
message,
|
|
22
|
+
placeholder,
|
|
23
|
+
initialValue: initial,
|
|
24
|
+
validate: (value) => {
|
|
25
|
+
const trimmed = (value ?? '').trim();
|
|
26
|
+
return trimmed ? validate?.(trimmed) : 'This value is required';
|
|
27
|
+
},
|
|
28
|
+
});
|
|
29
|
+
return unwrap(answer).trim();
|
|
30
|
+
}
|
|
31
|
+
export async function password(message, environmentVariable) {
|
|
32
|
+
const fromEnvironment = environmentVariable ? process.env[environmentVariable] : undefined;
|
|
33
|
+
if (fromEnvironment)
|
|
34
|
+
return fromEnvironment;
|
|
35
|
+
if (!hasTerminal()) {
|
|
36
|
+
throw needsAnswer(environmentVariable ? `${message} (or set ${environmentVariable})` : message);
|
|
37
|
+
}
|
|
38
|
+
return unwrap(await clack.password({ message }));
|
|
39
|
+
}
|
|
40
|
+
export async function confirm(message, initial) {
|
|
41
|
+
if (!isInteractive())
|
|
42
|
+
return initial;
|
|
43
|
+
return unwrap(await clack.confirm({ message, initialValue: initial }));
|
|
44
|
+
}
|
|
45
|
+
export async function select(message, choices, initial) {
|
|
46
|
+
if (!isInteractive()) {
|
|
47
|
+
const fallback = initial ?? choices[0]?.value;
|
|
48
|
+
if (fallback === undefined)
|
|
49
|
+
throw needsAnswer(message);
|
|
50
|
+
return fallback;
|
|
51
|
+
}
|
|
52
|
+
return unwrap(await clack.select({ message, options: asClackOptions(choices), initialValue: initial }));
|
|
53
|
+
}
|
|
54
|
+
export async function multiselect(message, choices, initial) {
|
|
55
|
+
if (!isInteractive() || choices.length === 0)
|
|
56
|
+
return initial;
|
|
57
|
+
const answer = await clack.multiselect({
|
|
58
|
+
message,
|
|
59
|
+
options: asClackOptions(choices),
|
|
60
|
+
initialValues: initial,
|
|
61
|
+
required: false,
|
|
62
|
+
});
|
|
63
|
+
return unwrap(answer);
|
|
64
|
+
}
|
|
65
|
+
function hasTerminal() {
|
|
66
|
+
return Boolean(process.stdin.isTTY && process.stdout.isTTY) && !process.env.CI;
|
|
67
|
+
}
|
|
68
|
+
function unwrap(answer) {
|
|
69
|
+
if (clack.isCancel(answer)) {
|
|
70
|
+
clack.cancel('Cancelled.');
|
|
71
|
+
process.exit(130);
|
|
72
|
+
}
|
|
73
|
+
return answer;
|
|
74
|
+
}
|
|
75
|
+
function needsAnswer(message) {
|
|
76
|
+
return new UserError(`"${message}" needs an answer, but wpbox is running without questions (no terminal or --yes).`);
|
|
77
|
+
}
|
|
78
|
+
function asClackOptions(choices) {
|
|
79
|
+
return choices;
|
|
80
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { UserError } from './errors.js';
|
|
3
|
+
export class CommandError extends Error {
|
|
4
|
+
command;
|
|
5
|
+
result;
|
|
6
|
+
constructor(command, result) {
|
|
7
|
+
super(`${command} failed (exit ${result.code})\n${lastLines(result.stderr || result.stdout, 15)}`.trim());
|
|
8
|
+
this.command = command;
|
|
9
|
+
this.result = result;
|
|
10
|
+
this.name = 'CommandError';
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
export function run(command, args, options = {}) {
|
|
14
|
+
const { cwd, env, input, inherit = false, allowFail = false } = options;
|
|
15
|
+
return new Promise((resolve, reject) => {
|
|
16
|
+
const child = spawn(command, args, {
|
|
17
|
+
cwd,
|
|
18
|
+
env: { ...process.env, ...env },
|
|
19
|
+
stdio: inherit ? 'inherit' : 'pipe',
|
|
20
|
+
windowsHide: true,
|
|
21
|
+
});
|
|
22
|
+
let stdout = '';
|
|
23
|
+
let stderr = '';
|
|
24
|
+
child.stdout?.on('data', (chunk) => (stdout += chunk));
|
|
25
|
+
child.stderr?.on('data', (chunk) => (stderr += chunk));
|
|
26
|
+
child.stdin?.end(input);
|
|
27
|
+
child.on('error', (error) => {
|
|
28
|
+
reject(error.code === 'ENOENT' ? new UserError(`Command not found: ${command}`) : error);
|
|
29
|
+
});
|
|
30
|
+
child.on('close', (exitCode) => {
|
|
31
|
+
const result = { code: exitCode ?? 1, stdout, stderr };
|
|
32
|
+
if (result.code === 0 || allowFail)
|
|
33
|
+
resolve(result);
|
|
34
|
+
else
|
|
35
|
+
reject(new CommandError(describe(command, args), result));
|
|
36
|
+
});
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
function describe(command, args) {
|
|
40
|
+
const shown = args.slice(0, 6).join(' ');
|
|
41
|
+
return args.length > 6 ? `${command} ${shown} …` : `${command} ${shown}`;
|
|
42
|
+
}
|
|
43
|
+
function lastLines(text, count) {
|
|
44
|
+
return text.trim().split('\n').slice(-count).join('\n');
|
|
45
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
const BYTE_UNITS = ['B', 'KB', 'MB', 'GB', 'TB'];
|
|
2
|
+
export function formatBytes(bytes) {
|
|
3
|
+
if (!Number.isFinite(bytes))
|
|
4
|
+
return '?';
|
|
5
|
+
let value = bytes;
|
|
6
|
+
let unit = 0;
|
|
7
|
+
while (value >= 1024 && unit < BYTE_UNITS.length - 1) {
|
|
8
|
+
value /= 1024;
|
|
9
|
+
unit++;
|
|
10
|
+
}
|
|
11
|
+
return `${value.toFixed(unit === 0 ? 0 : 1)} ${BYTE_UNITS[unit]}`;
|
|
12
|
+
}
|
|
13
|
+
export function formatPercent(done, total) {
|
|
14
|
+
if (!total)
|
|
15
|
+
return '';
|
|
16
|
+
return `${Math.min(100, Math.floor((done / total) * 100))}%`;
|
|
17
|
+
}
|
|
18
|
+
export function formatProgress(done, total) {
|
|
19
|
+
const percent = formatPercent(done, total);
|
|
20
|
+
const sizes = total ? `${formatBytes(done)} / ${formatBytes(total)}` : formatBytes(done);
|
|
21
|
+
return percent ? `${percent} (${sizes})` : sizes;
|
|
22
|
+
}
|
package/dist/utils/fs.js
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
const IGNORED_FILES = new Set(['.DS_Store', 'Thumbs.db']);
|
|
4
|
+
export function isDirEmpty(dir) {
|
|
5
|
+
try {
|
|
6
|
+
return fs.readdirSync(dir).every((name) => IGNORED_FILES.has(name));
|
|
7
|
+
}
|
|
8
|
+
catch {
|
|
9
|
+
return true;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
export function listDirectories(dir) {
|
|
13
|
+
try {
|
|
14
|
+
return fs
|
|
15
|
+
.readdirSync(dir, { withFileTypes: true })
|
|
16
|
+
.filter((entry) => entry.isDirectory())
|
|
17
|
+
.map((entry) => entry.name)
|
|
18
|
+
.sort();
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return [];
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
export function clearDirectory(dir) {
|
|
25
|
+
for (const name of fs.readdirSync(dir)) {
|
|
26
|
+
fs.rmSync(path.join(dir, name), { recursive: true, force: true });
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
export function safeJoin(root, relativePath) {
|
|
30
|
+
const target = path.resolve(root, ...relativePath.split('/'));
|
|
31
|
+
const insideRoot = target === root || target.startsWith(root + path.sep);
|
|
32
|
+
return insideRoot ? target : null;
|
|
33
|
+
}
|
|
34
|
+
export function* walkFiles(root, relativeDir = '') {
|
|
35
|
+
let entries;
|
|
36
|
+
try {
|
|
37
|
+
entries = fs.readdirSync(path.join(root, ...splitPosix(relativeDir)), { withFileTypes: true });
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
for (const entry of entries) {
|
|
43
|
+
const relativePath = relativeDir ? `${relativeDir}/${entry.name}` : entry.name;
|
|
44
|
+
if (entry.isDirectory())
|
|
45
|
+
yield* walkFiles(root, relativePath);
|
|
46
|
+
else
|
|
47
|
+
yield relativePath;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
export function toLocalPath(root, posixPath) {
|
|
51
|
+
return path.join(root, ...splitPosix(posixPath));
|
|
52
|
+
}
|
|
53
|
+
export function mergeDirectory(from, to, options) {
|
|
54
|
+
fs.mkdirSync(to, { recursive: true });
|
|
55
|
+
for (const name of fs.readdirSync(from)) {
|
|
56
|
+
const source = path.join(from, name);
|
|
57
|
+
const target = path.join(to, name);
|
|
58
|
+
if (fs.existsSync(target)) {
|
|
59
|
+
if (!options.overwrite) {
|
|
60
|
+
if (bothDirectories(source, target))
|
|
61
|
+
mergeDirectory(source, target, options);
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
fs.rmSync(target, { recursive: true, force: true });
|
|
65
|
+
}
|
|
66
|
+
transfer(source, target, options.move);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
function transfer(source, target, move) {
|
|
70
|
+
if (move && tryRename(source, target))
|
|
71
|
+
return;
|
|
72
|
+
fs.cpSync(source, target, { recursive: true, preserveTimestamps: true });
|
|
73
|
+
}
|
|
74
|
+
function tryRename(source, target) {
|
|
75
|
+
try {
|
|
76
|
+
fs.renameSync(source, target);
|
|
77
|
+
return true;
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
return false;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
function bothDirectories(a, b) {
|
|
84
|
+
return fs.statSync(a).isDirectory() && fs.statSync(b).isDirectory();
|
|
85
|
+
}
|
|
86
|
+
function splitPosix(posixPath) {
|
|
87
|
+
return posixPath.split('/').filter(Boolean);
|
|
88
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
const IDLE_WAIT_MS = 25;
|
|
2
|
+
export async function processQueue(workers, queue, handle) {
|
|
3
|
+
let failure = null;
|
|
4
|
+
let busy = 0;
|
|
5
|
+
const drain = async (worker) => {
|
|
6
|
+
while (failure === null && (queue.length > 0 || busy > 0)) {
|
|
7
|
+
const item = queue.shift();
|
|
8
|
+
if (item === undefined) {
|
|
9
|
+
await sleep(IDLE_WAIT_MS);
|
|
10
|
+
continue;
|
|
11
|
+
}
|
|
12
|
+
busy++;
|
|
13
|
+
try {
|
|
14
|
+
await handle(worker, item);
|
|
15
|
+
}
|
|
16
|
+
catch (error) {
|
|
17
|
+
failure = error;
|
|
18
|
+
}
|
|
19
|
+
finally {
|
|
20
|
+
busy--;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
await Promise.all(workers.map(drain));
|
|
25
|
+
if (failure !== null)
|
|
26
|
+
throw failure;
|
|
27
|
+
}
|
|
28
|
+
function sleep(ms) {
|
|
29
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
30
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { EXCLUDED_CONTENT } from '../backup/layout.js';
|
|
4
|
+
import { log, pc } from '../ui/output.js';
|
|
5
|
+
import { clearDirectory, isDirEmpty, listDirectories, mergeDirectory } from '../utils/fs.js';
|
|
6
|
+
const VOLUME_BATCH_SIZE = 100;
|
|
7
|
+
const COPY_TO_VOLUME_SCRIPT = `
|
|
8
|
+
set -e
|
|
9
|
+
for item in "$@"; do
|
|
10
|
+
target="/var/www/html/wp-content/$item"
|
|
11
|
+
rm -rf "$target"
|
|
12
|
+
mkdir -p "$(dirname "$target")"
|
|
13
|
+
cp -a "$SOURCE/$item" "$target"
|
|
14
|
+
chown -R www-data:www-data "$target"
|
|
15
|
+
done`;
|
|
16
|
+
export function listCode(contentDir, kind) {
|
|
17
|
+
return listDirectories(path.join(contentDir, kind));
|
|
18
|
+
}
|
|
19
|
+
export function detectCustomCode(contentDir, kind) {
|
|
20
|
+
return listCode(contentDir, kind).filter((name) => !hasWordPressOrgReadme(path.join(contentDir, kind, name)));
|
|
21
|
+
}
|
|
22
|
+
export async function placeContent(options) {
|
|
23
|
+
placeDevCode(options, 'themes', options.devCode.themes, options.paths.srcThemes);
|
|
24
|
+
placeDevCode(options, 'plugins', options.devCode.plugins, options.paths.srcPlugins);
|
|
25
|
+
placeUploads(options);
|
|
26
|
+
await copyEverythingElseToVolume(options);
|
|
27
|
+
}
|
|
28
|
+
function placeDevCode(options, kind, names, srcRoot) {
|
|
29
|
+
for (const name of names) {
|
|
30
|
+
const from = path.join(options.contentDir, kind, name);
|
|
31
|
+
const to = path.join(srcRoot, name);
|
|
32
|
+
if (!fs.existsSync(from)) {
|
|
33
|
+
log.warn(`src/${kind}/${name}: not in the backup, left as is.`);
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
if (!isDirEmpty(to) && !options.overwrite) {
|
|
37
|
+
log.warn(`src/${kind}/${name} already has files: kept your version ${pc.dim('(use --force to overwrite)')}`);
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
if (options.overwrite)
|
|
41
|
+
clearDirectory(to);
|
|
42
|
+
mergeDirectory(from, to, { move: options.disposable, overwrite: true });
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
function placeUploads(options) {
|
|
46
|
+
const uploads = path.join(options.contentDir, 'uploads');
|
|
47
|
+
if (!fs.existsSync(uploads))
|
|
48
|
+
return;
|
|
49
|
+
mergeDirectory(uploads, options.paths.srcUploads, { move: options.disposable, overwrite: options.overwrite });
|
|
50
|
+
}
|
|
51
|
+
async function copyEverythingElseToVolume(options) {
|
|
52
|
+
const items = volumeItems(options.contentDir, options.devCode);
|
|
53
|
+
const sourceInContainer = `/wpbox/${path.relative(options.paths.box, options.contentDir).split(path.sep).join('/')}`;
|
|
54
|
+
for (let start = 0; start < items.length; start += VOLUME_BATCH_SIZE) {
|
|
55
|
+
const batch = items.slice(start, start + VOLUME_BATCH_SIZE);
|
|
56
|
+
await options.compose.shell('wordpress', COPY_TO_VOLUME_SCRIPT, batch, { env: { SOURCE: sourceInContainer } });
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
function volumeItems(contentDir, devCode) {
|
|
60
|
+
const devNames = { themes: devCode.themes, plugins: devCode.plugins };
|
|
61
|
+
return fs.readdirSync(contentDir).flatMap((topLevel) => {
|
|
62
|
+
if (topLevel === 'uploads' || EXCLUDED_CONTENT.has(topLevel))
|
|
63
|
+
return [];
|
|
64
|
+
if (topLevel !== 'themes' && topLevel !== 'plugins')
|
|
65
|
+
return [topLevel];
|
|
66
|
+
return fs
|
|
67
|
+
.readdirSync(path.join(contentDir, topLevel))
|
|
68
|
+
.filter((name) => !devNames[topLevel].includes(name))
|
|
69
|
+
.map((name) => `${topLevel}/${name}`);
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
function hasWordPressOrgReadme(dir) {
|
|
73
|
+
return fs.readdirSync(dir).some((file) => file.toLowerCase() === 'readme.txt');
|
|
74
|
+
}
|