-
-
Notifications
You must be signed in to change notification settings - Fork 188
/
importPackage.ts
69 lines (61 loc) · 2.21 KB
/
importPackage.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import { dirname, resolve } from 'path';
import * as prettier from 'prettier';
import * as svelte from 'svelte/compiler';
import sveltePreprocess from 'svelte-preprocess';
import { Logger } from './logger';
/**
* Whether or not the current workspace can be trusted.
* TODO rework this to a class which depends on the LsConfigManager
* and inject that class into all places where it's needed (Document etc.)
*/
let isTrusted = true;
export function setIsTrusted(_isTrusted: boolean) {
isTrusted = _isTrusted;
}
/**
* This function encapsulates the require call in one place
* so we can replace its content inside rollup builds
* so it's not transformed.
*/
function dynamicRequire(dynamicFileToRequire: string): any {
// prettier-ignore
return require(dynamicFileToRequire);
}
export function getPackageInfo(packageName: string, fromPath: string) {
const paths = [__dirname];
if (isTrusted) {
paths.unshift(fromPath);
}
const packageJSONPath = require.resolve(`${packageName}/package.json`, {
paths
});
const { version } = dynamicRequire(packageJSONPath);
const [major, minor, patch] = version.split('.');
return {
path: dirname(packageJSONPath),
version: {
full: version,
major: Number(major),
minor: Number(minor),
patch: Number(patch)
}
};
}
export function importPrettier(fromPath: string): typeof prettier {
const pkg = getPackageInfo('prettier', fromPath);
const main = resolve(pkg.path);
Logger.debug('Using Prettier v' + pkg.version.full, 'from', main);
return dynamicRequire(main);
}
export function importSvelte(fromPath: string): typeof svelte {
const pkg = getPackageInfo('svelte', fromPath);
const main = resolve(pkg.path, 'compiler');
Logger.debug('Using Svelte v' + pkg.version.full, 'from', main);
return dynamicRequire(main + (pkg.version.major >= 4 ? '.cjs' : ''));
}
export function importSveltePreprocess(fromPath: string): typeof sveltePreprocess {
const pkg = getPackageInfo('svelte-preprocess', fromPath);
const main = resolve(pkg.path);
Logger.debug('Using svelte-preprocess v' + pkg.version.full, 'from', main);
return dynamicRequire(main);
}