2022-12-21 13:17:50 +00:00
|
|
|
const Myt = require('./myt');
|
2022-12-21 12:34:17 +00:00
|
|
|
const Command = require('./lib/command');
|
2022-05-08 20:44:40 +00:00
|
|
|
const fs = require('fs-extra');
|
2023-01-25 17:16:43 +00:00
|
|
|
const path = require('path');
|
2022-05-08 20:44:40 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Cleans old applied versions.
|
|
|
|
*/
|
2022-12-21 12:34:17 +00:00
|
|
|
class Clean extends Command {
|
|
|
|
static usage = {
|
|
|
|
description: 'Cleans old applied versions'
|
|
|
|
};
|
|
|
|
|
2022-12-29 09:15:02 +00:00
|
|
|
static opts = {
|
2022-12-21 12:34:17 +00:00
|
|
|
default: {
|
|
|
|
remote: 'production'
|
|
|
|
}
|
|
|
|
};
|
2022-05-08 20:44:40 +00:00
|
|
|
|
2024-01-04 12:02:40 +00:00
|
|
|
static reporter = {
|
|
|
|
versionsDeleted: function(nVersions) {
|
|
|
|
console.log(`Old versions deleted: ${nVersions}`);
|
|
|
|
},
|
|
|
|
noVersionsDeleted: 'No versions to delete.'
|
|
|
|
};
|
|
|
|
|
2022-12-21 13:17:50 +00:00
|
|
|
async run(myt, opts) {
|
|
|
|
await myt.dbConnect();
|
|
|
|
const version = await myt.fetchDbVersion() || {};
|
2022-05-08 20:44:40 +00:00
|
|
|
const number = version.number;
|
|
|
|
|
|
|
|
const oldVersions = [];
|
2022-12-21 12:34:17 +00:00
|
|
|
const versionDirs = await fs.readdir(opts.versionsDir);
|
2022-05-08 20:44:40 +00:00
|
|
|
for (const versionDir of versionDirs) {
|
2022-12-21 13:17:50 +00:00
|
|
|
const dirVersion = myt.parseVersionDir(versionDir);
|
2022-05-08 20:44:40 +00:00
|
|
|
if (!dirVersion) continue;
|
|
|
|
|
|
|
|
if (parseInt(dirVersion.number) < parseInt(number))
|
|
|
|
oldVersions.push(versionDir);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (opts.maxOldVersions
|
|
|
|
&& oldVersions.length > opts.maxOldVersions) {
|
|
|
|
oldVersions.splice(-opts.maxOldVersions);
|
|
|
|
|
2023-01-25 17:16:43 +00:00
|
|
|
const archiveDir = path.join(opts.versionsDir, '.archive');
|
|
|
|
if (!await fs.pathExists(archiveDir))
|
|
|
|
await fs.mkdir(archiveDir);
|
|
|
|
|
2022-05-08 20:44:40 +00:00
|
|
|
for (const oldVersion of oldVersions)
|
2023-01-25 17:16:43 +00:00
|
|
|
await fs.move(
|
|
|
|
path.join(opts.versionsDir, oldVersion),
|
|
|
|
path.join(archiveDir, oldVersion)
|
|
|
|
);
|
2022-05-08 20:44:40 +00:00
|
|
|
|
2024-01-04 12:02:40 +00:00
|
|
|
this.emit('versionsDeleted', oldVersions.length);
|
2022-05-08 20:44:40 +00:00
|
|
|
} else
|
2024-01-04 12:02:40 +00:00
|
|
|
this.emit('noVersionsDeleted');
|
2022-05-08 20:44:40 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = Clean;
|
|
|
|
|
|
|
|
if (require.main === module)
|
2024-01-04 12:02:40 +00:00
|
|
|
new Myt().cli(Clean);
|