Proper parsing of full description

This commit is contained in:
Rene Saarsoo 2020-09-17 23:59:47 +03:00
parent a588432516
commit 62f0bfbf25
2 changed files with 27 additions and 14 deletions

View File

@ -1,7 +1,5 @@
import * as fs from "fs"; import * as fs from "fs";
import { parseRule } from "./parser"; import { parseFile } from "./parser";
const isDefined = <T>(x: T | undefined): x is T => Boolean(x);
const filename = process.argv[2]; const filename = process.argv[2];
@ -9,13 +7,9 @@ console.log(`Parsing: ${filename}`);
const file = fs.readFileSync(filename, "utf8"); const file = fs.readFileSync(filename, "utf8");
file parseFile(file).forEach((rule) => {
.split(/\n/) console.log(rule.type);
.map(parseRule) rule.params.forEach((p) => {
.filter(isDefined) console.log(` ${p.type}: ${p.value}`);
.forEach((rule) => {
console.log(rule.type);
rule.params.forEach((p) => {
console.log(` ${p.type}: ${p.value}`);
});
}); });
});

View File

@ -30,8 +30,9 @@ const parseParams = (type: RuleType, text: string): Param[] => {
switch (type) { switch (type) {
case RuleType.Name: case RuleType.Name:
case RuleType.Author: case RuleType.Author:
case RuleType.Description: case RuleType.Description: {
return [{ type: ParamType.Text, value: text }]; return [{ type: ParamType.Text, value: text }];
}
case RuleType.Warmup: case RuleType.Warmup:
case RuleType.Rest: case RuleType.Rest:
case RuleType.Interval: case RuleType.Interval:
@ -40,7 +41,7 @@ const parseParams = (type: RuleType, text: string): Param[] => {
} }
}; };
export const parseRule = (line: string): Rule | undefined => { const parseRule = (line: string): Rule | undefined => {
const matches = line.match(/^(\w+):(.*)$/); const matches = line.match(/^(\w+):(.*)$/);
if (!matches) { if (!matches) {
return undefined; return undefined;
@ -55,3 +56,21 @@ export const parseRule = (line: string): Rule | undefined => {
params: parseParams(type, matches[2].trim()), params: parseParams(type, matches[2].trim()),
}; };
}; };
export const parseFile = (file: string): Rule[] => {
const rules: Rule[] = [];
file.split("\n").forEach((line) => {
const rule = parseRule(line);
if (rule) {
rules.push(rule);
return;
}
const lastRule = rules[rules.length - 1];
if (lastRule && lastRule.type === RuleType.Description) {
lastRule.params.push({ type: ParamType.Text, value: line.trim() });
}
});
return rules;
};