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