]> git.tdb.fi Git - libs/datafile.git/blob - tool/tool.cpp
4e6608766a8e7cbacb47900e337ba0c80436e6f6
[libs/datafile.git] / tool / tool.cpp
1 #include <msp/core/getopt.h>
2 #include <msp/io/buffered.h>
3 #include <msp/io/console.h>
4 #include <msp/io/file.h>
5 #include <msp/datafile/parser.h>
6 #include <msp/datafile/statement.h>
7 #include <msp/datafile/writer.h>
8 #include "compiler.h"
9 #include "tool.h"
10
11 using namespace std;
12 using namespace Msp;
13
14 DataTool::DataTool(int argc, char **argv):
15         in_fn("-"),
16         out_fn("-"),
17         binary(false),
18         compile(false)
19 {
20         GetOpt getopt;
21         getopt.add_option('b', "binary", binary, GetOpt::NO_ARG);
22         getopt.add_option('c', "compile", compile, GetOpt::NO_ARG);
23         getopt.add_option('o', "output", out_fn, GetOpt::REQUIRED_ARG);
24         getopt(argc, argv);
25
26         const vector<string> &args = getopt.get_args();
27         if(!args.empty())
28                 in_fn = args[0];
29 }
30
31 int DataTool::main()
32 {
33         IO::Base *in;
34         if(in_fn=="-")
35                 in = &IO::cin;
36         else
37                 in = new IO::File(in_fn);
38
39         IO::Base *out;
40         if(out_fn=="-")
41                 out = &IO::cout;
42         else
43                 out = new IO::File(out_fn, IO::M_WRITE);
44
45         {
46                 IO::Buffered in_buf(*in);
47                 DataFile::Parser parser(in_buf, in_fn);
48                 IO::Buffered out_buf(*out);
49                 DataFile::Writer writer(out_buf);
50                 if(binary)
51                         writer.set_binary(true);
52
53                 if(compile)
54                 {
55                         Compiler compiler(writer);
56                         compiler.load(parser);
57                 }
58                 else
59                 {
60                         while(parser)
61                         {
62                                 DataFile::Statement st = parser.parse();
63                                 if(st.valid)
64                                 {
65                                         writer.write(st);
66                                         out_buf.flush();
67                                 }
68                         }
69                 }
70         }
71
72         if(in!=&IO::cin)
73                 delete in;
74         if(out!=&IO::cout)
75                 delete out;
76
77         return 0;
78 }