error.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. /*
  2. * libdpkg - Debian packaging suite library routines
  3. * error.c - error message reporting
  4. *
  5. * Copyright © 2011-2015 Guillem Jover <guillem@debian.org>
  6. *
  7. * This is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  19. */
  20. #include <config.h>
  21. #include <compat.h>
  22. #include <errno.h>
  23. #include <string.h>
  24. #include <stdlib.h>
  25. #include <dpkg/dpkg.h>
  26. #include <dpkg/varbuf.h>
  27. #include <dpkg/error.h>
  28. static void DPKG_ATTR_VPRINTF(3)
  29. dpkg_error_set(struct dpkg_error *err, int type, const char *fmt, va_list args)
  30. {
  31. struct varbuf str = VARBUF_INIT;
  32. if (err == NULL)
  33. return;
  34. err->type = type;
  35. varbuf_vprintf(&str, fmt, args);
  36. err->str = str.buf;
  37. }
  38. int
  39. dpkg_put_warn(struct dpkg_error *err, const char *fmt, ...)
  40. {
  41. va_list args;
  42. va_start(args, fmt);
  43. dpkg_error_set(err, DPKG_MSG_WARN, fmt, args);
  44. va_end(args);
  45. return -1;
  46. }
  47. int
  48. dpkg_put_error(struct dpkg_error *err, const char *fmt, ...)
  49. {
  50. va_list args;
  51. va_start(args, fmt);
  52. dpkg_error_set(err, DPKG_MSG_ERROR, fmt, args);
  53. va_end(args);
  54. return -1;
  55. }
  56. int
  57. dpkg_put_errno(struct dpkg_error *err, const char *fmt, ...)
  58. {
  59. va_list args;
  60. char *new_fmt;
  61. m_asprintf(&new_fmt, "%s (%s)", fmt, strerror(errno));
  62. va_start(args, fmt);
  63. dpkg_error_set(err, DPKG_MSG_ERROR, new_fmt, args);
  64. va_end(args);
  65. free(new_fmt);
  66. return -1;
  67. }
  68. void
  69. dpkg_error_print(struct dpkg_error *err, const char *fmt, ...)
  70. {
  71. va_list args;
  72. char *str;
  73. va_start(args, fmt);
  74. m_vasprintf(&str, fmt, args);
  75. va_end(args);
  76. if (err->type == DPKG_MSG_WARN)
  77. warning("%s: %s", str, err->str);
  78. else
  79. ohshit("%s: %s", str, err->str);
  80. free(str);
  81. }
  82. void
  83. dpkg_error_destroy(struct dpkg_error *err)
  84. {
  85. err->type = DPKG_MSG_NONE;
  86. free(err->str);
  87. err->str = NULL;
  88. }