Blob


1 /* Common parts for printing diff output */
2 /*
3 * Copyright (c) 2020 Neels Hofmeyr <neels@hofmeyr.de>
4 *
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
8 *
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 */
18 #include <unistd.h>
20 #include <diff/diff_output.h>
22 static char
23 get_atom_byte(struct diff_atom *atom, off_t off)
24 {
25 char ch;
26 off_t cur;
28 if (atom->at != NULL)
29 return atom->at[off];
31 cur = lseek(atom->d->root->fd, 0, SEEK_CUR);
32 if (cur == -1)
33 abort(); /* XXX cannot return error */
35 if (cur != atom->pos + off &&
36 lseek(atom->d->root->fd, atom->pos + off, SEEK_SET) == -1)
37 abort(); /* XXX cannot return error */
39 if (read(atom->d->root->fd, &ch, sizeof(ch)) == -1)
40 abort(); /* XXX cannot return error */
42 return ch;
43 }
45 void
46 diff_output_lines(FILE *dest, const char *prefix, struct diff_atom *start_atom,
47 unsigned int count)
48 {
49 struct diff_atom *atom;
50 foreach_diff_atom(atom, start_atom, count) {
51 fprintf(dest, "%s", prefix);
52 int i;
53 unsigned int len = atom->len;
54 if (len) {
55 char ch;
56 ch = get_atom_byte(atom, len - 1);
57 if (ch == '\n')
58 len--;
59 if (len) {
60 ch = get_atom_byte(atom, len - 1);
61 if (ch == '\r')
62 len--;
63 }
64 }
66 for (i = 0; i < len; i++) {
67 char c = get_atom_byte(atom, i);
68 if ((c < 0x20 || c >= 0x7f) && c != '\t')
69 fprintf(dest, "\\x%02x", (unsigned char)c);
70 else
71 fprintf(dest, "%c", c);
72 }
73 fprintf(dest, "\n");
74 }
75 }