aboutsummaryrefslogtreecommitdiff
path: root/src/function/external_text_formatter.cc
blob: 048f81af05bd69b89a25df501ae077879e25623b (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
#include "external_text_formatter.h"

#include <xalanc/XSLT/XSLTInputSource.hpp>

#include <xercesc/parsers/XercesDOMParser.hpp>

#include <boost/process.hpp>

#include <sstream>

#include "support/xerces_string_guard.h"
#include "support/dom/result_node_facade.h"

namespace {

using InputXSLT::XercesStringGuard;

inline xercesc::DOMNode* importDocumentElement(
	boost::process::pistream& outputStream,
	xercesc::DOMDocument* const domDocument
) {
	std::stringstream xmlStream(
		"<output>" + std::string(
			(std::istreambuf_iterator<char>(outputStream)),
			(std::istreambuf_iterator<char>())
		) + "</output>"
	);

	xercesc::XercesDOMParser parser;
	parser.parse(xalan::XSLTInputSource(xmlStream));

	return domDocument->importNode(
		parser.getDocument()->getDocumentElement(),
		true
	);
}

}

namespace InputXSLT {

DomDocumentCache::document_ptr FunctionExternalTextFormatter::constructDocument(
	boost::filesystem::path formatterPath,
	std::string             stdinText
) const {
	DomDocumentCache::document_ptr domDocument(
		DomDocumentCache::createDocument("content")
	);

	boost::process::context context;
	context.stdout_behavior = boost::process::capture_stream();
	context.stdin_behavior  = boost::process::capture_stream();

	boost::process::child formatterProcess(
		boost::process::launch(
			formatterPath,
			std::vector<std::string>{""},
			context
		)
	);

	boost::process::postream& inputStream  = formatterProcess.get_stdin();
	boost::process::pistream& outputStream = formatterProcess.get_stdout();

	inputStream << stdinText;
	inputStream.close();

	boost::process::status status = formatterProcess.wait();

	ResultNodeFacade result(domDocument.get(), "output");
	result.setAttribute("formatter", formatterPath.filename().string());
	result.setAttribute("code",      std::to_string(status.exit_status()));

	if ( status.exited() ) {
		try {
			result.setContent(
				importDocumentElement(
					outputStream,
					domDocument.get()
				)->getChildNodes()
			);

			result.setAttribute("result", "success");
		}
		catch ( const xercesc::DOMException& exception ) {
			result.setAttribute("result", "error");

			result.setValueNode(
				"error",
				*XercesStringGuard<char>(exception.msg)
			);
		}
	} else {
		result.setAttribute("result", "error");
	}


	return domDocument;
}

}