forked from TryGhost/Ghost-CLI
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbackup.js
230 lines (201 loc) · 8.12 KB
/
backup.js
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
'use strict';
const Command = require('../command');
const Promise = require('bluebird');
const createDebug = require('debug');
const Zip = require('adm-zip');
const walker = require('klaw-sync');
const fs = require('fs-extra');
const path = require('path');
const errors = require('../').errors;
const debug = createDebug('ghost-cli:backup');
function absolutePath(inputPath) {
return path.isAbsolute(inputPath) ? inputPath : path.join(process.cwd(), inputPath);
}
class BackupCommand extends Command {
run(argv) {
const instance = this.system.getInstance();
return this.ui.listr([{
task: this.initialize,
title: 'Checking configuration'
}, {
title: 'Backing up extensions',
task: this.backupExtensions
}, {
title: 'Backing up database',
task: this.backupDatabase
}, {
title: 'Backing up config files',
task: this.backupConfig
}, {
title: 'Backing up content folder',
task: this.backupContent.bind(this)
}, {
title: 'Writing backup file',
task: this.writeZipFile
}],{
system: this.system,
argv: argv,
instance: instance
});
}
initialize(ctx) {
const datetime = (new Date()).toJSON().substring(0, 10);
ctx.database = {};
ctx.saveLocation = process.cwd();
if (ctx.argv.output) {
ctx.saveLocation = absolutePath(ctx.argv.output);
}
try {
fs.ensureDirSync(ctx.saveLocation);
// After we're sure the directory exists, check to make sure we can write to it
fs.accessSync(ctx.saveLocation, fs.W_OK);
} catch (error) {
ctx.instance.ui.log('Ghost doesn\'t have permission to write to the output folder', 'red');
return Promise.reject(new errors.SystemError(error));
}
const saveRoot = ctx.saveLocation
ctx.saveLocation = path.join(saveRoot, `${ctx.instance.name}.backup.${datetime}.zip`);
let offset = 1;
while (fs.existsSync(ctx.saveLocation)) {
ctx.saveLocation = path.join(saveRoot, `${ctx.instance.name}.backup.${datetime}-${offset}.zip`);
offset += 1;
}
// The zip library used (adm-zip) has a known issue where the zip is structurally sound,
// but Windows has issues reading / unzipping it. To counteract this, all files are read
// and added via the `addFile` method, where the file permissions can be set, seemingly
// resolving the issue. See https://github.com/cthackers/adm-zip/issues/171
ctx.zipFile = new Zip();
if (ctx.instance.running()) {
ctx.instance.ui.log('Ghost is currently running. Backing up might take longer and slow down your site', 'yellow');
ctx.instance.loadRunningEnvironment(true);
} else {
ctx.instance.checkEnvironment();
}
return Promise.resolve();
}
backupContent(ctx, dontcare, folder) {
folder = folder || './content';
// path MUST be relative
if (folder.indexOf('./') !== 0) {
folder = './' + folder;
}
if (ctx.argv.verbose) {
ctx.instance.ui.logVerbose(`Backing up ${folder}`,'blue');
}
let files;
try {
files = walker(folder, {nodir: true});
} catch (error) {
debug(`Failed reading ${folder}: ${error}`);
return Promise.reject(new errors.SystemError({
context: error,
message: 'Failed to read content folder'
}));
}
const cwd = process.cwd();
const promises = files.map((file) => {
const location = file.path.replace(/\\/g,'/');
let dir = path.dirname(location);
dir = path.relative(cwd, dir);
const name = path.basename(location);
const localFile = `${dir}/${name}`;
return fs.readFile(`./${localFile}`).then((fileData) => {
ctx.zipFile.addFile(localFile, fileData, '', 644);
}).catch((err) => {
if (err.code === 'EISDIR') { // Symlink
return this.backupContent(ctx, null, localFile).catch((error) => {
debug(error);
ctx.instance.ui.log(`Failed to backup ${localFile}`, 'yellow');
// Even though this specific file couldn't be backed up, we want to continue
return Promise.resolve();
});
} else {
debug(err);
ctx.instance.ui.log(`Failed to backup ${localFile}`, 'yellow');
// Even though this specific file couldn't be backed up, we want to continue
return Promise.resolve();
}
});
});
return Promise.all(promises);
}
backupConfig(ctx) {
debug('Intializing zip file');
try {
const configFileName = `config.${ctx.system.environment}.json`;
const readFile = fs.readFileSync;
// Add environment-specific config file
ctx.zipFile.addFile(configFileName, readFile(configFileName), '', 644);
// Add CLI config file
ctx.zipFile.addFile('.ghost-cli', readFile('.ghost-cli'), '', 644);
return Promise.resolve();
} catch (error) {
debug(`Failed creating zip: ${error}`);
return Promise.reject(new errors.SystemError({
context: error,
message: 'Failed backing up configuration files'
}));
}
}
backupExtensions(ctx) {
const isArray = require('lodash/isArray');
const read = fs.readFileSync;
return ctx.system.hook('backup').then((extensionFiles) => {
extensionFiles.forEach((filesToAdd) => {
if (isArray(filesToAdd)) {
filesToAdd.forEach((metadata) => {
try {
ctx.zipFile.addFile(`extension/${metadata.fileName}`, read(metadata.location), '', 644);
} catch (error) {
ctx.ui.log(`Not backing up "${metadata.description || metadata.location}" - ${error.message}`);
}
});
} /* else if(filesToAdd !== undefined) {
// @todo: do we need to do anything here?
debug('Bad data passed');
}*/
});
}).catch(Promise.reject);
}
writeZipFile(ctx) {
// Write zip file to specified folder
debug(`Writing zipFile to ${ctx.saveLocation}`);
ctx.zipFile.writeZip(ctx.saveLocation);
ctx.instance.ui.log(`Wrote backup to ${ctx.saveLocation}`);
// clear up memory
ctx.zipFile = null;
}
backupDatabase(ctx) {
debug('Creating database backup');
let exporter;
try {
// This is based on cwd, not cli-install location
exporter = require(absolutePath('current/core/server/data/export/'));
} catch (error) {
debug(`Failed to load exporter: ${error}`);
// @todo: specific error type?
return Promise.reject(new Error('Unable to initialize database exporter'));
}
return exporter.doExport().then((database) => {
database = JSON.stringify(database);
ctx.zipFile.addFile('database.json', Buffer.from(database), '', 644);
return Promise.resolve();
}).catch((error) => {
if (error.code === 'ECONNREFUSED') {
// @todo: should this be a system error?
return Promise.reject(new Error('Unable to connect to MySQL'));
} else {
return Promise.reject(error);
}
});
}
}
BackupCommand.description = 'Create a backup of your installation';
BackupCommand.options = {
output: {
alias: 'o',
description: 'Folder to save backup in',
type: 'string'
}
};
module.exports = BackupCommand;