test-line-buffer.c 1.9 KB
Newer Older
D
David Barr 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * test-line-buffer.c: code to exercise the svn importer's input helper
 */

#include "git-compat-util.h"
#include "vcs-svn/line_buffer.h"

static uint32_t strtouint32(const char *s)
{
	char *end;
	uintmax_t n = strtoumax(s, &end, 10);
	if (*s == '\0' || *end != '\0')
		die("invalid count: %s", s);
	return (uint32_t) n;
}

17 18 19 20 21
static void handle_command(const char *command, const char *arg, struct line_buffer *buf)
{
	switch (*command) {
	case 'c':
		if (!prefixcmp(command, "copy ")) {
22
			buffer_copy_bytes(buf, strtouint32(arg));
23 24 25 26 27
			return;
		}
	case 'r':
		if (!prefixcmp(command, "read ")) {
			const char *s = buffer_read_string(buf, strtouint32(arg));
28 29 30 31 32 33
			fputs(s, stdout);
			return;
		}
	case 's':
		if (!prefixcmp(command, "skip ")) {
			buffer_skip_bytes(buf, strtouint32(arg));
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
			return;
		}
	default:
		die("unrecognized command: %s", command);
	}
}

static void handle_line(const char *line, struct line_buffer *stdin_buf)
{
	const char *arg = strchr(line, ' ');
	if (!arg)
		die("no argument in line: %s", line);
	handle_command(line, arg + 1, stdin_buf);
}

D
David Barr 已提交
49 50
int main(int argc, char *argv[])
{
51
	struct line_buffer stdin_buf = LINE_BUFFER_INIT;
52 53 54
	struct line_buffer file_buf = LINE_BUFFER_INIT;
	struct line_buffer *input = &stdin_buf;
	const char *filename;
D
David Barr 已提交
55 56
	char *s;

57 58 59 60 61 62
	if (argc == 1)
		filename = NULL;
	else if (argc == 2)
		filename = argv[1];
	else
		usage("test-line-buffer [file] < script");
63 64

	if (buffer_init(&stdin_buf, NULL))
D
David Barr 已提交
65
		die_errno("open error");
66 67 68 69 70 71
	if (filename) {
		if (buffer_init(&file_buf, filename))
			die_errno("error opening %s", filename);
		input = &file_buf;
	}

72
	while ((s = buffer_read_line(&stdin_buf)))
73 74 75 76
		handle_line(s, input);

	if (filename && buffer_deinit(&file_buf))
		die("error reading from %s", filename);
77
	if (buffer_deinit(&stdin_buf))
D
David Barr 已提交
78 79 80
		die("input error");
	if (ferror(stdout))
		die("output error");
81
	buffer_reset(&stdin_buf);
D
David Barr 已提交
82 83
	return 0;
}