vscode-texinfo/src/utils.ts

65 lines
2.2 KiB
TypeScript
Raw Normal View History

2020-10-03 18:04:18 +00:00
/**
2020-10-17 13:41:03 +00:00
* utils.ts
2020-10-03 18:04:18 +00:00
*
* @author CismonX <admin@cismon.net>
* @license MIT
*/
import * as child_process from 'child_process';
import * as htmlparser from 'node-html-parser';
import * as vscode from 'vscode';
2020-10-22 22:37:47 +00:00
import Logger from './logger';
2020-10-03 18:04:18 +00:00
/**
* Open a prompt with two buttons, "Confirm" and "Cancel", and wait for user action.
*
* @param message The message to be displayed on the prompt.
* @param confirm Text to be displayed on the "Confirm" button.
2020-10-22 22:37:47 +00:00
* @param error Whether the prompt is shown as an error message. Default false.
2020-10-10 17:36:05 +00:00
* @returns Whether the user clicked the "Confirm" button.
2020-10-03 18:04:18 +00:00
*/
2020-10-22 22:37:47 +00:00
export async function prompt(message: string, confirm: string, error = false) {
const func = error ? vscode.window.showErrorMessage : vscode.window.showInformationMessage;
return confirm === await func(message, confirm, 'Cancel');
2020-10-03 18:04:18 +00:00
}
/**
* Execute command and get output.
*
* @param path Path to the executable file.
* @param args Arguments to be passed to the command.
* @param maxBuffer Max output buffer size.
2020-10-10 17:36:05 +00:00
* @returns The output data, or `undefined` if execution fails.
2020-10-03 18:04:18 +00:00
*/
export function exec(path: string, args: string[], maxBuffer: number) {
2020-10-20 20:07:44 +00:00
return new Promise<string | undefined>(resolve => {
2020-10-03 18:04:18 +00:00
child_process.execFile(path, args, { maxBuffer: maxBuffer }, (error, stdout, stderr) => {
if (error) {
2020-10-22 22:37:47 +00:00
Logger.log(stderr ? stderr : error.message);
2020-10-03 18:04:18 +00:00
resolve(undefined);
} else {
2020-10-22 22:37:47 +00:00
stderr && Logger.log(stderr);
2020-10-03 18:04:18 +00:00
resolve(stdout);
}
});
});
}
/**
* Transform and replace the `src` attribute value of all `img` elements from given HTML code using given function.
*
* @param htmlCode
* @param transformer
* @returns The HTML code after transformation.
*/
export function transformHtmlImageUri(htmlCode: string, transformer: (src: string) => string) {
const dom = htmlparser.parse(htmlCode);
const elements = dom.querySelectorAll('img');
2020-10-20 20:07:44 +00:00
elements.forEach(element => {
const src = element.getAttribute('src');
src && element.setAttribute('src', transformer(src));
2020-10-10 17:36:05 +00:00
});
// If nothing is transformed, return the original HTML code, for better performance.
return elements.length === 0 ? htmlCode : dom.outerHTML;
}