Как отобразить описание операнда командной строки в выводе —help

Я использую Boost.program_options для разбора командной строки для моей реализации утилит POSIX. В качестве простого примера возьмем cmp.

Теперь я хотел бы иметь дополнительный аргумент --help который показывает описание всех аргументов, что важно в этом случае. Я имею:

po::options_description options("Options");
options.add_options()("help", "Show this help output.")
(",l", "(Lowercase ell.) Write the byte number (decimal) and the differing bytes (octal) for each difference.")
(",s", "Write nothing for differing files; return exit status only.")

po::positional_options_description operands;
operands.add("file1", 1);//, "A pathname of the first file to be compared. If file1 is '-', the standard input shall be used.")
operands.add("file2", 1);//, "A pathname of the second file to be compared. If file2 is '-', the standard input shall be used.");

po::variables_map vm;
po::store(po::command_line_parser(argc, argv).options(options).positional(operands).run(), vm);
po::notify(vm);

if(vm.count("help"))
{
std::cout << "cmp: compare two files\nUsage: cmp [ -l | -s ] file1 file2\n" << options;
return 0;
}

который не может показать file1 а также file2 описание опций. Я могу, конечно, добавить их в options, но это добавило бы как минимум два нежелательных аргумента [-]-file{1,2}чего я действительно не хочу. Я просто хочу этот вывод для --help (без явного его кодирования):

cmp: compare two files
Usage: cmp [ -l | -s ] file1 file2
Options:
--help                Show this help output.
-l                    (Lowercase ell.) Write the byte number (decimal) and the differing bytes (octal) for each difference.
-s                    Write nothing for differing files; return exit status only.
Operands:
file1                 A pathname of the first file to be compared. If file1 is '-', the standard input shall be used.
file2                 A pathname of the second file to be compared. If file2 is '-', the standard input shall be used.

Есть ли способ достичь этого без взлома библиотеки? Я думаю, что это довольно простой материал, но я не могу найти его ни в одном из учебные пособия.

ОБНОВИТЬ Для всеобщего блага я представил запрос функции для этого, надеюсь, обратно совместимым способом.

5

Решение

Это не идеально, но как насчет создания «фиктивного» набора параметров программы, позволяющего форматирующему устройству boost :: program_options отформатировать для вас текст справки, а затем просто удалить штрихи с помощью быстрой замены?

Затем выведите текст справки в дополнение к options текст справки.

Что-то вроде этого:

po::options_description dummy_options("Operands");
dummy_options.add_options()
("file1", po::value<std::string>(), "A pathname of the first file to be compared. If file1 is '-', the standard input shall be used.")
("file2", po::value<std::string>(), "A pathname of the second file to be compared. If file2 is '-', the standard input shall be used.")
;

std::stringstream s;
s << dummy_options;
std::string dummy_help_text = s.str();
boost::replace_all(dummy_help_text, "--", "");
boost::replace_all(dummy_help_text, "arg", "     ");

std::cout << dummy_help_text << std::endl;

Вывод выглядит так:

Operands:
file1                 A pathname of the first file to be compared. If file1
is '-', the standard input shall be used.
file2                 A pathname of the second file to be compared. If file2
is '-', the standard input shall be used.

Это не идеально, потому что, между прочим, интервал между столбцами не будет совпадать с выводом справки от вашего другого options выход. Но для чего-то быстрого и грязного, которое в основном работает, это могло бы быть хорошо.

Во всяком случае, это мысль.

(Я не вижу ничего в API Boost.Program_Options, который бы позволял вам делать это «правильным» способом. https://stackoverflow.com/a/3621947/368896 дает подсказку, что такого рода вещи не поддерживаются, но сейчас 3 года.)

1

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector