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