support_run_diff.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /* Invoke the system diff tool to compare two strings.
  2. Copyright (C) 2016-2019 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; if not, see
  14. <http://www.gnu.org/licenses/>. */
  15. #include <support/run_diff.h>
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. #include <string.h>
  19. #include <support/check.h>
  20. #include <support/support.h>
  21. #include <support/temp_file.h>
  22. #include <support/xunistd.h>
  23. #include <sys/wait.h>
  24. static char *
  25. write_to_temp_file (const char *prefix, const char *str)
  26. {
  27. char *template = xasprintf ("run_diff-%s", prefix);
  28. char *name = NULL;
  29. int fd = create_temp_file (template, &name);
  30. TEST_VERIFY_EXIT (fd >= 0);
  31. free (template);
  32. xwrite (fd, str, strlen (str));
  33. xclose (fd);
  34. return name;
  35. }
  36. void
  37. support_run_diff (const char *left_label, const char *left,
  38. const char *right_label, const char *right)
  39. {
  40. /* Ensure that the diff command output is ordered properly with
  41. standard output. */
  42. TEST_VERIFY_EXIT (fflush (stdout) == 0);
  43. char *left_path = write_to_temp_file ("left-diff", left);
  44. char *right_path = write_to_temp_file ("right-diff", right);
  45. pid_t pid = xfork ();
  46. if (pid == 0)
  47. {
  48. execlp ("diff", "diff", "-u",
  49. "--label", left_label, "--label", right_label,
  50. "--", left_path, right_path,
  51. NULL);
  52. _exit (17);
  53. }
  54. else
  55. {
  56. int status;
  57. xwaitpid (pid, &status, 0);
  58. if (!WIFEXITED (status) || WEXITSTATUS (status) != 1)
  59. printf ("warning: could not run diff, exit status: %d\n"
  60. "*** %s ***\n%s\n"
  61. "*** %s ***\n%s\n",
  62. status, left_label, left, right_label, right);
  63. }
  64. free (right_path);
  65. free (left_path);
  66. }