将optparse库的API进行了重大改进,包括: - 修改结构体字段为const类型以提高安全性 - 添加了宏定义SCC_OPTPARSE_OPT和SCC_OPTPARSE_OPT_END用于简化选项定义 - 重构了解析逻辑,引入greedy_mode和current状态跟踪 - 改进了短选项和长选项的解析机制 - 添加了参数计数验证功能(min_args/max_args检查) - 调整了函数返回值,parse函数现在返回int类型表示是否还有更多参数 - 完善了错误处理和边界条件检查
54 lines
1.6 KiB
C
54 lines
1.6 KiB
C
#ifndef __SCC_OPTPARSER_H__
|
|
#define __SCC_OPTPARSER_H__
|
|
|
|
typedef struct scc_optparse_opt {
|
|
char prefix;
|
|
char short_name;
|
|
const char *long_name;
|
|
const char *default_value;
|
|
void (*invoke)(void *value);
|
|
int min_args;
|
|
int max_args;
|
|
} scc_optparse_opt_t;
|
|
|
|
#define SCC_OPTPARSE_OPT(prefix, short_name, long_name, min_args, max_args, \
|
|
default_value, invoke) \
|
|
{prefix, short_name, long_name, default_value, invoke, min_args, max_args}
|
|
#define SCC_OPTPARSE_OPT_END() {0}
|
|
|
|
typedef enum scc_optparse_error {
|
|
SCC_OPT_ERROR_NONE,
|
|
SCC_OPT_ERROR_NOT_FOUND_LONG_ARG,
|
|
SCC_OPT_ERROR_NOT_FOUND_SHORT_ARG,
|
|
SCC_OPT_ERROR_NOT_ENOUGH_ARGS,
|
|
SCC_OPT_ERROR_TOO_MANY_ARGS,
|
|
} scc_optparse_error_t;
|
|
|
|
typedef struct scc_optparse_result {
|
|
const scc_optparse_opt_t *opt;
|
|
const char *value;
|
|
int error;
|
|
} scc_optparse_result_t;
|
|
|
|
typedef struct {
|
|
int argc;
|
|
const char **argv;
|
|
const scc_optparse_opt_t *opts;
|
|
int handle_positional;
|
|
int greedy_mode;
|
|
struct {
|
|
const scc_optparse_opt_t *opt;
|
|
int count; // check for min_args <= count <= max_args
|
|
int arg_pos; // for argv pos
|
|
int opt_pos; // for short pos
|
|
} current;
|
|
} scc_optparse_t;
|
|
|
|
void scc_optparse_init(scc_optparse_t *parser, int argc, const char **argv);
|
|
void scc_optparse_drop(scc_optparse_t *parser);
|
|
void scc_optparse_set(scc_optparse_t *parser, const scc_optparse_opt_t *opts);
|
|
void scc_optparse_reset(scc_optparse_t *parser);
|
|
int scc_optparse_parse(scc_optparse_t *parser, scc_optparse_result_t *res);
|
|
|
|
#endif /* __SCC_OPTPARSER_H__ */
|