2 * wiggle - apply rejected patches
4 * Copyright (C) 2003 Neil Brown <neilb@cse.unsw.edu.au>
5 * Copyright (C) 2013 Neil Brown <neilb@suse.de>
6 * Copyright (C) 2014-2020 Neil Brown <neil@brown.name>
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program.
23 * Email: <neil@brown.name>
29 * Files are read in whole and stored in a
30 * struct stream {char*, len}
33 * loading the file "-" reads from stdin which might require
34 * reading into several buffers
38 #include <sys/types.h>
44 static void join_streams(struct stream list[], int cnt)
46 /* join all the streams in the list (upto body=NULL)
47 * into one by re-allocing list[0].body and copying
53 for (i = 0; i < cnt ; i++)
56 c = realloc(list[0].body, len+1);
58 wiggle_die("memory allocation");
63 for (i = 1; i < cnt; i++) {
64 memcpy(c, list[i].body, list[i].len);
72 static struct stream wiggle_load_regular(int fd)
79 s.body = wiggle_xmalloc(s.len+1);
80 if (read(fd, s.body, s.len) != s.len)
81 wiggle_die("file read");
87 static struct stream wiggle_load_other(int fd)
90 struct stream list[10];
94 list[i].body = wiggle_xmalloc(8192);
95 list[i].len = read(fd, list[i].body, 8192);
97 wiggle_die("file read");
102 join_streams(list, i);
106 join_streams(list, i);
110 struct stream wiggle_load_segment(FILE *f,
111 unsigned int start, unsigned int end)
115 s.body = wiggle_xmalloc(s.len+1);
117 if (fread(s.body, 1, s.len, f) != (size_t)s.len)
118 wiggle_die("file read");
119 /* ensure string is 'nul' terminated - for sscanf */
124 struct stream wiggle_load_file(char *name)
134 if (sscanf(name, "_wiggle_:%d:%d:%n", &start, &end,
135 &prefix_len) >= 2 && prefix_len > 0) {
136 FILE *f = fopen(name + prefix_len, "r");
138 s = wiggle_load_segment(f, start, end);
145 if (strcmp(name, "-") == 0)
148 fd = open(name, O_RDONLY);
152 wiggle_check_dir(name, fd);
153 if (fstat(fd, &stb) == 0) {
155 if (S_ISREG(stb.st_mode))
156 s = wiggle_load_regular(fd);
158 s = wiggle_load_other(fd);