-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathmigration.js
89 lines (80 loc) · 2.56 KB
/
migration.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
const dotenvExt = require('dotenv-extended');
const fs = require('fs');
const path = require('path');
let isLocal = false;
// Load environment variables
dotenvExt.load({
path: path.join(process.env.INIT_CWD ?? '.', '.env'),
defaults: path.join(process.env.INIT_CWD ?? '.', '.env.defaults'),
errorOnMissing: false,
includeProcessEnv: true,
});
const type = 'CHAT';
const isMysqlMigration = process.env.MYSQL_MIGRATION === 'true'; // MySQL migration flag
try {
if (fs.existsSync('.infolder')) {
isLocal = true;
}
} catch (err) {
console.info('\n');
}
if (isLocal) {
console.info(`Skipping migrations`);
} else if (
!(process.env[`${type}_MIGRATION`] || process.env.SOURCELOOP_MIGRATION)
) {
console.warn(
`${type}_MIGRATION or SOURCELOOP_MIGRATION variables not found in the environment, skipping automigration.`,
);
} else {
const DBMigrate = require('db-migrate');
dotenvExt.load({
schema: path.join('.', 'migrations', '.env.schema'),
path: path.join(process.env.INIT_CWD, '.env'),
errorOnMissing: true,
includeProcessEnv: true,
});
// Set migration directory and database config path based on MYSQL_MIGRATION flag
const migrationDir = isMysqlMigration ? 'mysql' : 'pg';
const dbmigrate = DBMigrate.getInstance(true, {
config: path.join('migrations', migrationDir, 'database.json'),
cwd: path.resolve(process.cwd(), 'migrations', migrationDir),
});
dbmigrate.up();
}
// Copy migration files if COPY flag is set
if (
process.env.SOURCELOOP_MIGRATION_COPY ||
process.env[`${type}_MIGRATION_COPY`]
) {
const migrationDir = isMysqlMigration ? 'mysql' : 'pg';
copyFolderRecursiveSync(
path.join('.', 'migrations', migrationDir, 'migrations'),
process.env.INIT_CWD,
);
}
// Utility functions for copying files and folders
function copyFileSync(source, target) {
let targetFile = target;
if (fs.existsSync(target) && fs.lstatSync(target).isDirectory()) {
targetFile = path.join(target, path.basename(source));
}
fs.writeFileSync(targetFile, fs.readFileSync(source));
}
function copyFolderRecursiveSync(source, target) {
const targetFolder = path.join(target, path.basename(source));
if (!fs.existsSync(targetFolder)) {
fs.mkdirSync(targetFolder);
}
if (fs.lstatSync(source).isDirectory()) {
const files = fs.readdirSync(source);
files.forEach(file => {
const curSource = path.join(source, file);
if (fs.lstatSync(curSource).isDirectory()) {
copyFolderRecursiveSync(curSource, targetFolder);
} else {
copyFileSync(curSource, targetFolder);
}
});
}
}