Files
pip/libs/main/application/picli.h

207 lines
10 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! \file picli.h
//! \ingroup Application
//! \brief
//! \~english Command-line argument parser
//! \~russian Парсер аргументов командной строки
//! \details
//! \~english The PICLI class provides convenient parsing of command-line arguments. It supports short keys (e.g., -c), full keys (e.g.,
//! --console), and arguments with/without values.
//! \~russian Класс PICLI предоставляет удобный разбор аргументов командной строки. Поддерживаются короткие ключи (например, -c), полные
//! ключи (например, --console) и аргументы с значениями/без значений.
/*
PIP - Platform Independent Primitives
Command-Line Parser
Ivan Pelipenko peri4ko@yandex.ru
This program 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 3 of the License, or
(at your option) any later version.
This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PICLI_H
#define PICLI_H
#include "piset.h"
#include "pistringlist.h"
//! \~english Command-line argument parser class
//! \~russian Класс парсера аргументов командной строки
class PIP_EXPORT PICLI {
public:
//! \~english Constructs %PICLI from "argc" and "argv" parameters of the main() function
//! \~russian Создает %PICLI из параметров "argc" и "argv" функции main()
PICLI(int argc, char * argv[]);
//! \~english Adds an argument with the specified name, short key (first letter of name) and full key (name)
//! \~russian Добавляет аргумент с указанным именем, коротким ключом (первая буква имени) и полным ключом (имя)
void addArgument(const PIString & name, bool value = false);
//! \~english Adds an argument with the specified name, short key and full key (equal to name)
//! \~russian Добавляет аргумент с указанным именем, коротким ключом и полным ключом (равным имени)
void addArgument(const PIString & name, const PIChar & shortKey, bool value = false);
//! \~english Adds an argument with the specified name, short key and full key (equal to name)
//! \~russian Добавляет аргумент с указанным именем, коротким ключом и полным ключом (равным имени)
void addArgument(const PIString & name, const char * shortKey, bool value = false);
//! \~english Adds an argument with the specified name, short key and full key
//! \~russian Добавляет аргумент с указанным именем, коротким ключом и полным ключом
void addArgument(const PIString & name, const PIChar & shortKey, const PIString & fullKey, bool value = false);
//! \~english Adds an argument with the specified name, short key and full key
//! \~russian Добавляет аргумент с указанным именем, коротким ключом и полным ключом
void addArgument(const PIString & name, const char * shortKey, const PIString & fullKey, bool value = false);
//! \~english Returns the unparsed command-line argument at the specified index (index 0 is the program execution command)
//! \~russian Возвращает неразобранный аргумент командной строки по указанному индексу (индекс 0 - команда выполнения программы)
PIString rawArgument(int index);
//! \~english Returns the mandatory command-line argument at the specified index
//! \~russian Возвращает обязательный аргумент командной строки по указанному индексу
PIString mandatoryArgument(int index);
//! \~english Returns the optional command-line argument at the specified index
//! \~russian Возвращает опциональный аргумент командной строки по указанному индексу
PIString optionalArgument(int index);
//! \~english Returns all unparsed command-line arguments
//! \~russian Возвращает все неразобранные аргументы командной строки
const PIStringList & rawArguments();
//! \~english Returns all mandatory command-line arguments
//! \~russian Возвращает все обязательные аргументы командной строки
const PIStringList & mandatoryArguments();
//! \~english Returns all optional command-line arguments
//! \~russian Возвращает все опциональные аргументы командной строки
const PIStringList & optionalArguments();
//! \~english Returns the program execution command without arguments
//! \~russian Возвращает команду выполнения программы без аргументов
PIString programCommand();
//! \~english Checks if the argument with the specified name was found in command-line
//! \~russian Проверяет, был ли найден аргумент с указанным именем в командной строке
bool hasArgument(const PIString & name);
//! \~english Returns the value of the argument with the specified name, or empty string if no value
//! \~russian Возвращает значение аргумента с указанным именем или пустую строку, если значение отсутствует
PIString argumentValue(const PIString & name);
//! \~english Returns the short key of the argument with the specified name, or empty string if argument not found
//! \~russian Возвращает короткий ключ аргумента с указанным именем или пустую строку, если аргумент не найден
PIString argumentShortKey(const PIString & name);
//! \~english Returns the full key of the argument with the specified name, or empty string if argument not found
//! \~russian Возвращает полный ключ аргумента с указанным именем или пустую строку, если аргумент не найден
PIString argumentFullKey(const PIString & name);
//! \~english Returns short key prefix.
//! \~russian Возвращает префикс короткого ключа.
const PIString & shortKeyPrefix() const { return _prefix_short; }
//! \~english Returns full key prefix.
//! \~russian Возвращает префикс полного ключа.
const PIString & fullKeyPrefix() const { return _prefix_full; }
//! \~english Returns mandatory arguments count.
//! \~russian Возвращает количество обязательных аргументов.
int mandatoryArgumentsCount() const { return _count_mand; }
//! \~english Returns optional arguments count.
//! \~russian Возвращает количество опциональных аргументов.
int optionalArgumentsCount() const { return _count_opt; }
//! \~english Sets short key prefix.
//! \~russian Устанавливает префикс короткого ключа.
void setShortKeyPrefix(const PIString & prefix);
//! \~english Sets full key prefix.
//! \~russian Устанавливает префикс полного ключа.
void setFullKeyPrefix(const PIString & prefix);
//! \~english Sets mandatory arguments count.
//! \~russian Устанавливает количество обязательных аргументов.
void setMandatoryArgumentsCount(const int count);
//! \~english Sets optional arguments count.
//! \~russian Устанавливает количество опциональных аргументов.
void setOptionalArgumentsCount(const int count);
//! \~english Returns the debug mode state
//! \~russian Возвращает состояние режима отладки
bool debug() const { return debug_; }
//! \~english Sets the debug mode state
//! \~russian Устанавливает состояние режима отладки
void setDebug(bool debug) { debug_ = debug; }
//! \~english Returns the class name
//! \~russian Возвращает имя класса
PIConstChars className() const { return "PICLI"; }
//! \~english Returns the object name
//! \~russian Возвращает имя объекта
PIString name() const { return PIStringAscii("CLI"); }
private:
//! \~english Represents a single command-line argument with its properties
//! \~russian Представляет один аргумент командной строки со всеми его свойствами
struct Argument {
//! \~english Argument name
//! \~russian Имя аргумента
PIString name;
//! \~english Short key character
//! \~russian Символ короткого ключа
PIChar short_key;
//! \~english Full key string
//! \~russian Строка полного ключа
PIString full_key;
//! \~english Argument value
//! \~russian Значение аргумента
PIString value;
//! \~english Flag indicating if the argument has a value
//! \~russian Флаг, указывающий, имеет ли аргумент значение
bool has_value = false;
//! \~english Flag indicating if the argument was found in command-line
//! \~russian Флаг, указывающий, был ли аргумент найден в командной строке
bool found = false;
//! \~english Argument constructor
//! \~russian Конструктор аргумента
Argument(const PIString & name, const PIChar & shortKey, const PIString & fullKey, bool hasValue) {
this->name = name;
this->short_key = shortKey;
this->full_key = fullKey;
this->has_value = hasValue;
}
};
void parse();
PIString _prefix_short = "-", _prefix_full = "--";
PIStringList _args_raw, _args_mand, _args_opt;
PISet<PIString> keys_full, keys_short;
PIVector<Argument> _args;
int _count_mand = 0, _count_opt = 0;
bool needParse = true, debug_ = true;
};
#endif // PICLI_H