forked from denoland/vscode_deno
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutil.ts
More file actions
258 lines (239 loc) · 7.21 KB
/
util.ts
File metadata and controls
258 lines (239 loc) · 7.21 KB
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
import { EXTENSION_NS } from "./constants";
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import * as process from "process";
import {
Location,
Range,
TextDocument,
workspace,
WorkspaceFolder,
} from "vscode";
import * as jsoncParser from "jsonc-parser/lib/esm/main.js";
import { semver } from "./semver";
import type { DenoInfoJson } from "./types";
import { spawnSync } from "child_process";
import type * as vscode from "vscode";
/** Assert that the condition is "truthy", otherwise throw. */
export function assert(cond: unknown, msg = "Assertion failed."): asserts cond {
if (!cond) {
throw new Error(msg);
}
}
/** Returns the absolute path to an existing deno command or
* the "deno" command name if not found. */
export async function getDenoCommandName() {
return await getDenoCommandPath() ?? "deno";
}
/** Returns the absolute path to an existing deno command. */
export async function getDenoCommandPath() {
const command = getWorkspaceConfigDenoExePath();
const workspaceFolders = workspace.workspaceFolders;
if (!command || !workspaceFolders) {
return command ?? await getDefaultDenoCommand();
} else if (!path.isAbsolute(command)) {
// if sent a relative path, iterate over workspace folders to try and resolve.
for (const workspace of workspaceFolders) {
const commandPath = path.resolve(workspace.uri.fsPath, command);
if (await fileExists(commandPath)) {
return commandPath;
}
}
return undefined;
} else {
return command;
}
}
function getWorkspaceConfigDenoExePath() {
const exePath = workspace.getConfiguration(EXTENSION_NS)
.get<string>("path");
// it is possible for the path to be blank. In that case, return undefined
if (typeof exePath === "string" && exePath.trim().length === 0) {
return undefined;
} else {
return exePath;
}
}
async function getDefaultDenoCommand() {
// Adapted from https://github.com/npm/node-which/blob/master/which.js
// Within vscode it will do `require("child_process").spawn("deno")`,
// which will prioritize "deno.exe" on the path instead of a possible
// higher precedence non-exe executable. This is a problem because, for
// example, version managers may have a `deno.bat` shim on the path. To
// ensure the resolution of the `deno` command matches what occurs on the
// command line, attempt to manually resolve the file path (issue #361).
const denoCmd = "deno";
const pathValue = process.env.PATH ?? "";
const pathFolderPaths = splitEnvValue(pathValue);
// resolve the default install location in case it's not on the PATH
pathFolderPaths.push(getUserDenoBinDir());
const pathExts = getPathExts();
const cmdFileNames = pathExts == null
? [denoCmd]
: pathExts.map((ext) => denoCmd + ext);
for (const pathFolderPath of pathFolderPaths) {
for (const cmdFileName of cmdFileNames) {
const cmdFilePath = path.join(pathFolderPath, cmdFileName);
if (await fileExists(cmdFilePath)) {
return cmdFilePath;
}
}
}
// nothing found
return undefined;
function getPathExts() {
if (os.platform() === "win32") {
const pathExtValue = process.env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM";
return splitEnvValue(pathExtValue);
} else {
return undefined;
}
}
function splitEnvValue(value: string) {
const pathSplitChar = os.platform() === "win32" ? ";" : ":";
return value
.split(pathSplitChar)
.map((item) => item.trim())
.filter((item) => item.length > 0);
}
function getUserDenoBinDir() {
return path.join(os.homedir(), ".deno", "bin");
}
}
export async function getDenoInfoJson(
outputChannel: vscode.OutputChannel,
): Promise<DenoInfoJson | null> {
try {
const command = await getDenoCommandName();
const { stdout, stderr, status, error } = spawnSync(command, [
"info",
"--json",
], {
encoding: "utf-8",
stdio: ["ignore", "pipe", "pipe"],
env: {
...process.env,
"NO_COLOR": "1",
},
});
if (error) {
throw error;
}
if (status != 0) {
throw `Command failed: ${stderr}`;
}
return JSON.parse(stdout);
} catch (error) {
outputChannel.appendLine(
`Couldn't get 'deno info --json' output: ${error}`,
);
return null;
}
}
function fileExists(executableFilePath: string): Promise<boolean> {
return new Promise<boolean>((resolve) => {
fs.stat(executableFilePath, (err, stat) => {
resolve(err == null && stat.isFile());
});
}).catch(() => {
// ignore all errors
return false;
});
}
export function getInspectArg(denoVersion?: string) {
if (
denoVersion && semver.valid(denoVersion) &&
semver.satisfies(denoVersion, ">=1.29.0")
) {
return "--inspect-wait";
} else {
return "--inspect-brk";
}
}
export function isWorkspaceFolder(value: unknown): value is WorkspaceFolder {
return typeof value === "object" && value != null &&
(value as WorkspaceFolder).name !== undefined;
}
export interface TaskDefinitionRange {
name: string;
command: string;
nameRange: Range;
valueRange: Range;
}
export function readTaskDefinitions(
document: TextDocument,
content = document.getText(),
) {
const root = jsoncParser.parseTree(content);
if (!root) {
return undefined;
}
if (root.type != "object" || !root.children) {
return undefined;
}
const tasksProperty = root.children.find((n) =>
n.type == "property" && n.children?.[0]?.value == "tasks"
);
if (!tasksProperty) {
return undefined;
}
const tasksValue = tasksProperty.children?.[1];
if (!tasksValue || tasksValue.type != "object" || !tasksValue.children) {
return undefined;
}
const tasks: TaskDefinitionRange[] = [];
for (const taskProperty of tasksValue.children) {
const taskKey = taskProperty.children?.[0];
if (
taskProperty.type != "property" || !taskKey || taskKey.type != "string"
) {
continue;
}
const taskValue = taskProperty.children?.[1];
if (!taskValue) {
continue;
}
let command;
if (taskValue.type == "string") {
command = taskValue.value;
} else if (taskValue.type == "object" && taskValue.children) {
const commandProperty = taskValue.children.find((n) =>
n.type == "property" && n.children?.[0]?.value == "command"
);
if (!commandProperty) {
continue;
}
const commandValue = commandProperty.children?.[1];
if (!commandValue || commandValue.type != "string") {
continue;
}
command = commandValue.value;
} else {
continue;
}
tasks.push({
name: taskKey.value,
nameRange: new Range(
document.positionAt(taskKey.offset),
document.positionAt(taskKey.offset + taskKey.length),
),
command,
valueRange: new Range(
document.positionAt(taskValue.offset),
document.positionAt(taskValue.offset + taskValue.length),
),
});
}
return {
location: new Location(
document.uri,
new Range(
document.positionAt(tasksProperty.offset),
document.positionAt(tasksProperty.offset + tasksProperty.length),
),
),
tasks,
};
}