summaryrefslogtreecommitdiff
path: root/src/srcut.cpp
blob: 44131a0043e6e78bef42089a8088fa59da09f65c (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
#include <fstream>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <unistd.h>
#include <vector>

using namespace std;

istream&
operator>>(istream& in, map<string, vector<string>>& container)
{
	static constexpr auto begin_marker = "--8<--";
	static constexpr auto end_marker   = "-->8--";

	auto is_comment = [](string_view s) -> bool {
		return s == "//" || s == "/*" || s == "#" || s == "##" || s == "--";
	};

	// --8<-- match_begin
	auto match_begin = [&is_comment](const string& line, string& name) -> bool {
		stringstream ss{ line };

		string comment, cut_mark;

		if ( !(ss >> comment >> cut_mark >> name) ) {
			return false;
		}

		if ( !is_comment(comment) ) {
			return false;
		}

		if ( cut_mark != begin_marker ) {
			return false;
		}

		return true;
	};
	// -->8--

	// --8<-- match_end
	auto match_end = [&is_comment](const string& line) -> bool {
		stringstream ss{ line };

		string comment, cut_mark;

		if ( !(ss >> comment >> cut_mark) ) {
			return false;
		}

		if ( !is_comment(comment) ) {
			return false;
		}

		if ( cut_mark != end_marker ) {
			return false;
		}

		return true;
	};
	// -->8--

	vector<string> chunks;
	for ( string line; getline(in, line); ) {
		string marker;
		if ( match_begin(line, marker) ) {
			chunks.emplace_back(marker);
		}
		else if ( match_end(line) ) {
			if ( !chunks.empty() ) {
				chunks.pop_back();
			}
		}
		else {
			for ( const auto& chunk: chunks ) {
				container[chunk].emplace_back(line);
			}
		}
	}

	return in;
}

ostream&
print(ostream& os, const string& key, const map<string, vector<string>>& container)
{
	const auto it = container.find(key);
	if ( it != container.end() ) {
		auto line = begin(it->second);
		while ( line != end(it->second) ) {
			os << *line << '\n';

			++line;
		}
	}
	else {
		cerr << "ERROR: " << key << " not found!" << endl;
	}
	return os;
}

int
main(int argc, char* argv[])
{
	int show_tags = 0;
	int ch;

	while ( (ch = getopt(argc, argv, "t")) != -1 ) {
		switch ( ch ) {
		case 't':
			show_tags = 1;
			break;
		default:
			cerr << "unbekannte option" << endl;
			return EXIT_FAILURE;
		}
	}
	argc -= optind;
	argv += optind;

	map<string, vector<string>> container;

	cin >> container;

	if ( show_tags ) {
		for ( const auto& it: container ) {
			cout << it.first << endl;
		}
	}
	else {
		for ( int i = 0; i < argc; ++i ) {
			print(cout, argv[i], container);
		}
	}
}