-
-
Notifications
You must be signed in to change notification settings - Fork 21
/
pip.ts
170 lines (145 loc) Β· 4.27 KB
/
pip.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
import { kw, python, PythonError } from "../mod.ts";
import { join } from "https://deno.land/[email protected]/path/mod.ts";
import { ensureDir } from "https://deno.land/[email protected]/fs/mod.ts";
import { green, yellow } from "https://deno.land/[email protected]/fmt/colors.ts";
import type { CacheLocation } from "https://deno.land/x/[email protected]/types.ts";
import { ensureCacheLocation } from "https://deno.land/x/[email protected]/download.ts";
import { hash } from "https://deno.land/x/[email protected]/util.ts";
const sys = python.import("sys");
const runpy = python.import("runpy");
const importlib = python.import("importlib");
// https://packaging.python.org/en/latest/specifications/name-normalization/
const MODULE_REGEX =
/^([a-z0-9]|[a-z0-9][a-z0-9._-]*[a-z0-9])([^a-z0-9._-].*)?$/i;
function normalizeModuleName(name: string) {
return name.replaceAll(/[-_.]+/g, "-").toLowerCase();
}
function getModuleNameAndVersion(module: string): {
name: string;
version?: string;
} {
const match = module.match(MODULE_REGEX);
const name = match?.[1];
const version = match?.[2];
if (name == null) {
throw new TypeError("Could not match any valid pip module name");
}
return {
name: normalizeModuleName(name),
version,
};
}
export class Pip {
#cacheLocation: Promise<string>;
constructor(location?: CacheLocation) {
this.#cacheLocation = Promise.all([
ensureCacheLocation(location),
globalThis.location !== undefined
? hash(globalThis.location.href)
: Promise.resolve("pip"),
]).then(async (parts) => {
const cacheLocation = join(...parts);
await ensureDir(cacheLocation);
if (!(cacheLocation in sys.path)) {
sys.path.insert(0, cacheLocation);
}
return cacheLocation;
});
}
/**
* Install a Python module using the `pip` package manager.
*
* @param module The Python module which you wish to install
*
* @example
* ```ts
* import { python } from "https://deno.land/x/python/mod.ts";
* import { install } from "https://deno.land/x/python/ext/pip.ts";
*
* await install("numpy");
* const numpy = python.import("numpy");
*
* ```
*/
async install(module: string) {
const argv = sys.argv;
sys.argv = [
"pip",
"install",
"-q",
"-t",
await this.#cacheLocation,
module,
];
console.log(`${green("Installing")} ${module}`);
try {
runpy.run_module("pip", kw`run_name=${"__main__"}`);
} catch (error) {
if (
!(
error instanceof PythonError &&
error.type.isInstance(python.builtins.SystemExit()) &&
error.value.asLong() === 0
)
) {
throw error;
}
} finally {
sys.argv = argv;
}
}
/**
* Install and import a Python module using the `pip` package manager.
*
* @param module The Python module which you wish to install
*
* @example
* ```ts
* import { python } from "https://deno.land/x/python/mod.ts";
* import { pip } from "https://deno.land/x/python/ext/pip.ts";
*
* const numpy = await pip.import("numpy==1.25.2");
*
* ```
*/
async import(module: string, entrypoint?: string) {
const { name } = getModuleNameAndVersion(module);
await this.install(module);
if (entrypoint) {
return python.import(entrypoint);
}
const packages = importlib.metadata.packages_distributions();
const entrypoints = [];
for (const entry of packages) {
if (packages[entry].valueOf().includes(name)) {
entrypoints.push(entry.valueOf());
}
}
if (entrypoints.length === 0) {
throw new TypeError(
`Failed to import module ${module}, could not find import name ${name}`,
);
}
entrypoint = entrypoints[0];
if (entrypoints.length > 1) {
if (entrypoints.includes(name)) {
entrypoint = entrypoints[entrypoints.indexOf(name)];
} else {
console.warn(
`${
yellow(
"Warning",
)
} could not determine a single entrypoint for module ${module}, please specify one of: ${
entrypoints.join(
", ",
)
}. Importing ${entrypoint}`,
);
}
}
return python.import(entrypoint!);
}
}
export const pip = new Pip();
export default pip;