forked from hverlin/mise-vscode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiseService.ts
More file actions
1223 lines (1060 loc) · 30.6 KB
/
Copy pathmiseService.ts
File metadata and controls
1223 lines (1060 loc) · 30.6 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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { existsSync } from "node:fs";
import { readlink, rm, symlink } from "node:fs/promises";
import * as os from "node:os";
import path from "node:path";
import { createCache } from "async-cache-dedupe";
import { parse } from "toml-v1";
import * as vscode from "vscode";
import { MISE_RELOAD } from "./commands";
import {
getCommandTTLCacheSeconds,
getConfiguredBinPath,
getCurrentWorkspaceFolderPath,
getMiseEnv,
isMiseExtensionEnabled,
shouldCheckForNewMiseVersion,
updateBinPath,
} from "./configuration";
import { expandPath, isWindows, mkdirp } from "./utils/fileUtils";
import { uniqBy } from "./utils/fn";
import { logger } from "./utils/logger";
import { resolveMisePath } from "./utils/miseBinLocator";
import { type MiseConfig, parseMiseConfig } from "./utils/miseDoctorParser";
import {
flattenJsonSchema,
idiomaticFileToTool,
idiomaticFiles,
} from "./utils/miseUtilts";
import { showSettingsNotification } from "./utils/notify";
import {
execAsync,
execAsyncMergeOutput,
isTerminalClosed,
runInVscodeTerminal,
} from "./utils/shell";
import { type MiseTaskInfo, parseTaskInfo } from "./utils/taskInfoParser";
// https://github.com/jdx/mise/blob/main/src/env.rs
const XDG_STATE_HOME =
process.env.XDG_STATE_HOME ?? path.join(os.homedir(), ".local", "state");
const STATE_DIR =
process.env.MISE_STATE_DIR ?? path.join(XDG_STATE_HOME, "mise");
const TRACKED_CONFIG_DIR = path.join(STATE_DIR, "tracked-configs");
const flattenSettings = (obj: object, prefix = "") => {
const result: Record<string, MiseSettingInfo> = {};
for (const [key, value] of Object.entries(obj)) {
const newKey = prefix ? `${prefix}.${key}` : key;
if (value && typeof value === "object" && !("value" in value)) {
Object.assign(result, flattenSettings(value, newKey));
} else {
result[newKey] = value;
}
}
return result;
};
const MIN_MISE_VERSION = [2025, 1, 5] as const;
function compareVersions(
a: readonly [number, number, number],
b: readonly [number, number, number],
) {
for (let i = 0; i < a.length; i++) {
// @ts-ignore
if (a[i] > b[i]) {
return 1;
}
// @ts-ignore
if (a[i] < b[i]) {
return -1;
}
}
return 0;
}
function isVersionGreaterOrEqualThan(
version: readonly [number, number, number],
target: readonly [number, number, number],
) {
return compareVersions(version, target) >= 0;
}
function ensureMiseCommand(
miseCommand: string | undefined,
): asserts miseCommand {
if (!miseCommand) {
throw new Error(
"Mise binary path is not configured. [Install mise](https://mise.jdx.dev/getting-started.html)",
);
}
}
export class MiseService {
private readonly context: vscode.ExtensionContext;
private readonly eventEmitter: vscode.EventEmitter<void>;
constructor(context: vscode.ExtensionContext) {
this.context = context;
this.eventEmitter = new vscode.EventEmitter();
}
subscribeToReloadEvent(listener: () => void): vscode.Disposable {
return this.eventEmitter.event(listener);
}
private hasVerifiedMiseVersion = false;
private _hasValidMiseBinPath = false;
private invalidMisePathErrorShown = false;
get hasValidMiseBinPath(): boolean {
return this._hasValidMiseBinPath;
}
private terminals: Map<string, vscode.Terminal | undefined> = new Map();
getCurrentWorkspaceFolderPath() {
return getCurrentWorkspaceFolderPath(this.context);
}
private dedupeCache = createCache({
ttl: 0,
storage: { type: "memory" },
}).define("execCmd", ({ command, setMiseEnv } = {}) =>
this.execMiseCommand(command, { setMiseEnv }),
);
private cache = createCache({
ttl: getCommandTTLCacheSeconds(),
storage: { type: "memory" },
}).define("execCmd", ({ command, setMiseEnv } = {}) =>
this.execMiseCommand(command, { setMiseEnv }),
);
private slowCache = createCache({
ttl: 60,
storage: { type: "memory" },
}).define("execCmd", ({ command, setMiseEnv } = {}) =>
this.execMiseCommand(command, { setMiseEnv }),
);
private longTTLCache = createCache({
ttl: 60,
storage: { type: "memory" },
})
.define("execCmd", ({ command, setMiseEnv } = {}) =>
this.execMiseCommand(command, { setMiseEnv }),
)
.define("fetchSchema", async () => {
const res = await fetch("https://mise.jdx.dev/schema/mise.json");
if (!res.ok) {
logger.warn(
`Failed to fetch Mise schema (status: ${res.status})`,
await res.text().catch(() => "Unknown error"),
);
return [];
}
const json = await res.json();
return flattenJsonSchema(json.$defs.settings);
});
async invalidateCache() {
await Promise.all([
this.dedupeCache.clear(),
this.slowCache.clear(),
this.cache.clear(),
]);
this.eventEmitter.fire();
}
async initializeMisePath() {
if (!isMiseExtensionEnabled()) {
return;
}
let miseBinaryPath = "mise";
const previousPath = getConfiguredBinPath();
try {
miseBinaryPath = await resolveMisePath();
if (previousPath !== miseBinaryPath) {
logger.info(`Mise binary path resolved to: ${miseBinaryPath}`);
await updateBinPath(miseBinaryPath);
if (previousPath) {
void showSettingsNotification(
`Mise binary path has been updated to: ${miseBinaryPath}`,
{ settingsKey: "mise.binPath", type: "info" },
);
}
}
} catch (error) {
if (!this.invalidMisePathErrorShown) {
void showSettingsNotification(
"Invalid configured mise bin path. Please configure the binary path.",
{ settingsKey: "mise.binPath", type: "error" },
);
this.invalidMisePathErrorShown = true;
}
logger.info("Failed to resolve mise binary path", error);
this._hasValidMiseBinPath = false;
return;
}
this._hasValidMiseBinPath = true;
if (!this.hasVerifiedMiseVersion) {
const version = await this.getVersion();
if (!version || version.includes("not configured")) {
return;
}
const hasValidMiseVersion = await this.hasValidMiseVersion();
if (!hasValidMiseVersion) {
const canSelfUpdate = await this.canSelfUpdate();
const isSelfUpdateDisabled = await this.isSelfUpdateDisabled();
const selection = await vscode.window.showErrorMessage(
`Mise version ${version} is not supported. Please update to a supported version.`,
{ modal: true },
canSelfUpdate && !isSelfUpdateDisabled
? "Run mise self-update"
: "open mise website",
);
this.hasVerifiedMiseVersion = true;
if (selection === "Run mise self-update") {
await this.runMiseToolActionInConsole("self-update -y");
}
if (selection === "open mise website") {
await vscode.env.openExternal(
vscode.Uri.parse("https://mise.jdx.dev/installing-mise.html"),
);
}
}
}
}
async execMiseCommand(command: string, { setMiseEnv = true } = {}) {
const miseCommand = this.createMiseCommand(command, { setMiseEnv });
ensureMiseCommand(miseCommand);
logger.debug(`> ${miseCommand}`);
return execAsync(miseCommand, {
cwd: this.getCurrentWorkspaceFolderPath(),
});
}
async runMiseToolActionInConsole(
command: string,
taskName?: string,
): Promise<void> {
try {
const miseCommand = this.createMiseCommand(command);
logger.info(`> ${miseCommand}`);
if (!miseCommand) {
logger.warn("Could not find mise binary");
return;
}
const execution = new vscode.ShellExecution(miseCommand);
const task = new vscode.Task(
{ type: "mise" },
vscode.TaskScope.Workspace,
taskName ?? `mise ${command}`,
"mise",
execution,
);
const p = new Promise((resolve) => {
const disposable = vscode.tasks.onDidEndTask((e) => {
if (e.execution.task === task) {
vscode.commands.executeCommand(MISE_RELOAD);
disposable.dispose();
resolve(undefined);
}
});
});
await vscode.tasks.executeTask(task);
return p as Promise<void>;
} catch (error) {
logger.error(`Failed to execute ${taskName}: ${error}`);
}
}
public getMiseBinaryPath(): string | undefined {
if (!this._hasValidMiseBinPath) {
return;
}
return getConfiguredBinPath();
}
public createMiseCommand(
command: string,
{ setMiseEnv = true } = {},
): string | undefined {
const miseBinaryPath = this.getMiseBinaryPath();
if (!miseBinaryPath) {
return undefined;
}
let miseCommand = miseBinaryPath.includes(" ")
? isWindows
? `& "${miseBinaryPath}"`
: `"${miseBinaryPath}"`
: miseBinaryPath;
const miseEnv = getMiseEnv();
if (miseEnv && setMiseEnv && !command.includes("use --path")) {
miseCommand = `${miseCommand} --env "${getMiseEnv()}"`;
}
return `${miseCommand} ${command}`;
}
private async handleUntrustedFile(error: Error): Promise<void> {
const trustAction = "Trust";
logger.info("Untrusted file error:", error);
const selection = await vscode.window.showErrorMessage(
"Do you trust the Mise configuration file in the current project?",
{ modal: true },
trustAction,
);
if (selection !== trustAction) {
throw new Error("User declined to trust file");
}
try {
await this.cache.execCmd({ command: "trust" });
} catch (trustError) {
logger.error("Error trusting mise configuration:", trustError as Error);
throw new Error(
`Failed to trust the Mise configuration. "${error}". Please try again or trust it manually.`,
);
}
}
async miseTrust() {
if (!this.getMiseBinaryPath()) {
return;
}
await this.cache.execCmd({ command: "trust", setMiseEnv: false });
}
async getTasks(
{ includeHidden }: { includeHidden?: boolean } = {
includeHidden: false,
},
): Promise<MiseTask[]> {
if (!this.getMiseBinaryPath()) {
return [];
}
try {
const { stdout } = await this.cache.execCmd({
command: includeHidden ? "tasks ls --json --hidden" : "tasks ls --json",
});
return JSON.parse(stdout);
} catch (error: unknown) {
if (error instanceof Error && error.message.includes("mise trust")) {
await this.handleUntrustedFile(error);
return this.getTasks();
}
logger.info("Error fetching mise tasks:", error as Error);
return [];
}
}
async getAllCachedTasks(): Promise<MiseTask[]> {
if (!this.getMiseBinaryPath()) {
return [];
}
const { stdout } = await this.slowCache.execCmd({
command: "tasks ls --json --hidden",
});
return JSON.parse(stdout);
}
async getAllCachedTasksSources(): Promise<string[]> {
const tasks = await this.getAllCachedTasks();
return [...new Set(tasks.map((task) => task.source))];
}
async getCurrentConfigFiles(): Promise<string[]> {
const files = await Promise.all([
this.getTasks().then((tasks) => tasks.map((task) => task.source)),
this.getMiseConfigFiles().then((files) => files.map((file) => file.path)),
]);
return [...new Set(files.flat().map((file) => expandPath(file)))];
}
async getTaskInfo(taskName: string): Promise<MiseTaskInfo | undefined> {
if (!this.getMiseBinaryPath()) {
return undefined;
}
try {
const { stdout } = await this.execMiseCommand(`tasks info "${taskName}"`);
return parseTaskInfo(stdout);
} catch (error: unknown) {
logger.info("Error fetching mise task info:", error as Error);
return undefined;
}
}
async getCurrentTools(
{
useCache,
}: {
useCache?: boolean;
} = { useCache: true },
): Promise<Array<MiseTool>> {
if (!this.getMiseBinaryPath()) {
return [];
}
try {
const cacheInstance = useCache ? this.cache : this.dedupeCache;
const { stdout } = await cacheInstance.execCmd({
command: "ls --current --offline --json",
});
return Object.entries(JSON.parse(stdout)).flatMap(([toolName, tools]) => {
return (tools as MiseTool[]).map((tool) => {
return {
name: toolName,
version: tool.version,
requested_version: tool.requested_version,
active: tool.active,
installed: tool.installed,
install_path: tool.install_path,
source: tool.source,
} satisfies MiseTool;
});
});
} catch (error) {
if (error instanceof Error && error.message.includes("mise trust")) {
await this.handleUntrustedFile(error);
return this.getCurrentTools();
}
return [];
}
}
async getAllTools(): Promise<Array<MiseTool>> {
if (!this.getMiseBinaryPath()) {
return [];
}
try {
const { stdout } = await this.cache.execCmd({
command: "ls --offline --json",
});
return Object.entries(JSON.parse(stdout)).flatMap(([toolName, tools]) => {
return (tools as MiseTool[]).map((tool) => {
return {
name: toolName,
version: tool.version,
requested_version: tool.requested_version,
active: tool.active,
installed: tool.installed,
install_path: tool.install_path,
source: tool.source,
} satisfies MiseTool;
});
});
} catch (error) {
if (error instanceof Error && error.message.includes("mise trust")) {
await this.handleUntrustedFile(error);
return this.getAllTools();
}
logger.info("Error fetching mise tools:", error as Error);
return [];
}
}
async getOutdatedTools({
bump = false,
} = {}): Promise<Array<MiseToolUpdate>> {
if (!this.getMiseBinaryPath()) {
return [];
}
const { stdout } = await this.cache.execCmd({
command: bump ? "outdated --bump --json" : "outdated --json",
});
if (!stdout) {
return [];
}
return Object.entries(JSON.parse(stdout)).map(([toolName, tool]) => {
const foundTool = tool as {
name: string;
requested: string;
current: string;
latest: string;
bump: string;
source: { type: string; path: string };
};
return {
name: toolName,
version: foundTool.current,
requested_version: foundTool.requested,
source: foundTool.source,
latest: foundTool.latest,
bump: foundTool.bump,
};
});
}
async useRmTool(filename: string, toolName: string) {
if (!this.getMiseBinaryPath()) {
return;
}
const cmd = ["use"];
if (filename) {
const normalizedPath = isWindows
? filename.replace(/\\/g, "/").replace(/^\//, "")
: filename;
cmd.push(`--path "${normalizedPath}"`);
}
cmd.push("--rm");
cmd.push(toolName);
await this.runMiseToolActionInConsole(cmd.join(" "));
}
async removeToolInConsole(toolName: string, version?: string) {
if (!this.getMiseBinaryPath()) {
return;
}
await this.runMiseToolActionInConsole(
version ? `uninstall ${toolName}@${version}` : `uninstall ${toolName}`,
);
}
async getEnvs(): Promise<MiseEnv[]> {
if (!this.getMiseBinaryPath()) {
return [];
}
try {
const { stdout } = await this.cache.execCmd({
command: "env --json",
});
return Object.entries(JSON.parse(stdout)).map(([key, value]) => ({
name: key,
value: value as string,
}));
} catch (error) {
if (error instanceof Error && error.message.includes("mise trust")) {
await this.handleUntrustedFile(error);
return this.getEnvs();
}
logger.info("Error fetching mise environments:", error as Error);
return [];
}
}
async getEnvWithInfo() {
if (!this.getMiseBinaryPath()) {
return [];
}
const { stdout } = await this.cache.execCmd({
command: "env --json-extended",
});
const parsed = JSON.parse(stdout) as Record<string, MiseEnvWithInfo>;
return Object.entries(parsed).map(([key, info]) => ({
name: key,
value: info.value ?? "",
tool: info?.tool,
source: info?.source ? expandPath(info.source) : undefined,
}));
}
async miseFmt() {
await this.execMiseCommand("fmt", { setMiseEnv: false });
}
async runTask(taskName: string, ...args: string[]): Promise<void> {
const terminal = this.getOrCreateTerminal("Mise run");
terminal.show();
const runTaskCmd = isWindows
? `run "${taskName.replace(/"/g, '\\"')}"`
: `run '${taskName.replace(/'/g, "\\'")}'`;
const baseCommand = this.createMiseCommand(runTaskCmd);
ensureMiseCommand(baseCommand);
await runInVscodeTerminal(terminal, `${baseCommand} ${args.join(" ")}`);
}
async watchTask(taskName: string, ...args: string[]): Promise<void> {
const terminalName = `mise-watch ${taskName}`;
const previousTerminal = this.terminals.get(terminalName);
if (previousTerminal) {
previousTerminal.dispose();
this.terminals.delete(terminalName);
}
const terminal = this.getOrCreateTerminal(terminalName);
terminal.show();
const watchTaskCmd = isWindows
? `watch "${taskName.replace(/"/g, '\\"')}"`
: `watch '${taskName.replace(/'/g, "\\'")}'`;
const baseCommand = this.createMiseCommand(watchTaskCmd);
ensureMiseCommand(baseCommand);
await runInVscodeTerminal(terminal, `${baseCommand} ${args.join(" ")}`);
}
private getOrCreateTerminal(name: string): vscode.Terminal {
let terminal = this.terminals.get(name);
if (!terminal || isTerminalClosed(terminal)) {
terminal = vscode.window.createTerminal({
name,
cwd: this.getCurrentWorkspaceFolderPath(),
});
vscode.window.onDidCloseTerminal((closedTerminal) => {
if (closedTerminal === terminal) {
terminal = undefined;
this.terminals.delete(name);
}
});
}
this.terminals.set(name, terminal);
return terminal;
}
async binPaths(name: string) {
const { stdout } = await this.cache.execCmd({
command: `bin-paths ${name}`,
});
return stdout.trim().split("\n");
}
async which(name: string): Promise<string | undefined> {
try {
const { stdout } = await this.cache.execCmd({ command: `which ${name}` });
const out = stdout.trim();
if (out === "") {
return undefined;
}
return out;
} catch (e) {
if (!(e as Error)?.message?.includes("it is not currently active")) {
logger.info(`Error running which ${name}`, e);
}
return undefined;
}
}
async getAllBinsForTool(toolName: string) {
const binDirs = await this.binPaths(toolName);
return (
await Promise.all(
binDirs.map(async (binDir) => {
try {
const files = await vscode.workspace.fs.readDirectory(
vscode.Uri.file(binDir),
);
return files.map(([name]) => path.join(binDir, name));
} catch (e) {
logger.info(`Error reading bin path: ${binDir}`, e as Error);
return [];
}
}),
)
).flat();
}
async getMiseConfiguration(): Promise<MiseConfig> {
const miseCmd = this.createMiseCommand("doctor", {
setMiseEnv: false,
});
const { stdout, stderr } = await execAsyncMergeOutput(miseCmd ?? "");
if (stderr) {
logger.debug(miseCmd, stderr);
}
return parseMiseConfig(stdout);
}
async miseDoctor() {
const { stdout, stderr } = await execAsyncMergeOutput(
this.createMiseCommand("doctor", { setMiseEnv: false }) ?? "",
);
return `${stdout}\n${stderr}`;
}
async getMiseConfigFiles() {
if (!this.getMiseBinaryPath()) {
return [];
}
const { stdout } = await this.cache.execCmd({
command: "config ls --json",
});
return JSON.parse(stdout) as Array<{
path: string;
tools: string[];
}>;
}
async getMiseTomlConfigFilePathsEvenIfMissing() {
if (!this.getMiseBinaryPath()) {
return [];
}
const configFiles = new Set<string>();
configFiles.add(
expandPath(
path.join(this.getCurrentWorkspaceFolderPath() || "", "mise.toml"),
),
);
configFiles.add(
expandPath(path.join(os.homedir(), ".config", "mise", "config.toml")),
);
const miseConfigs = (await this.getMiseConfigFiles())
.map((file) => expandPath(file.path))
.filter((path) => path.endsWith(".toml"));
for (const file of miseConfigs) {
configFiles.add(expandPath(file));
}
return Array.from(configFiles);
}
async miseReshim() {
await this.execMiseCommand("reshim", { setMiseEnv: false }).catch(
(error) => {
logger.info("mise reshim", error as Error);
},
);
}
async getVersion() {
const miseCommand = this.createMiseCommand("version", {
setMiseEnv: false,
});
if (!miseCommand) {
return "";
}
const { stdout, stderr } = await execAsyncMergeOutput(miseCommand ?? "");
if (stderr) {
if (stderr.includes("run mise self-update")) {
logger.debug(`Mise version stderr: ${stderr.trim()}`);
} else {
logger.info(`Mise version stderr: ${stderr.trim()}`);
}
}
return stdout.trim();
}
async getParsedMiseVersion() {
const version = await this.getVersion();
const match = /(\d+)\.(\d+)\.(\d+)/.exec(version);
if (!match) {
return undefined;
}
const [, year, minor, patch] = match.map((n) =>
n ? Number.parseInt(n, 10) : 0,
);
return [year, minor, patch] as [number, number, number];
}
// Checks whether the mise binary has the self-update command
async canSelfUpdate() {
if (!this.getMiseBinaryPath()) {
return false;
}
try {
await this.execMiseCommand("self-update --help");
return true;
} catch (e) {
return false;
}
}
// Checks for the presence of the `.disable-self-update` sentinel file in the Mise lib
// dir, to determine if self-update is disabled (ie installed using a package manager).
// It's a re-implementation of the `is_available()` function from `SelfUpdate`.
// https://github.com/jdx/mise/blob/863505d4089126780c2352fb1218c6550c3cf9d8/src/cli/self_update.rs#L100
isSelfUpdateDisabled(): boolean {
logger.info("Checking if self-update is disabled...");
try {
const miseBinPath = this.getMiseBinaryPath();
logger.info(`miseBinPath: ${miseBinPath}`);
if (!miseBinPath) {
return false; // Default to allowing self-update if we can't determine the path
}
// Get canonical path of the mise binary
const canonicalPath = require("node:fs").realpathSync(miseBinPath);
// Get parent directory, then parent of that (two levels up)
const parentDir = path.dirname(canonicalPath);
const grandParentDir = path.dirname(parentDir);
// Check for sentinel files that disable self-update
const disablePaths = [
path.join(grandParentDir, "lib", ".disable-self-update"), // kept for compatibility
path.join(grandParentDir, "lib", "mise", ".disable-self-update"),
];
for (const disablePath of disablePaths) {
if (existsSync(disablePath)) {
logger.info(`Self-update disabled by sentinel file: ${disablePath}`);
return true;
}
}
return false;
} catch (error) {
// If filesystem operations fail, fall back to allowing self-update
logger.debug(`Failed to check for self-update disable files: ${error}`);
return false;
}
}
async hasValidMiseVersion() {
if (!this.getMiseBinaryPath()) {
return false;
}
const version = await this.getParsedMiseVersion();
if (!version) {
return false;
}
return isVersionGreaterOrEqualThan(version, MIN_MISE_VERSION);
}
async checkNewMiseVersion() {
if (!isMiseExtensionEnabled()) {
return;
}
if (!shouldCheckForNewMiseVersion()) {
return;
}
const miseConfig = await this.getMiseConfiguration();
const newMiseVersionAvailable =
miseConfig.problems?.newMiseVersionAvailable;
if (newMiseVersionAvailable) {
const ignoreVersion = this.context.globalState.get<string>(
"mise.ignoreNewVersion",
);
if (ignoreVersion === newMiseVersionAvailable.latestVersion) {
return;
}
const canSelfUpdate = await this.canSelfUpdate();
const isSelfUpdateDisabled = await this.isSelfUpdateDisabled();
if (isSelfUpdateDisabled) {
return;
}
const suggestion = await vscode.window.showInformationMessage(
`New Mise version available ${newMiseVersionAvailable?.latestVersion}. (Current: ${newMiseVersionAvailable?.currentVersion})`,
canSelfUpdate ? "Update Mise" : "How to update Mise",
"Show changelog",
"Ignore this update",
);
if (suggestion === "How to update Mise") {
await vscode.env.openExternal(
vscode.Uri.parse("https://mise.jdx.dev/cli/self-update.html"),
);
}
if (suggestion === "Update Mise") {
await this.runMiseToolActionInConsole("self-update -y");
}
if (suggestion === "Show changelog") {
await vscode.env.openExternal(
vscode.Uri.parse(
"https://github.com/jdx/mise/blob/HEAD/CHANGELOG.md",
),
);
await this.checkNewMiseVersion();
}
if (suggestion === "Ignore this update") {
this.context.globalState.update(
"mise.ignoreNewVersion",
newMiseVersionAvailable.latestVersion,
);
}
}
}
async miseToolInfo(toolName: string) {
if (!this.getMiseBinaryPath()) {
return;
}
const { stdout } = await this.cache.execCmd({
command: `tool "${toolName.replace(/"/g, '\\"')}" --json`,
});
return JSON.parse(stdout) as MiseToolInfo;
}
async miseRegistry() {
if (!this.getMiseBinaryPath()) {
return [];
}
const { stdout } = await this.longTTLCache.execCmd({
command: "registry",
setMiseEnv: false,
});
return stdout
.trim()
.split("\n")
.slice(1)
.map((line) => {
const [short, full] = line.split(/\s+/);
return { short, full };
})
.filter((entry) => entry.short && entry.full)
.filter(
(entry, index, self) =>
self.findIndex((e) => e.short === entry.short) === index,
);
}
async miseBackends() {
if (!this.getMiseBinaryPath()) {
return [];
}
const { stdout } = await this.longTTLCache.execCmd({
command: "backends",
setMiseEnv: false,
});
return stdout.trim().split("\n");
}
async listRemoteVersions(
toolName: string,
{ yes = false } = {},
): Promise<string[]> {
if (!this.getMiseBinaryPath()) {
return [];
}
try {
const { stdout } = await this.longTTLCache.execCmd({
command: `ls-remote ${toolName}${yes ? " --yes" : ""}`,
setMiseEnv: false,
});
if (yes) {
return this.listRemoteVersions(toolName);
}
return stdout.trim().split("\n").reverse();
} catch (error) {
if (
error instanceof Error &&
error?.message?.includes("community-developed plugin")
) {
const selection = await vscode.window.showQuickPick(["Yes", "No"], {
title: `${toolName} is a community-developed plugin. Do you trust it?`,
placeHolder: "Yes",
});
if (selection === "Yes") {
return this.listRemoteVersions(toolName, { yes: true });
}
}
logger.info("Error fetching remote versions:", error as Error);
throw error;
}
}
async hasMissingTools() {
if (!this.getMiseBinaryPath()) {
return false;
}
const tools = await this.getCurrentTools();