Processa comandos para definir dados da declaração.
[cascardo/declara.git] / declara.c
1 /*
2  *  Copyright (C) 2015  Thadeu Lima de Souza Cascardo <cascardo@cascardo.eti.br>
3  *
4  *  This program is free software; you can redistribute it and/or modify
5  *  it under the terms of the GNU General Public License as published by
6  *  the Free Software Foundation; either version 3 of the License, or
7  *  (at your option) any later version.
8  *
9  *  This program is distributed in the hope that it will be useful,
10  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *  GNU General Public License for more details.
13  *
14  *  You should have received a copy of the GNU General Public License along
15  *  with this program; if not, write to the Free Software Foundation, Inc.,
16  *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17  */
18
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <unistd.h>
25
26 #include "declaracao.h"
27 #include "cmd.h"
28 #include "base.h"
29
30 static int realprocess(struct declaracao *dec, int fd)
31 {
32         char *line = NULL;
33         size_t lsz = 0;
34         FILE *f;
35         int r;
36         f = fdopen(fd, "r");
37         if (!f)
38                 return -errno;
39         while ((r = getline(&line, &lsz, f)) > 0) {
40                 cmd_run(dec, line);
41         }
42         free(line);
43         return r;
44 }
45
46 static int process(char *filename)
47 {
48         int r = 0;
49         int fd;
50         struct declaracao *dec;
51         dec = declaracao_new(-1);
52         if (!dec)
53                 return -errno;
54         fd = open(filename, O_RDONLY);
55         if (fd < 0) {
56                 r = -errno;
57                 goto out_open;
58         }
59         realprocess(dec, fd);
60         close(fd);
61 out_open:
62         declaracao_free(dec);
63         return r;
64 }
65
66 static void usage(void)
67 {
68         fprintf(stderr, "declara <filename>\n");
69         exit(1);
70 }
71
72 int main(int argc, char **argv)
73 {
74         char *filename;
75         int r;
76         if (argc < 2)
77                 usage();
78
79         cmd_init();
80         base_cmd_init();
81
82         filename = argv[1];
83         r = process(filename);
84         if (r)
85                 return 1;
86         return 0;
87 }