docutils-ts
Version:
Port of the Python Docutils library to TypeScript
110 lines (109 loc) • 3.42 kB
JavaScript
import Component from "./component.js";
import * as universal from "./transforms/universal.js";
import parsers from "./parsers/index.js";
import newDocument from "./newDocument.js";
import { InvalidStateError } from "./exceptions.js";
export default class Reader extends Component {
getTransforms() {
return [...super.getTransforms(), universal.Decorations]; // TODO : fixme !
// universal.ExportInternals, universal.StripComments ];
}
constructor(args) {
super({ logger: args.logger });
this.componentType = 'reader';
this.input = '';
this.debug = false;
const { parser, parseFn, parserName } = args;
this.componentType = 'reader';
this.configSection = 'readers';
if (parser !== undefined) {
this.parser = parser;
}
if (parseFn !== undefined) {
this.parseFn = parseFn;
}
if (args.debugFn) {
this.debugFn = args.debugFn;
}
if (args.debug) {
this.debug = args.debug || false;
}
if (parser === undefined) {
if (parserName) {
this.setParser(parserName);
}
}
this.source = undefined;
this.input = '';
}
setParser(parserName) {
const ParserClass = parsers.getParserClass(parserName);
this.parser = new ParserClass({
debug: this.debug,
debugFn: this.debugFn,
logger: this.logger,
});
}
/**
* Magic read method::
*
* test123
*
*/
read(source, parser, settings) {
this.source = source;
if (!this.parser) {
this.parser = parser;
}
this.settings = settings;
if (!this.source) {
throw new Error('Need source');
}
this.logger.silly('calling read on source');
return this.source.read().then((input) => {
this.input = input;
this.parse();
return this.document;
});
}
/* read method without callbcks and other junk */
read2(input, settings) {
this.input = input;
this.settings = settings;
this.parse();
return this.document;
}
/* Delegates to this.parser, providing arguments
based on instance variables */
parse() {
const input = Array.isArray(this.input) ? this.input.join('') : this.input;
if (this.parser) {
const document = this.newDocument();
this.parser.parse(input, document);
this.document = document;
if (this.input === undefined) {
throw new Error(`need input, i have ${this.input}`);
}
}
else if (this.parseFn !== undefined) {
const document = this.parseFn(input);
this.document = document;
}
else {
throw new InvalidStateError();
}
//this.document!.currentSource = '';
//this.document!.currentLine = 0;
}
newDocument() {
if (!this.settings) {
throw new InvalidStateError("need settings");
}
const document = newDocument({
logger: this.logger,
sourcePath: this.source && this.source.sourcePath || '',
}, this.settings);
return document;
}
}
export { Reader };