b1340795419b9af45a737f20aa35cc933275c0c7
[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 #include "rendimento.h"
30 #include "calcula.h"
31
32 static int realprocess(struct declaracao *dec, int fd)
33 {
34         char *line = NULL;
35         size_t lsz = 0;
36         FILE *f;
37         int r;
38         int n = 1;
39         f = fdopen(fd, "r");
40         if (!f)
41                 return -errno;
42         while ((r = getline(&line, &lsz, f)) > 0) {
43                 r = cmd_run(dec, line);
44                 if (r < 0) {
45                         fprintf(stderr, "Não foi possível executar comando na linha %d: %s\n",
46                                 n, strerror(-r));
47                 }
48                 n++;
49         }
50         free(line);
51         return r;
52 }
53
54 static int process(char *filename)
55 {
56         int r = 0;
57         int fd;
58         struct declaracao *dec;
59         dec = declaracao_new(-1);
60         if (!dec)
61                 return -errno;
62         fd = open(filename, O_RDONLY);
63         if (fd < 0) {
64                 r = -errno;
65                 goto out_open;
66         }
67         realprocess(dec, fd);
68         close(fd);
69 out_open:
70         declaracao_free(dec);
71         return r;
72 }
73
74 static void usage(void)
75 {
76         fprintf(stderr, "declara <filename>\n");
77         exit(1);
78 }
79
80 int main(int argc, char **argv)
81 {
82         char *filename;
83         int r;
84         if (argc < 2)
85                 usage();
86
87         cmd_init();
88         base_cmd_init();
89         rendimento_cmd_init();
90         calcula_cmd_init();
91
92         filename = argv[1];
93         r = process(filename);
94         if (r)
95                 return 1;
96         return 0;
97 }