Blob


1 /*
2 * Copyright (c) 2021 Omar Polo <op@omarpolo.com>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 /*
18 * A streaming text/x-patch parser
19 */
21 #include "compat.h"
23 #include <stdlib.h>
24 #include <string.h>
26 #include "parser.h"
27 #include "telescope.h"
28 #include "utils.h"
29 #include "xwrapper.h"
31 static int tpatch_emit_line(struct buffer *, const char *, size_t);
32 static int tpatch_parse_line(struct buffer *, const char *, size_t);
34 const struct parser textpatch_parser = {
35 .name = "text/x-patch",
36 .parseline = &tpatch_parse_line,
37 .initflags = PARSER_IN_PATCH_HDR,
38 };
40 static int
41 tpatch_emit_line(struct buffer *b, const char *line, size_t linelen)
42 {
43 struct line *l;
45 l = xcalloc(1, sizeof(*l));
47 if (b->parser_flags & PARSER_IN_PATCH_HDR)
48 l->type = LINE_PATCH_HDR;
49 else
50 l->type = LINE_PATCH;
52 if (linelen != 0) {
53 l->line = xcalloc(1, linelen + 1);
55 memcpy(l->line, line, linelen);
57 if (!(b->parser_flags & PARSER_IN_PATCH_HDR))
58 switch (*l->line) {
59 case '+':
60 l->type = LINE_PATCH_ADD;
61 break;
62 case '-':
63 l->type = LINE_PATCH_DEL;
64 break;
65 case '@':
66 l->type = LINE_PATCH_HUNK_HDR;
67 break;
68 case ' ':
69 /* context lines */
70 break;
71 default:
72 /*
73 * A single patch file can have more
74 * than one "header" if touches more
75 * than one file.
76 */
77 l->type = LINE_PATCH_HDR;
78 b->parser_flags |= PARSER_IN_PATCH_HDR;
79 break;
80 }
82 if (!strncmp(l->line, "+++", 3))
83 b->parser_flags &= ~PARSER_IN_PATCH_HDR;
84 }
86 TAILQ_INSERT_TAIL(&b->head, l, lines);
88 return 1;
89 }
91 static int
92 tpatch_parse_line(struct buffer *b, const char *line, size_t linelen)
93 {
94 return tpatch_emit_line(b, line, linelen);
95 }