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
|
// Copyright Contributors to the DNF5 project.
// Copyright Contributors to the libdnf project.
// SPDX-License-Identifier: LGPL-2.1-or-later
//
// This file is part of libdnf: https://github.com/rpm-software-management/libdnf/
//
// Libdnf is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 2.1 of the License, or
// (at your option) any later version.
//
// Libdnf is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with libdnf. If not, see <https://www.gnu.org/licenses/>.
#include "libdnf5-cli/argument_parser.hpp"
#include "output/argument_parser.hpp"
#include "utils/string.hpp"
#include <fmt/format.h>
#include <libdnf5/common/exception.hpp>
#include <libdnf5/utils/bgettext/bgettext-lib.h>
#include <libdnf5/utils/bgettext/bgettext-mark-domain.h>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <regex>
#include <set>
#include <utility>
namespace libdnf5::cli {
namespace {
std::size_t replace_all(std::string & inout, std::string_view what, std::string_view with) {
std::size_t count = 0;
for (std::string::size_type pos = 0; inout.npos != (pos = inout.find(what.data(), pos, what.length()));
pos += with.length(), ++count) {
inout.replace(pos, what.length(), with.data(), with.length());
}
return count;
}
// Function to replace occurrences of ${<index>} with strings from the array
std::string format_string(const std::string & format, int argc, const char * const argv[]) {
const std::regex placeholder(R"(\$\{(\d+)\})");
std::string formatted;
// Search for all occurrences of ${<index>}
auto begin = format.cbegin();
auto end = format.cend();
std::smatch match;
while (std::regex_search(begin, end, match, placeholder)) {
formatted.append(begin, match[0].first); // Append text before the placeholder
int index;
try {
index = std::stoi(match[1]);
} catch (const std::invalid_argument & ex) {
throw Error(
M_("Misconfigured alias \"{}\": cannot convert \"{}\" to a number"),
std::string(argv[0]),
match[0].str());
} catch (const std::out_of_range & ex) {
index = -1;
}
if (index < 0 || index >= argc) {
throw Error(
M_("Misconfigured alias \"{}\": index \"{}\" out of range"), std::string(argv[0]), match[0].str());
}
formatted += argv[index]; // Replace placeholder with corresponding string
begin = match[0].second; // Continue after the last match
}
formatted.append(begin, end); // Append the remaining text
return formatted;
}
std::pair<BgettextMessage, std::string> get_conflict_arg_msg(const ArgumentParser::Argument * conflict_arg) {
if (const auto * named_arg = dynamic_cast<const ArgumentParser::NamedArg *>(conflict_arg)) {
std::string conflict;
if (!named_arg->get_long_name().empty()) {
conflict = "--" + named_arg->get_long_name();
}
if (!named_arg->get_long_name().empty() && named_arg->get_short_name() != '\0') {
conflict += "/";
}
if (named_arg->get_short_name() != '\0') {
conflict = std::string("-") + named_arg->get_short_name();
}
return {M_("\"{}\" not allowed together with named argument \"{}\""), conflict};
} else if (dynamic_cast<const ArgumentParser::Command *>(conflict_arg)) {
return {M_("\"{}\" not allowed in command \"{}\""), conflict_arg->get_id()};
} else {
return {M_("\"{}\" not allowed together with positional argument \"{}\""), conflict_arg->get_id()};
}
}
} // namespace
class ArgumentParser::ArgumentParserImpl {
public:
void assert_root_command() { libdnf_assert(root_command != nullptr, "Root command is not set"); }
std::vector<std::unique_ptr<Command>> cmds;
std::vector<std::unique_ptr<NamedArg>> named_args;
std::vector<std::unique_ptr<PositionalArg>> pos_args;
std::vector<std::unique_ptr<Group>> groups;
std::vector<std::unique_ptr<std::vector<Argument *>>> conflict_args_groups;
std::vector<std::unique_ptr<libdnf5::Option>> values_init;
std::vector<std::unique_ptr<std::vector<std::unique_ptr<libdnf5::Option>>>> values;
Command * root_command{nullptr};
Command * selected_command{nullptr};
bool inherit_named_args{false};
const char * const * complete_arg_ptr{nullptr};
bool complete_add_description{true}; // Indicates whether to add a description to the suggested arguments
};
// =============== ArgumentParser::Group methods ===============
ArgumentParser::Group::~Group() = default;
void ArgumentParser::Group::set_header(std::string header) noexcept {
this->header = std::move(header);
}
const std::string & ArgumentParser::Group::get_id() const noexcept {
return id;
}
const std::string & ArgumentParser::Group::get_header() const noexcept {
return header;
}
void ArgumentParser::Group::register_argument(Argument * arg) {
for (auto * item : arguments) {
if (item->id == arg->id) {
throw ArgumentParserGroupArgumentIdRegisteredError(
M_("Argument id \"{}\" already registered in group \"{}\""), arg->id, id);
}
}
arguments.push_back(arg);
}
const std::vector<ArgumentParser::Argument *> & ArgumentParser::Group::get_arguments() const noexcept {
return arguments;
}
ArgumentParser::Group::Group(const std::string & id) : id(id) {}
// =============== ArgumentParser::Argument methods ===============
ArgumentParser::Argument::~Argument() = default;
void ArgumentParser::Argument::set_long_description(std::string descr) noexcept {
long_description = std::move(descr);
}
void ArgumentParser::Argument::set_description(std::string descr) noexcept {
description = std::move(descr);
}
void ArgumentParser::Argument::set_conflict_arguments(std::vector<Argument *> * args) noexcept {
conflict_args = args;
}
void ArgumentParser::Argument::add_conflict_argument(ArgumentParser::Argument & conflict_arg) {
auto add_conflict = [](Argument & arg, Argument & conflict_arg) {
if (arg.conflict_args) {
auto it = std::find(arg.conflict_args->begin(), arg.conflict_args->end(), &conflict_arg);
if (it == arg.conflict_args->end()) {
arg.conflict_args->push_back(&conflict_arg);
}
} else {
// Creates a new group of conflict arguments if it does not exist
arg.conflict_args = arg.owner.add_conflict_args_group(std::make_unique<std::vector<Argument *>>());
arg.conflict_args->push_back(&conflict_arg);
}
};
// Adds forward conflict
add_conflict(*this, conflict_arg);
// Adds reverse (back) conflict
add_conflict(conflict_arg, *this);
}
void ArgumentParser::Argument::add_conflict_arguments_from_another(Argument & src_arg) {
// Return immediately if there are no conflicting arguments in the source argument or it is a self-assignment.
if (!src_arg.conflict_args || &src_arg == this) {
return;
}
for (std::size_t idx = 0; idx < src_arg.conflict_args->size(); ++idx) {
auto * conflict_arg = (*src_arg.conflict_args)[idx];
// Don't add a conflict to the argument itself and to the source argument.
if (conflict_arg == this || conflict_arg == &src_arg) {
continue;
}
add_conflict_argument(*conflict_arg);
}
}
const std::string & ArgumentParser::Argument::get_id() const noexcept {
return id;
}
const std::string & ArgumentParser::Argument::get_long_description() const {
return long_description;
}
const std::string & ArgumentParser::Argument::get_description() const {
return description;
}
std::vector<ArgumentParser::Argument *> * ArgumentParser::Argument::get_conflict_arguments() noexcept {
return conflict_args;
}
int ArgumentParser::Argument::get_parse_count() const noexcept {
return parse_count;
}
void ArgumentParser::Argument::reset_parse_count() noexcept {
parse_count = 0;
}
ArgumentParser::Argument * ArgumentParser::Argument::get_conflict_argument() const noexcept {
if (conflict_args) {
for (auto * arg : *conflict_args) {
if (arg != this && arg->get_parse_count() > 0) {
return arg;
}
}
}
return nullptr;
}
void ArgumentParser::Argument::set_complete(bool complete) noexcept {
this->complete = complete;
}
bool ArgumentParser::Argument::get_complete() const noexcept {
return complete;
}
void ArgumentParser::Argument::help() const noexcept {}
ArgumentParser & ArgumentParser::Argument::get_argument_parser() const noexcept {
return owner;
}
void ArgumentParser::Argument::set_user_data(ArgumentParserUserData * user_data) noexcept {
this->user_data = user_data;
}
ArgumentParserUserData * ArgumentParser::Argument::get_user_data() const noexcept {
return user_data;
}
ArgumentParser::Argument::Argument(ArgumentParser & owner, std::string id) : owner(owner) {
if (id.find('.') != id.npos) {
throw ArgumentParserArgumentInvalidIdError(M_("Invalid character '.' in argument id \"{}\""), id);
}
this->id = std::move(id);
}
// =============== ArgumentParser::PositionalArg methods ===============
ArgumentParser::PositionalArg::~PositionalArg() = default;
int ArgumentParser::PositionalArg::get_nvals() const noexcept {
return nvals;
}
void ArgumentParser::PositionalArg::set_store_value(bool enable) {
libdnf_assert(!enable || values, "set_store_value(true) was called but storage array \"values\" is not set");
store_value = enable;
}
bool ArgumentParser::PositionalArg::get_store_value() const noexcept {
return store_value;
}
std::vector<std::unique_ptr<libdnf5::Option>> * ArgumentParser::PositionalArg::get_linked_values() noexcept {
return values;
}
void ArgumentParser::PositionalArg::set_parse_hook_func(ParseHookFunc && func) {
parse_hook = std::move(func);
}
const ArgumentParser::PositionalArg::ParseHookFunc & ArgumentParser::PositionalArg::get_parse_hook_func()
const noexcept {
return parse_hook;
}
void ArgumentParser::PositionalArg::set_complete_hook_func(CompleteHookFunc && func) {
complete_hook = std::move(func);
}
const ArgumentParser::PositionalArg::CompleteHookFunc & ArgumentParser::PositionalArg::get_complete_hook_func()
const noexcept {
return complete_hook;
}
void ArgumentParser::PositionalArg::set_nrepeats(int nrepeats) {
this->nrepeats = nrepeats;
}
int ArgumentParser::PositionalArg::get_nrepeats() const noexcept {
return nrepeats;
}
ArgumentParser::PositionalArg::PositionalArg(
ArgumentParser & owner, const std::string & id, std::vector<std::unique_ptr<libdnf5::Option>> * values)
: Argument(owner, id),
init_value(nullptr),
values(values) {
libdnf_assert(values && !values->empty(), "\"values\" constructor parameter cannot be nullptr or an empty vector");
nvals = static_cast<int>(values->size());
}
ArgumentParser::PositionalArg::PositionalArg(
ArgumentParser & owner,
const std::string & id,
int nvals,
libdnf5::Option * init_value,
std::vector<std::unique_ptr<libdnf5::Option>> * values)
: Argument(owner, id),
nvals(nvals),
init_value(init_value),
values(values),
store_value(values) {
libdnf_assert(!values || init_value, "\"init_value\" constructor parameter cannot be nullptr if \"value\" is set");
}
int ArgumentParser::PositionalArg::parse(const char * option, int argc, const char * const argv[]) {
if (const auto * arg = get_conflict_argument()) {
auto [fmt_message, conflict_option] = get_conflict_arg_msg(arg);
throw ArgumentParserConflictingArgumentsError(fmt_message, std::string(option), conflict_option);
}
if (owner.p_impl->complete_arg_ptr) {
int usable_argc = 1;
while (usable_argc < argc && *argv[usable_argc] != '-') {
++usable_argc;
}
auto count = static_cast<size_t>(nvals > 0 ? nvals : (nvals == OPTIONAL ? 1 : usable_argc));
for (size_t i = 0; i < count; ++i) {
if (owner.p_impl->complete_arg_ptr == argv + i) {
if (get_complete() && complete_hook) {
auto result = complete_hook(argv[i]);
if (result.size() == 1) {
if (result[0] != option) {
std::cout << result[0] << std::endl;
}
} else {
for (const auto & line : result) {
std::cout << line << std::endl;
}
}
}
return static_cast<int>(count);
}
}
}
if (argc < nvals) {
throw ArgumentParserPositionalArgFewValuesError(M_("Too few values for positional argument \"{}\""), this->id);
}
for (int i = 1; i < nvals; ++i) {
if (*argv[i] == '-') {
throw ArgumentParserPositionalArgFewValuesError(
M_("Too few values for positional argument \"{}\""), this->id);
}
}
int usable_argc = 1;
if (nvals <= 0) {
while (usable_argc < argc && *argv[usable_argc] != '-') {
++usable_argc;
}
}
auto count = static_cast<size_t>(nvals > 0 ? nvals : (nvals == OPTIONAL ? 1 : usable_argc));
if (store_value) {
for (size_t i = 0; i < count; ++i) {
if (values->size() <= i) {
values->push_back(std::unique_ptr<libdnf5::Option>((*init_value).clone()));
}
(*values)[i]->set(libdnf5::Option::Priority::COMMANDLINE, argv[i]);
}
}
++parse_count;
if (parse_hook) {
parse_hook(this, static_cast<int>(count), argv);
}
return static_cast<int>(count);
}
// =============== ArgumentParser::NamedArg methods ===============
ArgumentParser::NamedArg::~NamedArg() = default;
void ArgumentParser::NamedArg::set_long_name(std::string long_name) noexcept {
this->long_name = std::move(long_name);
}
void ArgumentParser::NamedArg::set_short_name(char short_name) {
this->short_name = short_name;
}
void ArgumentParser::NamedArg::set_has_value(bool has_value) {
this->has_value = has_value;
}
void ArgumentParser::NamedArg::link_value(libdnf5::Option * value) {
this->value = value;
}
void ArgumentParser::NamedArg::set_const_value(std::string const_value) noexcept {
const_val = std::move(const_value);
}
const std::string & ArgumentParser::NamedArg::get_long_name() const noexcept {
return long_name;
}
char ArgumentParser::NamedArg::get_short_name() const noexcept {
return short_name;
}
bool ArgumentParser::NamedArg::get_has_value() const noexcept {
return has_value;
}
const std::string & ArgumentParser::NamedArg::get_const_value() const noexcept {
return const_val;
}
libdnf5::Option * ArgumentParser::NamedArg::get_linked_value() noexcept {
return value;
}
const libdnf5::Option * ArgumentParser::NamedArg::get_linked_value() const noexcept {
return value;
}
void ArgumentParser::NamedArg::set_store_value(bool enable) noexcept {
store_value = enable;
}
bool ArgumentParser::NamedArg::get_store_value() const noexcept {
return store_value;
}
void ArgumentParser::NamedArg::set_parse_hook_func(ParseHookFunc && func) {
parse_hook = std::move(func);
}
const ArgumentParser::NamedArg::ParseHookFunc & ArgumentParser::NamedArg::get_parse_hook_func() const noexcept {
return parse_hook;
}
void ArgumentParser::NamedArg::set_arg_value_help(std::string text) {
arg_value_help = std::move(text);
}
const std::string & ArgumentParser::NamedArg::get_arg_value_help() const noexcept {
return arg_value_help;
}
libdnf5::cli::ArgumentParser::NamedArg * ArgumentParser::NamedArg::add_alias(
const std::string & id,
const std::string & long_name,
char short_name,
libdnf5::cli::ArgumentParser::Group * group) {
auto * alias = get_argument_parser().add_new_named_arg(id);
alias->set_long_name(long_name);
alias->set_short_name(short_name);
// Set description
std::string descr;
if (get_short_name() != '\0') {
descr = std::string("'-") + get_short_name() + "'";
if (!get_long_name().empty()) {
descr += ", ";
}
}
if (!get_long_name().empty()) {
descr += "'--" + get_long_name() + "'";
}
alias->set_description(fmt::format("Alias for {}", descr));
// Copy from source argument
alias->set_has_value(get_has_value());
alias->link_value(get_linked_value());
alias->set_store_value(get_store_value());
alias->set_const_value(get_const_value());
alias->set_arg_value_help(get_arg_value_help());
alias->set_parse_hook_func(libdnf5::cli::ArgumentParser::NamedArg::ParseHookFunc(get_parse_hook_func()));
// Do not offer aliases in completion
alias->set_complete(false);
if (group) {
group->register_argument(alias);
}
alias->add_conflict_arguments_from_another(*this);
return alias;
}
void ArgumentParser::NamedArg::attach_named_arg(const std::string & id_path, const std::string & value) {
attached_named_args.push_back({id_path, value});
}
ArgumentParser::NamedArg::NamedArg(ArgumentParser & owner, const std::string & id) : Argument(owner, id) {}
int ArgumentParser::NamedArg::parse_long(const char * option, int argc, const char * const argv[]) {
if (const auto * arg = get_conflict_argument()) {
auto [fmt_message, conflict_option] = get_conflict_arg_msg(arg);
throw ArgumentParserConflictingArgumentsError(fmt_message, "--" + std::string(option), conflict_option);
}
const char * arg_value;
int consumed_args;
const auto * assign_ptr = strchr(option, '=');
if (has_value) {
if (assign_ptr) {
arg_value = assign_ptr + 1;
consumed_args = 1;
} else {
if (argc < 2) {
throw ArgumentParserNamedArgMissingValueError(
M_("Missing value for named argument \"--{}\""), std::string(option));
}
arg_value = argv[1];
consumed_args = 2;
}
} else {
if (assign_ptr) {
throw ArgumentParserNamedArgValueNotExpectedError(
M_("Unexpected value for named argument \"--{}\""), std::string(option));
}
arg_value = const_val.c_str();
consumed_args = 1;
}
if (store_value && value) {
value->set(libdnf5::Option::Priority::COMMANDLINE, arg_value);
}
++parse_count;
if (parse_hook) {
parse_hook(this, option, arg_value);
}
// Invoke the attached named arguments
for (auto & target_named_arg : attached_named_args) {
auto & target_arg = owner.get_named_arg(target_named_arg.id_path, false);
std::string long_name = assign_ptr ? std::string(option, assign_ptr) : option;
if (target_arg.get_has_value()) {
std::string target_arg_val = target_named_arg.value;
replace_all(target_arg_val, "${}", arg_value);
long_name += "=" + target_arg_val;
}
const char * const args[1] = {long_name.c_str()};
target_arg.parse_long(long_name.c_str(), 1, args);
}
return consumed_args;
}
int ArgumentParser::NamedArg::parse_short(const char * option, int argc, const char * const argv[]) {
if (const auto * arg = get_conflict_argument()) {
auto [fmt_message, conflict_option] = get_conflict_arg_msg(arg);
throw ArgumentParserConflictingArgumentsError(fmt_message, '-' + std::string(option), conflict_option);
}
const char * arg_value;
int consumed_args;
if (has_value) {
if (option[1] != '\0') {
arg_value = option + 1;
consumed_args = 1;
} else {
if (argc < 2) {
throw ArgumentParserNamedArgMissingValueError(M_("Missing value for named argument \"-{}\""), *option);
}
arg_value = argv[1];
consumed_args = 2;
}
} else {
arg_value = const_val.c_str();
consumed_args =
option[1] == '\0' ? 1 : 0; // consume only if we are the last option in group, example of 3 options: -cvf
}
if (store_value && value) {
value->set(libdnf5::Option::Priority::COMMANDLINE, arg_value);
}
++parse_count;
if (parse_hook) {
parse_hook(this, option, arg_value);
}
// Invoke the attached named arguments
for (auto & target_named_arg : attached_named_args) {
auto & target_arg = owner.get_named_arg(target_named_arg.id_path, false);
const char * args[2];
int args_count = 1;
std::string target_arg_val;
if (target_arg.get_has_value()) {
target_arg_val = target_named_arg.value;
replace_all(target_arg_val, "${}", arg_value);
args[args_count++] = target_arg_val.c_str();
}
char short_name[] = {option[0], '\0'};
args[0] = short_name;
target_arg.parse_short(short_name, args_count, args);
}
return consumed_args;
}
// =============== ArgumentParser::Command methods ===============
template <class Arg>
static Arg * find_arg(const std::vector<Arg *> & args, const std::string & id) {
for (auto * item : args) {
if (item->get_id() == id) {
return item;
}
}
return nullptr;
}
static std::string get_named_arg_names(const ArgumentParser::NamedArg * arg) {
std::string arg_names;
if (arg->get_short_name() != '\0') {
arg_names = std::string("-") + arg->get_short_name();
if (arg->get_has_value()) {
arg_names += arg->get_arg_value_help().empty() ? " VALUE" : ' ' + arg->get_arg_value_help();
}
if (!arg->get_long_name().empty()) {
arg_names += ", ";
}
}
if (!arg->get_long_name().empty()) {
arg_names += "--" + arg->get_long_name();
if (arg->get_has_value()) {
arg_names += arg->get_arg_value_help().empty() ? "=VALUE" : '=' + arg->get_arg_value_help();
}
}
return arg_names;
}
ArgumentParser::Command::~Command() = default;
void ArgumentParser::Command::help() const noexcept {
auto & cmds = get_commands();
auto & named_args = get_named_args();
auto & pos_args = get_positional_args();
auto & groups = get_groups();
libdnf5::cli::output::Usage usage_output;
// generate usage
std::string usage;
for (const auto * cmd = this; cmd; cmd = cmd->parent) {
std::string tmp = cmd->get_id();
if (!cmd->get_named_args().empty()) {
tmp += cmd->parent ? " [OPTIONS]" : " [GLOBAL OPTIONS]";
}
if (!cmd->get_positional_args().empty()) {
tmp += " [ARGUMENTS]";
}
usage = tmp + ' ' + usage;
}
if (!cmds.empty()) {
usage += "<COMMAND> ...";
}
// print usage
auto * usage_header = usage_output.add_header(_("Usage:"));
for (auto & line : libdnf5::utils::string::split(usage, "\n")) {
usage_output.add_line(line, usage_header);
}
// print description
if (!long_description.empty()) {
usage_output.add_newline();
auto * desc_header = usage_output.add_header(_("Description:"));
for (auto & line : libdnf5::utils::string::split(long_description, "\n")) {
usage_output.add_line(line, desc_header);
}
}
libdnf5::cli::output::Help help;
// Arguments used in groups are not printed as ungrouped.
std::set<Argument *> args_used_in_groups;
if (!commands_help_header.empty() && !cmds.empty()) {
const std::set<Argument *> cmds_set(cmds.begin(), cmds.end());
// Processing commands in groups.
for (auto * grp : groups) {
// we'll initialize the header line later when the first line with an argument is added
struct libscols_line * header{nullptr};
for (auto * arg : grp->get_arguments()) {
if (dynamic_cast<Command *>(arg) && cmds_set.count(arg) > 0) {
if (!header) {
help.add_newline();
header = help.add_header(grp->get_header());
}
help.add_line(arg->get_id(), arg->get_description(), header);
args_used_in_groups.insert(arg);
}
}
}
// gather commands that don't belong to any group
std::vector<Command *> ungrouped_commands;
for (auto * cmd : cmds) {
if (args_used_in_groups.count(cmd) == 0) {
ungrouped_commands.push_back(cmd);
}
}
// print the commands that don't belong to any group
// avoid printing `commands_help_header` if the list is empty
if (!ungrouped_commands.empty()) {
help.add_newline();
struct libscols_line * header = help.add_header(commands_help_header);
for (auto * arg : ungrouped_commands) {
help.add_line(arg->get_id(), arg->get_description(), header);
}
}
}
if (!named_args_help_header.empty() && !named_args.empty()) {
const std::set<Argument *> named_args_set(named_args.begin(), named_args.end());
// Processing named arguments in groups.
for (auto * grp : groups) {
// we'll initialize the header line later when the first line with an argument is added
struct libscols_line * header{nullptr};
for (auto * arg : grp->get_arguments()) {
auto * named_arg = dynamic_cast<NamedArg *>(arg);
if (named_arg && named_args_set.count(arg) > 0) {
if (!header) {
help.add_newline();
header = help.add_header(grp->get_header());
}
help.add_line(get_named_arg_names(named_arg), arg->get_description(), header);
args_used_in_groups.insert(arg);
}
}
}
// gather named args that don't belong to any group
std::vector<NamedArg *> ungrouped_named_args;
for (auto * arg : named_args) {
if (args_used_in_groups.count(static_cast<NamedArg *>(arg)) == 0) {
ungrouped_named_args.push_back(arg);
}
}
// print the named args that don't belong to any group
// avoid printing `named_args_help_header` if the list is empty
if (!ungrouped_named_args.empty()) {
help.add_newline();
struct libscols_line * header = help.add_header(named_args_help_header);
for (const auto * arg : ungrouped_named_args) {
help.add_line(get_named_arg_names(arg), arg->get_description(), header);
}
}
}
if (!positional_args_help_header.empty() && !pos_args.empty()) {
const std::set<Argument *> pos_args_set(pos_args.begin(), pos_args.end());
// Processing positional arguments in groups.
for (auto * grp : groups) {
// we'll initialize the header line later when the first line with an argument is added
struct libscols_line * header{nullptr};
for (auto * arg : grp->get_arguments()) {
if (dynamic_cast<PositionalArg *>(arg) && pos_args_set.count(arg) > 0) {
if (!header) {
help.add_newline();
header = help.add_header(grp->get_header());
}
help.add_line(arg->get_id(), arg->get_description(), header);
args_used_in_groups.insert(arg);
}
}
}
// Processing ungrouped positional arguments.
help.add_newline();
struct libscols_line * header = help.add_header(positional_args_help_header);
for (const auto * arg : pos_args) {
help.add_line(arg->get_id(), arg->get_description(), header);
}
}
usage_output.print();
help.print();
}
void ArgumentParser::Command::set_commands_help_header(std::string text) noexcept {
commands_help_header = std::move(text);
}
void ArgumentParser::Command::set_named_args_help_header(std::string text) noexcept {
named_args_help_header = std::move(text);
}
void ArgumentParser::Command::set_positional_args_help_header(std::string text) noexcept {
positional_args_help_header = std::move(text);
}
const std::string & ArgumentParser::Command::get_commands_help_header() const noexcept {
return commands_help_header;
}
const std::string & ArgumentParser::Command::get_named_args_help_header() const noexcept {
return named_args_help_header;
}
const std::string & ArgumentParser::Command::get_positional_args_help_header() const noexcept {
return positional_args_help_header;
}
ArgumentParser::Command * ArgumentParser::Command::get_parent() const noexcept {
return parent;
}
std::vector<std::string> ArgumentParser::Command::get_invocation() const noexcept {
std::vector<std::string> invocation = {get_id()};
if (parent) {
auto parent_invocation = parent->get_invocation();
invocation.insert(invocation.begin(), parent_invocation.begin(), parent_invocation.end());
}
return invocation;
}
ArgumentParser::Command::Command(ArgumentParser & owner, const std::string & id) : Argument(owner, id) {}
void ArgumentParser::Command::print_complete(
const char * arg, std::vector<ArgumentParser::NamedArg *> named_args, size_t used_positional_arguments) {
const bool add_description = get_argument_parser().p_impl->complete_add_description;
// Using the Help class to print the completion suggestions wits description, as it prints a table of two columns
// which is also what we need here.
libdnf5::cli::output::Help help;
// Used to store a list of suggestions when a table is not needed (description is not added).
std::vector<std::string> suggestions;
std::string last;
// Search for matching commands.
if (arg[0] == '\0' || arg[0] != '-') {
for (const auto * opt : get_commands()) {
if (!opt->get_complete()) {
continue;
}
auto & name = opt->get_id();
if (name.compare(0, strlen(arg), arg) == 0) {
if (add_description) {
help.add_line(name, '(' + opt->get_description() + ')', nullptr);
} else {
suggestions.emplace_back(name);
}
last = name + ' ';
}
}
// No matching command found. But there may be a positional argument.
if (last.empty() && used_positional_arguments < get_positional_args().size()) {
auto pos_arg = get_positional_args()[used_positional_arguments];
if (pos_arg->get_complete() && pos_arg->complete_hook) {
auto result = pos_arg->complete_hook(arg);
if (result.size() == 1) {
if (result[0] == arg) {
return;
}
std::cout << result[0] << std::endl;
return;
}
for (const auto & line : result) {
std::cout << line << std::endl;
}
}
}
}
// Search for matching named arguments.
if (arg[0] == '-') {
for (const auto * opt : named_args) {
if (!opt->get_complete()) {
continue;
}
if ((arg[1] == '\0' && opt->get_short_name() != '\0') ||
(arg[1] == opt->get_short_name() && arg[2] == '\0')) {
std::string name = std::string("-") + opt->get_short_name();
if (add_description) {
std::string extended_name = name;
if (opt->get_has_value()) {
extended_name += opt->get_arg_value_help().empty() ? "VALUE" : opt->get_arg_value_help();
}
help.add_line(extended_name, '(' + opt->get_description() + ')', nullptr);
} else {
suggestions.emplace_back(name);
}
last = name;
if (!opt->get_has_value()) {
last += ' ';
}
}
if (!opt->get_long_name().empty()) {
std::string name = "--" + opt->get_long_name();
if (name.compare(0, strlen(arg), arg) == 0) {
if (opt->get_has_value()) {
name += '=';
}
if (add_description) {
std::string extended_name = name;
if (opt->get_has_value()) {
extended_name += opt->get_arg_value_help().empty() ? "VALUE" : opt->get_arg_value_help();
}
help.add_line(extended_name, '(' + opt->get_description() + ')', nullptr);
} else {
suggestions.emplace_back(name);
}
last = name;
if (!opt->get_has_value()) {
last += ' ';
}
}
}
}
}
// Prints the completed argument or suggestions if there is more than one solution.
// Suggestions may be completed with a description.
if (scols_table_get_nlines(help.get_table()) > 1) {
help.print();
} else if (suggestions.size() > 1) {
for (const auto & suggestion : suggestions) {
std::cout << suggestion << std::endl;
}
} else if (!last.empty() && last != arg) {
std::cout << last << std::endl;
}
}
// =============== ArgumentParser::CommandOrdinary methods ===============
ArgumentParser::CommandOrdinary::~CommandOrdinary() = default;
void ArgumentParser::CommandOrdinary::register_command(Command * cmd) {
for (auto * item : cmds) {
if (item->id == cmd->id) {
throw ArgumentParserIdAlreadyRegisteredError(
M_("Command id \"{}\" already registered for command \"{}\""), cmd->id, id);
}
}
cmd->parent = this;
cmds.push_back(cmd);
}
void ArgumentParser::CommandOrdinary::register_named_arg(NamedArg * arg) {
for (auto * item : named_args) {
if (item->id == arg->id) {
throw ArgumentParserIdAlreadyRegisteredError(
M_("Named argument id \"{}\" already registered for command \"{}\""), arg->id, id);
}
}
named_args.push_back(arg);
}
void ArgumentParser::CommandOrdinary::register_positional_arg(PositionalArg * arg) {
for (auto * item : pos_args) {
if (item->id == arg->id) {
throw ArgumentParserIdAlreadyRegisteredError(
M_("Positional argument id \"{}\" already registered for command \"{}\""), arg->id, id);
}
}
pos_args.push_back(arg);
}
void ArgumentParser::CommandOrdinary::register_group(Group * grp) {
for (auto * item : groups) {
if (item->id == grp->id) {
throw ArgumentParserIdAlreadyRegisteredError(
M_("Group id \"{}\" already registered for command \"{}\""), grp->id, id);
}
}
groups.push_back(grp);
}
const std::vector<ArgumentParser::Command *> & ArgumentParser::CommandOrdinary::get_commands() const noexcept {
return cmds;
}
const std::vector<ArgumentParser::NamedArg *> & ArgumentParser::CommandOrdinary::get_named_args() const noexcept {
return named_args;
}
const std::vector<ArgumentParser::PositionalArg *> & ArgumentParser::CommandOrdinary::get_positional_args()
const noexcept {
return pos_args;
}
const std::vector<ArgumentParser::Group *> & ArgumentParser::CommandOrdinary::get_groups() const noexcept {
return groups;
}
ArgumentParser::Command & ArgumentParser::CommandOrdinary::get_command(const std::string & id) const {
if (auto ret = find_arg(cmds, id)) {
return *ret;
}
throw ArgumentParserNotFoundError(M_("Command id \"{}\" does not contain subcommand with id \"{}\""), this->id, id);
}
ArgumentParser::NamedArg & ArgumentParser::CommandOrdinary::get_named_arg(const std::string & id) const {
if (auto ret = find_arg(named_args, id)) {
return *ret;
}
throw ArgumentParserNotFoundError(
M_("Command id \"{}\" does not contain named argument with id \"{}\""), this->id, id);
}
ArgumentParser::PositionalArg & ArgumentParser::CommandOrdinary::get_positional_arg(const std::string & id) const {
if (auto ret = find_arg(pos_args, id)) {
return *ret;
}
throw ArgumentParserNotFoundError(
M_("Command id \"{}\" does not contain positional argument with id \"{}\""), this->id, id);
}
ArgumentParser::Group & ArgumentParser::CommandOrdinary::get_group(const std::string & id) const {
if (auto ret = find_arg(groups, id)) {
return *ret;
}
throw ArgumentParserNotFoundError(M_("Command id \"{}\" does not contain group with id \"{}\""), this->id, id);
}
void ArgumentParser::CommandOrdinary::set_parse_hook_func(ParseHookFunc && func) {
parse_hook = std::move(func);
}
const ArgumentParser::Command::ParseHookFunc & ArgumentParser::CommandOrdinary::get_parse_hook_func() const noexcept {
return parse_hook;
}
void ArgumentParser::CommandOrdinary::parse(const char * option, int argc, const char * const argv[]) {
std::vector<NamedArg *> extended_named_args;
bool inherit_named_args_from_parent = owner.p_impl->inherit_named_args && parent;
if (inherit_named_args_from_parent) {
auto named_args_count = named_args.size();
for (auto previous = parent; previous; previous = previous->parent) {
named_args_count += previous->get_named_args().size();
}
extended_named_args.reserve(named_args_count);
extended_named_args.insert(extended_named_args.end(), named_args.begin(), named_args.end());
for (auto previous = parent; previous; previous = previous->parent) {
auto & prev_named_args = previous->get_named_args();
extended_named_args.insert(extended_named_args.end(), prev_named_args.begin(), prev_named_args.end());
}
}
size_t used_positional_arguments = 0;
int short_option_idx = 0;
for (int i = 1; i < argc;) {
char unused_short_option = 0;
if (owner.p_impl->complete_arg_ptr) {
if (argv + i > owner.p_impl->complete_arg_ptr) {
return;
} else if (argv + i == owner.p_impl->complete_arg_ptr) {
print_complete(
argv[i],
inherit_named_args_from_parent ? extended_named_args : named_args,
used_positional_arguments);
return;
}
}
bool used = false;
const auto * tmp = argv[i];
if (*tmp == '-') {
bool long_option = *++tmp == '-';
if (long_option) {
++tmp;
}
const auto * assign_ptr = strchr(tmp, '=');
for (auto * opt : (inherit_named_args_from_parent ? extended_named_args : named_args)) {
if (long_option) {
if (!opt->get_long_name().empty() &&
(assign_ptr ? std::string(tmp).compare(
0, static_cast<size_t>(assign_ptr - tmp), opt->get_long_name()) == 0
: opt->get_long_name() == tmp)) {
i += opt->parse_long(tmp, argc - i, &argv[i]);
used = true;
break;
}
} else {
if (opt->get_short_name() != '\0' && opt->get_short_name() == tmp[short_option_idx]) {
auto used_args = opt->parse_short(tmp + short_option_idx, argc - i, &argv[i]);
if (used_args > 0) {
i += used_args;
short_option_idx = 0;
} else {
++short_option_idx;
}
used = true;
break;
}
}
}
if (!used && !long_option) {
unused_short_option = tmp[short_option_idx];
}
}
if (!used) {
for (auto & cmd : cmds) {
if (cmd->id == argv[i]) {
if (const auto * arg = get_conflict_argument()) {
auto [fmt_message, conflict_option] = get_conflict_arg_msg(arg);
throw ArgumentParserConflictingArgumentsError(
fmt_message, std::string(option), conflict_option);
}
// the last subcommand wins
owner.p_impl->selected_command = cmd;
cmd->parse(argv[i], argc - i, &argv[i]);
i = argc;
used = true;
// The subcommand processed the completion of the argument. There is no need to continue parsing.
if (owner.p_impl->complete_arg_ptr) {
return;
}
break;
}
}
}
if (!used && *argv[i] != '-' && used_positional_arguments < pos_args.size()) {
auto * pos_arg = pos_args[used_positional_arguments];
i += pos_arg->parse(argv[i], argc - i, &argv[i]);
auto nrepeats = pos_arg->get_nrepeats();
if ((nrepeats > 0 && pos_arg->parse_count >= nrepeats) || nrepeats == PositionalArg::OPTIONAL) {
++used_positional_arguments;
}
used = true;
}
if (!used) {
std::string unknown_argument;
if (unused_short_option) {
unknown_argument = std::string("-") + std::string(1, unused_short_option);
} else {
unknown_argument = std::string(argv[i]);
}
throw ArgumentParserUnknownArgumentError(
std::string(id),
unknown_argument,
M_("Unknown argument \"{}\" for command \"{}\""),
unknown_argument,
id);
}
}
++parse_count;
// Test that all required positional arguments are present.
for (const auto * pos_arg : pos_args) {
const auto nrepeats = pos_arg->get_nrepeats();
if (nrepeats > 0 || nrepeats == PositionalArg::AT_LEAST_ONE) {
const auto nvals = pos_arg->get_nvals();
if (pos_arg->get_parse_count() == 0 && nvals != PositionalArg::UNLIMITED &&
nvals != PositionalArg::OPTIONAL) {
throw ArgumentParserMissingPositionalArgumentError(
M_("Missing positional argument \"{}\" for command \"{}\""), pos_arg->get_id(), id);
}
}
}
if (parse_hook) {
parse_hook(this, option, argc, argv);
}
}
ArgumentParser::CommandOrdinary::CommandOrdinary(ArgumentParser & owner, const std::string & id) : Command(owner, id) {}
// =============== ArgumentParser::CommandAlias methods ===============
ArgumentParser::CommandAlias::~CommandAlias() = default;
void ArgumentParser::CommandAlias::register_command(Command * cmd) {
attached_command.register_command(cmd);
}
void ArgumentParser::CommandAlias::register_named_arg(NamedArg * arg) {
attached_command.register_named_arg(arg);
}
void ArgumentParser::CommandAlias::register_positional_arg(PositionalArg * arg) {
attached_command.register_positional_arg(arg);
}
void ArgumentParser::CommandAlias::register_group(Group * grp) {
attached_command.register_group(grp);
}
std::vector<std::string> ArgumentParser::CommandAlias::get_invocation() const noexcept {
return attached_command.get_invocation();
}
const std::vector<ArgumentParser::Command *> & ArgumentParser::CommandAlias::get_commands() const noexcept {
return attached_command.get_commands();
}
const std::vector<ArgumentParser::NamedArg *> & ArgumentParser::CommandAlias::get_named_args() const noexcept {
return attached_command.get_named_args();
}
const std::vector<ArgumentParser::PositionalArg *> & ArgumentParser::CommandAlias::get_positional_args()
const noexcept {
return attached_command.get_positional_args();
}
const std::vector<ArgumentParser::Group *> & ArgumentParser::CommandAlias::get_groups() const noexcept {
return attached_command.get_groups();
}
ArgumentParser::Command & ArgumentParser::CommandAlias::get_command(const std::string & id) const {
return attached_command.get_command(id);
}
ArgumentParser::NamedArg & ArgumentParser::CommandAlias::get_named_arg(const std::string & id) const {
return attached_command.get_named_arg(id);
}
ArgumentParser::PositionalArg & ArgumentParser::CommandAlias::get_positional_arg(const std::string & id) const {
return attached_command.get_positional_arg(id);
}
ArgumentParser::Group & ArgumentParser::CommandAlias::get_group(const std::string & id) const {
return attached_command.get_group(id);
}
void ArgumentParser::CommandAlias::set_parse_hook_func(ParseHookFunc && func) {
attached_command.set_parse_hook_func(std::move(func));
}
const ArgumentParser::Command::ParseHookFunc & ArgumentParser::CommandAlias::get_parse_hook_func() const noexcept {
return attached_command.get_parse_hook_func();
}
void ArgumentParser::CommandAlias::parse(const char * option, int argc, const char * const argv[]) {
const auto number_of_required_values = static_cast<int>(required_values.size());
if (argc <= number_of_required_values) {
throw ArgumentParserNamedArgMissingValueError(
M_("Missing value for command alias \"{}\""), std::string(option));
}
// Invoke the attached named arguments
for (auto & target_named_arg : attached_named_args) {
auto & target_arg = owner.get_named_arg(target_named_arg.id_path, false);
const char * args[2];
int args_count = 1;
std::string value;
if (target_arg.get_has_value()) {
value = format_string(target_named_arg.value, number_of_required_values + 1, argv);
args[args_count++] = value.c_str();
}
args[0] = option;
target_arg.parse_long(option, args_count, args);
}
auto & cmds = attached_command.get_commands();
auto & named_args = attached_command.get_named_args();
auto & pos_args = attached_command.get_positional_args();
std::vector<NamedArg *> extended_named_args;
bool inherit_named_args_from_parent = owner.p_impl->inherit_named_args && parent;
if (inherit_named_args_from_parent) {
auto named_args_count = named_args.size();
for (auto previous = parent; previous; previous = previous->parent) {
named_args_count += previous->get_named_args().size();
}
extended_named_args.reserve(named_args_count);
extended_named_args.insert(extended_named_args.end(), named_args.begin(), named_args.end());
for (auto previous = parent; previous; previous = previous->parent) {
auto & prev_named_args = previous->get_named_args();
extended_named_args.insert(extended_named_args.end(), prev_named_args.begin(), prev_named_args.end());
}
}
size_t used_positional_arguments = 0;
int short_option_idx = 0;
for (int i = 1 + number_of_required_values; i < argc;) {
if (owner.p_impl->complete_arg_ptr) {
if (argv + i > owner.p_impl->complete_arg_ptr) {
return;
} else if (argv + i == owner.p_impl->complete_arg_ptr) {
print_complete(
argv[i],
inherit_named_args_from_parent ? extended_named_args : named_args,
used_positional_arguments);
return;
}
}
bool used = false;
const auto * tmp = argv[i];
if (*tmp == '-') {
bool long_option = *++tmp == '-';
if (long_option) {
++tmp;
}
const auto * assign_ptr = strchr(tmp, '=');
for (auto * opt : (inherit_named_args_from_parent ? extended_named_args : named_args)) {
if (long_option) {
if (!opt->get_long_name().empty() &&
(assign_ptr ? std::string(tmp).compare(
0, static_cast<size_t>(assign_ptr - tmp), opt->get_long_name()) == 0
: opt->get_long_name() == tmp)) {
i += opt->parse_long(tmp, argc - i, &argv[i]);
used = true;
break;
}
} else {
if (opt->get_short_name() != '\0' && opt->get_short_name() == tmp[short_option_idx]) {
auto used_args = opt->parse_short(tmp + short_option_idx, argc - i, &argv[i]);
if (used_args > 0) {
i += used_args;
short_option_idx = 0;
} else {
++short_option_idx;
}
used = true;
break;
}
}
}
}
if (!used) {
for (auto & cmd : cmds) {
if (cmd->id == argv[i]) {
if (const auto * arg = get_conflict_argument()) {
auto [fmt_message, conflict_option] = get_conflict_arg_msg(arg);
throw ArgumentParserConflictingArgumentsError(
fmt_message, std::string(option), conflict_option);
}
// the last subcommand wins
owner.p_impl->selected_command = cmd;
cmd->parse(argv[i], argc - i, &argv[i]);
i = argc;
used = true;
// The subcommand processed the completion of the argument. There is no need to continue parsing.
if (owner.p_impl->complete_arg_ptr) {
return;
}
break;
}
}
}
if (!used && *argv[i] != '-' && used_positional_arguments < pos_args.size()) {
auto * pos_arg = pos_args[used_positional_arguments];
i += pos_arg->parse(argv[i], argc - i, &argv[i]);
auto nrepeats = pos_arg->get_nrepeats();
if ((nrepeats > 0 && pos_arg->parse_count >= nrepeats) || nrepeats == PositionalArg::OPTIONAL) {
++used_positional_arguments;
}
used = true;
}
if (!used) {
throw ArgumentParserUnknownArgumentError(
std::string(id),
std::string(argv[i]),
M_("Unknown argument \"{}\" for command \"{}\""),
std::string(argv[i]),
id);
}
}
++parse_count;
// Test that all required positional arguments are present.
for (const auto * pos_arg : pos_args) {
const auto nrepeats = pos_arg->get_nrepeats();
if (nrepeats > 0 || nrepeats == PositionalArg::AT_LEAST_ONE) {
const auto nvals = pos_arg->get_nvals();
if (pos_arg->get_parse_count() == 0 && nvals != PositionalArg::UNLIMITED &&
nvals != PositionalArg::OPTIONAL) {
throw ArgumentParserMissingPositionalArgumentError(
M_("Missing positional argument \"{}\" for command \"{}\""), pos_arg->get_id(), id);
}
}
}
if (auto & parse_hook = attached_command.get_parse_hook_func()) {
parse_hook(&attached_command, option, argc, argv);
}
}
ArgumentParser::Command & ArgumentParser::CommandAlias::get_attached_command() noexcept {
return attached_command;
}
void ArgumentParser::CommandAlias::attach_named_arg(const std::string & id_path, const std::string & value) {
attached_named_args.push_back({id_path, value});
}
void ArgumentParser::CommandAlias::add_required_value(const std::string & value_help, const std::string & descr) {
required_values.emplace_back(value_help, descr);
}
ArgumentParser::CommandAlias::CommandAlias(ArgumentParser & owner, const std::string & id, Command & attached_command)
: Command(owner, id),
attached_command(attached_command) {}
// =============== ArgumentParser methods ===============
ArgumentParser::ArgumentParser() : p_impl(new ArgumentParserImpl) {}
ArgumentParser::~ArgumentParser() = default;
ArgumentParser::CommandOrdinary * ArgumentParser::add_new_command(const std::string & id) {
std::unique_ptr<CommandOrdinary> arg(new CommandOrdinary(*this, id));
auto * ptr = arg.get();
p_impl->cmds.push_back(std::move(arg));
return ptr;
}
ArgumentParser::CommandAlias * ArgumentParser::add_new_command_alias(
const std::string & id, Command & attached_command) {
std::unique_ptr<CommandAlias> arg(new CommandAlias(*this, id, attached_command));
auto * ptr = arg.get();
p_impl->cmds.push_back(std::move(arg));
return ptr;
}
ArgumentParser::NamedArg * ArgumentParser::add_new_named_arg(const std::string & id) {
std::unique_ptr<NamedArg> arg(new NamedArg(*this, id));
auto * ptr = arg.get();
p_impl->named_args.push_back(std::move(arg));
return ptr;
}
ArgumentParser::PositionalArg * ArgumentParser::add_new_positional_arg(
const std::string & id, std::vector<std::unique_ptr<libdnf5::Option>> * values) {
std::unique_ptr<PositionalArg> arg(new PositionalArg(*this, id, values));
auto * ptr = arg.get();
p_impl->pos_args.push_back(std::move(arg));
return ptr;
}
ArgumentParser::PositionalArg * ArgumentParser::add_new_positional_arg(
const std::string & id,
int nargs,
libdnf5::Option * init_value,
std::vector<std::unique_ptr<libdnf5::Option>> * values) {
std::unique_ptr<PositionalArg> arg(new PositionalArg(*this, id, nargs, init_value, values));
auto * ptr = arg.get();
p_impl->pos_args.push_back(std::move(arg));
return ptr;
}
ArgumentParser::Group * ArgumentParser::add_new_group(const std::string & id) {
std::unique_ptr<Group> group(new Group(id));
auto * ptr = group.get();
p_impl->groups.push_back(std::move(group));
return ptr;
}
std::vector<ArgumentParser::Argument *> * ArgumentParser::add_conflict_args_group(
std::unique_ptr<std::vector<Argument *>> && conflict_args_group) {
auto * ptr = conflict_args_group.get();
p_impl->conflict_args_groups.push_back(std::move(conflict_args_group));
return ptr;
}
libdnf5::Option * ArgumentParser::add_init_value(std::unique_ptr<libdnf5::Option> && src) {
auto * ptr = src.get();
p_impl->values_init.push_back(std::move(src));
return ptr;
}
std::vector<std::unique_ptr<libdnf5::Option>> * ArgumentParser::add_new_values() {
std::unique_ptr<std::vector<std::unique_ptr<libdnf5::Option>>> tmp(
new std::vector<std::unique_ptr<libdnf5::Option>>);
auto * ptr = tmp.get();
p_impl->values.push_back(std::move(tmp));
return ptr;
}
std::vector<std::unique_ptr<libdnf5::Option>> * ArgumentParser::add_values(
std::unique_ptr<std::vector<std::unique_ptr<libdnf5::Option>>> && values) {
auto * ptr = values.get();
p_impl->values.push_back(std::move(values));
return ptr;
}
void ArgumentParser::set_root_command(Command * command) noexcept {
p_impl->root_command = command;
}
ArgumentParser::Command * ArgumentParser::get_root_command() noexcept {
return p_impl->root_command;
}
ArgumentParser::Command * ArgumentParser::get_selected_command() noexcept {
return p_impl->selected_command;
}
void ArgumentParser::parse(int argc, const char * const argv[]) {
p_impl->assert_root_command();
// mark root command as selected; overwrite with a subcommand in Command::parse()
p_impl->selected_command = p_impl->root_command;
p_impl->root_command->parse(argv[0], argc, argv);
}
void ArgumentParser::reset_parse_count() {
for (auto & i : p_impl->pos_args) {
i->reset_parse_count();
}
for (auto & i : p_impl->named_args) {
i->reset_parse_count();
}
for (auto & i : p_impl->cmds) {
i->reset_parse_count();
}
}
void ArgumentParser::set_inherit_named_args(bool enable) noexcept {
p_impl->inherit_named_args = enable;
}
bool ArgumentParser::get_inherit_named_args() const noexcept {
return p_impl->inherit_named_args;
}
ArgumentParser::Command & ArgumentParser::get_command(const std::string & id_path) {
p_impl->assert_root_command();
auto * cmd = p_impl->root_command;
if (id_path.empty()) {
return *cmd;
}
std::string::size_type start_pos = 0;
auto dot_pos = id_path.find('.');
while (dot_pos != id_path.npos) {
cmd = &cmd->get_command(std::string(id_path, start_pos, dot_pos - start_pos));
start_pos = dot_pos + 1;
dot_pos = id_path.find('.', start_pos);
}
cmd = &cmd->get_command(std::string(id_path, start_pos));
return *cmd;
}
template <class Arg>
static const std::vector<Arg *> & get_command_args(ArgumentParser::Command & command) {
if constexpr (std::is_same<Arg, ArgumentParser::NamedArg>::value) {
return command.get_named_args();
}
if constexpr (std::is_same<Arg, ArgumentParser::PositionalArg>::value) {
return command.get_positional_args();
}
}
template <class Arg>
static Arg * get_arg(ArgumentParser::Command * root_command, const std::string & id_path, bool search_in_parent) {
auto * cmd = root_command;
std::string::size_type start_pos = 0;
auto dot_pos = id_path.find('.');
auto arg_id_name = dot_pos == id_path.npos ? id_path : std::string(id_path, id_path.rfind('.') + 1);
Arg * ret = nullptr;
while (dot_pos != id_path.npos) {
if (search_in_parent) {
if (auto tmp = find_arg(get_command_args<Arg>(*cmd), arg_id_name)) {
ret = tmp;
}
}
cmd = &cmd->get_command(std::string(id_path, start_pos, dot_pos - start_pos));
start_pos = dot_pos + 1;
dot_pos = id_path.find('.', start_pos);
}
if (auto tmp = find_arg(get_command_args<Arg>(*cmd), arg_id_name)) {
ret = tmp;
}
return ret;
}
ArgumentParser::NamedArg & ArgumentParser::get_named_arg(const std::string & id_path, bool search_in_parent) {
p_impl->assert_root_command();
if (auto ret = get_arg<ArgumentParser::NamedArg>(p_impl->root_command, id_path, search_in_parent)) {
return *ret;
}
throw ArgumentParserNotFoundError(M_("Named argument with path id \"{}\" not found"), id_path);
}
ArgumentParser::PositionalArg & ArgumentParser::get_positional_arg(const std::string & id_path, bool search_in_parent) {
p_impl->assert_root_command();
if (auto ret = get_arg<ArgumentParser::PositionalArg>(p_impl->root_command, id_path, search_in_parent)) {
return *ret;
}
throw ArgumentParserNotFoundError(M_("Positional argument with path id \"{}\" not found"), id_path);
}
const std::vector<std::unique_ptr<ArgumentParser::Command>> & ArgumentParser::get_commands() const noexcept {
return p_impl->cmds;
}
const std::vector<std::unique_ptr<ArgumentParser::NamedArg>> & ArgumentParser::get_named_args() const noexcept {
return p_impl->named_args;
}
const std::vector<std::unique_ptr<ArgumentParser::PositionalArg>> & ArgumentParser::get_positional_args()
const noexcept {
return p_impl->pos_args;
}
void ArgumentParser::complete(int argc, const char * const argv[], int complete_arg_idx) {
if (complete_arg_idx < 1 || complete_arg_idx >= argc) {
return;
}
p_impl->complete_arg_ptr = argv + complete_arg_idx;
try {
parse(argc, argv);
} catch (...) {
}
}
void ArgumentParser::set_complete_add_description(bool enable) noexcept {
p_impl->complete_add_description = enable;
}
bool ArgumentParser::get_complete_add_description() noexcept {
return p_impl->complete_add_description;
}
} // namespace libdnf5::cli
|