04a1c7041dc16bd35d5c1798d9376c604b59b0c7
[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         f = fdopen(fd, "r");
39         if (!f)
40                 return -errno;
41         while ((r = getline(&line, &lsz, f)) > 0) {
42                 cmd_run(dec, line);
43         }
44         free(line);
45         return r;
46 }
47
48 static int process(char *filename)
49 {
50         int r = 0;
51         int fd;
52         struct declaracao *dec;
53         dec = declaracao_new(-1);
54         if (!dec)
55                 return -errno;
56         fd = open(filename, O_RDONLY);
57         if (fd < 0) {
58                 r = -errno;
59                 goto out_open;
60         }
61         realprocess(dec, fd);
62         close(fd);
63 out_open:
64         declaracao_free(dec);
65         return r;
66 }
67
68 static void usage(void)
69 {
70         fprintf(stderr, "declara <filename>\n");
71         exit(1);
72 }
73
74 int main(int argc, char **argv)
75 {
76         char *filename;
77         int r;
78         if (argc < 2)
79                 usage();
80
81         cmd_init();
82         base_cmd_init();
83         rendimento_cmd_init();
84         calcula_cmd_init();
85
86         filename = argv[1];
87         r = process(filename);
88         if (r)
89                 return 1;
90         return 0;
91 }