summaryrefslogtreecommitdiff
path: root/file.c
blob: 1145173e25614c72fe896d57f09e0a1d99b5b578 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
 * file.c - Open and read a file
 *
 * Written 2016 by Werner Almesberger
 * Copyright 2016 by Werner Almesberger
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 */

#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "util.h"
#include "main.h"
#include "git-file.h"
#include "file.h"


bool file_cat(void *user, const char *line)
{
	printf("%s\n", line);
	return 1;
}


static void read_from_file(FILE *file,
    bool (*parse)(void *user, const char *line), void *user)
{
	char buf[1000];
	char *nl;

	while (fgets(buf, sizeof(buf), file)) {
		nl = strchr(buf, '\n');
		if (nl)
			*nl = 0;
		if (!parse(user, buf))
			break;
	}
}


void file_read(const char *name, bool (*parse)(void *user, const char *line),
    void *user)
{
	FILE *file;
	char *colon, *tmp;

	file = fopen(name, "r");
	if (file) {
		if (verbose)
			fprintf(stderr, "reading %s\n", name);
		read_from_file(file, parse, user);
		fclose(file);
		return;
	}

	if (verbose)
		perror(name);

	colon = strchr(name, ':');
	if (!colon) {
		if (!verbose)
			perror(name);
		exit(1);
	}

	tmp = stralloc(name);
	tmp[colon - name] = 0;
	git_read(tmp, colon + 1, parse, user);
	free(tmp);
}