-
Notifications
You must be signed in to change notification settings - Fork 90
Expand file tree
/
Copy pathshell-api.ts
More file actions
423 lines (384 loc) · 12.2 KB
/
shell-api.ts
File metadata and controls
423 lines (384 loc) · 12.2 KB
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
import type {
ShellResult,
ShellCommandAutocompleteParameters,
} from './decorators';
import {
shellApiClassDefault,
ShellApiClass,
returnsPromise,
returnType,
platforms,
toShellResult,
directShellCommand,
shellCommandCompleter,
} from './decorators';
import { asPrintable } from './enums';
import Mongo from './mongo';
import type Database from './database';
import type { CommandResult } from './result';
import { CursorIterationResult } from './result';
import type ShellInstanceState from './shell-instance-state';
import { assertArgsDefinedType, assertCLI } from './helpers';
import type {
ServerApi,
ServerApiVersion,
} from '@mongosh/service-provider-core';
import { DEFAULT_DB } from '@mongosh/service-provider-core';
import {
CommonErrors,
MongoshUnimplementedError,
MongoshInternalError,
} from '@mongosh/errors';
import { DBQuery } from './dbquery';
import { promisify } from 'util';
import type { ClientSideFieldLevelEncryptionOptions } from './field-level-encryption';
import { dirname } from 'path';
import { ShellUserConfig } from '@mongosh/types';
import i18n from '@mongosh/i18n';
import { MONGOSH_VERSION } from './mongosh-version';
import type { ShellLog } from './shell-log';
const instanceStateSymbol = Symbol.for('@@mongosh.instanceState');
const loadCallNestingLevelSymbol = Symbol.for('@@mongosh.loadCallNestingLevel');
/**
* Class for representing the `config` object in mongosh.
*/
@shellApiClassDefault
export class ShellConfig extends ShellApiClass {
_instanceState: ShellInstanceState;
defaults: Readonly<ShellUserConfig>;
constructor(instanceState: ShellInstanceState) {
super();
this._instanceState = instanceState;
this.defaults = Object.freeze(new ShellUserConfig());
}
@returnsPromise
async set<K extends keyof ShellUserConfig>(
key: K,
value: ShellUserConfig[K]
): Promise<string> {
assertArgsDefinedType([key], ['string'], 'config.set');
const { evaluationListener } = this._instanceState;
// Only allow known config keys here:
const isValidKey = (await this._allKeys()).includes(key);
if (isValidKey) {
const validationResult = await evaluationListener.validateConfig?.(
key,
value
);
if (validationResult) {
return `Cannot set option "${key}": ${validationResult}`;
}
}
const result =
isValidKey && (await evaluationListener.setConfig?.(key, value));
if (result !== 'success') {
return `Option "${key}" is not available in this environment`;
}
return `Setting "${key}" has been changed`;
}
// @ts-expect-error TS does not understand that the return type templating
// always interacts well with the decorators
@returnsPromise
async get<K extends keyof ShellUserConfig>(
key: K
): Promise<ShellUserConfig[K]> {
assertArgsDefinedType([key], ['string'], 'config.get');
const { evaluationListener } = this._instanceState;
return (await evaluationListener.getConfig?.(key)) ?? this.defaults[key];
}
@returnsPromise
async reset<K extends keyof ShellUserConfig>(key: K): Promise<string> {
assertArgsDefinedType([key], ['string'], 'config.reset');
const { evaluationListener } = this._instanceState;
const result = await evaluationListener.resetConfig?.(key);
if (result !== 'success') {
return `Option "${key}" cannot be changed in this environment`;
}
return `Setting "${key}" has been reset to its default value`;
}
async _allKeys(): Promise<(keyof ShellUserConfig)[]> {
const { evaluationListener } = this._instanceState;
return ((await evaluationListener.listConfigOptions?.()) ??
Object.keys(this.defaults)) as (keyof ShellUserConfig)[];
}
async [asPrintable](): Promise<
Map<keyof ShellUserConfig, ShellUserConfig[keyof ShellUserConfig]>
> {
return new Map(
await Promise.all(
(
await this._allKeys()
).map(async (key) => [key, await this.get(key)] as const)
)
);
}
}
/**
* Complete e.g. `use adm` by returning `['admin']`.
*/
async function useCompleter(
params: ShellCommandAutocompleteParameters,
args: string[]
): Promise<string[] | undefined> {
if (args.length > 2) return undefined;
return await params.getDatabaseCompletions(args[1] ?? '');
}
/**
* Complete a `show` subcommand.
*/
// eslint-disable-next-line @typescript-eslint/require-await
async function showCompleter(
params: ShellCommandAutocompleteParameters,
args: string[]
): Promise<string[] | undefined> {
if (args.length > 2) return undefined;
if (args[1] === 'd') {
// Special-case: The user might want `show dbs` or `show databases`, but they won't care about which they get.
return ['databases'];
}
const candidates = [
'databases',
'dbs',
'collections',
'tables',
'profile',
'users',
'roles',
'log',
'logs',
'startupWarnings',
'automationNotices',
'nonGenuineMongoDBCheck',
];
return candidates.filter((str) => str.startsWith(args[1] ?? ''));
}
/**
* This class contains all the *global* properties that are considered part
* of the immediate shell API. Some of these properties are decorated with
* {@link directShellCommand}, which means that they will be usable without
* parentheses (`use foo` as an alias for `use('foo')`, for example).
* Those also specify a custom autocompletion helper.
*/
@shellApiClassDefault
export default class ShellApi extends ShellApiClass {
// Use symbols to make sure these are *not* among the things copied over into
// the global scope.
[instanceStateSymbol]: ShellInstanceState;
[loadCallNestingLevelSymbol]: number;
DBQuery: DBQuery;
config: ShellConfig;
constructor(instanceState: ShellInstanceState) {
super();
this[instanceStateSymbol] = instanceState;
this[loadCallNestingLevelSymbol] = 0;
this.DBQuery = new DBQuery(instanceState);
this.config = new ShellConfig(instanceState);
}
get log(): ShellLog {
return this[instanceStateSymbol].shellLog;
}
get _instanceState(): ShellInstanceState {
return this[instanceStateSymbol];
}
get loadCallNestingLevel(): number {
return this[loadCallNestingLevelSymbol];
}
set loadCallNestingLevel(value: number) {
this[loadCallNestingLevelSymbol] = value;
}
@directShellCommand
@shellCommandCompleter(useCompleter)
use(db: string): any {
return this._instanceState.currentDb._mongo.use(db);
}
@directShellCommand
@returnsPromise
@shellCommandCompleter(showCompleter)
async show(cmd: string, arg?: string): Promise<CommandResult> {
return await this._instanceState.currentDb._mongo.show(cmd, arg);
}
@directShellCommand
@returnsPromise
@shellCommandCompleter(showCompleter)
async _untrackedShow(cmd: string, arg?: string): Promise<CommandResult> {
return await this._instanceState.currentDb._mongo.show(cmd, arg, false);
}
@directShellCommand
@returnsPromise
@platforms(['CLI'])
async exit(exitCode?: number): Promise<never> {
assertArgsDefinedType([exitCode], [[undefined, 'number']], 'exit');
assertCLI(
this._instanceState.initialServiceProvider.platform,
'the exit/quit commands'
);
await this._instanceState.close(true);
// This should never actually return.
await this._instanceState.evaluationListener.onExit?.(exitCode);
throw new MongoshInternalError('.onExit listener returned');
}
@directShellCommand
@returnsPromise
@platforms(['CLI'])
async quit(exitCode?: number): Promise<never> {
return await this.exit(exitCode);
}
@returnsPromise
@returnType('Mongo')
@platforms(['CLI'])
public async Mongo(
uri?: string,
fleOptions?: ClientSideFieldLevelEncryptionOptions,
otherOptions?: { api?: ServerApi | ServerApiVersion }
): Promise<Mongo> {
assertCLI(
this._instanceState.initialServiceProvider.platform,
'new Mongo connections'
);
const mongo = new Mongo(this._instanceState, uri, fleOptions, otherOptions);
await mongo.connect();
this._instanceState.mongos.push(mongo);
return mongo;
}
@returnsPromise
@returnType('Database')
@platforms(['CLI'])
async connect(uri: string, user?: string, pwd?: string): Promise<Database> {
assertArgsDefinedType(
[uri, user, pwd],
['string', [undefined, 'string'], [undefined, 'string']],
'connect'
);
assertCLI(
this._instanceState.initialServiceProvider.platform,
'new Mongo connections'
);
const mongo = new Mongo(this._instanceState, uri);
await mongo.connect(user, pwd);
this._instanceState.mongos.push(mongo);
const db = mongo._serviceProvider.initialDb || DEFAULT_DB;
return mongo.getDB(db);
}
@directShellCommand
@returnsPromise
async it(): Promise<any> {
if (!this._instanceState.currentCursor) {
return new CursorIterationResult();
}
return await this._instanceState.currentCursor._it();
}
version(): string {
return MONGOSH_VERSION;
}
@returnsPromise
async load(filename: string): Promise<true> {
assertArgsDefinedType([filename], ['string'], 'load');
if (!this._instanceState.evaluationListener.onLoad) {
throw new MongoshUnimplementedError(
'load is not currently implemented for this platform',
CommonErrors.NotImplemented
);
}
this._instanceState.messageBus.emit('mongosh:api-load-file', {
nested: this.loadCallNestingLevel > 0,
filename,
});
const { resolvedFilename, evaluate } =
await this._instanceState.evaluationListener.onLoad(filename);
const context = this._instanceState.context;
const previousFilename = context.__filename;
context.__filename = resolvedFilename;
context.__dirname = dirname(resolvedFilename);
this.loadCallNestingLevel++;
try {
await evaluate();
} finally {
this.loadCallNestingLevel--;
if (previousFilename) {
context.__filename = previousFilename;
context.__dirname = dirname(previousFilename);
} else {
delete context.__filename;
delete context.__dirname;
}
}
return true;
}
@returnsPromise
@platforms(['CLI'])
async enableTelemetry(): Promise<any> {
try {
const result = await this._instanceState.evaluationListener.setConfig?.(
'enableTelemetry',
true
);
if (result === 'success') {
return i18n.__('cli-repl.cli-repl.enabledTelemetry');
}
} catch (err: unknown) {
return String(err);
}
}
@returnsPromise
@platforms(['CLI'])
async disableTelemetry(): Promise<any> {
try {
const result = await this._instanceState.evaluationListener.setConfig?.(
'enableTelemetry',
false
);
if (result === 'success') {
return i18n.__('cli-repl.cli-repl.disabledTelemetry');
}
} catch (err: unknown) {
return String(err);
}
}
@returnsPromise
@platforms(['CLI'])
async passwordPrompt(): Promise<string> {
const { evaluationListener } = this._instanceState;
if (!evaluationListener.onPrompt) {
throw new MongoshUnimplementedError(
'passwordPrompt() is not available in this shell',
CommonErrors.NotImplemented
);
}
return await evaluationListener.onPrompt('Enter password', 'password');
}
@returnsPromise
async sleep(ms: number): Promise<void> {
return await promisify(setTimeout)(ms);
}
private async _print(
origArgs: any[],
type: 'print' | 'printjson'
): Promise<void> {
const { evaluationListener } = this._instanceState;
const args: ShellResult[] = await Promise.all(
origArgs.map((arg) => toShellResult(arg))
);
await evaluationListener.onPrint?.(args, type);
}
@returnsPromise
async print(...origArgs: any[]): Promise<void> {
await this._print(origArgs, 'print');
}
@returnsPromise
async printjson(...origArgs: any[]): Promise<void> {
await this._print(origArgs, 'printjson');
}
@returnsPromise
async convertShardKeyToHashed(value: any): Promise<unknown> {
return this._instanceState.currentDb._mongo.convertShardKeyToHashed(value);
}
@directShellCommand
@returnsPromise
async cls(): Promise<void> {
const { evaluationListener } = this._instanceState;
await evaluationListener.onClearCommand?.();
}
isInteractive(): boolean {
return this._instanceState.isInteractive;
}
}