-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathcompletion_installation.dart
More file actions
469 lines (416 loc) · 15.2 KB
/
completion_installation.dart
File metadata and controls
469 lines (416 loc) · 15.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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
import 'dart:io';
import 'package:cli_completion/installer.dart';
import 'package:mason_logger/mason_logger.dart';
import 'package:meta/meta.dart';
import 'package:path/path.dart' as path;
/// {@template shell_completion_installation}
/// Manages the installation of completion scripts for the current shell.
///
/// Creation should be done via [CompletionInstallation.fromSystemShell].
/// {@endtemplate}
class CompletionInstallation {
/// {@macro shell_completion_installation}
@visibleForTesting
CompletionInstallation({
required this.configuration,
required this.logger,
required this.isWindows,
required this.environment,
});
/// Creates a [CompletionInstallation] given the current [systemShell].
///
/// If [systemShell] is null, it will assume that the current shell is
/// unknown and [configuration] will be null.
///
/// Pass [isWindowsOverride] to override the default value of
/// [Platform.isWindows].
///
/// Pass [environmentOverride] to override the default value of
/// [Platform.environment].
factory CompletionInstallation.fromSystemShell({
required SystemShell? systemShell,
required Logger logger,
bool? isWindowsOverride,
Map<String, String>? environmentOverride,
}) {
final isWindows = isWindowsOverride ?? Platform.isWindows;
final environment = environmentOverride ?? Platform.environment;
final configuration = systemShell == null
? null
: ShellCompletionConfiguration.fromSystemShell(systemShell);
return CompletionInstallation(
configuration: configuration,
logger: logger,
isWindows: isWindows,
environment: environment,
);
}
/// The injected [Logger];
final Logger logger;
/// Defines whether the installation is running on windows or not.
final bool isWindows;
/// Describes the environment variables. Usually
/// equals to [Platform.environment].
final Map<String, String> environment;
/// The associated [ShellCompletionConfiguration] inferred from the current
/// shell. It is null if the current shell is unknown.
final ShellCompletionConfiguration? configuration;
/// Define the [Directory] in which the
/// completion configuration files will be stored.
///
/// If [isWindows] is true, it will return the directory defined by
/// %LOCALAPPDATA%/DartCLICompletion
///
/// If [isWindows] is false, it will return the directory defined by
/// $XDG_CONFIG_HOME/.dart_cli_completion or $HOME/.dart_cli_completion
@visibleForTesting
Directory get completionConfigDir {
if (isWindows) {
// Use localappdata on windows
final localAppData = environment['LOCALAPPDATA']!;
return Directory(path.join(localAppData, 'DartCLICompletion'));
} else {
// Try using XDG config folder
var dirPath = environment['XDG_CONFIG_HOME'];
// Fallback to $HOME if not following XDG specification
if (dirPath == null || dirPath.isEmpty) {
dirPath = environment['HOME'];
}
return Directory(path.join(dirPath!, '.dart-cli-completion'));
}
}
/// Define the [File] in which the completion configuration is stored.
@visibleForTesting
File get completionConfigurationFile {
return File(path.join(completionConfigDir.path, 'config.json'));
}
/// Install completion configuration files for a [rootCommand] in the
/// current shell.
///
/// It will create:
/// - A completion script file in [completionConfigDir] that is named after
/// the [rootCommand] and the current shell (e.g. `very_good.bash`).
/// - A config file in [completionConfigDir] that is named after the current
/// shell (e.g. `bash-config.bash`) that sources the aforementioned
/// completion script file.
/// - A line in the shell config file (e.g. `.bash_profile`) that sources
/// the aforementioned config file.
///
/// If [force] is true, it will overwrite the command's completion files even
/// if they already exist. If false, it will check if is already installed, or
/// if it has been explicitly uninstalled before installing it.
void install(String rootCommand, {bool force = false}) {
final configuration = this.configuration;
if (configuration == null) {
throw CompletionInstallationException(
message: 'Unknown shell.',
rootCommand: rootCommand,
);
}
if (!force && !_shouldInstall(rootCommand)) {
return;
}
logger.detail(
'Installing completion for the command $rootCommand '
'on ${configuration.shell.name}',
);
createCompletionConfigDir();
final completionFileCreated = writeCompletionScriptForCommand(rootCommand);
writeCompletionConfigForShell(rootCommand);
writeToShellConfigFile(rootCommand);
if (completionFileCreated) {
_logSourceInstructions(rootCommand);
}
final completionConfiguration = CompletionConfiguration.fromFile(
completionConfigurationFile,
);
completionConfiguration
.copyWith(
uninstalls: completionConfiguration.uninstalls.exclude(
command: rootCommand,
systemShell: configuration.shell,
),
installs: completionConfiguration.installs.include(
command: rootCommand,
systemShell: configuration.shell,
),
)
.writeTo(completionConfigurationFile);
}
/// Wether the completion configuration files for a [rootCommand] should be
/// installed or not.
///
/// It will return false if the root command is already installed or it
/// has been explicitly uninstalled.
bool _shouldInstall(String rootCommand) {
final completionConfiguration = CompletionConfiguration.fromFile(
completionConfigurationFile,
);
final systemShell = configuration!.shell;
final isInstalled = completionConfiguration.installs.contains(
command: rootCommand,
systemShell: systemShell,
);
final isUninstalled = completionConfiguration.uninstalls.contains(
command: rootCommand,
systemShell: systemShell,
);
return !isInstalled && !isUninstalled;
}
/// Create a directory in which the completion config files shall be saved.
/// If the directory already exists, it will do nothing.
///
/// The directory is defined by [completionConfigDir].
@visibleForTesting
void createCompletionConfigDir() {
final completionConfigDirPath = completionConfigDir.path;
logger.info(
'Creating completion configuration directory '
'at $completionConfigDirPath',
);
if (completionConfigDir.existsSync()) {
logger.warn(
'A ${completionConfigDir.path} directory was already found.',
);
return;
}
completionConfigDir.createSync();
}
/// Creates a configuration file exclusively to [rootCommand] and the
/// identified shell.
///
/// The file will be named after the [rootCommand] and the current shell
/// (e.g. `very_good.bash`).
///
/// The file will be created in [completionConfigDir].
///
/// If the file already exists, it will do nothing.
///
/// Returns true if the file was created, false otherwise.
@visibleForTesting
bool writeCompletionScriptForCommand(String rootCommand) {
final configuration = this.configuration!;
final completionConfigDirPath = completionConfigDir.path;
final commandScriptName = '$rootCommand.${configuration.shell.name}';
final commandScriptPath = path.join(
completionConfigDirPath,
commandScriptName,
);
logger.info(
'Writing completion script for $rootCommand on $commandScriptPath',
);
final scriptFile = File(commandScriptPath);
if (scriptFile.existsSync()) {
logger.warn(
'A script file for $rootCommand was already found on '
'$commandScriptPath.',
);
return false;
}
scriptFile.writeAsStringSync(configuration.scriptTemplate(rootCommand));
return true;
}
/// Adds a reference for the command-specific config file created on
/// [writeCompletionScriptForCommand] the the global completion config file.
@visibleForTesting
void writeCompletionConfigForShell(String rootCommand) {
final configuration = this.configuration!;
final completionConfigDirPath = completionConfigDir.path;
final configPath = path.join(
completionConfigDirPath,
configuration.completionConfigForShellFileName,
);
logger.info('Adding config for $rootCommand config entry to $configPath');
final configFile = File(configPath);
if (!configFile.existsSync()) {
logger.info('No file found at $configPath, creating one now');
configFile.createSync();
}
if (ScriptConfigurationEntry(rootCommand).existsIn(configFile)) {
logger.warn(
'A config entry for $rootCommand was already found on $configPath.',
);
return;
}
final commandScriptName = '$rootCommand.${configuration.shell.name}';
_sourceScriptOnFile(
configFile: configFile,
scriptName: rootCommand,
scriptPath: path.join(completionConfigDirPath, commandScriptName),
);
}
String get _shellRCFilePath =>
_resolveHome(configuration!.shellRCFile, environment);
/// Write a source to the completion global script in the shell configuration
/// file, which its location is described by the [configuration].
@visibleForTesting
void writeToShellConfigFile(String rootCommand) {
final configuration = this.configuration!;
logger.info(
'Adding dart cli completion config entry '
'to $_shellRCFilePath',
);
final shellRCFile = File(_shellRCFilePath);
if (!shellRCFile.existsSync()) {
throw CompletionInstallationException(
rootCommand: rootCommand,
message: 'No configuration file found at ${shellRCFile.path}',
);
}
if (const ScriptConfigurationEntry('Completion').existsIn(shellRCFile)) {
logger.warn(
'''A completion config entry was already found on $_shellRCFilePath.''',
);
return;
}
_sourceScriptOnFile(
configFile: shellRCFile,
scriptName: 'Completion',
description:
'Completion scripts setup. '
'Remove the following line to uninstall',
scriptPath: path.join(
completionConfigDir.path,
configuration.completionConfigForShellFileName,
),
);
}
/// Tells the user to source the shell configuration file.
void _logSourceInstructions(String rootCommand) {
final level = logger.level;
logger
..level = Level.info
..info(
'\n'
'Completion files installed. To enable completion, run the following '
'command in your shell:\n'
'${lightCyan.wrap('source $_shellRCFilePath')}'
'\n',
)
..level = level;
}
void _sourceScriptOnFile({
required File configFile,
required String scriptName,
required String scriptPath,
String? description,
}) {
assert(
configFile.existsSync(),
'Sourcing a script line into an nonexistent config file.',
);
final configFilePath = configFile.path;
description ??= 'Completion config for "$scriptName"';
final content =
'''
## $description
${configuration!.sourceLineTemplate(scriptPath)}''';
ScriptConfigurationEntry(scriptName).appendTo(
configFile,
content: content,
);
logger.info('Added config to $configFilePath');
}
/// Uninstalls the completion for the command [rootCommand] on the current
/// shell.
///
/// Before uninstalling, it checks if the completion is installed:
/// - The shell has an existing RCFile with a completion
/// [ScriptConfigurationEntry].
/// - The shell has an existing completion configuration file with a
/// [ScriptConfigurationEntry] for the [rootCommand].
///
/// If any of the above is not true, it throws a
/// [CompletionUninstallationException].
///
/// Upon a successful uninstallation the executable [ScriptConfigurationEntry]
/// is removed from the shell configuration file. If after this removal the
/// latter is empty, it is deleted together with the the executable completion
/// script and the completion [ScriptConfigurationEntry] from the shell RC
/// file. In the case that there are no other completion scripts installed on
/// other shells the completion config directory is deleted, leaving the
/// user's system as it was before the installation.
void uninstall(String rootCommand) {
final configuration = this.configuration!;
logger.detail(
'''Uninstalling completion for the command $rootCommand on ${configuration.shell.name}''',
);
final shellRCFile = File(_shellRCFilePath);
if (!shellRCFile.existsSync()) {
throw CompletionUninstallationException(
rootCommand: rootCommand,
message: 'No shell RC file found at ${shellRCFile.path}',
);
}
const completionEntry = ScriptConfigurationEntry('Completion');
if (!completionEntry.existsIn(shellRCFile)) {
throw CompletionUninstallationException(
rootCommand: rootCommand,
message: 'Completion is not installed at ${shellRCFile.path}',
);
}
final shellCompletionConfigurationFile = File(
path.join(
completionConfigDir.path,
configuration.completionConfigForShellFileName,
),
);
final executableEntry = ScriptConfigurationEntry(rootCommand);
if (!executableEntry.existsIn(shellCompletionConfigurationFile)) {
throw CompletionUninstallationException(
rootCommand: rootCommand,
message:
'''No shell script file found at ${shellCompletionConfigurationFile.path}''',
);
}
final executableShellCompletionScriptFile = File(
path.join(
completionConfigDir.path,
'$rootCommand.${configuration.shell.name}',
),
);
if (executableShellCompletionScriptFile.existsSync()) {
executableShellCompletionScriptFile.deleteSync();
}
executableEntry.removeFrom(
shellCompletionConfigurationFile,
shouldDelete: true,
);
if (!shellCompletionConfigurationFile.existsSync()) {
completionEntry.removeFrom(shellRCFile);
}
final completionConfigDirContent = completionConfigDir.listSync();
final onlyHasConfigurationFile =
completionConfigDirContent.length == 1 &&
path.absolute(completionConfigDirContent.first.path) ==
path.absolute(completionConfigurationFile.path);
if (completionConfigDirContent.isEmpty || onlyHasConfigurationFile) {
completionConfigDir.deleteSync(recursive: true);
} else {
final completionConfiguration = CompletionConfiguration.fromFile(
completionConfigurationFile,
);
completionConfiguration
.copyWith(
uninstalls: completionConfiguration.uninstalls.include(
command: rootCommand,
systemShell: configuration.shell,
),
installs: completionConfiguration.installs.exclude(
command: rootCommand,
systemShell: configuration.shell,
),
)
.writeTo(completionConfigurationFile);
}
}
}
/// Resolve the home from a path string
String _resolveHome(
String originalPath,
Map<String, String> environment,
) {
final after = originalPath.split('~/').last;
final home = path.absolute(environment['HOME']!);
return path.join(home, after);
}