2023-03-02 16:07:36 -05:00
|
|
|
const { ModelOperations } = require('@vscode/vscode-languagedetection');
|
2023-03-10 22:21:15 -05:00
|
|
|
const languages = require('../utils/languages.js');
|
2023-03-02 16:07:36 -05:00
|
|
|
const codeRegex = /(```[\s\S]*?```)/g;
|
2023-03-10 22:21:15 -05:00
|
|
|
// const languageMatch = /```(\w+)/;
|
2023-03-11 21:42:08 -05:00
|
|
|
const replaceRegex = /```\w+\n/g;
|
2023-03-02 16:07:36 -05:00
|
|
|
|
2023-03-10 22:21:15 -05:00
|
|
|
const detectCode = async (input) => {
|
2023-03-02 16:07:36 -05:00
|
|
|
try {
|
2023-03-10 22:21:15 -05:00
|
|
|
let text = input;
|
2023-03-02 16:07:36 -05:00
|
|
|
if (!text.match(codeRegex)) {
|
|
|
|
|
return text;
|
|
|
|
|
}
|
|
|
|
|
|
2023-03-10 22:21:15 -05:00
|
|
|
const langMatches = text.match(replaceRegex);
|
|
|
|
|
|
|
|
|
|
if (langMatches?.length > 0) {
|
|
|
|
|
langMatches.forEach(match => {
|
|
|
|
|
let lang = match.split('```')[1].trim();
|
|
|
|
|
|
|
|
|
|
if (languages.has(lang)) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
console.log('[detectCode.js] replacing', match, 'with', '```shell');
|
2023-03-11 21:42:08 -05:00
|
|
|
text = text.replace(match, '```shell\n');
|
2023-03-10 22:21:15 -05:00
|
|
|
});
|
|
|
|
|
|
2023-03-02 16:07:36 -05:00
|
|
|
return text;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const modelOperations = new ModelOperations();
|
2023-03-06 12:49:22 -05:00
|
|
|
const regexSplit = (await import('./regexSplit.mjs')).default;
|
2023-03-02 16:07:36 -05:00
|
|
|
const parts = regexSplit(text, codeRegex);
|
|
|
|
|
|
2023-03-06 12:49:22 -05:00
|
|
|
const output = parts.map(async (part) => {
|
2023-03-02 16:07:36 -05:00
|
|
|
if (part.match(codeRegex)) {
|
|
|
|
|
const code = part.slice(3, -3);
|
2023-03-10 22:21:15 -05:00
|
|
|
let lang = (await modelOperations.runModel(code))[0].languageId;
|
|
|
|
|
return part.replace(/^```/, `\`\`\`${languages.has(lang) ? lang : 'shell'}`);
|
2023-03-02 16:07:36 -05:00
|
|
|
} else {
|
2023-03-02 16:31:00 -05:00
|
|
|
return part;
|
2023-03-02 16:07:36 -05:00
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return (await Promise.all(output)).join('');
|
|
|
|
|
} catch (e) {
|
|
|
|
|
console.log('Error in detectCode function\n', e);
|
2023-03-11 14:46:21 -05:00
|
|
|
return input;
|
2023-03-02 16:07:36 -05:00
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
module.exports = detectCode;
|