inLimbo
TUI Music Player that keeps you in Limbo.
 
Loading...
Searching...
No Matches
cmd-line-args.hpp
Go to the documentation of this file.
1#ifndef COMMAND_LINE_ARGS_HPP
2#define COMMAND_LINE_ARGS_HPP
3
4#include <iostream>
5#include <map>
6#include <string>
7#include <vector>
8#include <stdexcept>
9
11{
12private:
13 std::map<std::string, std::string> args; // flag-value pairs
14 std::vector<std::string> positionalArgs; // pos args
15 std::vector<std::string> validFlags; // Valid flags for error checking
16
17public:
18 CommandLineArgs(int argc, char* argv[], const std::vector<std::string>& allowedFlags = {})
19 : validFlags(allowedFlags)
20 {
21 parseArgs(argc, argv);
22 }
23
24 std::string get(const std::string& flag, const std::string& defaultValue = "") const
25 {
26 auto it = args.find(flag);
27 if (it != args.end())
28 {
29 return it->second;
30 }
31 return defaultValue;
32 }
33
34 bool hasFlag(const std::string& flag) const
35 {
36 return args.find(flag) != args.end();
37 }
38
39 const std::vector<std::string>& getPositionalArgs() const
40 {
41 return positionalArgs;
42 }
43
44 void printUsage(const std::string& programName) const
45 {
46 std::cerr << "Usage: " << programName << " [options] [positional arguments]\n";
47 if (!validFlags.empty())
48 {
49 std::cerr << "Valid options:\n";
50 for (const auto& flag : validFlags)
51 {
52 std::cerr << " " << flag << "\n";
53 }
54 }
55 }
56
57private:
58 void parseArgs(int argc, char* argv[])
59 {
60 for (int i = 1; i < argc; ++i) // Skip argv[0] (program name)
61 {
62 std::string arg = argv[i];
63
64 if (arg[0] == '-') // It's a flag
65 {
66 std::string flag = arg;
67 std::string value;
68
69 // Check if the flag has a value
70 if (i + 1 < argc && argv[i + 1][0] != '-')
71 {
72 value = argv[++i]; // Consume the next argument as the value
73 }
74
75 // Validate the flag if a list of valid flags is provided
76 if (!validFlags.empty() && std::find(validFlags.begin(), validFlags.end(), flag) == validFlags.end())
77 {
78 throw std::invalid_argument("Invalid flag: " + flag);
79 }
80
81 args[flag] = value;
82 }
83 else // It's a positional argument
84 {
85 positionalArgs.push_back(arg);
86 }
87 }
88 }
89};
90
91#endif // COMMAND_LINE_ARGS_HPP
void printUsage(const std::string &programName) const
Definition cmd-line-args.hpp:44
bool hasFlag(const std::string &flag) const
Definition cmd-line-args.hpp:34
CommandLineArgs(int argc, char *argv[], const std::vector< std::string > &allowedFlags={})
Definition cmd-line-args.hpp:18
const std::vector< std::string > & getPositionalArgs() const
Definition cmd-line-args.hpp:39
std::string get(const std::string &flag, const std::string &defaultValue="") const
Definition cmd-line-args.hpp:24