-
Notifications
You must be signed in to change notification settings - Fork 1
/
combine.js
183 lines (173 loc) · 6.19 KB
/
combine.js
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
#!/usr/bin/env node
'use strict';
import {readFile, readdir, writeFile} from 'fs/promises';
import {argv} from 'process';
const MONTHS = ['', 'januar', 'februar', 'mart', 'april', 'maj', 'jun', 'jul', 'avgust', 'septembar', 'oktobar', 'novembar', 'decembar'];
const TYPES = {
k: 'kolokvijum',
k1: 'prvi kolokvijum',
k2: 'drugi kolokvijum',
k3: 'treći kolokvijum'
};
const isWeb = !argv.includes('--print');
const ALL_DIRECTORIES = ['os1', 'os2'];
const GENERATE_OPTIONS = {
1: 'k1',
2: 'k2',
3: 'k3',
c: 'combined'
};
async function processFile(year, month, type, categories, baseDir) {
const text = await readFile(`${baseDir}/${year}/${month}/${type}.md`, {
encoding: 'utf-8'
});
const sections = text.split(/-{60,100}/);
if (sections.length === 2) {
// Not yet processed
return;
}
const url = sections
.shift()
.trim()
.split('/')
.map(s => encodeURIComponent(s))
.join('/');
let task = 0;
for (const section of sections) {
++task;
const sectionTrimmed = section.trim();
const firstLine = sectionTrimmed.split('\n', 1)[0].trim().split(' ');
const category = firstLine[0];
const keywords = firstLine.slice(1);
const content = sectionTrimmed.replace(/.*[\r\n]*/, '');
if (!categories[category]) {
categories[category] = [];
}
categories[category].push({url, content, year, month, type, task, keywords});
}
}
async function getYears(baseDir) {
const arg = argv.find(arg => arg.startsWith('--year='));
if (arg) {
return arg.substring(7).split(',').map(year => year.trim());
} else {
return (await readdir(baseDir)).filter((x) => !(isNaN(x))).reverse();
}
}
function formatUrls(url, solutionUrl, baseUrl) {
const urlRow = (url && isWeb) ?
`- [Postavka](${baseUrl}${url})\n` :
'';
const solutionUrlRow = (solutionUrl && isWeb) ?
`- [Rešenje](${baseUrl}${solutionUrl})\n` :
'';
return `${urlRow}${solutionUrlRow}`;
}
function getGenerateOptions() {
const arg = argv.find(arg => arg.startsWith('--generate')) || 'c123';
return arg
// Read character by character.
.split('')
// Map characters to their respective generation options.
.map(c => GENERATE_OPTIONS[c])
// Remove extraneous characters.
.filter(Boolean);
}
function getCategories(option, colloquia) {
return option === 'combined' ?
// Combine all categories.
['k1', 'k2', 'k3']
.map(k => colloquia[k])
.flat() :
colloquia[option];
}
async function processDirectory(baseDir) {
const meta = JSON.parse(await readFile(`${baseDir}/meta.json`, {
encoding : 'utf-8'
}));
const {baseUrl, colloquia} = meta;
const categories = {};
for (const year of await getYears(baseDir)) {
for (const month of await readdir(`${baseDir}/${year}`)) {
for (const typeExt of await readdir(`${baseDir}/${year}/${month}`)) {
await processFile(year, month, typeExt.split('.')[0], categories, baseDir);
}
}
}
// Connect solutions to categories
const categoriesConnected = {};
for (const category in categories) {
const entries = categories[category];
if (entries.length === 0) {
continue;
}
categoriesConnected[category] = [];
for (const entry of entries) {
const {content, type, year, month, task} = entry;
if (type.endsWith('-sol')) {
continue;
}
const solution = entries.find(
entry2 => entry2.type === `${type}-sol` &&
entry2.year === year &&
entry2.month === month &&
entry2.task === task
);
if (!solution) {
console.error('No solution for', entry);
categoriesConnected[category].push({
...entry,
solutionUrl: '#nema'
});
continue;
}
categoriesConnected[category].push({
...entry,
content: `${content}\n\n### Rešenje\n\n${solution.content}`,
solutionUrl: solution.url
});
}
}
const header = await readFile(`${baseDir}/header.md`, {
encoding: 'utf-8'
});
const footer = await readFile(`${baseDir}/footer.md`, {
encoding: 'utf-8'
});
for (const option of getGenerateOptions()) {
const categoryKeys = getCategories(option, colloquia);
const filenameCategory = option === 'combined' ? '' : `-${option}`;
const filenameVersion = isWeb ? '-web' : '-print';
const filename = `${baseDir}${filenameCategory}${filenameVersion}.md`;
const body = Object.entries(categoriesConnected)
// Filter out categories which are not in the current set for generation.
.filter(([category]) => categoryKeys.includes(category))
// Sort by position in the generation set.
.sort(([c1], [c2]) => categoryKeys.indexOf(c1) - categoryKeys.indexOf(c2))
// Map contents of each category.
.map(
([category, entries]) => `# ${meta.categories[category]}\n${entries.map(
({url, content, year, month, type, task, solutionUrl, keywords}) =>
`## ${task}. zadatak, ${TYPES[type]}, ${MONTHS[month]} ${year}.\n${
keywords
.map(kw => `\\index{${meta.keywords[kw]}}`)
.join(' ')
}\n\n${formatUrls(url, solutionUrl, baseUrl)}\n${content}`
).join('\n\n')}`
).join('\n\n\\pagebreak\n');
await writeFile(filename, `${header}${body}${footer}`, {
encoding: 'utf-8'
});
}
}
async function main() {
const dirArg = argv[2];
if (dirArg && !dirArg.startsWith('--')) {
await processDirectory(dirArg);
} else {
for (const dir of ALL_DIRECTORIES) {
await processDirectory(dir);
}
}
}
main();