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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
mod access_commands;
mod commands;
mod core_commands;
pub mod registry;
use std::collections::HashMap;
use std::fs::File;
use std::sync::{Arc, RwLock};
use crate::server::database::PvDatabase;
use registry::*;
/// Error-handling mode set by the `on error` command (M-6).
/// Mirrors C `iocsh.cpp` `onCallFunc` (`continue` / `break` / `halt` /
/// `wait`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
enum OnError {
/// Default: report the error and run the next line.
#[default]
Continue,
/// Stop the script at the first failing line (return its error).
Break,
/// Like `break` — C `halt` aborts; in-process this is equivalent
/// to stopping the current script with the failing error.
Halt,
/// Pause `delay` seconds after a failing line, then continue.
Wait(u64),
}
/// Interactive IOC shell with extensible command registration.
pub struct IocShell {
registry: Arc<RwLock<CommandRegistry>>,
ctx: CommandContext,
/// Error-handling mode for the running script (M-6). `Cell`
/// because the shell drives one script at a time on a single
/// thread; the `on error` command mutates it mid-script.
on_error: std::cell::Cell<OnError>,
}
impl IocShell {
/// Create a new shell with built-in commands registered.
pub fn new(db: Arc<PvDatabase>, handle: tokio::runtime::Handle) -> Self {
let mut registry = CommandRegistry::new();
commands::register_builtins(&mut registry);
Self {
registry: Arc::new(RwLock::new(registry)),
ctx: CommandContext::new(db, handle),
on_error: std::cell::Cell::new(OnError::Continue),
}
}
/// Register an additional command (thread-safe, takes &self).
pub fn register(&self, def: CommandDef) {
self.registry.write().unwrap().register(def);
}
/// Execute a single line of input.
///
/// Supports C EPICS iocsh output redirection:
/// - `command > file` — redirect stdout to file (overwrite)
/// - `command >> file` — redirect stdout to file (append)
pub fn execute_line(&self, line: &str) -> CommandResult {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
return Ok(CommandOutcome::Continue);
}
// Handle `< filename` include syntax (no macro substitution).
if let Some(rest) = line.strip_prefix('<') {
let filename = registry::substitute_env_vars(rest.trim());
return self
.execute_script(&filename)
.map(|_| CommandOutcome::Continue);
}
// Handle `iocshLoad <path> [macros]` (Issue #847): include with
// macro substitution applied to each line of the script. `<`
// lacks macro support so a separate dispatch is required;
// intercepting before registry lookup lets the loaded
// script's own lines re-enter `execute_line` (supporting
// `<` / `iocshLoad` / redirects / registered commands
// recursively). `tokenize` already runs `substitute_env_vars`
// on each token so we use the substituted path and macros
// string directly.
{
let toks = tokenize(line);
match toks.first().map(|s| s.as_str()) {
Some("iocshLoad") => {
if toks.len() < 2 {
return Err("iocshLoad <path> [macros]".into());
}
let macros = toks
.get(2)
.map(|s| commands::parse_macro_string(s))
.unwrap_or_default();
return self
.execute_script_with_macros(&toks[1], ¯os)
.map(|_| CommandOutcome::Continue);
}
// H-5: `iocshCmd("cmd")` runs a single command line;
// `iocshRun("c1; c2")` runs `;`-separated commands.
// Both re-enter `execute_line`, so they must be
// dispatched here (the registry handler signature has
// no access to the shell). Mirrors C `iocsh.cpp`
// `iocshCmd` / `iocshRun`.
Some("iocshCmd") => {
let Some(cmd) = toks.get(1) else {
return Err("iocshCmd <command>".into());
};
return self.execute_line(cmd);
}
Some("iocshRun") => {
let Some(cmds) = toks.get(1) else {
return Err("iocshRun <commands>".into());
};
let mut last = Ok(CommandOutcome::Continue);
for one in cmds.split(';') {
let one = one.trim();
if one.is_empty() {
continue;
}
match self.execute_line(one) {
Ok(CommandOutcome::Exit) => return Ok(CommandOutcome::Exit),
Ok(CommandOutcome::Continue) => {}
Err(e) => last = Err(e),
}
}
return last;
}
// M-6: `on error continue|break|halt|wait <delay>` —
// sets how the running script reacts to a failing
// line. Mirrors C `iocsh.cpp` `onCallFunc`.
Some("on") => {
return self.handle_on_command(&toks);
}
_ => {}
}
}
// Handle `> filename` / `>> filename` output redirection
let (cmd_line, redirect) = parse_redirect(line);
if let Some(redir) = redirect {
let result = self.execute_command(cmd_line, Some(&redir));
return result;
}
self.execute_command(cmd_line, None)
}
/// Execute a command, optionally redirecting output to a file.
fn execute_command(&self, line: &str, redirect: Option<&Redirect>) -> CommandResult {
if let Some(redir) = redirect {
// C parity: iocsh.cpp supports fd-numbered redirects 1..9
// (`2>file` for stderr, etc.). Only fd 1 (stdout) is plumbed
// through CommandContext::with_output today; fd 2+ is parsed
// for syntax compatibility (so an st.cmd that says
// `dbl 2>/dev/null` doesn't error) but the captured output
// still routes through the stdout sink. Emit a diagnostic
// so operators know the fd-2 capture is approximate.
if redir.fd != 1 {
eprintln!(
"iocsh: fd {} redirect not fully plumbed — routing to stdout sink",
redir.fd
);
}
let file_result = if redir.append {
std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&redir.path)
} else {
File::create(&redir.path)
};
match file_result {
Ok(file) => self
.ctx
.with_output(file, || self.execute_command_inner(line)),
Err(e) => {
eprintln!("cannot open '{}': {}", redir.path, e);
Ok(CommandOutcome::Continue)
}
}
} else {
self.execute_command_inner(line)
}
}
fn execute_command_inner(&self, line: &str) -> CommandResult {
// L-5: C `iocsh.cpp` split() flags an unbalanced quote or a
// trailing backslash and skips the line. Surface the same
// diagnostic instead of silently tokenizing a malformed line.
if let Some(diag) = registry::lint_line(line) {
return Err(diag.to_string());
}
let tokens = tokenize(line);
if tokens.is_empty() {
return Ok(CommandOutcome::Continue);
}
let cmd_name = &tokens[0];
let arg_tokens = &tokens[1..];
let registry = self.registry.read().unwrap();
// Special handling for help — needs access to the registry
if cmd_name == "help" {
return self.execute_help(arg_tokens, ®istry);
}
let def = registry
.get(cmd_name)
.ok_or_else(|| format!("unknown command: '{cmd_name}'"))?;
let args = parse_args(arg_tokens, &def.args)?;
def.handler.call(&args, &self.ctx)
}
/// Execute a script with per-line macro substitution applied,
/// mirroring C `iocshLoad("path", "K=V,...")` (Issue #847).
/// Macros use `$(KEY)` / `${KEY}` syntax via `db_loader::substitute_macros`.
/// Per-line errors are reported (matching `execute_script`) but
/// the script continues to the next line.
pub fn execute_script_with_macros(
&self,
path: &str,
macros: &HashMap<String, String>,
) -> Result<(), String> {
let content =
std::fs::read_to_string(path).map_err(|e| format!("cannot read '{path}': {e}"))?;
let mut last_err: Option<String> = None;
for (line_num, line) in join_backslash_continuations(&content) {
let expanded = if macros.is_empty() {
line
} else {
crate::server::db_loader::substitute_macros(&line, macros)
};
println!("{expanded}");
match self.execute_line(&expanded) {
Ok(CommandOutcome::Continue) => {}
Ok(CommandOutcome::Exit) => {
return last_err.map(Err).unwrap_or(Ok(()));
}
Err(e) => {
eprintln!("{path}:{line_num}: Error: {e}");
let formatted = format!("{path}:{line_num}: {e}");
// M-6: honour `on error break|halt` — stop the
// script at the first failing line.
if self.react_to_error() {
return Err(formatted);
}
last_err = Some(formatted);
}
}
}
last_err.map(Err).unwrap_or(Ok(()))
}
/// Execute a script file line by line, echoing each line like C++ iocsh.
///
/// C parity (144f975): errors from individual commands are reported but
/// do not abort execution. The final return value is `Err` if any command
/// failed — the equivalent of `iocshSetError` propagating a non-zero exit
/// status to startup-script callers (e.g., automated IOC verification).
pub fn execute_script(&self, path: &str) -> Result<(), String> {
let content =
std::fs::read_to_string(path).map_err(|e| format!("cannot read '{}': {}", path, e))?;
let mut last_err: Option<String> = None;
for (line_num, line) in join_backslash_continuations(&content) {
// Echo each logical line (C++ iocsh behavior — continuations
// are already collapsed so the echo shows the joined line).
println!("{line}");
match self.execute_line(&line) {
Ok(CommandOutcome::Continue) => {}
Ok(CommandOutcome::Exit) => {
return last_err.map(Err).unwrap_or(Ok(()));
}
Err(e) => {
eprintln!("{path}:{line_num}: Error: {e}");
let formatted = format!("{path}:{line_num}: {e}");
// M-6: honour `on error break|halt` — stop the
// script at the first failing line instead of
// the hardcoded "continue, report at end".
if self.react_to_error() {
return Err(formatted);
}
last_err = Some(formatted);
}
}
}
last_err.map(Err).unwrap_or(Ok(()))
}
/// Run the interactive REPL. Blocks until exit or EOF.
///
/// When stdin is not a terminal (piped input, `<script.cmd` shell
/// redirect, here-doc, ...) the rustyline interactive editor is
/// skipped and lines come straight from `BufRead::lines()` with no
/// prompt — mirrors epics-base PR #848 ("Skip readline interactive
/// setup when not interactive"). Avoids `epics> ` prompt noise in
/// the captured stderr stream when an operator pipes a script in.
pub fn run_repl(&self) -> Result<(), String> {
use std::io::IsTerminal;
if std::io::stdin().is_terminal() {
self.run_repl_interactive()
} else {
self.run_repl_piped()
}
}
fn run_repl_interactive(&self) -> Result<(), String> {
// History capacity from `EPICS_RS_IOCSH_HISTORY_SIZE` (default
// 500). Mirrors epics-base PR #459 — bound the history so a
// long-running IOC shell session does not grow unbounded.
// Lower bound 16 keeps history useful even for hostile env values.
let history_size = crate::runtime::env::get("EPICS_RS_IOCSH_HISTORY_SIZE")
.and_then(|s| s.parse::<usize>().ok())
.unwrap_or(500)
.max(16);
let config = rustyline::Config::builder()
.max_history_size(history_size)
.map_err(|e| format!("invalid rustyline history config: {e}"))?
.build();
let mut rl = rustyline::DefaultEditor::with_config(config)
.map_err(|e| format!("failed to initialize readline: {e}"))?;
// epics-base 8-D `c0da3dd` ANSI color: tint the prompt
// BRIGHT-GREEN (matching C `ANSI_GREEN` in errlog.h:282 —
// `\033[32;1m`) and route errors through bold red so an
// operator can scan a long terminal scrollback for command
// outcomes. Honour the `NO_COLOR=1` env var convention
// (https://no-color.org) and fall through to plain output
// when stdout is not a TTY (already TTY-gated by `run_repl`
// dispatch but defensive).
let want_color = use_ansi_color();
// `\x1b[32;1m` = bright green (matches C `ANSI_GREEN`); `\x1b[0m`
// = reset. rustyline 14 auto-strips ANSI escape sequences when
// computing prompt visible width, so the `\x01...\x02` reader
// markers GNU readline expects are NOT required — and they
// were actively breaking some terminals (xterm/iTerm2 render
// SOH/STX as visible glyphs which then misalign the cursor
// when output prints from another thread between prompts).
let prompt = if want_color {
"\x1b[32;1mepics> \x1b[0m"
} else {
"epics> "
};
loop {
match rl.readline(prompt) {
Ok(line) => {
let line = line.trim().to_string();
if line.is_empty() {
continue;
}
let _ = rl.add_history_entry(&line);
match self.execute_line(&line) {
Ok(CommandOutcome::Continue) => {}
Ok(CommandOutcome::Exit) => break,
Err(e) => eprintln!("{}", format_error(&e, want_color)),
}
}
Err(rustyline::error::ReadlineError::Eof) => break,
Err(rustyline::error::ReadlineError::Interrupted) => continue,
Err(e) => {
eprintln!(
"{}",
format_error(&format!("readline error: {e}"), want_color)
);
break;
}
}
}
Ok(())
}
fn run_repl_piped(&self) -> Result<(), String> {
use std::io::BufRead;
let stdin = std::io::stdin();
let mut handle = stdin.lock();
let mut line = String::new();
loop {
line.clear();
match handle.read_line(&mut line) {
Ok(0) => break, // EOF
Ok(_) => {
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
match self.execute_line(trimmed) {
Ok(CommandOutcome::Continue) => {}
Ok(CommandOutcome::Exit) => break,
Err(e) => eprintln!("Error: {e}"),
}
}
Err(e) => {
eprintln!("stdin read error: {e}");
break;
}
}
}
Ok(())
}
/// Handle the `on error ...` command (M-6). Tokens are the
/// already-tokenised line (`["on", "error", "<mode>", ...]`).
fn handle_on_command(&self, toks: &[String]) -> CommandResult {
if toks.get(1).map(|s| s.as_str()) != Some("error") {
return Err("on error continue|break|halt|wait <delay>".into());
}
let mode = match toks.get(2).map(|s| s.as_str()) {
Some("continue") => OnError::Continue,
Some("break") => OnError::Break,
Some("halt") => OnError::Halt,
Some("wait") => {
let delay = toks
.get(3)
.and_then(|s| s.parse::<u64>().ok())
.ok_or("on error wait <delay-seconds>")?;
OnError::Wait(delay)
}
_ => return Err("on error continue|break|halt|wait <delay>".into()),
};
self.on_error.set(mode);
Ok(CommandOutcome::Continue)
}
/// React to a failing script line per the current `on error`
/// mode. Returns `true` if the script should stop (with the
/// error) — `false` to continue to the next line.
fn react_to_error(&self) -> bool {
match self.on_error.get() {
OnError::Continue => false,
OnError::Break | OnError::Halt => true,
OnError::Wait(delay) => {
if delay > 0 {
std::thread::sleep(std::time::Duration::from_secs(delay));
}
false
}
}
}
fn execute_help(&self, arg_tokens: &[String], registry: &CommandRegistry) -> CommandResult {
if let Some(name) = arg_tokens.first() {
if let Some(def) = registry.get(name) {
self.ctx.println(&def.usage);
} else {
self.ctx.println(&format!("unknown command: '{name}'"));
}
} else {
self.ctx.println("Available commands:");
for name in registry.list() {
self.ctx.println(&format!(" {name}"));
}
}
Ok(CommandOutcome::Continue)
}
}
/// Collapse C iocsh backslash-newline line continuations into logical
/// lines (epics-base PR #603). A physical line ending in `\` joins to
/// the next line: the trailing backslash is stripped, the newline is
/// dropped, and the next physical line's contents (including any
/// leading whitespace) follow immediately. `\` followed by any other
/// character — including a space before the newline — keeps the
/// backslash literal and terminates the logical line normally.
/// epics-base 8-D `c0da3dd` ANSI color: returns `true` if the iocsh
/// REPL should emit ANSI color sequences. Honours `NO_COLOR` env var
/// (https://no-color.org) and `EPICS_RS_IOCSH_NO_COLOR=1` opt-out;
/// otherwise on by default in the interactive (TTY) path.
fn use_ansi_color() -> bool {
if std::env::var_os("NO_COLOR").is_some() {
return false;
}
if let Ok(v) = std::env::var("EPICS_RS_IOCSH_NO_COLOR") {
let t = v.trim().to_ascii_uppercase();
if matches!(t.as_str(), "1" | "YES" | "TRUE" | "ON") {
return false;
}
}
true
}
/// Format an error string with optional ANSI bold-red prefix.
/// Plain `Error: <msg>` when color is off — preserves grep-ability.
fn format_error(msg: &str, color: bool) -> String {
if color {
format!("\x1b[1;31mError:\x1b[0m {msg}")
} else {
format!("Error: {msg}")
}
}
///
/// Returns `(physical_line_number, logical_line)` pairs. The line
/// number is the 1-based index of the *first* physical line in the
/// group, matching where a user would look for an error.
pub(crate) fn join_backslash_continuations(input: &str) -> Vec<(usize, String)> {
let mut out = Vec::new();
let mut current = String::new();
let mut start_line: Option<usize> = None;
for (idx, line) in input.lines().enumerate() {
let physical_no = idx + 1;
if start_line.is_none() {
start_line = Some(physical_no);
}
if let Some(stripped) = line.strip_suffix('\\') {
current.push_str(stripped);
} else {
current.push_str(line);
out.push((
start_line.take().unwrap_or(physical_no),
std::mem::take(&mut current),
));
}
}
if !current.is_empty() {
out.push((start_line.unwrap_or(1), current));
}
out
}
struct Redirect {
path: String,
append: bool,
/// File descriptor target. C iocsh (iocsh.cpp:287-303) accepts
/// `1>` through `9>` (and `1>>` ... `9>>`). The Rust port currently
/// only plumbs through stdout (fd 1) — `with_output` captures
/// `ctx.println` / `print_fmt` writes. Tracking the fd here lets
/// us recognize the C syntax without erroring; non-1 fds emit a
/// diagnostic but otherwise route to stdout (best-effort) so an
/// st.cmd `2>/dev/null` doesn't fail-fast.
fd: u8,
}
/// Parse `>` / `>>` / `N>` / `N>>` redirect from a line.
/// Returns (command_part, optional redirect).
///
/// C parity (iocsh.cpp:287-303): `1>file` through `9>file` and the
/// double-`>>` (append) variants. Default fd when bare `>` is used is
/// stdout (fd 1).
fn parse_redirect(line: &str) -> (&str, Option<Redirect>) {
let bytes = line.as_bytes();
let mut in_quote = false;
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'"' => in_quote = !in_quote,
b'>' if !in_quote => {
// C parity: if the char before `>` is a single ASCII
// digit 1..9 AND that digit follows a separator (start
// of line, space, tab) — interpret as N>.
let (op_start, fd) = if i > 0 && bytes[i - 1].is_ascii_digit() {
let d = bytes[i - 1];
// Confirm the digit is at a token boundary: either
// i==1 (digit is first non-empty char in line) or
// the char before the digit is whitespace.
let at_boundary =
i == 1 || matches!(bytes[i - 2], b' ' | b'\t' | b'\r' | b'\n');
if at_boundary && (b'1'..=b'9').contains(&d) {
(i - 1, d - b'0')
} else {
(i, 1u8)
}
} else {
(i, 1u8)
};
let is_append = i + 1 < bytes.len() && bytes[i + 1] == b'>';
let cmd = line[..op_start].trim_end();
let skip = if is_append { 2 } else { 1 };
let path = line[i + skip..].trim();
if path.is_empty() {
return (line, None);
}
return (
cmd,
Some(Redirect {
path: registry::substitute_env_vars(path),
append: is_append,
fd,
}),
);
}
_ => {}
}
i += 1;
}
(line, None)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::server::records::ai::AiRecord;
fn make_shell() -> IocShell {
let rt = tokio::runtime::Runtime::new().unwrap();
let db = Arc::new(PvDatabase::new());
let handle = rt.handle().clone();
rt.block_on(async {
db.add_record("TEST_REC", Box::new(AiRecord::new(42.0)))
.await
.unwrap();
});
std::mem::forget(rt);
IocShell::new(db, handle)
}
/// Round-16 regression: a CommandDef must be cloneable so the
/// post-init `afterIocRunning` shell can re-register
/// site-specific user commands. Pre-fix the handler was
/// `Box<dyn CommandHandler>` and CommandDef itself was not
/// Clone — `IocApplication::run` skipped user commands when
/// spawning the post-init shell, leaving them dead.
#[test]
fn command_def_is_clone_and_handler_shared() {
use std::sync::atomic::{AtomicUsize, Ordering};
let calls = Arc::new(AtomicUsize::new(0));
let calls_clone = calls.clone();
let cmd = CommandDef::new(
"myCmd",
vec![],
"myCmd — count invocations",
move |_args: &[ArgValue], _ctx: &CommandContext| {
calls_clone.fetch_add(1, Ordering::Relaxed);
Ok(CommandOutcome::Continue)
},
);
// Cloning the CommandDef shares the same handler counter —
// the Arc<dyn CommandHandler> is what enables the round-16
// afterIocRunning re-registration.
let cmd_dup = cmd.clone();
let shell = make_shell();
shell.register(cmd);
shell.execute_line("myCmd").unwrap();
let shell2 = make_shell();
shell2.register(cmd_dup);
shell2.execute_line("myCmd").unwrap();
assert_eq!(calls.load(Ordering::Relaxed), 2);
}
#[test]
fn test_execute_line_dbl() {
let shell = make_shell();
let result = shell.execute_line("dbl");
assert!(matches!(result, Ok(CommandOutcome::Continue)));
}
#[test]
fn test_execute_line_unknown() {
let shell = make_shell();
let result = shell.execute_line("nonexistent_cmd");
assert!(result.is_err());
}
#[test]
fn test_execute_line_empty() {
let shell = make_shell();
let result = shell.execute_line("");
assert!(matches!(result, Ok(CommandOutcome::Continue)));
}
#[test]
fn test_execute_line_comment() {
let shell = make_shell();
let result = shell.execute_line("# this is a comment");
assert!(matches!(result, Ok(CommandOutcome::Continue)));
}
#[test]
fn test_execute_line_missing_required_arg() {
let shell = make_shell();
let result = shell.execute_line("dbgf");
assert!(result.is_err());
}
#[test]
fn test_execute_line_help() {
let shell = make_shell();
let result = shell.execute_line("help");
assert!(matches!(result, Ok(CommandOutcome::Continue)));
}
#[test]
fn test_execute_line_help_specific() {
let shell = make_shell();
let result = shell.execute_line("help dbl");
assert!(matches!(result, Ok(CommandOutcome::Continue)));
}
#[test]
fn test_execute_line_include_syntax() {
let shell = make_shell();
// A non-existent file should return an error
let result = shell.execute_line("< nonexistent_file.cmd");
assert!(result.is_err());
}
#[test]
fn test_register_custom_command() {
let shell = make_shell();
shell.register(CommandDef::new(
"myCmd",
vec![],
"myCmd - custom command",
|_args: &[ArgValue], _ctx: &CommandContext| Ok(CommandOutcome::Continue),
));
let result = shell.execute_line("myCmd");
assert!(matches!(result, Ok(CommandOutcome::Continue)));
}
#[test]
fn test_redirect_dbl_to_file() {
let shell = make_shell();
let tmp = std::env::temp_dir().join("iocsh_test_dbl_redirect.txt");
let _ = std::fs::remove_file(&tmp);
let line = format!("dbl > {}", tmp.display());
let result = shell.execute_line(&line);
assert!(matches!(result, Ok(CommandOutcome::Continue)));
let content = std::fs::read_to_string(&tmp).unwrap();
assert!(
content.contains("TEST_REC"),
"dbl output should contain TEST_REC, got: {content}"
);
std::fs::remove_file(&tmp).ok();
}
#[test]
fn test_redirect_append() {
let shell = make_shell();
let tmp = std::env::temp_dir().join("iocsh_test_append.txt");
std::fs::write(&tmp, "existing\n").unwrap();
let line = format!("dbl >> {}", tmp.display());
let result = shell.execute_line(&line);
assert!(matches!(result, Ok(CommandOutcome::Continue)));
let content = std::fs::read_to_string(&tmp).unwrap();
assert!(content.starts_with("existing\n"));
assert!(content.contains("TEST_REC"));
std::fs::remove_file(&tmp).ok();
}
#[test]
fn test_parse_redirect() {
let (cmd, redir) = parse_redirect("dbl > /tmp/out.txt");
assert_eq!(cmd, "dbl");
let r = redir.unwrap();
assert_eq!(r.path, "/tmp/out.txt");
assert!(!r.append);
assert_eq!(r.fd, 1, "bare > defaults to fd 1");
let (cmd, redir) = parse_redirect("dbl >> /tmp/out.txt");
assert_eq!(cmd, "dbl");
let r = redir.unwrap();
assert!(r.append);
assert_eq!(r.fd, 1);
let (cmd, redir) = parse_redirect("dbl");
assert_eq!(cmd, "dbl");
assert!(redir.is_none());
}
/// C parity (iocsh.cpp:287-303): `1>file` and `1>>file` are
/// fd-numbered variants of `>` and `>>`, and `2>file` requests
/// stderr capture. The parser MUST accept these forms; bare `dbl
/// 2>err.log` should not error out the line.
#[test]
fn test_parse_redirect_fd_numbered() {
// 1> equivalent to >
let (cmd, redir) = parse_redirect("dbl 1>/tmp/out.txt");
assert_eq!(cmd, "dbl");
let r = redir.unwrap();
assert_eq!(r.path, "/tmp/out.txt");
assert!(!r.append);
assert_eq!(r.fd, 1);
// 2> stderr
let (cmd, redir) = parse_redirect("dbl 2>/tmp/err.txt");
assert_eq!(cmd, "dbl");
let r = redir.unwrap();
assert_eq!(r.path, "/tmp/err.txt");
assert!(!r.append);
assert_eq!(r.fd, 2);
// 2>> stderr append
let (cmd, redir) = parse_redirect("dbl 2>>/tmp/err.txt");
assert_eq!(cmd, "dbl");
let r = redir.unwrap();
assert_eq!(r.path, "/tmp/err.txt");
assert!(r.append);
assert_eq!(r.fd, 2);
// Digit not at boundary — `cmd5>file` is NOT a fd-redirect;
// `5` is part of the previous token. Should parse as bare `>`
// with fd=1, path=file. (The cmd portion includes the trailing
// `5`; this is a syntax oddity but matches C behavior.)
let (cmd, redir) = parse_redirect("cmd5>file");
let r = redir.unwrap();
assert_eq!(r.fd, 1, "digit not at boundary is part of command");
assert_eq!(cmd, "cmd5");
// 9> high fd parses to fd=9
let (_cmd, redir) = parse_redirect("foo 9>x");
assert_eq!(redir.unwrap().fd, 9);
// `0>` does NOT parse as fd-numbered (C only accepts 1..9);
// it parses as bare `>` with fd=1 leaving `0` in cmd.
let (cmd, redir) = parse_redirect("foo 0>x");
let r = redir.unwrap();
assert_eq!(r.fd, 1);
assert_eq!(cmd, "foo 0");
}
/// epics-base PR #812 — `dbCreateRecord <type> <name>` creates a
/// new record at runtime through the same factory registry as
/// `dbLoadRecords`. Verifies the happy path plus three rejection
/// branches (duplicate name, bad name, unknown record type).
#[test]
fn test_execute_line_db_create_record_happy_path() {
let shell = make_shell();
let result = shell.execute_line("dbCreateRecord ai NEW:AI");
assert!(matches!(result, Ok(CommandOutcome::Continue)));
// Record is now visible via dbl.
let result = shell.execute_line("dbl ai");
assert!(matches!(result, Ok(CommandOutcome::Continue)));
}
#[test]
fn test_execute_line_db_create_record_rejects_duplicate() {
let shell = make_shell();
// TEST_REC was added by make_shell() — re-creating must fail
// gracefully (logged via println, returns Continue, not Err).
shell.execute_line("dbCreateRecord ai TEST_REC").unwrap();
// After the rejected call, the original record (val=42.0) is
// still there, not overwritten. Verify with dbgf which reads
// the live VAL.
let r = shell.execute_line("dbgf TEST_REC");
assert!(matches!(r, Ok(CommandOutcome::Continue)));
}
#[test]
fn test_execute_line_db_create_record_rejects_bad_name() {
let shell = make_shell();
// Space inside the name → validate_record_name returns Err.
// Quote so the parser keeps the space as one argument.
let r = shell.execute_line("dbCreateRecord ai \"BAD NAME\"");
// The command itself returns Continue (errors are printed),
// and the record must NOT be in the registry afterward.
assert!(matches!(r, Ok(CommandOutcome::Continue)));
}
#[test]
fn test_execute_line_db_create_record_rejects_unknown_type() {
let shell = make_shell();
let r = shell.execute_line("dbCreateRecord nonexistent NEW_REC");
assert!(matches!(r, Ok(CommandOutcome::Continue)));
}
/// PR #603 — line ending in `\` joins to the next physical line.
/// Mirrors the 8 scenarios in epics-base
/// `modules/libcom/test/multiline-input.txt`. Uses `concat!` (no
/// Rust source-line continuation) so trailing whitespace before
/// `\\\n` and leading whitespace on continuation chunks is
/// preserved verbatim — `String::lines()` then sees the exact
/// physical line layout from the upstream test file.
#[test]
fn test_backslash_continuation_scenarios() {
let input = concat!(
"1 not a multiline string\n",
"2 first multiline \\\n",
"string\n",
"3 second multiline \\\n",
"string \\\n",
"with more lines\n",
"4 several lines .. \\\n",
"next line is empty: \\\n",
"\\\n",
"next has only a space:\\\n",
" \\\n",
"next line has 3 spaces:\\\n",
" \\\n",
"END\n",
"5 it is fine to sp\\\n",
"it words, or really \\\n",
"c\\\n",
"h\\\n",
"o\\\n",
"p\\\n",
" them up!\n",
"\\\n",
"6 start with backslash , fine with me but why?\n",
"7 have a trailing space after backslash \\ \n",
"8 not part of the string no. 7\n",
);
let lines: Vec<String> = join_backslash_continuations(input)
.into_iter()
.map(|(_, l)| l)
.collect();
assert_eq!(lines[0], "1 not a multiline string");
assert_eq!(lines[1], "2 first multiline string");
assert_eq!(lines[2], "3 second multiline string with more lines");
assert_eq!(
lines[3],
"4 several lines .. next line is empty: next has only a space: next line has 3 spaces: END"
);
assert_eq!(
lines[4],
"5 it is fine to spit words, or really chop them up!"
);
assert_eq!(lines[5], "6 start with backslash , fine with me but why?");
assert_eq!(lines[6], "7 have a trailing space after backslash \\ ");
assert_eq!(lines[7], "8 not part of the string no. 7");
assert_eq!(lines.len(), 8);
}
/// Logical line numbers reported by `join_backslash_continuations`
/// point at the *first* physical line of the joined group — this
/// is what the user reads in the script when debugging.
#[test]
fn test_backslash_continuation_line_numbers() {
let input = "a\nb \\\nc\nd\n";
let out = join_backslash_continuations(input);
assert_eq!(
out,
vec![(1, "a".into()), (2, "b c".into()), (4, "d".into())]
);
}
/// EOF without trailing newline: emit the partial as a final line
/// (matches `String::lines()` semantics).
#[test]
fn test_backslash_continuation_no_trailing_newline() {
let out = join_backslash_continuations("partial");
assert_eq!(out, vec![(1, "partial".into())]);
}
/// CRLF input must yield the same logical lines as LF (Rust's
/// `str::lines()` strips the CR for us).
#[test]
fn test_backslash_continuation_crlf() {
let out = join_backslash_continuations("a \\\r\nb\r\n");
assert_eq!(out, vec![(1, "a b".into())]);
}
/// End-to-end: a backslash-continued script line tokenizes and
/// runs as one logical command.
#[test]
fn test_iocsh_script_backslash_continuation_end_to_end() {
let shell = make_shell();
let tmp = std::env::temp_dir().join("iocsh_multiline.cmd");
// dbgf TEST_REC.VAL — but split across two physical lines.
std::fs::write(&tmp, "dbgf \\\nTEST_REC.VAL\n").unwrap();
let result = shell.execute_script(tmp.to_str().unwrap());
std::fs::remove_file(&tmp).ok();
assert!(result.is_ok(), "joined `dbgf TEST_REC.VAL` must succeed");
}
/// Issue #847 — `iocshLoad <path> [macros]` reads a script and
/// substitutes `$(KEY)` / `${KEY}` per-call macros before
/// dispatching each line through the standard `execute_line`
/// pipeline. Verifies the happy path: a macro-parameterised
/// command is recognised after substitution.
#[test]
fn test_iocsh_load_macro_substitutes_command_name() {
let shell = make_shell();
let tmp = std::env::temp_dir().join("iocsh_load_macro_cmd.cmd");
std::fs::write(&tmp, "$(CMD)\n").unwrap();
let line = format!("iocshLoad {} CMD=dbl", tmp.display());
let result = shell.execute_line(&line);
std::fs::remove_file(&tmp).ok();
assert!(matches!(result, Ok(CommandOutcome::Continue)));
}
/// Without macros, `iocshLoad` behaves like `<` (no substitution).
#[test]
fn test_iocsh_load_no_macros() {
let shell = make_shell();
let tmp = std::env::temp_dir().join("iocsh_load_no_macros.cmd");
std::fs::write(&tmp, "dbl\n").unwrap();
let line = format!("iocshLoad {}", tmp.display());
let result = shell.execute_line(&line);
std::fs::remove_file(&tmp).ok();
assert!(matches!(result, Ok(CommandOutcome::Continue)));
}
/// Missing required `<path>` arg surfaces an error to the caller.
#[test]
fn test_iocsh_load_missing_path_errors() {
let shell = make_shell();
let result = shell.execute_line("iocshLoad");
assert!(result.is_err());
}
/// epics-base 144f975 — `dbLoadRecords` rejection (e.g., duplicate
/// name) must propagate an `Err` back to the iocsh script chain
/// (the Rust equivalent of `iocshSetError`). Pre-fix the command
/// printed the error and returned `Ok(Continue)`, so a startup
/// script silently succeeded. Verifies `execute_script` surfaces
/// C `dbLexRoutines.c:1173-1180` parity: dbLoadRecords with a
/// duplicate record name of a DIFFERENT record_type must propagate
/// Err. Same-name + same-type merges (covered by
/// `commands::tests::test_db_load_records_same_type_duplicate_merges_fields`).
#[test]
fn test_db_load_records_different_type_duplicate_propagates() {
let shell = make_shell();
// make_shell already added TEST_REC as an `ai`. Loading a .db
// that redefines it as `mbbo` must hit the type-mismatch
// branch and surface Err to the script chain.
let db_path = std::env::temp_dir().join("iocsh_dup_load.db");
std::fs::write(&db_path, "record(mbbo, \"TEST_REC\") {}\n").unwrap();
let script_path = std::env::temp_dir().join("iocsh_dup_load.cmd");
std::fs::write(
&script_path,
format!("dbLoadRecords {}\n", db_path.display()),
)
.unwrap();
let result = shell.execute_script(script_path.to_str().unwrap());
let _ = std::fs::remove_file(&db_path);
let _ = std::fs::remove_file(&script_path);
assert!(
result.is_err(),
"dbLoadRecords with type-mismatched duplicate must propagate Err"
);
}
/// C++-style call `iocshLoad("path", "K=V,...")` must tokenize to
/// the same args as the space form — quotes around the macro
/// string protect the comma so it stays one token.
#[test]
fn test_iocsh_load_cpp_paren_syntax() {
let shell = make_shell();
let tmp = std::env::temp_dir().join("iocsh_load_paren.cmd");
std::fs::write(&tmp, "$(CMD)\n").unwrap();
let line = format!("iocshLoad(\"{}\", \"CMD=dbl\")", tmp.display());
let result = shell.execute_line(&line);
std::fs::remove_file(&tmp).ok();
assert!(matches!(result, Ok(CommandOutcome::Continue)));
}
/// Per-line errors during an iocshLoad must not abort the rest of
/// the script (matches the `execute_script` semantics) but the
/// final result is `Err` so callers detect a non-zero exit.
#[test]
fn test_iocsh_load_per_line_errors_continue_and_propagate() {
let shell = make_shell();
let tmp = std::env::temp_dir().join("iocsh_load_err.cmd");
std::fs::write(&tmp, "nonexistent_cmd\ndbl\n").unwrap();
let line = format!("iocshLoad {}", tmp.display());
let result = shell.execute_line(&line);
std::fs::remove_file(&tmp).ok();
assert!(
result.is_err(),
"iocshLoad with bad command must surface Err"
);
}
#[test]
fn test_execute_line_db_create_record_missing_args() {
let shell = make_shell();
// Both args are required — missing recordName must Err.
let r = shell.execute_line("dbCreateRecord ai");
assert!(r.is_err());
}
/// epics-base 8-D `c0da3dd`: `format_error` emits a bold-red
/// `Error:` prefix when color is on, plain `Error:` otherwise.
#[test]
fn test_format_error_with_and_without_color() {
let plain = format_error("oops", false);
assert_eq!(plain, "Error: oops");
let colored = format_error("oops", true);
assert!(colored.starts_with("\x1b[1;31mError:\x1b[0m "));
assert!(colored.contains("oops"));
}
/// H-5: `iocshCmd("dbl")` runs a single command line by
/// re-entering the shell.
#[test]
fn test_iocsh_cmd_runs_single_command() {
let shell = make_shell();
let result = shell.execute_line(r#"iocshCmd("dbl")"#);
assert!(matches!(result, Ok(CommandOutcome::Continue)));
}
/// H-5: `iocshRun` runs `;`-separated commands.
#[test]
fn test_iocsh_run_runs_multiple_commands() {
let shell = make_shell();
let result = shell.execute_line(r#"iocshRun("dbl; pwd")"#);
assert!(matches!(result, Ok(CommandOutcome::Continue)));
}
/// H-5: core commands `echo`, `pwd`, `date` are registered so a
/// stock `st.cmd` no longer errors on them.
#[test]
fn test_core_commands_registered() {
let shell = make_shell();
for line in ["echo hello", "pwd", "date", "epicsPrtEnvParams"] {
assert!(
matches!(shell.execute_line(line), Ok(CommandOutcome::Continue)),
"core command line `{line}` must run"
);
}
}
/// H-5: the `as*` family is registered — `asInit` without a
/// filename errors (it does not silently succeed).
#[test]
fn test_as_commands_registered() {
let shell = make_shell();
// asInit without asSetFilename must error.
assert!(shell.execute_line("asInit").is_err());
// asprules with no config loaded prints a notice, returns Ok.
assert!(matches!(
shell.execute_line("asprules"),
Ok(CommandOutcome::Continue)
));
}
/// H-6: `dbsr` is the Database Server Report, not the name search.
#[test]
fn test_dbsr_is_server_report() {
let shell = make_shell();
let tmp = std::env::temp_dir().join("iocsh_dbsr_report.txt");
let _ = std::fs::remove_file(&tmp);
let line = format!("dbsr > {}", tmp.display());
assert!(matches!(
shell.execute_line(&line),
Ok(CommandOutcome::Continue)
));
let content = std::fs::read_to_string(&tmp).unwrap();
assert!(
content.contains("Database Server Report"),
"dbsr must print the server report, got: {content}"
);
// The server report must NOT be a record listing.
assert!(
!content.contains("Total:") || content.contains("Total channels"),
"dbsr must not be the dbgrep name-search output"
);
std::fs::remove_file(&tmp).ok();
}
/// M-6: `on error break` stops the script at the first failing
/// line. Without it (default `continue`) the whole script runs.
#[test]
fn test_on_error_break_stops_script() {
let shell = make_shell();
let tmp = std::env::temp_dir().join("iocsh_on_error_break.cmd");
// Line 2 fails; line 3 would create a record if reached.
std::fs::write(
&tmp,
"on error break\nnonexistent_cmd\ndbCreateRecord ai SHOULD_NOT_EXIST\n",
)
.unwrap();
let result = shell.execute_script(tmp.to_str().unwrap());
std::fs::remove_file(&tmp).ok();
assert!(result.is_err(), "on error break must surface Err");
// The record from line 3 must NOT have been created.
assert!(
shell.execute_line("dbgf SHOULD_NOT_EXIST").is_err(),
"on error break must stop before line 3 runs"
);
}
/// M-1: single-quoted arguments tokenize as one token.
#[test]
fn test_single_quote_tokenization() {
assert_eq!(
tokenize("dbpf REC:VAL 'hello world'"),
vec!["dbpf", "REC:VAL", "hello world"]
);
assert_eq!(tokenize("cmd('a, b', c)"), vec!["cmd", "a, b", "c"]);
}
/// L-5: an unbalanced quote / trailing backslash is flagged.
#[test]
fn test_malformed_line_is_rejected() {
let shell = make_shell();
assert!(
shell.execute_line(r#"echo "unterminated"#).is_err(),
"unbalanced quote must be rejected"
);
assert!(
shell.execute_line("echo trailing\\").is_err(),
"trailing backslash must be rejected"
);
}
/// `NO_COLOR` and `EPICS_RS_IOCSH_NO_COLOR` env vars opt out of
/// the ANSI prompt. Defensive — uses `serial_test` group key so
/// concurrent env-mutating tests don't race.
#[test]
#[serial_test::serial(epics_env)]
fn test_use_ansi_color_respects_no_color() {
// Snapshot + restore so the test doesn't leak state to siblings.
let no_color = std::env::var_os("NO_COLOR");
let epics_no = std::env::var_os("EPICS_RS_IOCSH_NO_COLOR");
// Clear both so the default path returns true.
unsafe {
std::env::remove_var("NO_COLOR");
std::env::remove_var("EPICS_RS_IOCSH_NO_COLOR");
}
assert!(use_ansi_color());
unsafe { std::env::set_var("NO_COLOR", "1") };
assert!(!use_ansi_color(), "NO_COLOR=1 must disable color");
unsafe { std::env::remove_var("NO_COLOR") };
unsafe { std::env::set_var("EPICS_RS_IOCSH_NO_COLOR", "yes") };
assert!(
!use_ansi_color(),
"EPICS_RS_IOCSH_NO_COLOR=yes must disable color"
);
unsafe { std::env::remove_var("EPICS_RS_IOCSH_NO_COLOR") };
// Restore.
if let Some(v) = no_color {
unsafe { std::env::set_var("NO_COLOR", v) };
}
if let Some(v) = epics_no {
unsafe { std::env::set_var("EPICS_RS_IOCSH_NO_COLOR", v) };
}
}
}