summaryrefslogtreecommitdiff
path: root/src/cli/Main.cpp
blob: 2658851cef816e1e0f4ac1480fdefec7d885d868 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
/*
    Ousía
    Copyright (C) 2014  Benjamin Paaßen, Andreas Stöckel

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

/**
 * @file Main.cpp
 *
 * This file provides the command line interface for Ousia. More information
 * on command line options can be found in the test.
 *
 * @author Benjamin Paaßen (bpaassen@techfak.uni-bielefeld.de)
 */

#include <unistd.h>  // Non-portable, needed for isatty

#include <algorithm>
#include <fstream>
#include <iostream>
#include <ostream>
#include <set>

#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>

#include <core/Registry.hpp>
#include <core/common/Rtti.hpp>
#include <core/frontend/TerminalLogger.hpp>
#include <core/managed/Manager.hpp>
#include <core/model/Document.hpp>
#include <core/model/Domain.hpp>
#include <core/model/Project.hpp>
#include <core/model/Typesystem.hpp>
#include <core/parser/ParserContext.hpp>
#include <core/parser/ParserScope.hpp>
#include <core/resource/ResourceManager.hpp>
#include <plugins/filesystem/FileLocator.hpp>
#include <plugins/html/DemoOutput.hpp>
#include <formats/osxml/OsxmlParser.hpp>
#include <formats/osml/OsmlParser.hpp>
#include <plugins/xml/XmlOutput.hpp>

const size_t ERROR_IN_COMMAND_LINE = 1;
const size_t SUCCESS = 0;
const size_t ERROR_UNHANDLED_EXCEPTION = 2;
const size_t ERROR_IN_DOCUMENT = 3;

using namespace ousia;

namespace po = boost::program_options;
namespace fs = boost::filesystem;

const char *MSG_COPYING =
    "Ousía\n"
    "Semantic Document Markup\n"
    "Copyright (C) 2014, 2015  Benjamin Paaßen, Andreas Stöckel\n"
    "\n"
    "This program is free software: you can redistribute it and/or modify\n"
    "it under the terms of the GNU General Public License as published by\n"
    "the Free Software Foundation, either version 3 of the License, or\n"
    "(at your option) any later version.\n"
    "\n"
    "This program is distributed in the hope that it will be useful,\n"
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
    "GNU General Public License for more details.\n";

const std::set<std::string> formats{"html", "xml"};

static void createOutput(Handle<Document> doc, std::ostream &out,
                         const std::string &format, Logger &logger)
{
	if (format == "html") {
		html::DemoHTMLTransformer transform;
		transform.writeHTML(doc, out, true);
	} else if (format == "xml") {
		xml::XmlTransformer transform;
		transform.writeXml(doc, out, logger, true);
	}
}

