修复调试脚本运行需要先保存

This commit is contained in:
whyour 2022-06-05 19:26:32 +08:00
parent be76ff4675
commit 8735321e34
3 changed files with 46 additions and 41 deletions

View File

@ -11,7 +11,7 @@ import { Logger } from 'winston';
import config from '../config'; import config from '../config';
import * as fs from 'fs'; import * as fs from 'fs';
import { celebrate, Joi } from 'celebrate'; import { celebrate, Joi } from 'celebrate';
import path, { join } from 'path'; import path, { join, parse } from 'path';
import ScriptService from '../services/script'; import ScriptService from '../services/script';
import multer from 'multer'; import multer from 'multer';
const route = Router(); const route = Router();
@ -218,17 +218,18 @@ export default (app: Router) => {
celebrate({ celebrate({
body: Joi.object({ body: Joi.object({
filename: Joi.string().required(), filename: Joi.string().required(),
content: Joi.string().optional(),
path: Joi.string().optional().allow(''), path: Joi.string().optional().allow(''),
}), }),
}), }),
async (req: Request, res: Response, next: NextFunction) => { async (req: Request, res: Response, next: NextFunction) => {
const logger: Logger = Container.get('logger'); const logger: Logger = Container.get('logger');
try { try {
let { filename, path } = req.body as { let { filename, content, path } = req.body;
filename: string; const { name, ext } = parse(filename);
path: string; const filePath = join(path, `${name}.swap${ext}`);
}; fs.writeFileSync(filePath, content || '', { encoding: 'utf8' });
const filePath = join(path, filename);
const scriptService = Container.get(ScriptService); const scriptService = Container.get(ScriptService);
const result = await scriptService.runScript(filePath); const result = await scriptService.runScript(filePath);
res.send(result); res.send(result);
@ -244,17 +245,17 @@ export default (app: Router) => {
celebrate({ celebrate({
body: Joi.object({ body: Joi.object({
filename: Joi.string().required(), filename: Joi.string().required(),
content: Joi.string().optional().allow(''),
path: Joi.string().optional().allow(''), path: Joi.string().optional().allow(''),
}), }),
}), }),
async (req: Request, res: Response, next: NextFunction) => { async (req: Request, res: Response, next: NextFunction) => {
const logger: Logger = Container.get('logger'); const logger: Logger = Container.get('logger');
try { try {
let { filename, path } = req.body as { let { filename, content, path } = req.body;
filename: string; const { name, ext } = parse(filename);
path: string; const filePath = join(path, `${name}.swap${ext}`);
};
const filePath = join(path, filename);
const scriptService = Container.get(ScriptService); const scriptService = Container.get(ScriptService);
const result = await scriptService.stopScript(filePath); const result = await scriptService.stopScript(filePath);
res.send(result); res.send(result);

View File

@ -1,8 +1,9 @@
import { Service, Inject } from 'typedi'; import { Service, Inject } from 'typedi';
import winston from 'winston'; import winston from 'winston';
import { spawn } from 'child_process'; import { ChildProcessWithoutNullStreams, spawn } from 'child_process';
import SockService from './sock'; import SockService from './sock';
import CronService from './cron'; import CronService from './cron';
import ScheduleService, { TaskCallbacks } from './schedule';
@Service() @Service()
export default class ScriptService { export default class ScriptService {
@ -10,38 +11,37 @@ export default class ScriptService {
@Inject('logger') private logger: winston.Logger, @Inject('logger') private logger: winston.Logger,
private sockService: SockService, private sockService: SockService,
private cronService: CronService, private cronService: CronService,
private scheduleService: ScheduleService,
) {} ) {}
public async runScript(path: string) { private taskCallbacks(): TaskCallbacks {
const cp = spawn(`task -l ${path} now`, { shell: '/bin/bash' }); return {
onEnd: async (cp, endTime, diff) => {
cp.stdout.on('data', (data) => {
this.sockService.sendMessage({ this.sockService.sendMessage({
type: 'manuallyRunScript', type: 'manuallyRunScript',
message: data.toString(), message: `\n## 执行结束... ${endTime.format(
'YYYY-MM-DD HH:mm:ss',
)} ${diff} `,
}); });
}); },
onError: async (message: string) => {
cp.stderr.on('data', (data) => {
this.sockService.sendMessage({ this.sockService.sendMessage({
type: 'manuallyRunScript', type: 'manuallyRunScript',
message: data.toString(), message,
}); });
}); },
onLog: async (message: string) => {
cp.on('error', (err) => {
this.sockService.sendMessage({ this.sockService.sendMessage({
type: 'manuallyRunScript', type: 'manuallyRunScript',
message: JSON.stringify(err), message,
});
}); });
},
};
}
cp.on('close', (err) => { public async runScript(filePath: string) {
this.sockService.sendMessage({ const command = `task -l ${filePath} now`;
type: 'manuallyRunScript', this.scheduleService.runTask(command, this.taskCallbacks());
message: `执行结束`,
});
});
return { code: 200 }; return { code: 200 };
} }

View File

@ -74,11 +74,13 @@ const EditModal = ({
const run = () => { const run = () => {
setLog(''); setLog('');
const content = editorRef.current.getValue().replace(/\r\n/g, '\n');
request request
.put(`${config.apiPrefix}scripts/run`, { .put(`${config.apiPrefix}scripts/run`, {
data: { data: {
filename: cNode.title, filename: cNode.title,
path: cNode.parent || '', path: cNode.parent || '',
content,
}, },
}) })
.then((data) => { .then((data) => {
@ -90,11 +92,13 @@ const EditModal = ({
if (!cNode || !cNode.title) { if (!cNode || !cNode.title) {
return; return;
} }
const content = editorRef.current.getValue().replace(/\r\n/g, '\n');
request request
.put(`${config.apiPrefix}scripts/stop`, { .put(`${config.apiPrefix}scripts/stop`, {
data: { data: {
filename: cNode.title, filename: cNode.title,
path: cNode.parent || '', path: cNode.parent || '',
content,
}, },
}) })
.then((data) => { .then((data) => {