forked from webhintio/hint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlebars-utils.ts
55 lines (43 loc) · 1.6 KB
/
handlebars-utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import * as Handlebars from 'handlebars';
import { fs } from '@hint/utils';
import { loadHintPackage } from 'hint/dist/src/lib/utils/packages/load-hint-package';
const { readFileAsync } = fs;
const pkg = loadHintPackage();
/**
* Searches the current version used for a package in `hint` and uses that version or the `defaultVersion`.
*
* This is used when creating a new hint via the CLI to make sure the dependencies are up-to-date in the moment
* of creation.
*/
Handlebars.registerHelper('dependencyVersion', (packageName, defaultVersion): string => {
const version = packageName === 'hint' ?
`^${pkg.version}` :
pkg.dependencies[packageName] ||
pkg.devDependencies[packageName] ||
defaultVersion;
return `"${packageName}": "${version}"`;
});
/**
* Use `escapeSafeString` function instead of triple curly brace in the templates
* to escape the backticks (`) in the user's input.
* Example:
* ```
* description: `This is a \`important\` hint that has 'single' and "double" quotes.`
* ```
*/
export const escapeSafeString = (str: string): hbs.SafeString => {
const result = str.replace(/(`)/g, '\\$1');
return new Handlebars.SafeString(result);
};
/** Reads a handlebars template from the file system and compiles it. */
export const compileTemplate = async (filePath: string, data: any): Promise<string> => {
let templateContent;
try {
templateContent = await readFileAsync(filePath);
} catch (err) {
throw (err);
}
const template = Handlebars.compile(templateContent);
return template(data);
};
export default Handlebars;