void parseCliArguments()

in sonic-db-cli/sonic-db-cli.cpp [183:245]


void parseCliArguments(
    int argc,
    char** argv,
    Options &options)
{
    // Parse argument with getopt https://man7.org/linux/man-pages/man3/getopt.3.html
    const char* short_options = "hsn";
    static struct option long_options[] = {
       {"help",        optional_argument, NULL,  'h' },
       {"unixsocket",  optional_argument, NULL,  's' },
       {"namespace",   optional_argument, NULL,  'n' },
       // The last element of the array has to be filled with zeros.
       {0,          0,       0,  0 }
    };
    
    // prevent getopt_long print "invalid option" message.
    opterr = 0;
    while(optind < argc)
    {
        int opt = getopt_long(argc, argv, short_options, long_options, NULL);
        if (opt != -1)
        {
            switch (opt) {
                case 'h':
                    options.m_help = true;
                    break;

                case 's':
                    options.m_unixsocket = true;
                    break;

                case 'n':
                    if (optind < argc)
                    {
                        options.m_namespace = argv[optind];
                        optind++;
                    }
                    else
                    {
                        throw invalid_argument("namespace value is missing.");
                    }
                    break;

                default:
                   // argv contains unknown argument
                   throw invalid_argument("Unknown argument:" + string(argv[optind]));
            }
        }
        else
        {
            // db_or_op and cmd are non-option arguments
            options.m_db_or_op = argv[optind];
            optind++;

            while(optind < argc)
            {
                auto cmdstr = string(argv[optind]);
                options.m_cmd.push_back(cmdstr);
                optind++;
            }
        }
    }
}