first commit

This commit is contained in:
Bob Polis
2021-11-05 16:47:27 +01:00
commit 91e1cca43e
6 changed files with 295 additions and 0 deletions

106
src/main.cpp Normal file
View File

@ -0,0 +1,106 @@
//
// main.cpp
// pw
//
// Created by Bob Polis at 2021-11-05
// Copyright (c) 2021 SwiftCoder. All rights reserved.
//
#include <iostream>
#include <cstdlib>
#include <string>
#include <stdexcept>
#include <getopt.h>
#include <libscnumerics.hpp>
void print_help() {
std::cout << "usage: pw [-h|--version]\n";
std::cout << " -h, --help show this help text and exit\n";
std::cout << " --version show version number and exit\n";
}
void print_version() {
std::cout << "pw version 1.0\n";
}
int main(int argc, char* argv[]) {
try {
std::string upper {"ABCDEFGHIJKLMNOPQRSTUVWXYZ"};
std::string lower {"abcdefghijklmnopqrstuvwxyz"};
std::string digits {"0123456789"};
std::string symbols {"_-=+<>,.!@#$%^&*"};
std::string valid;
int len {12};
bool noflags {true};
int opt_char, opt_val;
struct option long_options[] = {
{"help", no_argument, nullptr, 'h'},
{"version", no_argument, &opt_val, 1},
{"upper", no_argument, nullptr, 'u'},
{"lower", no_argument, nullptr, 'l'},
{"digit", no_argument, nullptr, 'd'},
{"symbol", no_argument, nullptr, 's'},
{"count", required_argument, nullptr, 'c'},
{nullptr, 0, nullptr, 0}
};
while ((opt_char = getopt_long(argc, argv, "c:hulds", long_options, nullptr)) != -1) {
std::string arg {optarg ? optarg : ""};
switch (opt_char) {
case 0: {
// handle long-only options here
switch (opt_val) {
case 1:
print_version();
return EXIT_SUCCESS;
}
break;
}
case 'h':
print_help();
return EXIT_SUCCESS;
case 'u':
noflags = false;
valid += upper;
break;
case 'l':
noflags = false;
valid += lower;
break;
case 'd':
noflags = false;
valid += digits;
break;
case 's':
noflags = false;
valid += symbols;
break;
case 'c':
len = std::stoi(optarg);
break;
case '?':
throw std::runtime_error("unrecognized option");
}
}
if (optind == argc) {
// here when no file args
if (noflags) {
valid = upper + lower + digits + symbols;
}
for (int i = 0; i < len; ++i) {
std::cout << sc::random::choice<char>(valid.begin(), valid.end());
}
std::cout << std::endl;
}
for (int i = optind; i < argc; ++i) {
try {
// process file argv[i]
} catch (const std::runtime_error& ex) {
std::cerr << "pw: " << ex.what() << '\n';
}
}
} catch (const std::exception& ex) {
std::cerr << "pw: " << ex.what() << '\n';
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}