1 | /* |
2 | * Copyright © 2021 Red Hat, Inc. |
3 | * |
4 | * This 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 | * |
9 | * This library is distributed in the hope that it will be useful, |
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
12 | * Lesser General Public License for more details. |
13 | * |
14 | * You should have received a copy of the GNU Lesser General Public |
15 | * License along with this library. If not, see <http://www.gnu.org/licenses/>. |
16 | * |
17 | * Authors: Matthias Clasen <mclasen@redhat.com> |
18 | */ |
19 | |
20 | #include <glib.h> |
21 | #include <glib/gstdio.h> |
22 | |
23 | #ifdef G_OS_WIN32 |
24 | #include <io.h> |
25 | #else |
26 | #include <unistd.h> |
27 | #endif |
28 | |
29 | #include "testsuite/testutils.h" |
30 | |
31 | char * |
32 | diff_with_file (const char *file1, |
33 | const char *text, |
34 | gssize len, |
35 | GError **error) |
36 | { |
37 | const char *command[] = { "diff" , "-u" , file1, NULL, NULL }; |
38 | char *diff, *tmpfile; |
39 | int fd; |
40 | |
41 | diff = NULL; |
42 | |
43 | if (g_find_program_in_path (program: "diff" )) |
44 | { |
45 | if (len < 0) |
46 | len = strlen (s: text); |
47 | |
48 | /* write the text buffer to a temporary file */ |
49 | fd = g_file_open_tmp (NULL, name_used: &tmpfile, error); |
50 | if (fd < 0) |
51 | return NULL; |
52 | |
53 | if (write (fd: fd, buf: text, n: len) != (int) len) |
54 | { |
55 | close (fd: fd); |
56 | g_set_error (err: error, |
57 | G_FILE_ERROR, code: G_FILE_ERROR_FAILED, |
58 | format: "Could not write data to temporary file '%s'" , tmpfile); |
59 | goto done; |
60 | } |
61 | close (fd: fd); |
62 | command[3] = tmpfile; |
63 | |
64 | /* run diff command */ |
65 | g_spawn_sync (NULL, |
66 | argv: (char **) command, |
67 | NULL, |
68 | flags: G_SPAWN_SEARCH_PATH, |
69 | NULL, NULL, |
70 | standard_output: &diff, |
71 | NULL, NULL, |
72 | error); |
73 | |
74 | done: |
75 | g_unlink (filename: tmpfile); |
76 | g_free (mem: tmpfile); |
77 | } |
78 | else |
79 | { |
80 | char *buf1; |
81 | gsize len1; |
82 | |
83 | if (!g_file_get_contents (filename: file1, contents: &buf1, length: &len1, error)) |
84 | return NULL; |
85 | |
86 | if ((len != -1 && len != len1) || |
87 | strncmp (s1: text, s2: buf1, n: len1) != 0) |
88 | diff = g_strdup (str: "Files differ.\n" ); |
89 | |
90 | g_free (mem: buf1); |
91 | } |
92 | |
93 | return diff; |
94 | } |
95 | |