-
-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathcompletion.js
82 lines (71 loc) · 2.23 KB
/
completion.js
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
'use strict';
const fs = require('fs');
const path = require('path');
const os = require('os');
const { UnsupportedShellError, CompletionScriptError } = require('./errors');
class Completion {
constructor(shell) {
this.supportedShells = ['bash', 'zsh'];
if (!this.supportedShells.includes(shell)) {
throw new UnsupportedShellError(shell, this.supportedShells);
}
this.shell = shell;
this.rcFilename = shell === 'zsh' ? '.zshrc' : '.bashrc';
}
getFilePath() {
const homeDir = os.homedir();
return path.join(homeDir, this.rcFilename);
}
appendScript(script) {
const rcFilePath = this.getFilePath();
return new Promise((resolve, reject) => {
fs.appendFile(rcFilePath, `\n${script}\n`, (err) => {
if (err) {
reject((new CompletionScriptError(`Error appending to ${rcFilePath}: ${err.message}`)));
} else {
console.log(`Completion script added to ${rcFilePath}`);
console.log(`Please restart your shell or run 'source ~/${this.rcFilename}' to enable completions`);
resolve();
}
});
});
}
getScript() {
return new Promise((resolve) => {
if (this.shell === 'zsh') {
resolve(this.getZshScript());
} else if (this.shell === 'bash') {
resolve(this.getBashScript());
}
});
}
getZshScript() {
const completionDir = path.join(__dirname, '..', 'bin', 'completion', 'zsh');
return `
# tldr zsh completion
fpath=(${completionDir} $fpath)
# You might need to force rebuild zcompdump:
# rm -f ~/.zcompdump; compinit
# If you're using oh-my-zsh, you can force reload of completions:
# autoload -U compinit && compinit
# Check if compinit is already loaded, if not, load it
if (( ! $+functions[compinit] )); then
autoload -Uz compinit
compinit -C
fi
`.trim();
}
getBashScript() {
return new Promise((resolve, reject) => {
const scriptPath = path.join(__dirname, '..', 'bin', 'completion', 'bash', 'tldr');
fs.readFile(scriptPath, 'utf8', (err, data) => {
if (err) {
reject(new CompletionScriptError(`Error reading bash completion script: ${err.message}`));
} else {
resolve(data);
}
});
});
}
}
module.exports = Completion;