-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathbackup-handler.ts
More file actions
executable file
·70 lines (61 loc) · 2.36 KB
/
backup-handler.ts
File metadata and controls
executable file
·70 lines (61 loc) · 2.36 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
import * as path from 'path';
import { copy } from 'fs-extra';
import { cliux, sanitizePath } from '@contentstack/cli-utilities';
import { fileHelper, trace } from './index';
import { ImportConfig } from '../types';
export default async function backupHandler(importConfig: ImportConfig): Promise<string> {
if (importConfig.hasOwnProperty('useBackedupDir')) {
return importConfig.useBackedupDir;
}
const sourceDir = importConfig.branchDir || importConfig.contentDir;
let backupDirPath: string;
const subDir = isSubDirectory(importConfig, sourceDir);
if (subDir) {
backupDirPath = path.resolve(sanitizePath(sourceDir), '..', '_backup_' + Math.floor(Math.random() * 1000));
if (importConfig.createBackupDir) {
cliux.print(
`Warning!!! Provided backup directory path is a sub directory of the content directory, Cannot copy to a sub directory. Hence new backup directory created - ${backupDirPath}`,
{
color: 'yellow',
},
);
}
} else {
// NOTE: If the backup folder's directory is provided, create it at that location; otherwise, the default path (working directory).
backupDirPath = path.join(process.cwd(), '_backup_' + Math.floor(Math.random() * 1000));
if (importConfig.createBackupDir) {
if (fileHelper.fileExistsSync(importConfig.createBackupDir)) {
fileHelper.removeDirSync(importConfig.createBackupDir);
}
fileHelper.makeDirectory(importConfig.createBackupDir);
backupDirPath = importConfig.createBackupDir;
}
}
if (backupDirPath) {
cliux.print('Copying content to the backup directory...');
return new Promise((resolve, reject) => {
return copy(sourceDir, backupDirPath, (error: any) => {
if (error) {
trace(error, 'error', true);
return reject(error);
}
resolve(backupDirPath);
});
});
}
}
/**
* Check whether provided backup directory path is sub directory or not
* @param importConfig
* @returns
*/
function isSubDirectory(importConfig: ImportConfig, sourceDir: string) {
const parent = sourceDir;
const child = importConfig.createBackupDir ? importConfig.createBackupDir : process.cwd();
const relative = path.relative(parent, child);
if (relative) {
return !relative.startsWith('..') && !path.isAbsolute(relative);
}
// true if both parent and child have same path
return true;
}