color.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * libdpkg - Debian packaging suite library routines
  3. * color.c - color support
  4. *
  5. * Copyright © 2015-2016 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 <http://www.gnu.org/licenses/>.
  19. */
  20. #include <config.h>
  21. #include <compat.h>
  22. #include <stdbool.h>
  23. #include <stdlib.h>
  24. #include <string.h>
  25. #include <unistd.h>
  26. #include <dpkg/macros.h>
  27. #include <dpkg/color.h>
  28. static enum color_mode color_mode = COLOR_MODE_UNKNOWN;
  29. static bool use_color = false;
  30. bool
  31. color_set_mode(const char *mode)
  32. {
  33. if (strcmp(mode, "auto") == 0) {
  34. color_mode = COLOR_MODE_AUTO;
  35. use_color = isatty(STDOUT_FILENO);
  36. } else if (strcmp(mode, "always") == 0) {
  37. color_mode = COLOR_MODE_ALWAYS;
  38. use_color = true;
  39. } else {
  40. color_mode = COLOR_MODE_NEVER;
  41. use_color = false;
  42. }
  43. return use_color;
  44. }
  45. static bool
  46. color_enabled(void)
  47. {
  48. const char *mode;
  49. if (color_mode != COLOR_MODE_UNKNOWN)
  50. return use_color;
  51. mode = getenv("DPKG_COLORS");
  52. if (mode == NULL)
  53. mode = "never";
  54. return color_set_mode(mode);
  55. }
  56. const char *
  57. color_get(const char *color)
  58. {
  59. if (!color_enabled())
  60. return "";
  61. return color;
  62. }