From 0c7eb0fe0c62b21006324628dbde711ddfd3d25e Mon Sep 17 00:00:00 2001 From: Glen Whitney Date: Wed, 28 Dec 2022 12:12:45 -0500 Subject: [PATCH] WIP: parse command line --- cpm/cxx/cpm.cxx | 48 +++++++++++++++++++++++++++++++++++++----------- 1 file changed, 37 insertions(+), 11 deletions(-) diff --git a/cpm/cxx/cpm.cxx b/cpm/cxx/cpm.cxx index 086aaa1..263af99 100644 --- a/cpm/cxx/cpm.cxx +++ b/cpm/cxx/cpm.cxx @@ -1,14 +1,40 @@ +#include +#include #include -int main (int argc, char* argv[]) -{ - using namespace std; - - if (argc < 2) - { - cerr << "error: missing name" << endl; - return 1; - } - - cout << "Hello, " << argv[1] << '!' << endl; +// From https://stackoverflow.com/questions/865668 +bool cmdOptionExists(char** begin, char** end, const std::string& option) { + return std::find(begin, end, option) != end; +} + +int main (int argc, char* argv[]) { + const std::string stdflag = "-"; + std::string infile = stdflag; + std::string outfile = ""; + bool showHelp = false; + + if (cmdOptionExists(argv, argv+argc, "-h")) showHelp = true; + else if (cmdOptionExists(argv, argv+argc, "--help")) showHelp = true; + else switch (argc) { + case 3: outfile = argv[2]; /* DROP */ + case 2: infile = argv[1]; /* DROP */ + case 1: break; + default: showHelp = true; + } + if (showHelp) { + std::cerr << R"( +Usage: cpm [infile [outfile]] + If infile is not specified or is '-', stdin is used. + If outfile is '-' or unspecified and infile is stdin, stdout is used. + Otherwise if outfile is unspecified, the name of the infile with its + final '.' extension (if any) removed and '.cxx' added is used. +)"; + return 1; + } + if (outfile.length() == 0) { + if (infile == stdflag) outfile = stdflag; + else outfile = infile.substr(0, infile.rfind('.')) + ".cxx"; + } + + std::cout << std::format("Transforming from {} to {}.\n", infile, outfile); }