-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcmd_alias.rs
475 lines (427 loc) · 16.4 KB
/
cmd_alias.rs
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
470
471
472
473
474
475
use std::io::Write;
use anyhow::{bail, Result};
use clap::{Command, CommandFactory, Parser};
/// Create command shortcuts.
///
/// Aliases can be used to make shortcuts for `zoo` commands or to compose multiple commands.
/// Run `zoo help alias set` to learn more.
#[derive(Parser, Debug, Clone)]
#[clap(verbatim_doc_comment)]
pub struct CmdAlias {
#[clap(subcommand)]
subcmd: SubCommand,
}
#[derive(Parser, Debug, Clone)]
enum SubCommand {
Set(CmdAliasSet),
Delete(CmdAliasDelete),
List(CmdAliasList),
}
#[async_trait::async_trait(?Send)]
impl crate::cmd::Command for CmdAlias {
async fn run(&self, ctx: &mut crate::context::Context) -> Result<()> {
match &self.subcmd {
SubCommand::Delete(cmd) => cmd.run(ctx).await,
SubCommand::Set(cmd) => cmd.run(ctx).await,
SubCommand::List(cmd) => cmd.run(ctx).await,
}
}
}
/// Delete an alias.
#[derive(Parser, Debug, Clone)]
#[clap(verbatim_doc_comment)]
pub struct CmdAliasDelete {
/// The alias to delete.
#[clap(name = "alias", required = true)]
pub alias: String,
}
#[async_trait::async_trait(?Send)]
impl crate::cmd::Command for CmdAliasDelete {
async fn run(&self, ctx: &mut crate::context::Context) -> Result<()> {
let mut alias_config = ctx.config.aliases()?;
let (expansion, ok) = alias_config.get(&self.alias);
if !ok {
bail!("no such alias {}", self.alias);
}
match alias_config.delete(&self.alias) {
Ok(_) => {
let cs = ctx.io.color_scheme();
writeln!(
ctx.io.out,
"{} Deleted alias {}; was {}",
cs.success_icon_with_color(nu_ansi_term::Color::Red),
self.alias,
expansion
)?;
}
Err(e) => {
bail!("failed to delete alias {}: {}", self.alias, e);
}
}
Ok(())
}
}
/// Create a shortcut for a `zoo` command.
///
/// Define a word that will expand to a full `zoo` command when invoked.
///
/// The expansion may specify additional arguments and flags. If the expansion includes
/// positional placeholders such as "$1", extra arguments that follow the alias will be
/// inserted appropriately. Otherwise, extra arguments will be appended to the expanded
/// command.
///
/// Use "-" as expansion argument to read the expansion string from standard input. This
/// is useful to avoid quoting issues when defining expansions.
///
/// If the expansion starts with "!" or if "--shell" was given, the expansion is a shell
/// expression that will be evaluated through the "sh" interpreter when the alias is
/// invoked. This allows for chaining multiple commands via piping and redirection.
#[derive(Parser, Debug, Clone)]
#[clap(verbatim_doc_comment)]
pub struct CmdAliasSet {
/// The alias to set.
#[clap(name = "alias", required = true)]
pub alias: String,
/// The expansion of the alias.
#[clap(name = "expansion", required = true)]
pub expansion: String,
/// Declare an alias to be passed through a shell interpreter.
#[clap(short, long)]
pub shell: bool,
}
#[async_trait::async_trait(?Send)]
impl crate::cmd::Command for CmdAliasSet {
async fn run(&self, ctx: &mut crate::context::Context) -> Result<()> {
let cs = ctx.io.color_scheme();
let mut config_aliases = ctx.config.aliases()?;
match get_expansion(self) {
Ok(mut expansion) => {
let mut is_shell = self.shell;
if is_shell && !expansion.starts_with('!') {
expansion = format!("!{expansion}");
}
is_shell = expansion.starts_with('!');
// Check if already exists.
if valid_command(&self.alias) {
bail!("could not create alias: {} is already a zoo command", self.alias);
}
if !is_shell && !valid_command(&expansion) {
bail!(
"could not create alias: {} does not correspond to a zoo command",
expansion
);
}
writeln!(
ctx.io.out,
"- Adding alias for {}: {}",
cs.bold(&self.alias),
cs.bold(&expansion)
)?;
let mut success_msg = format!("{} Added alias.", cs.success_icon());
let (old_expansion, ok) = config_aliases.get(&self.alias);
if ok {
success_msg = format!(
"{} Changed alias {} from {} to {}",
cs.success_icon(),
cs.bold(&self.alias),
cs.bold(&old_expansion),
cs.bold(&expansion)
);
}
match config_aliases.add(&self.alias, &expansion) {
Ok(_) => {
writeln!(ctx.io.out, "{success_msg}")?;
}
Err(e) => {
bail!("could not create alias: {}", e);
}
}
}
Err(e) => {
bail!("failed to parse expansion {}: {}", self.expansion, e);
}
}
Ok(())
}
}
/// List your aliases.
///
/// This command prints out all of the aliases `zoo` is configured to use.
#[derive(Parser, Debug, Clone)]
#[clap(verbatim_doc_comment)]
pub struct CmdAliasList {}
#[async_trait::async_trait(?Send)]
impl crate::cmd::Command for CmdAliasList {
async fn run(&self, ctx: &mut crate::context::Context) -> Result<()> {
let config_aliases = ctx.config.aliases()?;
if config_aliases.map.is_empty() {
writeln!(ctx.io.out, "no aliases configured")?;
return Ok(());
}
let mut tw = tabwriter::TabWriter::new(vec![]);
for (alias, expansion) in config_aliases.list().iter() {
writeln!(tw, "{alias}:\t{expansion}")?;
}
tw.flush()?;
let table = String::from_utf8(tw.into_inner()?)?;
writeln!(ctx.io.out, "{table}")?;
Ok(())
}
}
fn get_expansion(cmd: &CmdAliasSet) -> Result<String> {
if cmd.expansion == "-" {
let mut expansion = String::new();
std::io::stdin().read_line(&mut expansion)?;
Ok(expansion)
} else {
Ok(cmd.expansion.to_string())
}
}
/// Check if a set of arguments is a valid `zoo` command.
pub fn valid_command(args: &str) -> bool {
let s = shlex::split(args);
if s.is_none() {
return false;
}
let args = s.unwrap_or_default();
if args.is_empty() {
return false;
}
// Convert our opts into a clap app.
let app: Command = crate::Opts::command();
// Try to get matches.
for subcmd in app.get_subcommands() {
if subcmd.get_name() != args[0] {
continue;
}
match subcmd.clone().try_get_matches_from(args) {
Ok(_) => {
// If we get here, we have a valid command.
return true;
}
Err(err) => {
return match err.kind() {
// These come from here: https://docs.rs/clap/latest/clap/enum.ErrorKind.html#variant.DisplayHelp
// We basically want to ignore any errors that are valid commands but invalid args.
clap::error::ErrorKind::DisplayHelp => true,
clap::error::ErrorKind::DisplayVersion => true,
clap::error::ErrorKind::MissingRequiredArgument => true,
clap::error::ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand => true,
_ => {
// If we get here, we have an invalid command.
false
}
};
}
}
}
false
}
#[cfg(test)]
mod test {
use crate::cmd::Command;
pub struct TestAlias {
name: String,
cmd: crate::cmd_alias::SubCommand,
want_out: String,
want_err: String,
}
pub struct TestValidCommand {
name: String,
cmd: String,
want: bool,
}
#[test]
fn test_valid_command() {
let tests = vec![
TestValidCommand {
name: "empty".to_string(),
cmd: "".to_string(),
want: false,
},
TestValidCommand {
name: "single arg valid".to_string(),
cmd: "completion".to_string(),
want: true,
},
TestValidCommand {
name: "multiple arg valid".to_string(),
cmd: "completion -s zsh".to_string(),
want: true,
},
TestValidCommand {
name: "single arg invalid".to_string(),
cmd: "foo".to_string(),
want: false,
},
TestValidCommand {
name: "multiple args invalid".to_string(),
cmd: "foo -H thing".to_string(),
want: false,
},
];
for t in tests {
let is_valid = crate::cmd_alias::valid_command(&t.cmd);
assert_eq!(is_valid, t.want, "test {}", t.name);
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
#[serial_test::serial]
async fn test_cmd_alias() {
let tests: Vec<TestAlias> = vec![
TestAlias {
name: "list empty".to_string(),
cmd: crate::cmd_alias::SubCommand::List(crate::cmd_alias::CmdAliasList {}),
want_out: "no aliases configured\n".to_string(),
want_err: "".to_string(),
},
TestAlias {
name: "add an alias".to_string(),
cmd: crate::cmd_alias::SubCommand::Set(crate::cmd_alias::CmdAliasSet {
alias: "cs".to_string(),
expansion: "config set".to_string(),
shell: false,
}),
want_out: "- Adding alias for cs: config set\n✔ Added alias.\n".to_string(),
want_err: "".to_string(),
},
TestAlias {
name: "update an alias".to_string(),
cmd: crate::cmd_alias::SubCommand::Set(crate::cmd_alias::CmdAliasSet {
alias: "cs".to_string(),
expansion: "config get".to_string(),
shell: false,
}),
want_out: "- Adding alias for cs: config get\n✔ Changed alias cs from config set to config get\n"
.to_string(),
want_err: "".to_string(),
},
TestAlias {
name: "add an alias with shell".to_string(),
cmd: crate::cmd_alias::SubCommand::Set(crate::cmd_alias::CmdAliasSet {
alias: "cp".to_string(),
expansion: "config list".to_string(),
shell: true,
}),
want_out: "- Adding alias for cp: !config list\n✔ Added alias.\n".to_string(),
want_err: "".to_string(),
},
TestAlias {
name: "add an alias with expandable args".to_string(),
cmd: crate::cmd_alias::SubCommand::Set(crate::cmd_alias::CmdAliasSet {
alias: "cs".to_string(),
expansion: "config set $1 $2".to_string(),
shell: false,
}),
want_out:
"- Adding alias for cs: config set $1 $2\n✔ Changed alias cs from config get to config set $1 $2"
.to_string(),
want_err: "".to_string(),
},
TestAlias {
name: "add already command -> config".to_string(),
cmd: crate::cmd_alias::SubCommand::Set(crate::cmd_alias::CmdAliasSet {
alias: "config".to_string(),
expansion: "alias set".to_string(),
shell: false,
}),
want_out: "".to_string(),
want_err: "could not create alias: config is already a zoo command".to_string(),
},
TestAlias {
name: "add already command -> completion".to_string(),
cmd: crate::cmd_alias::SubCommand::Set(crate::cmd_alias::CmdAliasSet {
alias: "completion".to_string(),
expansion: "alias set".to_string(),
shell: false,
}),
want_out: "".to_string(),
want_err: "could not create alias: completion is already a zoo command".to_string(),
},
TestAlias {
name: "add does not exist".to_string(),
cmd: crate::cmd_alias::SubCommand::Set(crate::cmd_alias::CmdAliasSet {
alias: "cp".to_string(),
expansion: "dne thing".to_string(),
shell: false,
}),
want_out: "".to_string(),
want_err: "could not create alias: dne thing does not correspond to a zoo command".to_string(),
},
TestAlias {
name: "list all".to_string(),
cmd: crate::cmd_alias::SubCommand::List(crate::cmd_alias::CmdAliasList {}),
want_out: "\"!config list\"\n".to_string(),
want_err: "".to_string(),
},
TestAlias {
name: "delete an alias".to_string(),
cmd: crate::cmd_alias::SubCommand::Delete(crate::cmd_alias::CmdAliasDelete {
alias: "cp".to_string(),
}),
want_out: "Deleted alias cp; was !config list".to_string(),
want_err: "".to_string(),
},
TestAlias {
name: "delete an alias not exist".to_string(),
cmd: crate::cmd_alias::SubCommand::Delete(crate::cmd_alias::CmdAliasDelete {
alias: "thing".to_string(),
}),
want_out: "".to_string(),
want_err: "no such alias thing".to_string(),
},
TestAlias {
name: "list after delete".to_string(),
cmd: crate::cmd_alias::SubCommand::List(crate::cmd_alias::CmdAliasList {}),
want_out: "cs: \"config set $1 $2\"\n".to_string(),
want_err: "".to_string(),
},
];
let mut config = crate::config::new_blank_config().unwrap();
let mut c = crate::config_from_env::EnvConfig::inherit_env(&mut config);
for t in tests {
let (mut io, stdout_path, stderr_path) = crate::iostreams::IoStreams::test();
io.set_stdout_tty(false);
io.set_color_enabled(false);
let mut ctx = crate::context::Context {
config: &mut c,
io,
debug: false,
};
let cmd_alias = crate::cmd_alias::CmdAlias { subcmd: t.cmd };
let result = cmd_alias.run(&mut ctx).await;
let stdout = std::fs::read_to_string(stdout_path).unwrap();
let stderr = std::fs::read_to_string(stderr_path).unwrap();
assert!(
stdout.contains(&t.want_out),
"test {} ->\nstdout: {}\nwant: {}",
t.name,
stdout,
t.want_out
);
match result {
Ok(()) => {
assert!(stdout.is_empty() == t.want_out.is_empty(), "test {}", t.name);
assert!(stderr.is_empty(), "test {}", t.name);
}
Err(err) => {
assert!(
err.to_string().contains(&t.want_err),
"test {} -> err: {}\nwant_err: {}",
t.name,
err,
t.want_err
);
assert!(
err.to_string().is_empty() == t.want_err.is_empty(),
"test {} -> err: {}\nwant_err: {}",
t.name,
err,
t.want_err
);
assert!(stderr.is_empty(), "test {}", t.name);
}
}
}
}
}