-
Notifications
You must be signed in to change notification settings - Fork 511
/
Copy pathUpdatePowerShell.ts
203 lines (170 loc) · 7.07 KB
/
UpdatePowerShell.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
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { spawn } from "child_process";
import * as fs from "fs"; // TODO: Remove, but it's for a stream.
import fetch, { RequestInit } from "node-fetch";
import * as os from "os";
import * as path from "path";
import * as semver from "semver";
import * as stream from "stream";
import * as util from "util";
import { MessageItem, ProgressLocation, window } from "vscode";
import { LanguageClient } from "vscode-languageclient/node";
import { Logger } from "../logging";
import { SessionManager } from "../session";
import * as Settings from "../settings";
import { isMacOS, isWindows } from "../utils";
import { EvaluateRequestType } from "./Console";
const streamPipeline = util.promisify(stream.pipeline);
const PowerShellGitHubReleasesUrl =
"https://api.github.com/repos/PowerShell/PowerShell/releases/latest";
const PowerShellGitHubPreReleasesUrl =
"https://api.github.com/repos/PowerShell/PowerShell/releases";
export class GitHubReleaseInformation {
public static async FetchLatestRelease(preview: boolean): Promise<GitHubReleaseInformation> {
const requestConfig: RequestInit = {};
// For CI. This prevents GitHub from rate limiting us.
if (process.env.PS_TEST_GITHUB_API_USERNAME && process.env.PS_TEST_GITHUB_API_PAT) {
const authHeaderValue = Buffer
.from(`${process.env.PS_TEST_GITHUB_API_USERNAME}:${process.env.PS_TEST_GITHUB_API_PAT}`)
.toString("base64");
requestConfig.headers = {
Authorization: `Basic ${authHeaderValue}`,
};
}
// Fetch the latest PowerShell releases from GitHub.
const response = await fetch(
preview ? PowerShellGitHubPreReleasesUrl : PowerShellGitHubReleasesUrl,
requestConfig);
if (!response.ok) {
const json = await response.json();
throw new Error(json.message || json || "response was not ok.");
}
// For preview, we grab all the releases and then grab the first prerelease.
const releaseJson = preview
// eslint-disable-next-line @typescript-eslint/no-explicit-any
? (await response.json()).find((release: any) => release.prerelease)
: await response.json();
return new GitHubReleaseInformation(
releaseJson.tag_name, releaseJson.assets);
}
public version: semver.SemVer;
public isPreview = false;
// TODO: Establish a type for the assets.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public assets: any[];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public constructor(version: string | semver.SemVer, assets: any[] = []) {
this.version = semver.parse(version)!;
if (semver.prerelease(this.version)) {
this.isPreview = true;
}
this.assets = assets;
}
}
interface IUpdateMessageItem extends MessageItem {
id: number;
}
export async function InvokePowerShellUpdateCheck(
sessionManager: SessionManager,
languageServerClient: LanguageClient,
localVersion: semver.SemVer,
arch: string,
release: GitHubReleaseInformation,
logger: Logger) {
const options: IUpdateMessageItem[] = [
{
id: 0,
title: "Yes",
},
{
id: 1,
title: "Not Now",
},
{
id: 2,
title: "Don't Show Again",
},
];
// If our local version is up-to-date, we can return early.
if (semver.compare(localVersion, release.version) >= 0) {
logger.writeDiagnostic("PowerShell is up-to-date!");
return;
}
const commonText = `You have an old version of PowerShell (${localVersion.raw
}). The current latest release is ${release.version.raw
}.`;
if (process.platform === "linux") {
void logger.writeAndShowInformation(`${commonText} We recommend updating to the latest version.`);
return;
}
const result = await window.showInformationMessage(
`${commonText} Would you like to update the version? ${isMacOS ? "(Homebrew is required on macOS)"
: "(This will close ALL pwsh terminals running in this Visual Studio Code session)"
}`, ...options);
// If the user cancels the notification.
if (!result) {
logger.writeDiagnostic("User canceled PowerShell update prompt.");
return;
}
// Yes choice.
switch (result.id) {
// Yes choice.
case 0:
if (isWindows) {
const msiMatcher = arch === "x86" ?
"win-x86.msi" : "win-x64.msi";
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const asset = release.assets.filter((a: any) => a.name.indexOf(msiMatcher) >= 0)[0];
const msiDownloadPath = path.join(os.tmpdir(), asset.name);
const res = await fetch(asset.browser_download_url);
if (!res.ok) {
throw new Error("unable to fetch MSI");
}
await window.withProgress({
title: "Downloading PowerShell Installer...",
location: ProgressLocation.Notification,
cancellable: false,
},
async () => {
// Streams the body of the request to a file.
await streamPipeline(res.body, fs.createWriteStream(msiDownloadPath));
});
// Stop the session because Windows likes to hold on to files.
logger.writeDiagnostic("MSI downloaded, stopping session and closing terminals!");
await sessionManager.stop();
// Close all terminals with the name "pwsh" in the current VS Code session.
// This will encourage folks to not close the instance of VS Code that spawned
// the MSI process.
for (const terminal of window.terminals) {
if (terminal.name === "pwsh") {
terminal.dispose();
}
}
// Invoke the MSI via cmd.
logger.writeDiagnostic(`Running '${msiDownloadPath}' to update PowerShell...`);
const msi = spawn("msiexec", ["/i", msiDownloadPath]);
msi.on("close", () => {
// Now that the MSI is finished, restart the session.
logger.writeDiagnostic("MSI installation finished, restarting session.");
void sessionManager.start();
fs.unlinkSync(msiDownloadPath);
});
} else if (isMacOS) {
const script = release.isPreview
? "brew upgrade --cask powershell-preview"
: "brew upgrade --cask powershell";
logger.writeDiagnostic(`Running '${script}' to update PowerShell...`);
await languageServerClient.sendRequest(EvaluateRequestType, {
expression: script,
});
}
break;
// Never choice.
case 2:
await Settings.change("promptToUpdatePowerShell", false, true, logger);
break;
default:
break;
}
}