progress.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * libdpkg - Debian packaging suite library routines
  3. * progress.c - generic progress reporting
  4. *
  5. * Copyright © 2009 Romain Francoise <rfrancoise@debian.org>
  6. * Copyright © 2009 Guillem Jover <guillem@debian.org>
  7. *
  8. * This is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 2 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. */
  21. #include <config.h>
  22. #include <compat.h>
  23. #include <unistd.h>
  24. #include <stdio.h>
  25. #include <dpkg/i18n.h>
  26. #include "progress.h"
  27. void
  28. progress_init(struct progress *progress, const char *text, int max)
  29. {
  30. progress->text = text;
  31. progress->max = max;
  32. progress->cur = 0;
  33. progress->last_percent = 0;
  34. progress->on_tty = isatty(1);
  35. if (progress->on_tty)
  36. printf("%s\r", text);
  37. else
  38. printf("%s", text);
  39. }
  40. void
  41. progress_step(struct progress *progress)
  42. {
  43. int cur_percent;
  44. if (!progress->on_tty)
  45. return;
  46. progress->cur++;
  47. cur_percent = (progress->cur * 100) / progress->max;
  48. if (cur_percent <= progress->last_percent)
  49. return;
  50. if (cur_percent % 5)
  51. return;
  52. progress->last_percent = cur_percent;
  53. printf("%s%d%%\r", progress->text, cur_percent);
  54. }
  55. void
  56. progress_done(struct progress *progress)
  57. {
  58. if (progress->on_tty)
  59. printf("%s", progress->text);
  60. }