Define simple configuration on INI files.
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

74 行
1.8 KiB

  1. #include "ini-config.h"
  2. const char* INI_ConfigGetCommandlineOption(uint8_t argc, const char* argv[], const char* val) {
  3. size_t n = strlen(val);
  4. int c = argc;
  5. while (--c > 0) {
  6. if (!strncmp(argv[c], val, n)) {
  7. if (!*(argv[c] + n) && c < argc - 1) {
  8. /* coverity treats unchecked argv as "tainted" */
  9. if (!argv[c + 1] || strlen(argv[c + 1]) > 1024)
  10. return NULL;
  11. return argv[c + 1];
  12. }
  13. if (argv[c][n] == '=')
  14. return &argv[c][n + 1];
  15. return argv[c] + n;
  16. }
  17. }
  18. return NULL;
  19. }
  20. void INI_ConfigLoad(INI_ConfigItem item[], const char* config_path) {
  21. uint8_t i;
  22. for (i = 0; item[i].type.size > 0; i += 1) {
  23. if (!item[i].type.load) {
  24. continue;
  25. }
  26. item[i].type.load(&item[i], config_path, item);
  27. }
  28. }
  29. INI_ConfigSaveResult INI_ConfigSave(INI_ConfigItem item[], const char* config_path) {
  30. uint8_t i;
  31. int32_t problems = 0;
  32. for (i = 0; item[i].type.size > 0; i += 1) {
  33. int32_t result = item[i].type.save ? item[i].type.save(&item[i], config_path, item) : 0;
  34. if (result < 0) {
  35. problems |= (1 << (int32_t) i);
  36. }
  37. }
  38. return -problems;
  39. }
  40. void INI_ConfigOverride(INI_ConfigItem item[], uint8_t argc, const char* argv[]) {
  41. uint8_t i;
  42. for (i = 0; item[i].type.size > 0; i += 1) {
  43. if (!item[i].type.override) {
  44. continue;
  45. }
  46. item[i].type.override(&item[i], argc, argv);
  47. // TODO specify command-line arg external from config item?
  48. }
  49. }
  50. INI_ConfigInitializeResult INI_ConfigInitialize(INI_ConfigItem item[], const char* config_path, uint8_t argc, const char* argv[]) {
  51. INI_ConfigLoad(item, config_path);
  52. INI_ConfigSaveResult save_result = INI_ConfigSave(item, config_path);
  53. if (save_result < 0) {
  54. return INI_CONFIG_INITIALIZE_RESULT_ERROR;
  55. }
  56. INI_ConfigOverride(item, argc, argv);
  57. if (save_result > 0) {
  58. return INI_CONFIG_INITIALIZE_RESULT_WARNING;
  59. }
  60. return INI_CONFIG_INITIALIZE_RESULT_OK;
  61. }