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