-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcompleter.js
101 lines (95 loc) · 2.87 KB
/
completer.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/*
###
Completer plugin
================
Provides tab completion. Options passed during creation are:
- `shell` , (required) A reference to your shell application.
###
module.exports = (settings) ->
# Validation
throw new Error 'No shell provided' if not settings.shell
shell = settings.shell
# Plug completer to interface
return unless shell.isShell
shell.interface().completer = (text, cb) ->
suggestions = []
routes = shell.routes
for route in routes
command = route.command
if command.substr(0, text.length) is text
suggestions.push command
cb(false, [suggestions, text])
null
*/
const longestCommonPrefix = require('./longest-common-prefix')
function processSuggestions (suggestions, startkey, text, cb) {
if (suggestions.length) {
const prefix = longestCommonPrefix(suggestions).substring(startkey.length)
if (prefix.length) { // one common prefix, so complete it
suggestions = [text + prefix]
}
}
cb(null, [suggestions, text])
}
module.exports = function (settings) {
if (!settings.shell) {
throw new Error('No shell provided')
}
if (!settings.appsettings) {
throw new Error('No appsettings provided')
}
const shell = settings.shell
const appsettings = settings.appsettings
if (!shell.isShell) {
return
}
shell.interface().completer = async function (text, cb) {
// first let's see if the command has spaces in
const bits = text.split(' ')
// if we have no space, then we haven't finished typing the command - so we want command auto-completion
if (bits.length === 1) {
const suggestions = []
const routes = shell.routes
for (const i in routes) {
const command = routes[i].command
if (command.substr(0, text.length) === text) {
suggestions.push(command)
}
}
cb(null, [suggestions, text])
} else {
// if we are in a sub-directory, we want documentid auto-completion
let startkey
if (appsettings.cloudantdb) {
startkey = bits[bits.length - 1] || ''
appsettings.cloudantdb.list({
limit: 10,
startkey,
endkey: startkey + '\uffff'
}, function (err, data) {
if (err) {
// handle error
}
const suggestions = data.rows.map(function (row) {
return row.id
})
processSuggestions(suggestions, startkey, text, cb)
})
} else {
// database/documentid autocompletion
startkey = bits[bits.length - 1] || ''
try {
const dbs = await settings.nano.db.list()
const suggestions = dbs.filter(function (db) {
return db.indexOf(startkey) === 0
})
processSuggestions(suggestions, startkey, text, cb)
} catch (e) {
console.log(e)
cb(null, [])
// do nothing
}
}
}
}
}