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
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
|
use crate::symfony::console::command::command::Command;
use crate::symfony::console::command::complete_command::CompleteCommand;
use crate::symfony::console::command::dump_completion_command::DumpCompletionCommand;
use crate::symfony::console::command::help_command::HelpCommand;
use crate::symfony::console::command::lazy_command::LazyCommand;
use crate::symfony::console::command::list_command::ListCommand;
use crate::symfony::console::command::signalable_command_interface::SignalableCommandInterface;
use crate::symfony::console::command_loader::command_loader_interface::CommandLoaderInterface;
use crate::symfony::console::completion::completion_input::CompletionInput;
use crate::symfony::console::completion::completion_suggestions::CompletionSuggestions;
use crate::symfony::console::console_events::ConsoleEvents;
use crate::symfony::console::event::console_command_event::ConsoleCommandEvent;
use crate::symfony::console::event::console_error_event::ConsoleErrorEvent;
use crate::symfony::console::event::console_signal_event::ConsoleSignalEvent;
use crate::symfony::console::event::console_terminate_event::ConsoleTerminateEvent;
use crate::symfony::console::exception::command_not_found_exception::CommandNotFoundException;
use crate::symfony::console::exception::exception_interface::ExceptionInterface;
use crate::symfony::console::exception::logic_exception::LogicException;
use crate::symfony::console::exception::namespace_not_found_exception::NamespaceNotFoundException;
use crate::symfony::console::exception::runtime_exception::RuntimeException;
use crate::symfony::console::formatter::output_formatter::OutputFormatter;
use crate::symfony::console::helper::debug_formatter_helper::DebugFormatterHelper;
use crate::symfony::console::helper::formatter_helper::{FormatBlockMessages, FormatterHelper};
use crate::symfony::console::helper::helper::Helper;
use crate::symfony::console::helper::helper_set::HelperSet;
use crate::symfony::console::helper::process_helper::ProcessHelper;
use crate::symfony::console::helper::question_helper::QuestionHelper;
use crate::symfony::console::input::argv_input::ArgvInput;
use crate::symfony::console::input::array_input::ArrayInput;
use crate::symfony::console::input::input_argument::InputArgument;
use crate::symfony::console::input::input_aware_interface::InputAwareInterface;
use crate::symfony::console::input::input_definition::InputDefinition;
use crate::symfony::console::input::input_interface::InputInterface;
use crate::symfony::console::input::input_option::InputOption;
use crate::symfony::console::output::console_output::ConsoleOutput;
use crate::symfony::console::output::console_output_interface::ConsoleOutputInterface;
use crate::symfony::console::output::output_interface::{self, OutputInterface};
use crate::symfony::console::signal_registry::signal_registry::SignalRegistry;
use crate::symfony::console::style::style_interface::StyleInterface;
use crate::symfony::console::style::symfony_style::SymfonyStyle;
use crate::symfony::console::terminal::Terminal;
use crate::symfony::contracts::event_dispatcher::event_dispatcher_interface::EventDispatcherInterface;
use crate::symfony::contracts::service::reset_interface::ResetInterface;
use indexmap::IndexMap;
use shirabe_php_shim::PhpMixed;
use std::cell::RefCell;
use std::rc::Rc;
/// An Application is the container for a collection of commands.
///
/// It is the main entry point of a Console application.
///
/// This class is optimized for a standard CLI environment.
#[derive(Debug)]
pub struct Application {
commands: IndexMap<String, Rc<RefCell<dyn Command>>>,
want_helps: bool,
running_command: Option<Rc<RefCell<dyn Command>>>,
name: String,
version: String,
command_loader: Option<Box<dyn CommandLoaderInterface>>,
catch_exceptions: bool,
auto_exit: bool,
definition: Option<Rc<RefCell<InputDefinition>>>,
helper_set: Option<Rc<RefCell<HelperSet>>>,
dispatcher: Option<Rc<RefCell<dyn EventDispatcherInterface>>>,
terminal: Terminal,
default_command: String,
single_command: bool,
initialized: bool,
signal_registry: Option<SignalRegistry>,
signals_to_dispatch_event: Vec<i64>,
}
impl Application {
pub fn __construct(name: &str, version: &str) -> Self {
let mut this = Application {
commands: IndexMap::new(),
want_helps: false,
running_command: None,
name: name.to_string(),
version: version.to_string(),
command_loader: None,
catch_exceptions: true,
auto_exit: true,
definition: None,
helper_set: None,
dispatcher: None,
terminal: Terminal::new(),
default_command: "list".to_string(),
single_command: false,
initialized: false,
signal_registry: None,
signals_to_dispatch_event: Vec::new(),
};
if shirabe_php_shim::defined("SIGINT") && SignalRegistry::is_supported() {
this.signal_registry = Some(SignalRegistry::new());
this.signals_to_dispatch_event = vec![
shirabe_php_shim::SIGINT,
shirabe_php_shim::SIGTERM,
shirabe_php_shim::SIGUSR1,
shirabe_php_shim::SIGUSR2,
];
}
this
}
/// @final
pub fn set_dispatcher(&mut self, dispatcher: Rc<RefCell<dyn EventDispatcherInterface>>) {
// TODO(plugin): the event dispatcher drives ConsoleEvents listeners (plugins).
self.dispatcher = Some(dispatcher);
}
pub fn set_command_loader(&mut self, command_loader: Box<dyn CommandLoaderInterface>) {
self.command_loader = Some(command_loader);
}
pub fn get_signal_registry(&self) -> anyhow::Result<&SignalRegistry> {
match &self.signal_registry {
None => Err(RuntimeException(shirabe_php_shim::RuntimeException {
message: "Signals are not supported. Make sure that the `pcntl` extension is installed and that \"pcntl_*\" functions are not disabled by your php.ini's \"disable_functions\" directive.".to_string(),
code: 0,
})
.into()),
Some(signal_registry) => Ok(signal_registry),
}
}
pub fn set_signals_to_dispatch_event(&mut self, signals_to_dispatch_event: Vec<i64>) {
self.signals_to_dispatch_event = signals_to_dispatch_event;
}
/// Runs the current application.
///
/// Returns 0 if everything went fine, or an error code.
///
/// Throws \Exception when running fails. Bypass this when set_catch_exceptions().
pub fn run(
&mut self,
input: Option<Rc<RefCell<dyn InputInterface>>>,
output: Option<Rc<RefCell<dyn OutputInterface>>>,
) -> anyhow::Result<i64> {
if shirabe_php_shim::function_exists("putenv") {
shirabe_php_shim::putenv(&format!("LINES={}", self.terminal.get_height()));
shirabe_php_shim::putenv(&format!("COLUMNS={}", self.terminal.get_width()));
}
let input: Rc<RefCell<dyn InputInterface>> = match input {
None => Rc::new(RefCell::new(ArgvInput::new(None, None)?)),
Some(input) => input,
};
let output: Rc<RefCell<dyn OutputInterface>> = match output {
None => Rc::new(RefCell::new(ConsoleOutput::new(None, None, None)?)),
Some(output) => output,
};
// TODO: PHP installs a temporary `set_exception_handler($renderException)` and cooperates
// with Symfony's ErrorHandler to keep/restore it. PHP's process-global exception handler
// stack has no Rust equivalent; the rendering itself is invoked directly in the catch
// branch below. Review needed for the handler save/restore dance.
let render_exception =
|this: &Application, e: &anyhow::Error, output: &Rc<RefCell<dyn OutputInterface>>| {
// if ($output instanceof ConsoleOutputInterface) render to its error output
// TODO(review): downcasting a `dyn OutputInterface` to `ConsoleOutputInterface`
// is not directly expressible; the ConsoleOutputInterface branch needs design.
this.render_throwable(e, output.clone());
};
let result = (|| -> anyhow::Result<i64> {
self.configure_io(&input, &output)?;
let exit_code = self.do_run(input.clone(), output.clone())?;
Ok(exit_code)
})();
let mut exit_code = match result {
Ok(exit_code) => exit_code,
Err(e) => {
if !self.catch_exceptions {
return Err(e);
}
render_exception(self, &e, &output);
// $exitCode = $e->getCode();
// is_numeric($exitCode) ? max(1, (int) $exitCode) : 1
// TODO(review): anyhow::Error has no PHP-style getCode(); the exit code derived
// from the exception's `code` field needs the downcast strategy decided.
let exit_code = shirabe_php_shim::php_exception_get_code(&e);
if shirabe_php_shim::is_numeric_string(&exit_code.to_string()) {
let exit_code = exit_code;
if exit_code <= 0 { 1 } else { exit_code }
} else {
1
}
}
};
// finally: handler restore. See TODO above; no-op here.
if self.auto_exit {
if exit_code > 255 {
exit_code = 255;
}
shirabe_php_shim::exit(exit_code);
}
Ok(exit_code)
}
/// Runs the current application.
///
/// Returns 0 if everything went fine, or an error code.
pub fn do_run(
&mut self,
input: Rc<RefCell<dyn InputInterface>>,
output: Rc<RefCell<dyn OutputInterface>>,
) -> anyhow::Result<i64> {
if input.borrow().has_parameter_option(
PhpMixed::from(vec![
PhpMixed::from("--version".to_string()),
PhpMixed::from("-V".to_string()),
]),
true,
) {
output
.borrow()
.writeln(&[self.get_long_version()], output_interface::OUTPUT_NORMAL);
return Ok(0);
}
// Makes ArgvInput::getFirstArgument() able to distinguish an option from an argument.
match input.borrow_mut().bind(&self.get_definition().borrow()) {
Ok(()) => {}
Err(e) => {
// Errors must be ignored, full binding/validation happens later when the command is known.
if !is_exception_interface(&e) {
return Err(e);
}
}
}
let mut input = input;
let mut name = self.get_command_name(&*input.borrow());
if input.borrow().has_parameter_option(
PhpMixed::from(vec![
PhpMixed::from("--help".to_string()),
PhpMixed::from("-h".to_string()),
]),
true,
) {
if name.is_none() {
name = Some("help".to_string());
input = Rc::new(RefCell::new(ArrayInput::new(
vec![(
PhpMixed::from("command_name".to_string()),
PhpMixed::from(self.default_command.clone()),
)],
None,
)?));
} else {
self.want_helps = true;
}
}
let name = match name {
Some(name) => name,
None => {
let name = self.default_command.clone();
let definition = self.get_definition();
let command_description = definition
.borrow()
.get_argument(&PhpMixed::from("command".to_string()))?
.get_description()
.to_string();
let _new_command_argument = InputArgument::new(
"command".to_string(),
Some(InputArgument::OPTIONAL),
command_description,
PhpMixed::from(name.clone()),
)?;
// $definition->setArguments(array_merge($definition->getArguments(),
// ['command' => new InputArgument('command', InputArgument::OPTIONAL, ...)]))
// TODO(review): get_arguments() yields Rc<InputArgument> (shared, non-Clone) while
// set_arguments() consumes owned InputArgument values. Re-building the merged
// argument list requires an InputArgument clone/ownership strategy not yet present.
definition.borrow_mut().set_arguments(todo!(
"merge existing arguments with the new 'command' argument"
))?;
name
}
};
let command: Rc<RefCell<dyn Command>>;
let find_result = (|| -> anyhow::Result<Rc<RefCell<dyn Command>>> {
self.running_command = None;
// the command name MUST be the first element of the input
self.find(&name)
})();
match find_result {
Ok(c) => {
command = c;
}
Err(e) => {
// if (!($e instanceof CommandNotFoundException && !$e instanceof NamespaceNotFoundException)
// || 1 !== count($alternatives = $e->getAlternatives()) || !$input->isInteractive())
let alternatives: Option<Vec<String>> = downcast_command_not_found(&e)
.filter(|_| !is_namespace_not_found(&e))
.map(|cnf| cnf.get_alternatives().clone());
let single_alternative = match &alternatives {
Some(alts) if alts.len() == 1 => Some(alts[0].clone()),
_ => None,
};
if single_alternative.is_none() || !input.borrow().is_interactive() {
let mut e = e;
if self.dispatcher.is_some() {
// TODO(plugin): dispatch ConsoleErrorEvent so listeners can handle/replace the error.
let _event = ConsoleErrorEvent::new(
todo!("wrap input as Box<dyn InputInterface> for the event"),
todo!("wrap output as Box<dyn OutputInterface> for the event"),
todo!("wrap anyhow::Error as Box<dyn Error> for the event"),
None,
);
let event: ConsoleErrorEvent = _event;
self.dispatcher
.as_ref()
.unwrap()
.borrow_mut()
.dispatch(todo!("event object"), ConsoleEvents::ERROR);
if event.get_exit_code() == 0 {
return Ok(0);
}
e = todo!("event.get_error() converted back to anyhow::Error");
}
return Err(e);
}
let alternative = single_alternative.unwrap();
let mut style = SymfonyStyle::new(input.clone(), output.clone());
output
.borrow()
.writeln(&["".to_string()], output_interface::OUTPUT_NORMAL);
let formatted_block = FormatterHelper::default().format_block(
FormatBlockMessages::String(shirabe_php_shim::sprintf(
"Command \"%s\" is not defined.",
&[PhpMixed::from(name.clone())],
)),
"error",
true,
);
output
.borrow()
.writeln(&[formatted_block], output_interface::OUTPUT_NORMAL);
if !style.confirm(
&shirabe_php_shim::sprintf(
"Do you want to run \"%s\" instead? ",
&[PhpMixed::from(alternative.clone())],
),
false,
) {
if self.dispatcher.is_some() {
// TODO(plugin): dispatch ConsoleErrorEvent for the declined-alternative case.
let event = ConsoleErrorEvent::new(
todo!("wrap input as Box<dyn InputInterface>"),
todo!("wrap output as Box<dyn OutputInterface>"),
todo!("wrap error as Box<dyn Error>"),
None,
);
self.dispatcher
.as_ref()
.unwrap()
.borrow_mut()
.dispatch(todo!("event object"), ConsoleEvents::ERROR);
return Ok(event.get_exit_code());
}
return Ok(1);
}
command = self.find(&alternative)?;
}
}
// if ($command instanceof LazyCommand) $command = $command->getCommand();
// TODO(review): LazyCommand is a distinct type from Command here; PHP unwraps the real
// command. The `commands` map stores Rc<RefCell<dyn Command>>, so the LazyCommand-unwrap path
// needs a design decision about how lazy commands are represented.
let _ = std::marker::PhantomData::<LazyCommand>;
self.running_command = Some(command.clone());
let exit_code = self.do_run_command(command.clone(), input.clone(), output.clone())?;
self.running_command = None;
Ok(exit_code)
}
pub fn reset(&mut self) {}
pub fn set_helper_set(&mut self, helper_set: Rc<RefCell<HelperSet>>) {
self.helper_set = Some(helper_set);
}
/// Get the helper set associated with the command.
pub fn get_helper_set(&mut self) -> Rc<RefCell<HelperSet>> {
if self.helper_set.is_none() {
self.helper_set = Some(self.get_default_helper_set());
}
self.helper_set.as_ref().unwrap().clone()
}
pub fn set_definition(&mut self, definition: Rc<RefCell<InputDefinition>>) {
self.definition = Some(definition);
}
/// Gets the InputDefinition related to this Application.
pub fn get_definition(&mut self) -> Rc<RefCell<InputDefinition>> {
if self.definition.is_none() {
self.definition = Some(Rc::new(RefCell::new(self.get_default_input_definition())));
}
if self.single_command {
let input_definition = self.definition.as_ref().unwrap().clone();
input_definition
.borrow_mut()
.set_arguments(Vec::new())
.unwrap();
return input_definition;
}
self.definition.as_ref().unwrap().clone()
}
/// Adds suggestions to `suggestions` for the current completion input (e.g. option or argument).
pub fn complete(
&mut self,
input: &CompletionInput,
suggestions: &mut CompletionSuggestions,
) -> anyhow::Result<()> {
if CompletionInput::TYPE_ARGUMENT_VALUE == input.get_completion_type()
&& input.get_completion_name().as_deref() == Some("command")
{
let mut command_names: Vec<PhpMixed> = Vec::new();
for (name, command) in self.all(None)? {
// skip hidden commands and aliased commands as they already get added below
if command.borrow().is_hidden() || command.borrow().get_name() != Some(name.clone())
{
continue;
}
command_names.push(PhpMixed::from(
command.borrow().get_name().unwrap_or_default(),
));
for name in command.borrow().get_aliases() {
command_names.push(PhpMixed::from(name));
}
}
// array_filter($commandNames)
let filtered: Vec<crate::symfony::console::completion::completion_suggestions::StringOrSuggestion> =
command_names
.into_iter()
.filter(|n| shirabe_php_shim::php_truthy(n))
.map(|n| {
crate::symfony::console::completion::completion_suggestions::StringOrSuggestion::String(
shirabe_php_shim::php_to_string(&n),
)
})
.collect();
suggestions.suggest_values(filtered);
return Ok(());
}
if CompletionInput::TYPE_OPTION_NAME == input.get_completion_type() {
// $suggestions->suggestOptions($this->getDefinition()->getOptions());
// TODO(review): get_options() yields Rc<InputOption> (shared, non-Clone) while
// suggest_options() consumes owned InputOption values; an ownership/clone strategy
// for InputOption is needed.
suggestions.suggest_options(todo!("owned options from get_definition().get_options()"));
return Ok(());
}
Ok(())
}
/// Gets the help message.
pub fn get_help(&self) -> String {
self.get_long_version()
}
/// Gets whether to catch exceptions or not during commands execution.
pub fn are_exceptions_caught(&self) -> bool {
self.catch_exceptions
}
/// Sets whether to catch exceptions or not during commands execution.
pub fn set_catch_exceptions(&mut self, boolean: bool) {
self.catch_exceptions = boolean;
}
/// Gets whether to automatically exit after a command execution or not.
pub fn is_auto_exit_enabled(&self) -> bool {
self.auto_exit
}
/// Sets whether to automatically exit after a command execution or not.
pub fn set_auto_exit(&mut self, boolean: bool) {
self.auto_exit = boolean;
}
/// Gets the name of the application.
pub fn get_name(&self) -> String {
self.name.clone()
}
/// Sets the application name.
pub fn set_name(&mut self, name: &str) {
self.name = name.to_string();
}
/// Gets the application version.
pub fn get_version(&self) -> String {
self.version.clone()
}
/// Sets the application version.
pub fn set_version(&mut self, version: &str) {
self.version = version.to_string();
}
/// Returns the long version of the application.
pub fn get_long_version(&self) -> String {
if "UNKNOWN" != self.get_name() {
if "UNKNOWN" != self.get_version() {
return shirabe_php_shim::sprintf(
"%s <info>%s</info>",
&[
PhpMixed::from(self.get_name()),
PhpMixed::from(self.get_version()),
],
);
}
return self.get_name();
}
"Console Tool".to_string()
}
/// Adds an array of command objects.
///
/// If a Command is not enabled it will not be added.
pub fn add_commands(&mut self, commands: Vec<Rc<RefCell<dyn Command>>>) -> anyhow::Result<()> {
for command in commands {
self.add(command)?;
}
Ok(())
}
/// Adds a command object.
///
/// If a command with the same name already exists, it will be overridden.
/// If the command is not enabled it will not be added.
pub fn add(
&mut self,
command: Rc<RefCell<dyn Command>>,
) -> anyhow::Result<Option<Rc<RefCell<dyn Command>>>> {
self.init()?;
// TODO(review): $command->setApplication($this) needs an Rc<RefCell<Application>> to the
// current instance. Application is held by value here; the self-reference required to set
// the command's back-pointer needs the shared-ownership design (Phase C).
command
.borrow_mut()
.set_application(todo!("Rc<RefCell<Application>> of self"));
if !command.borrow().is_enabled() {
command.borrow_mut().set_application(None);
return Ok(None);
}
// if (!$command instanceof LazyCommand) { $command->getDefinition(); }
// TODO(review): LazyCommand vs Command type distinction; eager definition probe omitted
// pending lazy-command representation decision.
command.borrow().get_definition();
if command.borrow().get_name().is_none() {
return Err(LogicException(shirabe_php_shim::LogicException {
message: shirabe_php_shim::sprintf(
"The command defined in \"%s\" cannot have an empty name.",
&[PhpMixed::from(shirabe_php_shim::get_debug_type_obj(
&command,
))],
),
code: 0,
})
.into());
}
let name = command.borrow().get_name().unwrap();
self.commands.insert(name, command.clone());
for alias in command.borrow().get_aliases() {
self.commands.insert(alias, command.clone());
}
Ok(Some(command))
}
/// Returns a registered command by name or alias.
///
/// Throws CommandNotFoundException when given command name does not exist.
pub fn get(&mut self, name: &str) -> anyhow::Result<Rc<RefCell<dyn Command>>> {
self.init()?;
if !self.has(name) {
return Err(CommandNotFoundException::new(
shirabe_php_shim::sprintf(
"The command \"%s\" does not exist.",
&[PhpMixed::from(name.to_string())],
),
Vec::new(),
0,
)
.into());
}
// When the command has a different name than the one used at the command loader level
if !self.commands.contains_key(name) {
return Err(CommandNotFoundException::new(
shirabe_php_shim::sprintf(
"The \"%s\" command cannot be found because it is registered under multiple names. Make sure you don't set a different name via constructor or \"setName()\".",
&[PhpMixed::from(name.to_string())],
),
Vec::new(),
0,
)
.into());
}
let command = self.commands[name].clone();
if self.want_helps {
self.want_helps = false;
let help_command = self.get("help")?;
// $helpCommand->setCommand($command);
// TODO(review): setCommand() is defined on HelpCommand, not on the concrete `Command`
// struct; calling it through the Rc<RefCell<dyn Command>> needs the Command-subclass
// representation decision (downcast to HelpCommand).
let _ = &command;
todo!("help_command.set_command(command)");
#[allow(unreachable_code)]
return Ok(help_command);
}
Ok(command)
}
/// Returns true if the command exists, false otherwise.
pub fn has(&mut self, name: &str) -> bool {
self.init().unwrap();
if self.commands.contains_key(name) {
return true;
}
if let Some(command_loader) = &self.command_loader {
if command_loader.has(name) {
let command = command_loader.get(name);
// $this->add($this->commandLoader->get($name))
// TODO(review): command_loader.get() returns Box<dyn Command> while add() expects
// Rc<RefCell<dyn Command>>; the loader return type needs reconciliation.
let _ = command;
return self
.add(todo!(
"Rc<RefCell<dyn Command>> from command_loader.get(name)"
))
.map(|c| c.is_some())
.unwrap_or(false);
}
}
false
}
/// Returns an array of all unique namespaces used by currently registered commands.
///
/// It does not return the global namespace which always exists.
pub fn get_namespaces(&mut self) -> anyhow::Result<Vec<String>> {
let mut namespaces: Vec<Vec<String>> = Vec::new();
for command in self.all(None)?.values() {
if command.borrow().is_hidden() {
continue;
}
namespaces.push(
self.extract_all_namespaces(&command.borrow().get_name().unwrap_or_default()),
);
for alias in command.borrow().get_aliases() {
namespaces.push(self.extract_all_namespaces(&alias));
}
}
// array_values(array_unique(array_filter(array_merge([], ...$namespaces))))
let mut merged: Vec<String> = Vec::new();
for ns in namespaces {
merged.extend(ns);
}
let merged: Vec<String> = merged.into_iter().filter(|s| !s.is_empty()).collect();
let mut seen = std::collections::HashSet::new();
let unique: Vec<String> = merged
.into_iter()
.filter(|s| seen.insert(s.clone()))
.collect();
Ok(unique)
}
/// Finds a registered namespace by a name or an abbreviation.
///
/// Throws NamespaceNotFoundException when namespace is incorrect or ambiguous.
pub fn find_namespace(&mut self, namespace: &str) -> anyhow::Result<String> {
let all_namespaces = self.get_namespaces()?;
// implode('[^:]*:', array_map('preg_quote', explode(':', $namespace))).'[^:]*'
let parts: Vec<String> = shirabe_php_shim::explode(":", namespace)
.into_iter()
.map(|p| shirabe_php_shim::preg_quote(&p, None))
.collect();
let expr = format!("{}{}", shirabe_php_shim::implode("[^:]*:", &parts), "[^:]*");
let namespaces = shirabe_php_shim::preg_grep(&format!("{{^{}}}", expr), &all_namespaces);
if namespaces.is_empty() {
let mut message = shirabe_php_shim::sprintf(
"There are no commands defined in the \"%s\" namespace.",
&[PhpMixed::from(namespace.to_string())],
);
let alternatives = self.find_alternatives(namespace, &all_namespaces);
if !alternatives.is_empty() {
if alternatives.len() == 1 {
message.push_str("\n\nDid you mean this?\n ");
} else {
message.push_str("\n\nDid you mean one of these?\n ");
}
message.push_str(&shirabe_php_shim::implode("\n ", &alternatives));
}
return Err(NamespaceNotFoundException(CommandNotFoundException::new(
message,
alternatives,
0,
))
.into());
}
let exact = namespaces.iter().any(|n| n == namespace);
if namespaces.len() > 1 && !exact {
return Err(NamespaceNotFoundException(CommandNotFoundException::new(
shirabe_php_shim::sprintf(
"The namespace \"%s\" is ambiguous.\nDid you mean one of these?\n%s.",
&[
PhpMixed::from(namespace.to_string()),
PhpMixed::from(self.get_abbreviation_suggestions(&namespaces)),
],
),
namespaces.clone(),
0,
))
.into());
}
// $exact ? $namespace : reset($namespaces)
if exact {
Ok(namespace.to_string())
} else {
Ok(namespaces[0].clone())
}
}
/// Finds a command by name or alias.
///
/// Contrary to get, this command tries to find the best match if you give it an
/// abbreviation of a name or alias.
///
/// Throws CommandNotFoundException when command name is incorrect or ambiguous.
pub fn find(&mut self, name: &str) -> anyhow::Result<Rc<RefCell<dyn Command>>> {
self.init()?;
let mut aliases: IndexMap<String, String> = IndexMap::new();
let commands_snapshot: Vec<Rc<RefCell<dyn Command>>> =
self.commands.values().cloned().collect();
for command in &commands_snapshot {
for alias in command.borrow().get_aliases() {
if !self.has(&alias) {
self.commands.insert(alias, command.clone());
}
}
}
if self.has(name) {
return self.get(name);
}
// $allCommands = commandLoader ? array_merge(loader->getNames(), array_keys(commands)) : array_keys(commands)
let all_commands: Vec<String> = match &self.command_loader {
Some(command_loader) => {
let mut all = command_loader.get_names();
all.extend(self.commands.keys().cloned());
all
}
None => self.commands.keys().cloned().collect(),
};
let parts: Vec<String> = shirabe_php_shim::explode(":", name)
.into_iter()
.map(|p| shirabe_php_shim::preg_quote(&p, None))
.collect();
let expr = format!("{}{}", shirabe_php_shim::implode("[^:]*:", &parts), "[^:]*");
let mut commands = shirabe_php_shim::preg_grep(&format!("{{^{}}}", expr), &all_commands);
if commands.is_empty() {
commands = shirabe_php_shim::preg_grep(&format!("{{^{}}}i", expr), &all_commands);
}
// if no commands matched or we just matched namespaces
if commands.is_empty()
|| shirabe_php_shim::preg_grep(&format!("{{^{}$}}i", expr), &commands).len() < 1
{
if let Some(pos) = shirabe_php_shim::strrpos(name, ":") {
// check if a namespace exists and contains commands
self.find_namespace(&name[..pos as usize])?;
}
let mut message = shirabe_php_shim::sprintf(
"Command \"%s\" is not defined.",
&[PhpMixed::from(name.to_string())],
);
let mut alternatives = self.find_alternatives(name, &all_commands);
if !alternatives.is_empty() {
// remove hidden commands
let mut filtered: Vec<String> = Vec::new();
for alt in alternatives {
if !self.get(&alt)?.borrow().is_hidden() {
filtered.push(alt);
}
}
alternatives = filtered;
if alternatives.len() == 1 {
message.push_str("\n\nDid you mean this?\n ");
} else {
message.push_str("\n\nDid you mean one of these?\n ");
}
message.push_str(&shirabe_php_shim::implode("\n ", &alternatives));
}
return Err(CommandNotFoundException::new(message, alternatives, 0).into());
}
// filter out aliases for commands which are already on the list
if commands.len() > 1 {
// $commandList = commandLoader ? array_merge(array_flip(loader->getNames()), commands) : commands
// TODO(review): $commandList mixes flipped loader names (string => int) with Command
// instances; this heterogeneous PHP array needs a typed representation. The alias
// de-duplication and the loader->get() lazy materialization are left to design.
let mut command_list: IndexMap<String, Rc<RefCell<dyn Command>>> =
self.commands.clone();
let commands_clone = commands.clone();
let mut new_commands: Vec<String> = Vec::new();
let mut seen = std::collections::HashSet::new();
for name_or_alias in commands {
if !command_list.contains_key(&name_or_alias) {
let loaded = self.command_loader.as_ref().unwrap().get(&name_or_alias);
let _ = loaded;
command_list.insert(
name_or_alias.clone(),
todo!("Rc<RefCell<dyn Command>> from command_loader.get(name_or_alias)"),
);
}
let command_name = command_list[&name_or_alias]
.borrow()
.get_name()
.unwrap_or_default();
aliases.insert(name_or_alias.clone(), command_name.clone());
let keep = command_name == name_or_alias || !commands_clone.contains(&command_name);
if keep && seen.insert(name_or_alias.clone()) {
new_commands.push(name_or_alias);
}
}
commands = new_commands;
if commands.len() > 1 {
let usable_width = self.terminal.get_width() - 10;
let abbrevs: Vec<String> = commands.clone();
let mut max_len: i64 = 0;
for abbrev in &abbrevs {
max_len = std::cmp::max(Helper::width(abbrev), max_len);
}
let mut formatted_abbrevs: Vec<PhpMixed> = Vec::new();
for cmd in commands.clone() {
if command_list[&cmd].borrow().is_hidden() {
// unset($commands[array_search($cmd, $commands)])
if let Some(idx) = commands.iter().position(|c| *c == cmd) {
commands.remove(idx);
}
formatted_abbrevs.push(PhpMixed::Bool(false));
continue;
}
let abbrev = format!(
"{} {}",
shirabe_php_shim::str_pad(
&cmd,
max_len as usize,
" ",
shirabe_php_shim::STR_PAD_LEFT
),
command_list[&cmd].borrow().get_description()
);
if Helper::width(&abbrev) > usable_width {
formatted_abbrevs.push(PhpMixed::from(format!(
"{}...",
Helper::substr(&abbrev, 0, Some(usable_width - 3))
)));
} else {
formatted_abbrevs.push(PhpMixed::from(abbrev));
}
}
if commands.len() > 1 {
let filtered: Vec<String> = formatted_abbrevs
.iter()
.filter(|a| shirabe_php_shim::php_truthy(a))
.map(|a| shirabe_php_shim::php_to_string(a))
.collect();
let suggestions = self.get_abbreviation_suggestions(&filtered);
return Err(CommandNotFoundException::new(
shirabe_php_shim::sprintf(
"Command \"%s\" is ambiguous.\nDid you mean one of these?\n%s.",
&[
PhpMixed::from(name.to_string()),
PhpMixed::from(suggestions),
],
),
commands.clone(),
0,
)
.into());
}
}
}
// $command = $this->get(reset($commands));
let command = self.get(&commands[0])?;
if command.borrow().is_hidden() {
return Err(CommandNotFoundException::new(
shirabe_php_shim::sprintf(
"The command \"%s\" does not exist.",
&[PhpMixed::from(name.to_string())],
),
Vec::new(),
0,
)
.into());
}
Ok(command)
}
/// Gets the commands (registered in the given namespace if provided).
///
/// The array keys are the full names and the values the command instances.
pub fn all(
&mut self,
namespace: Option<&str>,
) -> anyhow::Result<IndexMap<String, Rc<RefCell<dyn Command>>>> {
self.init()?;
if namespace.is_none() {
if self.command_loader.is_none() {
return Ok(self.commands.clone());
}
let mut commands = self.commands.clone();
let names = self.command_loader.as_ref().unwrap().get_names();
for name in names {
if !commands.contains_key(&name) && self.has(&name) {
commands.insert(name.clone(), self.get(&name)?);
}
}
return Ok(commands);
}
let namespace = namespace.unwrap();
let mut commands: IndexMap<String, Rc<RefCell<dyn Command>>> = IndexMap::new();
let entries: Vec<(String, Rc<RefCell<dyn Command>>)> = self
.commands
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
for (name, command) in entries {
if namespace
== self.extract_namespace(
&name,
Some(shirabe_php_shim::substr_count(namespace, ":") + 1),
)
{
commands.insert(name, command);
}
}
if self.command_loader.is_some() {
let names = self.command_loader.as_ref().unwrap().get_names();
for name in names {
if !commands.contains_key(&name)
&& namespace
== self.extract_namespace(
&name,
Some(shirabe_php_shim::substr_count(namespace, ":") + 1),
)
&& self.has(&name)
{
commands.insert(name.clone(), self.get(&name)?);
}
}
}
Ok(commands)
}
/// Returns an array of possible abbreviations given a set of names.
pub fn get_abbreviations(names: Vec<String>) -> IndexMap<String, Vec<String>> {
let mut abbrevs: IndexMap<String, Vec<String>> = IndexMap::new();
for name in names {
let mut len = shirabe_php_shim::strlen(&name);
while len > 0 {
let abbrev = shirabe_php_shim::substr(&name, 0, Some(len));
abbrevs.entry(abbrev).or_default().push(name.clone());
len -= 1;
}
}
abbrevs
}
pub fn render_throwable(&self, e: &anyhow::Error, output: Rc<RefCell<dyn OutputInterface>>) {
output
.borrow()
.writeln(&["".to_string()], output_interface::VERBOSITY_QUIET);
self.do_render_throwable(e, output.clone());
if let Some(running_command) = &self.running_command {
output.borrow().writeln(
&[shirabe_php_shim::sprintf(
"<info>%s</info>",
&[PhpMixed::from(
OutputFormatter::escape(&shirabe_php_shim::sprintf(
&running_command.borrow_mut().get_synopsis(false),
&[PhpMixed::from(self.get_name())],
))
.unwrap(),
)],
)],
output_interface::VERBOSITY_QUIET,
);
output
.borrow()
.writeln(&["".to_string()], output_interface::VERBOSITY_QUIET);
}
}
pub fn do_render_throwable(&self, e: &anyhow::Error, output: Rc<RefCell<dyn OutputInterface>>) {
// do { ... } while ($e = $e->getPrevious());
// TODO(review): PHP walks the exception chain via getPrevious() and reads getMessage(),
// getCode(), getFile(), getLine(), getTrace(). anyhow::Error exposes a source() chain but
// not file/line/trace; faithful rendering of the trace needs a Throwable-equivalent.
let _ = output;
let _ = e;
todo!("render exception chain (getMessage/getCode/getFile/getLine/getTrace/getPrevious)")
}
/// Configures the input and output instances based on the user arguments and options.
pub fn configure_io(
&self,
input: &Rc<RefCell<dyn InputInterface>>,
output: &Rc<RefCell<dyn OutputInterface>>,
) -> anyhow::Result<()> {
if input.borrow().has_parameter_option(
PhpMixed::from(vec![PhpMixed::from("--ansi".to_string())]),
true,
) {
output.borrow().set_decorated(true);
} else if input.borrow().has_parameter_option(
PhpMixed::from(vec![PhpMixed::from("--no-ansi".to_string())]),
true,
) {
output.borrow().set_decorated(false);
}
if input.borrow().has_parameter_option(
PhpMixed::from(vec![
PhpMixed::from("--no-interaction".to_string()),
PhpMixed::from("-n".to_string()),
]),
true,
) {
input.borrow_mut().set_interactive(false);
}
let mut shell_verbosity = shirabe_php_shim::getenv("SHELL_VERBOSITY").unwrap_or_default();
let shell_verbosity_int: i64 = shell_verbosity.parse().unwrap_or(0);
let mut shell_verbosity: i64 = shell_verbosity_int;
match shell_verbosity_int {
-1 => {
output
.borrow()
.set_verbosity(output_interface::VERBOSITY_QUIET);
}
1 => {
output
.borrow()
.set_verbosity(output_interface::VERBOSITY_VERBOSE);
}
2 => {
output
.borrow()
.set_verbosity(output_interface::VERBOSITY_VERY_VERBOSE);
}
3 => {
output
.borrow()
.set_verbosity(output_interface::VERBOSITY_DEBUG);
}
_ => {
shell_verbosity = 0;
}
}
if input.borrow().has_parameter_option(
PhpMixed::from(vec![
PhpMixed::from("--quiet".to_string()),
PhpMixed::from("-q".to_string()),
]),
true,
) {
output
.borrow()
.set_verbosity(output_interface::VERBOSITY_QUIET);
shell_verbosity = -1;
} else if input
.borrow()
.has_parameter_option(PhpMixed::from("-vvv".to_string()), true)
|| input
.borrow()
.has_parameter_option(PhpMixed::from("--verbose=3".to_string()), true)
|| input.borrow().get_parameter_option(
PhpMixed::from("--verbose".to_string()),
PhpMixed::Bool(false),
true,
) == PhpMixed::from(3i64)
{
output
.borrow()
.set_verbosity(output_interface::VERBOSITY_DEBUG);
shell_verbosity = 3;
} else if input
.borrow()
.has_parameter_option(PhpMixed::from("-vv".to_string()), true)
|| input
.borrow()
.has_parameter_option(PhpMixed::from("--verbose=2".to_string()), true)
|| input.borrow().get_parameter_option(
PhpMixed::from("--verbose".to_string()),
PhpMixed::Bool(false),
true,
) == PhpMixed::from(2i64)
{
output
.borrow()
.set_verbosity(output_interface::VERBOSITY_VERY_VERBOSE);
shell_verbosity = 2;
} else if input
.borrow()
.has_parameter_option(PhpMixed::from("-v".to_string()), true)
|| input
.borrow()
.has_parameter_option(PhpMixed::from("--verbose=1".to_string()), true)
|| input
.borrow()
.has_parameter_option(PhpMixed::from("--verbose".to_string()), true)
|| shirabe_php_shim::php_truthy(&input.borrow().get_parameter_option(
PhpMixed::from("--verbose".to_string()),
PhpMixed::Bool(false),
true,
))
{
output
.borrow()
.set_verbosity(output_interface::VERBOSITY_VERBOSE);
shell_verbosity = 1;
}
if shell_verbosity == -1 {
input.borrow_mut().set_interactive(false);
}
if shirabe_php_shim::function_exists("putenv") {
shirabe_php_shim::putenv(&format!("SHELL_VERBOSITY={}", shell_verbosity));
}
shirabe_php_shim::env_set("SHELL_VERBOSITY", shell_verbosity.to_string());
shirabe_php_shim::server_set("SHELL_VERBOSITY", shell_verbosity.to_string());
let _ = &mut shell_verbosity;
Ok(())
}
/// Runs the current command.
///
/// If an event dispatcher has been attached to the application, events are also
/// dispatched during the life-cycle of the command.
///
/// Returns 0 if everything went fine, or an error code.
pub fn do_run_command(
&mut self,
command: Rc<RefCell<dyn Command>>,
input: Rc<RefCell<dyn InputInterface>>,
output: Rc<RefCell<dyn OutputInterface>>,
) -> anyhow::Result<i64> {
if let Some(helper_set) = command.borrow().get_helper_set() {
for (_alias, helper) in helper_set.borrow().get_iterator() {
// if ($helper instanceof InputAwareInterface) $helper->setInput($input);
// TODO(review): downcasting a HelperInterface to InputAwareInterface is not
// expressible without a typed mechanism; needs design.
let _ = helper;
let _ = std::marker::PhantomData::<dyn InputAwareInterface>;
}
}
if !self.signals_to_dispatch_event.is_empty() {
// $commandSignals = $command instanceof SignalableCommandInterface ? $command->getSubscribedSignals() : []
// TODO(review): Command is not a SignalableCommandInterface here; downcast needed.
let command_signals: Vec<i64> = Vec::new();
let _ = std::marker::PhantomData::<dyn SignalableCommandInterface>;
if !command_signals.is_empty() || self.dispatcher.is_some() {
if self.signal_registry.is_none() {
return Err(RuntimeException(shirabe_php_shim::RuntimeException {
message: "Unable to subscribe to signal events. Make sure that the `pcntl` extension is installed and that \"pcntl_*\" functions are not disabled by your php.ini's \"disable_functions\" directive.".to_string(),
code: 0,
})
.into());
}
if Terminal::has_stty_available() {
// TODO: registers SIGINT/SIGTERM handlers that restore the stty mode via
// shell_exec('stty ...'). pcntl signal handlers have no faithful Rust
// equivalent in Phase A.
let _stty_mode = shirabe_php_shim::shell_exec("stty -g");
for _signal in [shirabe_php_shim::SIGINT, shirabe_php_shim::SIGTERM] {
todo!("register signal handler to restore stty mode");
}
}
}
if self.dispatcher.is_some() {
// TODO(plugin): for each signal, register a handler that dispatches ConsoleSignalEvent.
for &signal in &self.signals_to_dispatch_event.clone() {
let _event = ConsoleSignalEvent::new(
todo!("Box<dyn Command>"),
todo!("Box<dyn InputInterface>"),
todo!("Box<dyn OutputInterface>"),
signal,
);
todo!("register signal handler dispatching ConsoleEvents::SIGNAL");
}
}
for _signal in command_signals {
// $this->signalRegistry->register($signal, [$command, 'handleSignal']);
todo!("register command->handle_signal as signal handler");
}
}
if self.dispatcher.is_none() {
return command.borrow_mut().run(
&mut *borrow_input_mut(&input),
&mut *borrow_output_mut(&output),
);
}
// bind before the console.command event, so the listeners have access to input options/arguments
match (|| -> anyhow::Result<()> {
command.borrow_mut().merge_application_definition(true);
input.borrow_mut().bind(command.borrow().get_definition())?;
Ok(())
})() {
Ok(()) => {}
Err(e) => {
// ignore invalid options/arguments for now, to allow the event listeners to customize the InputDefinition
if !is_exception_interface(&e) {
return Err(e);
}
}
}
// TODO(plugin): the whole dispatcher block below drives ConsoleCommandEvent /
// ConsoleErrorEvent / ConsoleTerminateEvent. The event objects require Box<dyn ...>
// wrappers for input/output/command and the dispatcher's dispatch() contract; their
// construction is left to the plugin/event design.
let _ = ConsoleCommandEvent::RETURN_CODE_DISABLED;
let _ = std::marker::PhantomData::<(
ConsoleCommandEvent,
ConsoleErrorEvent,
ConsoleTerminateEvent,
)>;
todo!("dispatcher-driven command run (console.command / console.error / console.terminate)")
}
/// Gets the name of the command based on input.
pub fn get_command_name(&self, input: &dyn InputInterface) -> Option<String> {
if self.single_command {
Some(self.default_command.clone())
} else {
input.get_first_argument()
}
}
/// Gets the default input definition.
pub fn get_default_input_definition(&self) -> InputDefinition {
use crate::symfony::console::input::input_definition::DefinitionItem;
InputDefinition::new(vec![
DefinitionItem::InputArgument(
InputArgument::new(
"command".to_string(),
Some(InputArgument::REQUIRED),
"The command to execute".to_string(),
PhpMixed::Null,
)
.unwrap(),
),
DefinitionItem::InputOption(
InputOption::new(
"--help",
PhpMixed::from("-h".to_string()),
Some(InputOption::VALUE_NONE),
format!(
"Display help for the given command. When no command is given display help for the <info>{}</info> command",
self.default_command
),
PhpMixed::Null,
)
.unwrap(),
),
DefinitionItem::InputOption(
InputOption::new(
"--quiet",
PhpMixed::from("-q".to_string()),
Some(InputOption::VALUE_NONE),
"Do not output any message".to_string(),
PhpMixed::Null,
)
.unwrap(),
),
DefinitionItem::InputOption(
InputOption::new(
"--verbose",
PhpMixed::from("-v|vv|vvv".to_string()),
Some(InputOption::VALUE_NONE),
"Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug".to_string(),
PhpMixed::Null,
)
.unwrap(),
),
DefinitionItem::InputOption(
InputOption::new(
"--version",
PhpMixed::from("-V".to_string()),
Some(InputOption::VALUE_NONE),
"Display this application version".to_string(),
PhpMixed::Null,
)
.unwrap(),
),
DefinitionItem::InputOption(
InputOption::new(
"--ansi",
PhpMixed::from("".to_string()),
Some(InputOption::VALUE_NEGATABLE),
"Force (or disable --no-ansi) ANSI output".to_string(),
PhpMixed::Null,
)
.unwrap(),
),
DefinitionItem::InputOption(
InputOption::new(
"--no-interaction",
PhpMixed::from("-n".to_string()),
Some(InputOption::VALUE_NONE),
"Do not ask any interactive question".to_string(),
PhpMixed::Null,
)
.unwrap(),
),
])
.unwrap()
}
/// Gets the default commands that should always be available.
pub fn get_default_commands(&self) -> Vec<Rc<RefCell<dyn Command>>> {
// return [new HelpCommand(), new ListCommand(), new CompleteCommand(), new DumpCompletionCommand()];
// TODO(review): HelpCommand/ListCommand/CompleteCommand/DumpCompletionCommand are ported as
// distinct structs (not subtypes of the concrete `Command` struct), so they cannot populate
// a Vec<Rc<RefCell<dyn Command>>>. Reconciling Command subclassing with Rust requires the
// command-hierarchy design decision (see also `add`/`find`/LazyCommand handling).
let _ = std::marker::PhantomData::<(
HelpCommand,
ListCommand,
CompleteCommand,
DumpCompletionCommand,
)>;
todo!("construct default commands once Command-subclass representation is decided")
}
/// Gets the default helper set with the helpers that should always be available.
pub fn get_default_helper_set(&self) -> Rc<RefCell<HelperSet>> {
use crate::symfony::console::helper::helper_interface::HelperInterface;
let helper_set = Rc::new(RefCell::new(HelperSet::default()));
let helpers: IndexMap<
crate::symfony::console::helper::helper_set::HelperSetKey,
Rc<RefCell<dyn HelperInterface>>,
> = {
let mut m: IndexMap<
crate::symfony::console::helper::helper_set::HelperSetKey,
Rc<RefCell<dyn HelperInterface>>,
> = IndexMap::new();
m.insert(
crate::symfony::console::helper::helper_set::HelperSetKey::Int(0),
Rc::new(RefCell::new(FormatterHelper::default())),
);
m.insert(
crate::symfony::console::helper::helper_set::HelperSetKey::Int(1),
Rc::new(RefCell::new(DebugFormatterHelper::default())),
);
m.insert(
crate::symfony::console::helper::helper_set::HelperSetKey::Int(2),
Rc::new(RefCell::new(ProcessHelper::default())),
);
m.insert(
crate::symfony::console::helper::helper_set::HelperSetKey::Int(3),
Rc::new(RefCell::new(QuestionHelper::default())),
);
m
};
HelperSet::new(&helper_set, helpers);
helper_set
}
/// Returns abbreviated suggestions in string format.
fn get_abbreviation_suggestions(&self, abbrevs: &[String]) -> String {
format!(" {}", shirabe_php_shim::implode("\n ", abbrevs))
}
/// Returns the namespace part of the command name.
///
/// This method is not part of public API and should not be used directly.
pub fn extract_namespace(&self, name: &str, limit: Option<i64>) -> String {
// $parts = explode(':', $name, -1);
let parts = shirabe_php_shim::explode_limit(":", name, -1);
// implode(':', null === $limit ? $parts : array_slice($parts, 0, $limit))
match limit {
None => shirabe_php_shim::implode(":", &parts),
Some(limit) => {
let sliced: Vec<String> = parts.into_iter().take(limit.max(0) as usize).collect();
shirabe_php_shim::implode(":", &sliced)
}
}
}
/// Finds alternative of $name among $collection, if nothing is found in
/// $collection, try in $abbrevs.
fn find_alternatives(&self, name: &str, collection: &[String]) -> Vec<String> {
let threshold = 1e3;
let mut alternatives: IndexMap<String, f64> = IndexMap::new();
let mut collection_parts: IndexMap<String, Vec<String>> = IndexMap::new();
for item in collection {
collection_parts.insert(item.clone(), shirabe_php_shim::explode(":", item));
}
for (i, subname) in shirabe_php_shim::explode(":", name).into_iter().enumerate() {
for (collection_name, parts) in &collection_parts {
let exists = alternatives.contains_key(collection_name);
if parts.get(i).is_none() && exists {
*alternatives.get_mut(collection_name).unwrap() += threshold;
continue;
} else if parts.get(i).is_none() {
continue;
}
let lev = shirabe_php_shim::levenshtein(&subname, &parts[i]) as f64;
if lev <= shirabe_php_shim::strlen(&subname) as f64 / 3.0
|| (!subname.is_empty() && parts[i].contains(&subname))
{
let v = if exists {
alternatives[collection_name] + lev
} else {
lev
};
alternatives.insert(collection_name.clone(), v);
} else if exists {
*alternatives.get_mut(collection_name).unwrap() += threshold;
}
}
}
for item in collection {
let lev = shirabe_php_shim::levenshtein(name, item) as f64;
if lev <= shirabe_php_shim::strlen(name) as f64 / 3.0 || item.contains(name) {
let v = if alternatives.contains_key(item) {
alternatives[item] - lev
} else {
lev
};
alternatives.insert(item.clone(), v);
}
}
// array_filter($alternatives, fn($lev) => $lev < 2 * $threshold)
alternatives.retain(|_, lev| *lev < 2.0 * threshold);
// ksort($alternatives, SORT_NATURAL | SORT_FLAG_CASE)
let mut keys: Vec<String> = alternatives.keys().cloned().collect();
shirabe_php_shim::sort_natural_flag_case(&mut keys);
keys
}
/// Sets the default Command name.
pub fn set_default_command(
&mut self,
command_name: &str,
is_single_command: bool,
) -> anyhow::Result<&mut Self> {
// $this->defaultCommand = explode('|', ltrim($commandName, '|'))[0];
let trimmed = shirabe_php_shim::ltrim(command_name, Some("|"));
self.default_command = shirabe_php_shim::explode("|", &trimmed)
.into_iter()
.next()
.unwrap_or_default();
if is_single_command {
// Ensure the command exist
self.find(command_name)?;
self.single_command = true;
}
Ok(self)
}
/// @internal
pub fn is_single_command(&self) -> bool {
self.single_command
}
fn split_string_by_width(&self, string: &str, width: i64) -> Vec<String> {
// str_split is not suitable for multi-byte characters, we should use preg_split to get char array properly.
let encoding = match shirabe_php_shim::mb_detect_encoding(string, None, true) {
None => return shirabe_php_shim::str_split(string, width),
Some(encoding) => encoding,
};
let utf8_string = shirabe_php_shim::mb_convert_encoding(string.into(), "utf8", &encoding);
let mut lines: Vec<String> = Vec::new();
let mut line = String::new();
let mut offset = 0i64;
let mut m: Vec<String> = Vec::new();
while shirabe_php_shim::preg_match_offset(r"/.{1,10000}/u", &utf8_string, &mut m, 0, offset)
{
offset += shirabe_php_shim::strlen(&m[0]);
for char in shirabe_php_shim::preg_split_chars(r"//u", &m[0]) {
// test if $char could be appended to current line
if shirabe_php_shim::mb_strwidth(&format!("{}{}", line, char), Some("utf8"))
<= width
{
line.push_str(&char);
continue;
}
// if not, push current line to array and make new line
lines.push(shirabe_php_shim::str_pad(
&line,
width as usize,
" ",
shirabe_php_shim::STR_PAD_LEFT,
));
line = char;
}
}
lines.push(if !lines.is_empty() {
shirabe_php_shim::str_pad(&line, width as usize, " ", shirabe_php_shim::STR_PAD_LEFT)
} else {
line.clone()
});
shirabe_php_shim::mb_convert_variables(&encoding, "utf8", &mut lines);
lines
}
/// Returns all namespaces of the command name.
fn extract_all_namespaces(&self, name: &str) -> Vec<String> {
// -1 as third argument is needed to skip the command short name when exploding
let parts = shirabe_php_shim::explode_limit(":", name, -1);
let mut namespaces: Vec<String> = Vec::new();
for part in parts {
if !namespaces.is_empty() {
let last = namespaces.last().unwrap().clone();
namespaces.push(format!("{}:{}", last, part));
} else {
namespaces.push(part);
}
}
namespaces
}
fn init(&mut self) -> anyhow::Result<()> {
if self.initialized {
return Ok(());
}
self.initialized = true;
for command in self.get_default_commands() {
self.add(command)?;
}
Ok(())
}
}
impl ResetInterface for Application {
fn reset(&mut self) {
Application::reset(self)
}
}
/// Helper mirroring PHP's `$e instanceof ExceptionInterface`.
fn is_exception_interface(e: &anyhow::Error) -> bool {
// anyhow::Error stores concrete error types; enumerate the console exceptions
// that implement ExceptionInterface (PHP's `$e instanceof ExceptionInterface`).
e.downcast_ref::<CommandNotFoundException>().is_some()
|| e.downcast_ref::<NamespaceNotFoundException>().is_some()
|| e.downcast_ref::<LogicException>().is_some()
|| e.downcast_ref::<RuntimeException>().is_some()
}
/// Helper mirroring PHP's `$e instanceof CommandNotFoundException`.
fn downcast_command_not_found(e: &anyhow::Error) -> Option<&CommandNotFoundException> {
if let Some(cnf) = e.downcast_ref::<CommandNotFoundException>() {
return Some(cnf);
}
e.downcast_ref::<NamespaceNotFoundException>().map(|n| &n.0)
}
/// Helper mirroring PHP's `$e instanceof NamespaceNotFoundException`.
fn is_namespace_not_found(e: &anyhow::Error) -> bool {
e.downcast_ref::<NamespaceNotFoundException>().is_some()
}
/// Borrows the shared input as a mutable `dyn InputInterface` for passing to
/// `Command::run`, which takes `&mut dyn InputInterface`.
fn borrow_input_mut(
input: &Rc<RefCell<dyn InputInterface>>,
) -> std::cell::RefMut<'_, dyn InputInterface> {
input.borrow_mut()
}
/// Borrows the shared output as a mutable `dyn OutputInterface` for passing to
/// `Command::run`, which takes `&mut dyn OutputInterface`.
fn borrow_output_mut(
output: &Rc<RefCell<dyn OutputInterface>>,
) -> std::cell::RefMut<'_, dyn OutputInterface> {
output.borrow_mut()
}
|