int main(int argc, char **argv)
{
	// Initialize terminal logger. Only use color if writing to a terminal (tty)
	bool useColor = isatty(STDOUT_FILENO) && isatty(STDERR_FILENO);
	TerminalLogger logger{std::cerr, useColor};

	// Program options
	po::options_description desc(
	    "Program usage\n./ousia [optional options] <-F format> <input "
	    "path>\nProgram options");
	std::string inputPath;
	std::string outputPath;
	std::string format;
	/*
	 * This is a rather strange access mechanism: add_options() returns an
	 * easy_init object that has overloaded the () operator to accept new
	 * initializations. Again: Rather strange syntax, but it works.
	 */
	desc.add_options()("help", "Program help")(
	    "input,i", po::value<std::string>(&inputPath)->required(),
	    "The input document file name")(
	    "include,I", po::value<std::vector<std::string>>(),
	    "Include paths, where resources like the input document "
	    "or additional domains, typesystems, etc. might be "
	    "found.")(
	    "output,o", po::value<std::string>(&outputPath),
	    "The output file name. Per default the input file name will be used.")(
	    "format,F", po::value<std::string>(&format)->required(),
	    "The output format that shall be produced.");
	// "input" should be a positional option, such that we can write:
	// ./ousia [some options] <my input file>
	// without having to use -i or I
	po::positional_options_description positional;
	positional.add("input", 1);
	po::variables_map vm;
	try {
		// try to read the values for each option to the variable map.
		po::store(po::command_line_parser(argc, argv)
		              .options(desc)
		              .positional(positional)
		              .run(),
		          vm);

		// first check the help option.
		if (vm.count("help")) {
			// write the program options description as generated by boost
			std::cout << MSG_COPYING << std::endl << std::endl << desc
			          << std::endl << std::endl;
			return SUCCESS;
		}

		// only if the user did not want help to we use notify, which checks
		// if all required options were given.
		po::notify(vm);
	}
	catch (po::error &e) {
		logger.error(e.what());
		std::cerr << desc << std::endl;
		return ERROR_IN_COMMAND_LINE;
	}

	// To comply with standard UNIX conventions the following should be changed:
	// TODO: Allow "-" for input and output files for reading from stdin and
	//       writing to stdout
	if (inputPath == "-") {
		logger.error("Currently no reading from std::in is supported!");
		return ERROR_IN_COMMAND_LINE;
	} else {
		inputPath = fs::canonical(inputPath).string();
	}

	// prepare output path
	if (!vm.count("output")) {
		// get the input filename.
		fs::path in{inputPath};
		// construct a working directory output path.
		fs::path outP = fs::canonical(".");
		outP /= (in.stem().string() + "." + format);
		outputPath = outP.string();
		std::cout << "Using " << outputPath << " as output path." << std::endl;
	}
	// check format.
	if (!formats.count(format)) {
		logger.error("Format must be one of: ");
		for (auto &f : formats) {
			logger.error(f);
		}
	}

	// TODO: REMOVE diagnostic code.
	// 	std::cout << "input : " << vm["input"].as<std::string>() << std::endl;
	// 	std::cout << "output : " << outputPath << std::endl;
	// 	std::cout << "format : " << vm["format"].as<std::string>() << std::endl;
	// 	if (vm.count("include")) {
	// 		std::vector<std::string> includes =
	// 		    vm["include"].as<std::vector<std::string>>();
	// 		std::cout << "includes : ";
	// 		for (auto &i : includes) {
	// 			std::cout << i << ", ";
	// 		}
	// 		std::cout << std::endl;
	// 	}

	// initialize global instances.
	Manager manager;
	Registry registry;
	ResourceManager resourceManager;
	ParserScope scope;
	Rooted<Project> project{new Project(manager)};
	FileLocator fileLocator;
	ParserContext context{registry, resourceManager, scope, project, logger};

	// Connect the Source Context Callback of the logger to provide the user
	// with context information (line, column, filename, text) for log messages
	logger.setSourceContextCallback(resourceManager.getSourceContextCallback());

	// fill registry
	registry.registerDefaultExtensions();
	OsmlParser osmlParser;
	OsxmlParser osxmlParser;
	registry.registerParser(
	    {"text/vnd.ousia.osml"},
	    {&RttiTypes::Document, &RttiTypes::Domain, &RttiTypes::Typesystem},
	    &osmlParser);
	registry.registerParser(
	    {"text/vnd.ousia.osml+xml"},
	    {&RttiTypes::Document, &RttiTypes::Domain, &RttiTypes::Typesystem},
	    &osxmlParser);
	registry.registerResourceLocator(&fileLocator);

	// register search paths
	fileLocator.addDefaultSearchPaths();
	// in user includes we allow every kind of resource.
	if (vm.count("include")) {
		std::vector<std::string> includes =
		    vm["include"].as<std::vector<std::string>>();
		for (auto &i : includes) {
			// Adding the search path as "UNKNOWN" suffices, as this search path
			// is automatically searched for all files.
			fileLocator.addSearchPath(i, ResourceType::UNKNOWN);
		}
	}

	// now all preparation is done and we can parse the input document.
	Rooted<Node> docNode = context.import(inputPath, "text/vnd.ousia.oxd", "",
	                                      {&RttiTypes::Document});
	if (logger.hasError() || docNode == nullptr) {
		logger.fatalError("Errors occured while parsing the document");
		return ERROR_IN_DOCUMENT;
	}
	Rooted<Document> doc = docNode.cast<Document>();
	// write output
	if (outputPath != "-") {
		std::fstream out{outputPath};
		createOutput(doc, out, format, logger);
	} else {
		createOutput(doc, std::cout, format, logger);
	}

	return SUCCESS;
}