From e76294bc6b1fe878a2ed5d5d4816385d600574da Mon Sep 17 00:00:00 2001 From: Matthew Peveler Date: Mon, 1 Feb 2021 01:48:01 +0000 Subject: include AsciiDoc API class in module Signed-off-by: Matthew Peveler --- asciidoc/__init__.py | 5 ++++ asciidoc/api.py | 65 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 asciidoc/api.py diff --git a/asciidoc/__init__.py b/asciidoc/__init__.py index 4086345..db10109 100644 --- a/asciidoc/__init__.py +++ b/asciidoc/__init__.py @@ -1 +1,6 @@ """asciidoc module""" + +from .api import AsciiDocAPI +from .asciidoc import execute, cli + +__all__ = ['AsciiDocAPI', 'execute', 'cli'] diff --git a/asciidoc/api.py b/asciidoc/api.py new file mode 100644 index 0000000..1e3d215 --- /dev/null +++ b/asciidoc/api.py @@ -0,0 +1,65 @@ +from . import asciidoc + + +class AsciiDocError(Exception): + pass + + +class Options(object): + """ + Stores asciidoc(1) command options. + """ + def __init__(self, values=[]): + self.values = values[:] + + def __call__(self, name, value=None): + """Shortcut for append method.""" + self.append(name, value) + + def append(self, name, value=None): + if type(value) in (int, float): + value = str(value) + self.values.append((name, value)) + + +class AsciiDocAPI(object): + """ + AsciiDoc API class. + """ + def __init__(self, asciidoc_py=None): + """ + Locate and import asciidoc.py. + Initialize instance attributes. + """ + self.options = Options() + self.attributes = {} + self.messages = [] + + def execute(self, infile, outfile=None, backend=None): + """ + Compile infile to outfile using backend format. + infile can outfile can be file path strings or file like objects. + """ + self.messages = [] + opts = Options(self.options.values) + if outfile is not None: + opts('--out-file', outfile) + if backend is not None: + opts('--backend', backend) + for k, v in self.attributes.items(): + if v == '' or k[-1] in '!@': + s = k + elif v is None: # A None value undefines the attribute. + s = k + '!' + else: + s = '%s=%s' % (k, v) + opts('--attribute', s) + args = [infile] + try: + try: + asciidoc.execute(self.cmd, opts.values, args) + finally: + self.messages = self.asciidoc.messages[:] + except SystemExit as e: + if e.code: + raise AsciiDocError(self.messages[-1]) -- cgit v1.2.1