refactor(cli): improve argument parsing and update special characters
All checks were successful
CMake / build (push) Successful in 42s

- Enhance CLI handling in main.cpp with better error messages, default length as size_t, and proper option validation
- Simplify special characters in passwdgen.cpp to a safer, common subset
This commit is contained in:
Gregory Gauthier 2026-03-06 16:52:59 +00:00
parent 5de5884aef
commit 24adb7d618
2 changed files with 26 additions and 22 deletions

View File

@ -7,38 +7,42 @@
#include <string>
int main(int argc, char *argv[]) {
int passwordLength = 0;
std::string progname(argv[0]);
size_t passwordLength = 32;
bool punc = false;
if (argc < 1) {
std::cout << random_string(32, false) << std::endl;
return 0;
}
for (int i = 1; i < argc; ++i) {
int i = 1;
while (i < argc) {
std::string arg = argv[i];
if ((arg == "-h") || (arg == "--help")) {
show_usage(argv[0]);
if (arg == "-h" || arg == "--help") {
show_usage(progname);
return 0;
}
if (arg == "-p") {
} else if (arg == "-p" || arg == "--punctuation") {
punc = true;
} else if ((arg == "-l") || (arg == "--length")) {
if (not argv[i +1]) {
std::cerr << "Specify a password length" << std::endl;
++i;
} else if (arg == "-l" || arg == "--length") {
if (++i >= argc) {
std::cerr << progname << ": error: option requires an argument -- " << arg << std::endl;
show_usage(progname);
return 1;
}
std::string passwordLengthStr = argv[i + 1];
try {
passwordLength = std::stoi(passwordLengthStr);
} catch ([[maybe_unused]] const std::invalid_argument& e){
std::cerr << "Length must be a valid integer" << std::endl;
int tmp = std::stoi(argv[i]);
if (tmp < 1) {
std::cerr << progname << ": invalid argument '" << argv[i] << "' for option " << arg << ": value too small" << std::endl;
return 1;
}
passwordLength = static_cast<size_t>(tmp);
} catch (const std::exception& e) {
std::cerr << progname << ": invalid argument '" << argv[i] << "' for option " << arg << ": " << e.what() << std::endl;
return 1;
}
++i;
} else {
std::cerr << progname << ": unrecognized option '" << arg << "'" << std::endl;
show_usage(progname);
return 1;
}
if (passwordLength == 0) {
passwordLength = 32;
}
std::string password = random_string(passwordLength, punc);
std::cout << password << std::endl;

View File

@ -6,7 +6,7 @@
std::string random_string(std::size_t length, bool punc) {
std::string CHARACTERS;
std::string ALPHANUM = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
const std::string SPECIALS = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
const std::string SPECIALS = "!@#$%^&*()_+-=[]{}|;:,./?";
if (punc) {
CHARACTERS = ALPHANUM.append(SPECIALS);