summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMatthew Peveler <matt.peveler@gmail.com>2021-02-01 01:48:01 +0000
committerMatthew Peveler <matt.peveler@gmail.com>2021-02-01 01:51:24 +0000
commite76294bc6b1fe878a2ed5d5d4816385d600574da (patch)
treeaf1a3310d7fa63d92b699ae7a44cb23f9715fe18
parent3d9c5e4206ab88aa58750b5fffaf4e83700ad951 (diff)
downloadasciidoc-py3-e76294bc6b1fe878a2ed5d5d4816385d600574da.tar.gz
include AsciiDoc API class in module
Signed-off-by: Matthew Peveler <matt.peveler@gmail.com>
-rw-r--r--asciidoc/__init__.py5
-rw-r--r--asciidoc/api.py65
2 files changed, 70 insertions, 0 deletions
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])