UNPKG

2.6 kBPlain TextView Raw
1import fs from 'fs'
2
3type PythonSystemPackageLookupMap = Map<string, Map<string, Map<string, Map<string, Array<string> | null>>>>
4
5/**
6 * Parses a value and converts it to a Map (recursively) if it is a plain JavaScript object, otherwise just return the
7 * value
8 */
9function valueToMap (value: any): any {
10 if (!Array.isArray(value) && typeof value === 'object') {
11 let m = new Map<any, any>()
12 for (let key in value) {
13 if (!value.hasOwnProperty(key)) {
14 continue
15 }
16
17 m.set(key, valueToMap(value[key]))
18 }
19 return m
20 }
21 return value
22}
23
24/**
25 * An object that looks up if any system packages are required for a Python package.
26 * The lookup is in the format {packageName: pythonVersion: systemPackageType: systemVersion: [sysPackage, sysPackage...]}
27 */
28export default class PythonSystemPackageLookup {
29 /**
30 * @param packageLookup: PythonSystemPackageLookupMap the Map
31 */
32 constructor (private readonly packageLookup: PythonSystemPackageLookupMap) {
33 }
34
35 /**
36 * Construct a `PythonSystemPackageLookup` by parsing a JSON representation of the package map from `path`
37 */
38 static fromFile (path: string): PythonSystemPackageLookup {
39 const dependencyLookupRaw = JSON.parse(fs.readFileSync(path, 'utf8'))
40 return new PythonSystemPackageLookup(valueToMap(dependencyLookupRaw))
41 }
42
43 /**
44 * Look up the system package required for a python package given python version, package type and system version.
45 * Will always return an Array, which will be empty if there are no packages to install.
46 */
47 lookupSystemPackage (pythonPackage: string, pythonMajorVersion: number, systemPackageType: string, systemVersion: string): Array<string> {
48 const pyPackageMap = this.packageLookup.get(pythonPackage)
49
50 if (!pyPackageMap) {
51 return []
52 }
53
54 const pyVersionStr = `${pythonMajorVersion}`
55
56 let pyVersionMap
57
58 if (pyPackageMap.has(pyVersionStr)) {
59 pyVersionMap = pyPackageMap.get(pyVersionStr)
60 } else {
61 pyVersionMap = pyPackageMap.get('default')
62 }
63
64 if (!pyVersionMap) {
65 return []
66 }
67
68 let systemVersionMap
69
70 if (pyVersionMap.has(systemPackageType)) {
71 systemVersionMap = pyVersionMap.get(systemPackageType)
72 } else {
73 systemVersionMap = pyVersionMap.get('default')
74 }
75
76 if (!systemVersionMap) {
77 return []
78 }
79
80 let systemPackages
81
82 if (systemVersionMap.has(systemVersion)) {
83 systemPackages = systemVersionMap.get(systemVersion)
84 } else {
85 systemPackages = systemVersionMap.get('default')
86 }
87
88 return systemPackages || []
89 }
90}