forked from NativeScript/nativescript-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauto-completion-service.ts
398 lines (358 loc) · 11 KB
/
auto-completion-service.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
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
import { homedir } from "os";
import * as path from "path";
import * as util from "util";
import * as _ from "lodash";
import { cache } from "../decorators";
import {
IAutoCompletionService,
IFileSystem,
IChildProcess,
IHostInfo,
} from "../declarations";
import { injector } from "../yok";
export class AutoCompletionService implements IAutoCompletionService {
private scriptsOk = true;
private scriptsUpdated = false;
private static COMPLETION_START_COMMENT_PATTERN =
"###-%s-completion-start-###";
private static COMPLETION_END_COMMENT_PATTERN = "###-%s-completion-end-###";
private static TABTAB_COMPLETION_START_REGEX_PATTERN =
"###-begin-%s-completion-###";
private static TABTAB_COMPLETION_END_REGEX_PATTERN =
"###-end-%s-completion-###";
private static GENERATED_TABTAB_COMPLETION_END =
"###-end-ns-completions-section-###";
private static GENERATED_TABTAB_COMPLETION_START =
"###-begin-ns-completions-section-###";
constructor(
private $fs: IFileSystem,
private $childProcess: IChildProcess,
private $logger: ILogger,
private $staticConfig: Config.IStaticConfig,
private $hostInfo: IHostInfo
) {}
public disableAnalytics = true;
@cache()
private get shellProfiles(): string[] {
return [
this.getHomePath(".bashrc"),
this.getHomePath(".zshrc"), // zsh - http://www.acm.uiuc.edu/workshops/zsh/startup_files.html
];
}
@cache()
private get cliRunCommandsFile(): string {
let cliRunCommandsFile = this.getHomePath(
util.format(".%src", this.$staticConfig.CLIENT_NAME.toLowerCase())
);
if (this.$hostInfo.isWindows) {
// on Windows bash, file is incorrectly written as C:\Users\<username>, which leads to errors when trying to execute the script:
// $ source ~/.bashrc
// sh.exe": C:Usersusername.appbuilderrc: No such file or directory
cliRunCommandsFile = cliRunCommandsFile.replace(/\\/g, "/");
}
return cliRunCommandsFile;
}
private getTabTabObsoleteRegex(clientName: string): RegExp {
const tabTabStartPoint = util.format(
AutoCompletionService.TABTAB_COMPLETION_START_REGEX_PATTERN,
clientName.toLowerCase()
);
const tabTabEndPoint = util.format(
AutoCompletionService.TABTAB_COMPLETION_END_REGEX_PATTERN,
clientName.toLowerCase()
);
const tabTabRegex = new RegExp(
util.format("%s[\\s\\S]*%s", tabTabStartPoint, tabTabEndPoint)
);
return tabTabRegex;
}
private getTabTabCompletionsRegex(): RegExp {
return new RegExp(
util.format(
"%s[\\s\\S]*%s",
AutoCompletionService.GENERATED_TABTAB_COMPLETION_START,
AutoCompletionService.GENERATED_TABTAB_COMPLETION_END
)
);
}
private removeObsoleteAutoCompletion(): void {
// In previous releases we were writing directly in .bash_profile, .bashrc, .zshrc and .profile - remove this old code
const shellProfilesToBeCleared = this.shellProfiles;
// Add .profile only here as we do not want new autocompletion in this file, but we have to remove our old code from it.
shellProfilesToBeCleared.push(this.getHomePath(".profile"));
shellProfilesToBeCleared.forEach((file) => {
try {
const text = this.$fs.readText(file);
let newText = text.replace(
this.getTabTabObsoleteRegex(this.$staticConfig.CLIENT_NAME),
""
);
if (this.$staticConfig.CLIENT_NAME_ALIAS) {
newText = newText.replace(
this.getTabTabObsoleteRegex(this.$staticConfig.CLIENT_NAME_ALIAS),
""
);
}
if (newText !== text) {
this.$logger.trace(
"Remove obsolete AutoCompletion from file %s.",
file
);
this.$fs.writeFile(file, newText);
}
} catch (error) {
if (error.code !== "ENOENT") {
this.$logger.trace(
"Error while trying to disable autocompletion for '%s' file. Error is:\n%s",
error.toString()
);
}
}
});
}
private removeOboleteTabTabCompletion(text: string) {
try {
let newText = text.replace(this.getTabTabObsoleteRegex("ns"), "");
newText = newText.replace(this.getTabTabObsoleteRegex("nsc"), "");
newText = newText.replace(
this.getTabTabObsoleteRegex("nativescript"),
""
);
newText = newText.replace(this.getTabTabObsoleteRegex("tns"), "");
return newText;
} catch (error) {
this.$logger.trace(
"Error while trying to disable autocompletion for '%s' file. Error is:\n%s",
error.toString()
);
return text;
}
}
@cache()
private get completionAliasDefinition() {
const pattern = "compdef _nativescript.js_yargs_completions %s";
const ns = util.format(pattern, "ns");
const tns = util.format(pattern, "tns");
return util.format(
"\n%s\n%s\n%s\n",
ns,
tns,
AutoCompletionService.GENERATED_TABTAB_COMPLETION_END
);
}
@cache()
private get completionShellScriptContent() {
const startText = util.format(
AutoCompletionService.COMPLETION_START_COMMENT_PATTERN,
this.$staticConfig.CLIENT_NAME.toLowerCase()
);
const content = util.format(
"if [ -f %s ]; then \n source %s \nfi",
this.cliRunCommandsFile,
this.cliRunCommandsFile
);
const endText = util.format(
AutoCompletionService.COMPLETION_END_COMMENT_PATTERN,
this.$staticConfig.CLIENT_NAME.toLowerCase()
);
return util.format("\n%s\n%s\n%s\n", startText, content, endText);
}
public isAutoCompletionEnabled(): boolean {
let result = true;
_.each(this.shellProfiles, (filePath) => {
result =
this.isNewAutoCompletionEnabledInFile(filePath) ||
this.isObsoleteAutoCompletionEnabledInFile(filePath);
if (!result) {
// break each
return false;
}
});
return result;
}
public disableAutoCompletion(): void {
_.each(this.shellProfiles, (shellFile) =>
this.removeAutoCompletionFromShellScript(shellFile)
);
this.removeObsoleteAutoCompletion();
if (this.scriptsOk && this.scriptsUpdated) {
this.$logger.info(
"Restart your shell to disable command auto-completion."
);
}
}
public async enableAutoCompletion(): Promise<void> {
await this.updateCLIShellScript();
_.each(this.shellProfiles, (shellFile) =>
this.addAutoCompletionToShellScript(shellFile)
);
this.removeObsoleteAutoCompletion();
if (this.scriptsOk && this.scriptsUpdated) {
this.$logger.info(
"Restart your shell to enable command auto-completion."
);
}
}
public isObsoleteAutoCompletionEnabled(): boolean {
let result = true;
_.each(this.shellProfiles, (shellProfile) => {
result = this.isObsoleteAutoCompletionEnabledInFile(shellProfile);
if (!result) {
// break each
return false;
}
});
return result;
}
private isNewAutoCompletionEnabledInFile(fileName: string): boolean {
try {
const data = this.$fs.readText(fileName);
if (data && data.indexOf(this.completionShellScriptContent) !== -1) {
return true;
}
} catch (err) {
this.$logger.trace(
"Error while checking is autocompletion enabled in file %s. Error is: '%s'",
fileName,
err.toString()
);
}
return false;
}
private isObsoleteAutoCompletionEnabledInFile(fileName: string): boolean {
try {
const text = this.$fs.readText(fileName);
return !!(
text.match(
this.getTabTabObsoleteRegex(this.$staticConfig.CLIENT_NAME)
) ||
text.match(this.getTabTabObsoleteRegex(this.$staticConfig.CLIENT_NAME))
);
} catch (err) {
this.$logger.trace(
"Error while checking is obsolete autocompletion enabled in file %s. Error is: '%s'",
fileName,
err.toString()
);
}
}
private addAutoCompletionToShellScript(fileName: string): void {
try {
if (
!this.isNewAutoCompletionEnabledInFile(fileName) ||
this.isObsoleteAutoCompletionEnabledInFile(fileName)
) {
this.$logger.trace(
"AutoCompletion is not enabled in %s file. Trying to enable it.",
fileName
);
this.$fs.appendFile(fileName, this.completionShellScriptContent);
this.scriptsUpdated = true;
}
} catch (err) {
this.$logger.info(
"Unable to update %s. Command-line completion might not work.",
fileName
);
// When npm is installed with sudo, in some cases the installation cannot write to shell profiles
// Advise the user how to enable autocompletion after the installation is completed.
if (
(err.code === "EPERM" || err.code === "EACCES") &&
!this.$hostInfo.isWindows &&
process.env.SUDO_USER
) {
this.$logger.info(
"To enable command-line completion, run '$ %s autocomplete enable'.",
this.$staticConfig.CLIENT_NAME
);
}
this.$logger.trace(err);
this.scriptsOk = false;
}
}
private removeAutoCompletionFromShellScript(fileName: string): void {
try {
if (this.isNewAutoCompletionEnabledInFile(fileName)) {
this.$logger.trace(
"AutoCompletion is enabled in %s file. Trying to disable it.",
fileName
);
let data = this.$fs.readText(fileName);
data = data.replace(this.completionShellScriptContent, "");
this.$fs.writeFile(fileName, data);
this.scriptsUpdated = true;
}
} catch (err) {
// If file does not exist, autocompletion was not working for it, so ignore this error.
if (err.code !== "ENOENT") {
this.$logger.info(
"Failed to update %s. Auto-completion may still work or work incorrectly. ",
fileName
);
this.$logger.info(err);
this.scriptsOk = false;
}
}
}
private async updateCLIShellScript(): Promise<void> {
const filePath = this.cliRunCommandsFile;
try {
let doUpdate = true;
if (this.$fs.exists(filePath)) {
const contents = this.$fs.readText(filePath);
const regExp = new RegExp(
AutoCompletionService.GENERATED_TABTAB_COMPLETION_START
);
let matchCondition = contents.match(regExp);
if (matchCondition) {
doUpdate = false;
}
}
if (doUpdate) {
const clientExecutableFileName = (
this.$staticConfig.CLIENT_NAME_ALIAS || this.$staticConfig.CLIENT_NAME
).toLowerCase();
const pathToExecutableFile = path.join(
__dirname,
`../../../bin/${clientExecutableFileName}.js`
);
if (this.$fs.exists(filePath)) {
const existingText = this.$fs.readText(filePath);
let newText = existingText.replace(
this.getTabTabCompletionsRegex(),
""
);
newText = this.removeOboleteTabTabCompletion(newText);
if (newText !== existingText) {
this.$logger.trace(
"Remove existing AutoCompletion from file %s.",
filePath
);
this.$fs.writeFile(filePath, newText);
}
}
// The generated seems to be inconsistent in it's start/end markers so adding our own.
this.$fs.appendFile(
filePath,
`\n${AutoCompletionService.GENERATED_TABTAB_COMPLETION_START}\n`
);
await this.$childProcess.exec(
`"${process.argv[0]}" "${pathToExecutableFile}" completion_generate_script >> "${filePath}"`
);
this.$fs.appendFile(filePath, this.completionAliasDefinition);
this.$fs.chmod(filePath, "0644");
}
} catch (err) {
this.$logger.info(
"Failed to update %s. Auto-completion may not work. ",
filePath
);
this.$logger.trace(err);
this.scriptsOk = false;
}
}
private getHomePath(fileName: string): string {
return path.join(homedir(), fileName);
}
}
injector.register("autoCompletionService", AutoCompletionService);