-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathall.js
More file actions
268 lines (241 loc) · 8.61 KB
/
Copy pathall.js
File metadata and controls
268 lines (241 loc) · 8.61 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
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
import chalk from 'chalk';
import fs from 'fs';
import ora from 'ora';
import path from 'path';
import { tmpdir } from 'os';
import Vantage from '../../../vantage.js';
import {
addCommonOptions,
addDatabaseOptions,
addUploadsOptions,
confirm,
copyUploads,
downloadArchive,
extractArchive,
findCompletedBackup,
formatAge,
getLatestBackup,
promptBackupChoice,
resolveMappings,
resolveTablesForSiteIds,
runComposerServer,
runPostSync,
searchReplaceAndImport,
startBackup,
validateLocalProject,
waitForBackup,
} from './util.js';
const handler = async function ( argv ) {
const {
app,
config,
path: pathOpt,
uploadsPath,
outputDir,
keepArchive,
yes,
latest,
resume,
debug,
table,
siteId,
searchReplaceKey,
replace: replacePairs,
skipSearchReplace,
dryRunSearchReplace,
skipPostSync,
} = argv;
const localPath = pathOpt || process.cwd();
const v = new Vantage( config );
// --dry-run-search-replace: just print mappings, no validation or network needed
if ( dryRunSearchReplace ) {
try {
const mappings = resolveMappings( localPath, searchReplaceKey, replacePairs, skipSearchReplace );
if ( Object.keys( mappings ).length === 0 ) {
console.log( chalk.yellow( 'No search-replace mappings found.' ) );
console.log( `Configure them under extra.altis.cloud.search-replace.${ searchReplaceKey } in composer.json, or use --replace.` );
} else {
console.log( chalk.bold( 'Search-replace mappings that would be applied:' ) );
for ( const [ from, to ] of Object.entries( mappings ) ) {
console.log( ` ${ chalk.red( from ) } → ${ chalk.green( to ) }` );
}
}
} catch ( err ) {
console.error( chalk.red( err.message ) );
process.exit( 1 );
}
return;
}
// 1. Validate local project
const spinner = ora( 'Validating local project…' ).start();
try {
validateLocalProject( localPath );
spinner.succeed( `Local project: ${ chalk.underline( localPath ) }` );
} catch ( err ) {
spinner.fail( err.message );
process.exit( 1 );
}
// 2. Resolve search-replace mappings (fail fast before any remote calls)
let mappings;
try {
mappings = resolveMappings( localPath, searchReplaceKey, replacePairs, skipSearchReplace );
} catch ( err ) {
console.error( chalk.red( err.message ) );
process.exit( 1 );
}
if ( Object.keys( mappings ).length === 0 ) {
console.log( chalk.yellow(
`No search-replace mappings found for key "${ searchReplaceKey }". Skipping search-replace. ` +
`Configure them under extra.altis.cloud.search-replace.${ searchReplaceKey } in composer.json, or use --replace.`
) );
} else {
console.log( chalk.dim( `Search-replace: ${ Object.keys( mappings ).length } mapping(s) from composer.json[${ searchReplaceKey }]` ) );
}
// 3. Choose backup (before confirm, so the user knows what they're agreeing to)
const startTime = new Date();
let logId = resume;
let backup = null;
if ( latest ) {
backup = await getLatestBackup( v, app );
if ( ! backup ) {
console.error( chalk.red( `No existing backup found for ${ chalk.bold( app ) }.` ) );
process.exit( 1 );
}
const age = formatAge( new Date( backup.date ) );
console.log( chalk.dim( `Using latest backup: ${ backup.id } (${ age } old)` ) );
} else if ( ! logId ) {
backup = await promptBackupChoice( v, app );
}
if ( siteId && siteId.length > 1 ) {
console.error( chalk.red( 'Error: --site-id only accepts a single value for full sync (uploads can only target one path).' ) );
process.exit( 1 );
}
if ( siteId?.length && ( latest || logId ) ) {
console.log( chalk.yellow( 'Warning: --site-id is ignored when using --latest or --resume (backup already created).' ) );
}
// 4. Confirm with full context (--latest implies --yes)
if ( ! yes && ! latest ) {
let confirmMsg;
if ( backup ) {
const age = formatAge( new Date( backup.date ) );
confirmMsg = `Import backup ${ chalk.bold( backup.id ) } (${ chalk.dim( age + ' old' ) }) — replace local DB and merge uploads?`;
} else if ( logId ) {
confirmMsg = `Resume backup ${ chalk.bold( logId ) } and import DB + uploads into local project?`;
} else {
confirmMsg = `Create a new backup of ${ chalk.bold( app ) } and replace local DB and uploads?`;
}
await confirm( confirmMsg );
}
const workDir = outputDir || fs.mkdtempSync( path.join( tmpdir(), 'altis-sync-' ) );
const archivePath = path.join( workDir, `${ app }.tar` );
const extractDir = path.join( workDir, `${ app }-extracted` );
try {
// 5. Create backup if needed
if ( ! backup && ! logId ) {
const backupSpinner = ora( `Creating remote backup for ${ chalk.bold( app ) }…` ).start();
let tableList = table ? table.flatMap( t => String( t ).split( ',' ) ) : [];
if ( siteId && siteId.length ) {
const siteIdList = siteId.flatMap( s => String( s ).split( ',' ) );
const siteTables = await resolveTablesForSiteIds( v, app, siteIdList );
tableList = [ ...new Set( [ ...tableList, ...siteTables ] ) ];
}
const resolvedUploadsPath = siteId?.length ? `sites/${ siteId[0] }` : uploadsPath;
const opts = {
database: 1,
uploads: 1,
...( tableList.length ? { tables: tableList } : {} ),
...( resolvedUploadsPath ? { uploads_path: resolvedUploadsPath } : {} ),
};
try {
logId = await startBackup( v, app, opts );
backupSpinner.succeed( `Backup started (log: ${ chalk.dim( logId ) })` );
console.log( chalk.dim( `Resume later with: altis-cli app sync-local all ${ app } --resume ${ logId }` ) );
} catch ( err ) {
backupSpinner.fail( `Failed to start backup: ${ err.message }` );
process.exit( 1 );
}
}
// 6. Wait for backup to complete (if creating new or resuming)
if ( ! backup ) {
console.log( chalk.bold( 'Streaming backup progress…' ) );
await waitForBackup( v, app, logId, startTime, debug );
// 7. Find completed backup
const findSpinner = ora( 'Finding completed backup…' ).start();
backup = await findCompletedBackup( v, app, startTime );
if ( ! backup ) {
findSpinner.fail(
`Backup completed but no download URL found. Run:\n altis-cli app backups ${ app }`
);
process.exit( 1 );
}
findSpinner.succeed( `Backup: ${ chalk.dim( backup.id ) }` );
}
// 6. Download archive
fs.mkdirSync( workDir, { recursive: true } );
await downloadArchive( backup.url, archivePath );
// 7. Extract
const extractSpinner = ora( 'Extracting archive…' ).start();
await extractArchive( archivePath, extractDir );
const sqlGzPath = path.join( extractDir, 'database.sql.gz' );
const uploadsDir = path.join( extractDir, 'uploads' );
if ( ! fs.existsSync( sqlGzPath ) ) {
extractSpinner.fail( 'database.sql.gz not found in archive.' );
process.exit( 1 );
}
if ( ! fs.existsSync( uploadsDir ) ) {
extractSpinner.fail( 'uploads/ not found in archive.' );
process.exit( 1 );
}
extractSpinner.succeed( 'Extracted.' );
// 8. Search-replace + import database
console.log( chalk.bold( 'Importing database…' ) );
await searchReplaceAndImport( sqlGzPath, mappings, localPath );
// 9. Cache flush
console.log( chalk.dim( 'Flushing object cache…' ) );
await runComposerServer( localPath, [ 'cli', '--', 'cache', 'flush' ] );
// 10. Post-sync hook
if ( ! skipPostSync ) {
console.log( chalk.dim( 'Running wp altis post-sync…' ) );
await runPostSync( localPath );
}
// 11. Copy uploads + import into S3
console.log( chalk.bold( 'Syncing uploads…' ) );
const copySpinner = ora( 'Copying uploads to content/uploads…' ).start();
copyUploads( extractDir, localPath );
copySpinner.succeed( 'Uploads copied.' );
console.log( chalk.dim( 'Syncing uploads to local S3…' ) );
try {
await runComposerServer( localPath, [ 's3', 'import-uploads' ] );
} catch {
await runComposerServer( localPath, [ 'import-uploads' ] );
}
console.log( chalk.bold.green( `\n✓ Database and uploads synced from ${ app }` ) );
} catch ( err ) {
console.error( chalk.red( `\nSync failed: ${ err.message }` ) );
if ( fs.existsSync( archivePath ) || fs.existsSync( extractDir ) ) {
console.log( chalk.dim( 'Kept files for debugging:' ) );
if ( fs.existsSync( archivePath ) ) console.log( ` ${ archivePath }` );
if ( fs.existsSync( extractDir ) ) console.log( ` ${ extractDir }` );
}
process.exit( 1 );
}
// 12. Cleanup
if ( ! keepArchive ) {
try {
fs.rmSync( archivePath, { force: true } );
fs.rmSync( extractDir, { recursive: true, force: true } );
} catch {
// Non-fatal
}
}
};
export default {
command: 'all <app>',
description: 'Sync database and uploads from a remote Altis Dashboard app into local-server.',
builder: cmd => {
addCommonOptions( cmd );
addDatabaseOptions( cmd );
addUploadsOptions( cmd );
},
handler,
};