* @brief Parses command-line arguments and executes the corresponding command or options. * * @param parser A pointer to the `CliParser` instance. Must not be NULL. * @param argc The argument count from `main`. * @param argv The argument vector from `main`. * * @return `CliStatusCode` indicating the result of parsing: * - `CLI_SUCCESS` on success. * - `CLI_ERROR_INVALID_ARG
| 761 | * - `CLI_ERROR_COMMAND_NOT_FOUND` for unrecognized commands. |
| 762 | */ |
| 763 | CliStatusCode cli_parse_args(CliParser *parser, int argc, char *argv[]) { |
| 764 | if (!parser || argc < 1 || !argv) { |
| 765 | CLI_LOG("[cli_parse_args] Error: Invalid parser or arguments.\n"); |
| 766 | return CLI_ERROR_INVALID_ARGUMENT; |
| 767 | } |
| 768 | |
| 769 | CLI_LOG("[cli_parse_args] Debug: Starting argument parsing.\n"); |
| 770 | |
| 771 | if (parser->preExecutionHook) { |
| 772 | parser->preExecutionHook(parser, parser->preExecutionHookUserData); |
| 773 | } |
| 774 | |
| 775 | CliStatusCode rc = CLI_SUCCESS; |
| 776 | |
| 777 | if(argc == 1) { |
| 778 | CLI_LOG("[cli_parse_args] Debug: in argc\n"); |
| 779 | const CliCommand *command = cli_find_command(parser, argv[0]); |
| 780 | if (command) { |
| 781 | command->handler(command, argc, argv, command->userData); |
| 782 | rc = CLI_SUCCESS; |
| 783 | goto done; |
| 784 | } |
| 785 | } |
| 786 | |
| 787 | for (int i = 1; i < argc; ++i) { |
| 788 | if (argv[i][0] == '-') { |
| 789 | bool optionProcessed = false; |
| 790 | |
| 791 | for (size_t j = 0; j < parser->numOptions; ++j) { |
| 792 | CliOption *option = &parser->options[j]; |
| 793 | |
| 794 | /* Match long option. */ |
| 795 | if (option->longOpt && strcmp(argv[i], option->longOpt) == 0) { |
| 796 | CLI_LOG("[cli_parse_args] Debug: Matched long option '%s'.\n", argv[i]); |
| 797 | const char *value = NULL; |
| 798 | if (option->optionType != CLI_NO_ARG && i + 1 < argc) { |
| 799 | value = argv[++i]; |
| 800 | } |
| 801 | if (option->handler) { |
| 802 | option->handler(option, value, option->userData); |
| 803 | } |
| 804 | optionProcessed = true; |
| 805 | break; |
| 806 | } |
| 807 | |
| 808 | /* Match short option. */ |
| 809 | if (option->shortOpt && argv[i][1] == option->shortOpt && argv[i][2] == '\0') { |
| 810 | CLI_LOG("[cli_parse_args] Debug: Matched short option '-%c'.\n", option->shortOpt); |
| 811 | const char *value = NULL; |
| 812 | if (option->optionType != CLI_NO_ARG && i + 1 < argc) { |
| 813 | value = argv[++i]; |
| 814 | } |
| 815 | if (option->handler) { |
| 816 | option->handler(option, value, option->userData); |
| 817 | } |
| 818 | optionProcessed = true; |
| 819 | break; |
| 820 | } |
no test coverage detected