-
Notifications
You must be signed in to change notification settings - Fork 121
/
chruby.ts
213 lines (180 loc) · 7.29 KB
/
chruby.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
204
205
206
207
208
209
210
211
212
213
/* eslint-disable no-process-env */
import os from "os";
import path from "path";
import * as vscode from "vscode";
import { asyncExec } from "../common";
import { WorkspaceChannel } from "../workspaceChannel";
import { ActivationResult, VersionManager } from "./versionManager";
interface RubyVersion {
engine?: string;
version: string;
}
// A tool to change the current Ruby version
// Learn more: https://github.com/postmodern/chruby
export class Chruby extends VersionManager {
// Only public so that we can point to a different directory in tests
public rubyInstallationUris = [
vscode.Uri.joinPath(vscode.Uri.file("/"), "opt", "rubies"),
vscode.Uri.joinPath(vscode.Uri.file(os.homedir()), ".rubies"),
];
constructor(
workspaceFolder: vscode.WorkspaceFolder,
outputChannel: WorkspaceChannel,
) {
super(workspaceFolder, outputChannel);
const configuredRubies = vscode.workspace
.getConfiguration("rubyLsp")
.get<string[] | undefined>("rubyVersionManager.chrubyRubies");
if (configuredRubies) {
this.rubyInstallationUris.push(
...configuredRubies.map((path) => vscode.Uri.file(path)),
);
}
}
async activate(): Promise<ActivationResult> {
const versionInfo = await this.discoverRubyVersion();
const rubyUri = await this.findRubyUri(versionInfo);
const { defaultGems, gemHome, yjit, version } =
await this.runActivationScript(rubyUri);
this.outputChannel.info(
`Activated Ruby environment: defaultGems=${defaultGems} gemHome=${gemHome} yjit=${yjit}`,
);
const rubyEnv = {
GEM_HOME: gemHome,
GEM_PATH: `${gemHome}${path.delimiter}${defaultGems}`,
PATH: `${path.join(gemHome, "bin")}${path.delimiter}${path.join(
defaultGems,
"bin",
)}${path.delimiter}${path.dirname(rubyUri.fsPath)}${path.delimiter}${process.env.PATH}`,
};
return {
env: { ...process.env, ...rubyEnv },
yjit,
version,
};
}
// Returns the full URI to the Ruby executable
protected async findRubyUri(rubyVersion: RubyVersion): Promise<vscode.Uri> {
if (/\d+\.\d+\.\d+/.exec(rubyVersion.version)) {
return this.findRubyUriForCompleteVersion(rubyVersion);
}
return this.findRubyUriWithOmittedPatch(rubyVersion);
}
private async findRubyUriWithOmittedPatch(
rubyVersion: RubyVersion,
): Promise<vscode.Uri> {
const possibleVersionNames = rubyVersion.engine
? [`${rubyVersion.engine}-${rubyVersion.version}`, rubyVersion.version]
: [rubyVersion.version, `ruby-${rubyVersion.version}`];
for (const uri of this.rubyInstallationUris) {
const directories = (await vscode.workspace.fs.readDirectory(uri)).sort(
(left, right) => right[0].localeCompare(left[0]),
);
for (const versionName of possibleVersionNames) {
const targetDirectory = directories.find(([name]) =>
name.startsWith(versionName),
);
if (targetDirectory) {
return vscode.Uri.joinPath(uri, targetDirectory[0], "bin", "ruby");
}
}
}
throw new Error(
`Cannot find installation directory for Ruby version ${possibleVersionNames.join(" or ")}.
Searched in ${this.rubyInstallationUris.map((uri) => uri.fsPath).join(", ")}`,
);
}
private async findRubyUriForCompleteVersion(
rubyVersion: RubyVersion,
): Promise<vscode.Uri> {
// If an engine was specified in the .ruby-version file, we favor looking for that first and also try just the
// version number. If no engine was specified, we first try just the version number and then we try using `ruby` as
// the default engine
const possibleVersionNames = rubyVersion.engine
? [`${rubyVersion.engine}-${rubyVersion.version}`, rubyVersion.version]
: [rubyVersion.version, `ruby-${rubyVersion.version}`];
for (const uri of this.rubyInstallationUris) {
let installationUri: vscode.Uri;
for (const versionName of possibleVersionNames) {
try {
installationUri = vscode.Uri.joinPath(uri, versionName);
await vscode.workspace.fs.stat(installationUri);
return vscode.Uri.joinPath(installationUri, "bin", "ruby");
} catch (_error: any) {
// Continue to the next version name
}
}
}
throw new Error(
`Cannot find installation directory for Ruby version ${possibleVersionNames.join(" or ")}.
Searched in ${this.rubyInstallationUris.map((uri) => uri.fsPath).join(", ")}`,
);
}
// Returns the Ruby version information including version and engine. E.g.: ruby-3.3.0, truffleruby-21.3.0
private async discoverRubyVersion(): Promise<RubyVersion> {
let uri = this.bundleUri;
const root = path.parse(uri.fsPath).root;
let version: string;
let rubyVersionUri: vscode.Uri;
while (uri.fsPath !== root) {
try {
rubyVersionUri = vscode.Uri.joinPath(uri, ".ruby-version");
const content = await vscode.workspace.fs.readFile(rubyVersionUri);
version = content.toString().trim();
} catch (error: any) {
// If the file doesn't exist, continue going up the directory tree
uri = vscode.Uri.file(path.dirname(uri.fsPath));
continue;
}
if (version === "") {
throw new Error(`Ruby version file ${rubyVersionUri} is empty`);
}
const match =
/((?<engine>[A-Za-z]+)-)?(?<version>\d+\.\d+(\.\d+)?(-[A-Za-z0-9]+)?)/.exec(
version,
);
if (!match?.groups) {
throw new Error(
`Ruby version file ${rubyVersionUri} contains invalid format. Expected (engine-)?version, got ${version}`,
);
}
this.outputChannel.info(
`Discovered Ruby version ${version} from ${rubyVersionUri.toString()}`,
);
return { engine: match.groups.engine, version: match.groups.version };
}
throw new Error("No .ruby-version file was found");
}
// Run the activation script using the Ruby installation we found so that we can discover gem paths
private async runActivationScript(rubyExecutableUri: vscode.Uri): Promise<{
defaultGems: string;
gemHome: string;
yjit: boolean;
version: string;
}> {
// Typically, GEM_HOME points to $HOME/.gem/ruby/version_without_patch. For example, for Ruby 3.2.2, it would be
// $HOME/.gem/ruby/3.2.0. However, chruby overrides GEM_HOME to use the patch part of the version, resulting in
// $HOME/.gem/ruby/3.2.2. In our activation script, we check if a directory using the patch exists and then prefer
// that over the default one.
const script = [
"user_dir = Gem.user_dir",
"paths = Gem.path",
"if paths.length > 2",
" paths.delete(Gem.default_dir)",
" paths.delete(Gem.user_dir)",
" if paths[0]",
" user_dir = paths[0] if Dir.exist?(paths[0])",
" end",
"end",
"newer_gem_home = File.join(File.dirname(user_dir), RUBY_VERSION)",
"gems = (Dir.exist?(newer_gem_home) ? newer_gem_home : user_dir)",
"data = { defaultGems: Gem.default_dir, gemHome: gems, yjit: !!defined?(RubyVM::YJIT), version: RUBY_VERSION }",
"STDERR.print(JSON.dump(data))",
].join(";");
const result = await asyncExec(
`${rubyExecutableUri.fsPath} -W0 -rjson -e '${script}'`,
{ cwd: this.bundleUri.fsPath },
);
return this.parseWithErrorHandling(result.stderr);
}
}