swaf/src/components/AutoUpdateComponent.ts

56 lines
1.8 KiB
TypeScript
Raw Permalink Normal View History

import {Router} from "express";
2020-05-05 15:19:23 +02:00
import config from "config";
import * as child_process from "child_process";
import ApplicationComponent from "../ApplicationComponent";
import {ForbiddenHttpError} from "../HttpError";
import {logger} from "../Logger";
2020-05-05 15:19:23 +02:00
export default class AutoUpdateComponent extends ApplicationComponent {
private static async runCommand(command: string): Promise<void> {
logger.info(`> ${command}`);
logger.info(child_process.execSync(command).toString());
}
public async checkSecuritySettings(): Promise<void> {
this.checkSecurityConfigField('gitlab_webhook_token');
}
public async init(router: Router): Promise<void> {
router.post('/update/push.json', (req, res) => {
2020-05-05 15:19:23 +02:00
const token = req.header('X-Gitlab-Token');
if (!token || token !== config.get<string>('gitlab_webhook_token'))
throw new ForbiddenHttpError('Invalid token', req.url);
2020-05-05 15:19:23 +02:00
this.update(req.body).catch(logger.error);
2020-05-05 15:19:23 +02:00
res.json({
'status': 'ok',
});
});
}
private async update(params: { [p: string]: unknown }) {
logger.info('Update params:', params);
2020-05-05 15:19:23 +02:00
try {
logger.info('Starting auto update...');
2020-05-05 15:19:23 +02:00
2020-06-15 12:58:27 +02:00
// Fetch
await AutoUpdateComponent.runCommand(`git pull`);
2020-05-05 15:19:23 +02:00
// Install new dependencies
await AutoUpdateComponent.runCommand(`yarn install --production=false`);
2020-05-05 15:19:23 +02:00
// Process assets
await AutoUpdateComponent.runCommand(`yarn dist`);
2020-05-05 15:19:23 +02:00
// Stop app
await this.getApp().stop();
logger.info('Success!');
2020-05-05 15:19:23 +02:00
} catch (e) {
logger.error(e, 'An error occurred while running the auto update.');
2020-05-05 15:19:23 +02:00
}
}
}