| 1 |
""" |
| 2 |
Generation of system docs by introspection and combination with static |
| 3 |
docs. |
| 4 |
""" |
| 5 |
|
| 6 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 7 |
#c |
| 8 |
#c This program is free software, covered by the GNU GPL. See the |
| 9 |
#c COPYING file in the source distribution. |
| 10 |
|
| 11 |
|
| 12 |
import locale |
| 13 |
import inspect |
| 14 |
import json |
| 15 |
import os |
| 16 |
import re |
| 17 |
import sys |
| 18 |
import textwrap |
| 19 |
import traceback |
| 20 |
|
| •21 |
from gavo import pkg_resources |
| 22 |
|
| 23 |
from gavo import base |
| 24 |
from gavo import rscdef |
| 25 |
from gavo import rscdesc |
| 26 |
from gavo import utils |
| 27 |
from gavo.base import config #noflake: used from processed document |
| 28 |
from gavo.base import complexattrs |
| 29 |
from gavo.base import structure |
| 30 |
from gavo.utils import Arg, exposedFunction, makeCLIParser, stanxml |
| 31 |
|
| 32 |
|
| 33 |
class RSTFragment: |
| 34 |
"""a collection of convenience methods for generation of RST. |
| 35 |
""" |
| 36 |
level1Underliner = "'" |
| 37 |
level2Underliner = "." |
| 38 |
|
| 39 |
def __init__(self): |
| 40 |
self.content = [] |
| 41 |
|
| 42 |
def makeSpace(self): |
| 43 |
"""adds an empty line unless the last line already is empty. |
| 44 |
""" |
| 45 |
if self.content and self.content[-1]!="\n": |
| 46 |
self.content.append("\n") |
| 47 |
|
| 48 |
def addHead(self, head, underliner): |
| 49 |
self.makeSpace() |
| 50 |
self.content.append(head+"\n") |
| 51 |
self.content.append(underliner*len(head)+"\n") |
| 52 |
self.content.append("\n") |
| 53 |
|
| 54 |
def addHead1(self, head): |
| 55 |
self.addHead(head, self.level1Underliner) |
| 56 |
|
| 57 |
def addHead2(self, head): |
| 58 |
self.addHead(head, self.level2Underliner) |
| 59 |
|
| 60 |
def delEmptySection(self): |
| 61 |
"""deletes something that looks like a headline if it's the last |
| 62 |
thing in our content list. |
| 63 |
""" |
| 64 |
try: |
| 65 |
# we suspect a headline if the last two contributions are a line |
| 66 |
# made up of on char type and an empty line. |
| 67 |
if self.content[-1]=="\n" and len(set(self.content[-2]))==2: |
| 68 |
self.content[-3:] = [] |
| 69 |
except IndexError: # not enough material to take something away |
| 70 |
pass |
| 71 |
|
| 72 |
def addULItem(self, content, bullet="*"): |
| 73 |
if content is None: |
| 74 |
return |
| 75 |
initialIndent = bullet+" " |
| 76 |
self.content.append(textwrap.fill(content, initial_indent=initialIndent, |
| 77 |
subsequent_indent=" "*len(initialIndent))+"\n") |
| 78 |
|
| 79 |
def addDLItem(self, term, definition): |
| 80 |
self.content.append("**%s**\n"%term) |
| 81 |
self.content.append(textwrap.fill(definition, |
| 82 |
initial_indent=" ", subsequent_indent=" ")) |
| 83 |
self.content.append("\n") |
| 84 |
|
| 85 |
def addDefinition(self, defHead, defBody): |
| 86 |
"""adds a definition list-style item . |
| 87 |
|
| 88 |
defBody is re-indented with two spaces, defHead is assumed to only |
| 89 |
contain a single line. |
| 90 |
""" |
| 91 |
self.content.append(defHead+"\n") |
| 92 |
self.content.append(utils.fixIndentation(defBody, " ", |
| 93 |
governingLine=2)+"\n") |
| 94 |
|
| 95 |
def addNormalizedPara(self, stuff): |
| 96 |
"""adds stuff to the document, making sure it's not glued to any |
| 97 |
previous material and removing whitespace as necessary for docstrings. |
| 98 |
""" |
| 99 |
self.makeSpace() |
| 100 |
self.content.append(utils.fixIndentation(stuff, "", governingLine=2)+"\n") |
| 101 |
|
| 102 |
def addRaw(self, stuff): |
| 103 |
self.content.append(stuff) |
| 104 |
|
| 105 |
|
| 106 |
class ParentPlaceholder: |
| 107 |
"""a sentinel left in the proto documentation, to be replaced by |
| 108 |
docs on the element parents found while processing. |
| 109 |
""" |
| 110 |
def __init__(self, elementName): |
| 111 |
self.elementName = elementName |
| 112 |
|
| 113 |
|
| 114 |
class DocumentStructure(dict): |
| 115 |
"""a dict keeping track of what elements have been processed and |
| 116 |
which children they had. |
| 117 |
|
| 118 |
From this information, it can later fill out the ParentPlaceholders |
| 119 |
left in the proto reference doc. |
| 120 |
|
| 121 |
This also keeps track of what macros can be used where. |
| 122 |
""" |
| 123 |
def __init__(self): |
| 124 |
dict.__init__(self) |
| 125 |
self.knownMacros = KnownMacros() |
| 126 |
|
| 127 |
def _makeDoc(self, parents): |
| 128 |
return "May occur in %s.\n"%", ".join("`Element %s`_"%name |
| 129 |
for name in parents) |
| 130 |
|
| 131 |
def fillOut(self, protoDoc): |
| 132 |
parentDict = {} |
| 133 |
for parent, children in self.items(): |
| 134 |
for child in children: |
| 135 |
parentDict.setdefault(child, []).append(parent) |
| 136 |
|
| 137 |
for index, item in enumerate(protoDoc): |
| 138 |
if isinstance(item, ParentPlaceholder): |
| 139 |
if item.elementName in parentDict: |
| 140 |
protoDoc[index] = self._makeDoc(parentDict[item.elementName]) |
| 141 |
else: |
| 142 |
protoDoc[index] = "" |
| 143 |
|
| 144 |
|
| 145 |
def getDocName(klass): |
| 146 |
return getattr(klass, "docName_", klass.name_) |
| 147 |
|
| 148 |
|
| 149 |
class StructDocMaker: |
| 150 |
"""A class encapsulating generation of documentation from structs. |
| 151 |
""" |
| 152 |
def __init__(self, docStructure): |
| 153 |
self.docParts = [] |
| 154 |
self.docStructure = docStructure |
| 155 |
self.visitedClasses = set() |
| 156 |
|
| 157 |
def _iterMatchingAtts(self, klass, condition): |
| 158 |
for att in sorted((a for a in klass.attrSeq |
| 159 |
if condition(a)), |
| 160 |
key=lambda att: att.name_): |
| 161 |
yield att |
| 162 |
|
| 163 |
def _iterAttsOfBase(self, klass, base): |
| 164 |
return self._iterMatchingAtts(klass, lambda a: isinstance(a, base)) |
| 165 |
|
| 166 |
def _iterAttsNotOfBase(self, klass, base): |
| 167 |
return self._iterMatchingAtts(klass, lambda a: not isinstance(a, base)) |
| 168 |
|
| 169 |
def _addMacroDocs(self, klass, content, docStructure): |
| 170 |
if not issubclass(klass, base.MacroPackage): |
| 171 |
return |
| 172 |
|
| 173 |
macNames = [] |
| 174 |
for attName in dir(klass): |
| 175 |
if attName.startswith("macro_"): |
| 176 |
name = attName[6:] |
| 177 |
docStructure.knownMacros.addMacro(name, |
| 178 |
getattr(klass, attName), klass) |
| 179 |
macNames.append(name) |
| 180 |
|
| 181 |
content.addNormalizedPara("Macros predefined here: "+", ".join( |
| 182 |
"`Macro %s`_"%name for name in sorted(macNames))) |
| 183 |
content.makeSpace() |
| 184 |
|
| 185 |
def _realAddDocsFrom(self, klass, docStructure): |
| 186 |
name = getDocName(klass) |
| 187 |
if name in self.docStructure: |
| 188 |
return |
| 189 |
|
| 190 |
self.visitedClasses.add(klass) |
| 191 |
content = RSTFragment() |
| 192 |
content.addHead1("Element %s"%name) |
| 193 |
if klass.__doc__: |
| 194 |
content.addNormalizedPara(klass.__doc__) |
| 195 |
else: |
| 196 |
content.addNormalizedPara("NOT DOCUMENTED") |
| 197 |
|
| 198 |
content.addRaw(ParentPlaceholder(name)) |
| 199 |
|
| 200 |
content.addHead2("Atomic Children") |
| 201 |
for att in self._iterAttsOfBase(klass, base.AtomicAttribute): |
| 202 |
content.addULItem(att.makeUserDoc()) |
| 203 |
content.delEmptySection() |
| 204 |
|
| 205 |
children = [] |
| 206 |
content.addHead2("Structure Children") |
| 207 |
for att in self._iterAttsOfBase(klass, complexattrs._StructMakingAttribute): |
| 208 |
try: |
| 209 |
content.addULItem(att.makeUserDoc()) |
| 210 |
if isinstance(getattr(att, "childFactory", None), structure.StructType): |
| 211 |
children.append(getDocName(att.childFactory)) |
| 212 |
if att.childFactory not in self.visitedClasses: |
| 213 |
self.addDocsFrom(att.childFactory, docStructure) |
| 214 |
except: |
| 215 |
sys.stderr.write("While gendoccing %s in %s:\n"%( |
| 216 |
att.name_, name)) |
| 217 |
traceback.print_exc() |
| 218 |
self.docStructure.setdefault(name, []).extend(children) |
| 219 |
content.delEmptySection() |
| 220 |
|
| 221 |
content.addHead2("Other Children") |
| 222 |
for att in self._iterAttsNotOfBase(klass, |
| 223 |
(base.AtomicAttribute, complexattrs._StructMakingAttribute)): |
| 224 |
content.addULItem(att.makeUserDoc()) |
| 225 |
content.delEmptySection() |
| 226 |
content.makeSpace() |
| 227 |
|
| 228 |
self._addMacroDocs(klass, content, docStructure) |
| 229 |
|
| 230 |
self.docParts.append((klass.name_, content.content)) |
| 231 |
|
| 232 |
def addDocsFrom(self, klass, docStructure): |
| 233 |
try: |
| 234 |
self._realAddDocsFrom(klass, docStructure) |
| 235 |
except (KeyboardInterrupt, SystemExit): |
| 236 |
sys.exit(2) |
| 237 |
except: |
| 238 |
sys.stderr.write("Cannot add docs from element %s\n"%klass.name_) |
| 239 |
traceback.print_exc() |
| 240 |
|
| 241 |
def getDocs(self): |
| 242 |
self.docParts.sort(key=lambda t: t[0].upper()) |
| 243 |
resDoc = [] |
| 244 |
for title, doc in self.docParts: |
| 245 |
resDoc.extend(doc) |
| 246 |
return resDoc |
| 247 |
|
| 248 |
|
| 249 |
class MacroDoc: |
| 250 |
"""documentation for a macro, including the objects that know about |
| 251 |
it. |
| 252 |
""" |
| 253 |
def __init__(self, name, macFunc, foundIn): |
| 254 |
self.name = name |
| 255 |
self.macFunc = macFunc |
| 256 |
self.inObjects = [foundIn] |
| 257 |
|
| 258 |
def addObject(self, macFunc, obj): |
| 259 |
"""declares that macFunc is also available on the python object obj. |
| 260 |
|
| 261 |
If also checks implements the "see <whatever>" mechanism described |
| 262 |
in KnownMacros. |
| 263 |
""" |
| 264 |
self.inObjects.append(obj) |
| 265 |
if (self.macFunc.__doc__ or "").startswith("see "): |
| 266 |
self.macFunc = macFunc |
| 267 |
|
| 268 |
def makeDoc(self, content): |
| 269 |
"""adds documentation of macFunc to the RSTFragment content. |
| 270 |
""" |
| 271 |
sig = inspect.signature(self.macFunc) |
| 272 |
|
| 273 |
# macros have args in {}, of course there's no self, and null-arg |
| 274 |
# macros have no {}... |
| 275 |
args = str(sig).replace("self, ", "" |
| 276 |
).replace("(", "{" |
| 277 |
).replace(")", "}" |
| 278 |
).replace("{self}", "" |
| 279 |
).replace("{}", "" |
| 280 |
).replace(", ", "}{") |
| 281 |
|
| 282 |
content.addRaw("::\n\n \\%s%s\n\n"%(self.name, args)) |
| 283 |
content.addRaw(utils.fixIndentation( |
| 284 |
self.macFunc.__doc__ or "undocumented", "", 1).replace("\\", "\\\\")) |
| 285 |
content.addNormalizedPara("Available in "+", ".join( |
| 286 |
sorted( |
| 287 |
"`Element %s`_"%c.name_ for c in self.inObjects))) |
| 288 |
|
| 289 |
|
| 290 |
class KnownMacros: |
| 291 |
"""An accumulator for all macros known to the various DaCHS objects. |
| 292 |
|
| 293 |
Note that macros with identical names are supposed to do essentially |
| 294 |
the same things. In particular, they must all have the same signature |
| 295 |
or the documentation will be wrong. |
| 296 |
|
| 297 |
When macros share names, all but one implementation should have |
| 298 |
a docstring just saying "see <whatever>"; that way, the docstring |
| 299 |
actually chosen is deterministic. |
| 300 |
""" |
| 301 |
def __init__(self): |
| 302 |
self.macros = {} |
| 303 |
|
| 304 |
def addMacro(self, name, macFunc, foundIn): |
| 305 |
"""registers macFunc as expanding name in the element foundIn. |
| 306 |
|
| 307 |
macFunc is the method, foundIn is the python class it's defined on. |
| 308 |
""" |
| 309 |
if name in self.macros: |
| 310 |
self.macros[name].addObject(macFunc, foundIn) |
| 311 |
else: |
| 312 |
self.macros[name] = MacroDoc(name, macFunc, foundIn) |
| 313 |
|
| 314 |
def getDocs(self): |
| 315 |
"""returns RST lines describing all macros fed in in addMacro. |
| 316 |
""" |
| 317 |
content = RSTFragment() |
| 318 |
for macName in sorted(self.macros): |
| 319 |
content.addHead1("Macro %s"%macName) |
| 320 |
self.macros[macName].makeDoc(content) |
| 321 |
content.makeSpace() |
| 322 |
return content.content |
| 323 |
|
| 324 |
|
| 325 |
def formatKnownMacros(docStructure): |
| 326 |
return docStructure.knownMacros.getDocs() |
| 327 |
|
| 328 |
|
| 329 |
def getStructDocs(docStructure): |
| 330 |
dm = StructDocMaker(docStructure) |
| 331 |
dm.addDocsFrom(rscdesc.RD, docStructure) |
| 332 |
return dm.getDocs() |
| 333 |
|
| 334 |
|
| 335 |
def getStructDocsFromRegistry(registry, docStructure): |
| 336 |
dm = StructDocMaker(docStructure) |
| 337 |
for name, struct in sorted(registry.items()): |
| 338 |
dm.addDocsFrom(struct, docStructure) |
| 339 |
return dm.getDocs() |
| 340 |
|
| 341 |
|
| 342 |
def getGrammarDocs(docStructure): |
| 343 |
registry = dict((n, rscdef.getGrammar(n)) for n in rscdef.GRAMMAR_REGISTRY) |
| 344 |
return getStructDocsFromRegistry(registry, docStructure) |
| 345 |
|
| 346 |
|
| 347 |
def getCoreDocs(docStructure): |
| 348 |
from gavo.svcs import core |
| 349 |
registry = dict((n, core.getCore(n)) for n in core.CORE_REGISTRY) |
| 350 |
return getStructDocsFromRegistry(registry, docStructure) |
| 351 |
|
| 352 |
|
| 353 |
def getActiveTagDocs(docStructure): |
| 354 |
from gavo.base import activetags |
| 355 |
return getStructDocsFromRegistry(activetags.getActiveTag.registry, |
| 356 |
docStructure) |
| 357 |
|
| 358 |
|
| 359 |
def getRendererDocs(docStructure): |
| 360 |
from gavo.svcs import RENDERER_REGISTRY, getRenderer |
| 361 |
content = RSTFragment() |
| 362 |
for rendName in sorted(RENDERER_REGISTRY): |
| 363 |
try: |
| 364 |
rend = getRenderer(rendName) |
| 365 |
except ImportError as msg: |
| 366 |
base.ui.notifyWarning("Missing dependency for renderer %s: %s"%( |
| 367 |
rendName, msg)) |
| 368 |
|
| 369 |
if rend.__doc__: |
| 370 |
content.addHead1("The %s Renderer"%rendName) |
| 371 |
metaStuff = "*This renderer's parameter style is \"%s\"."%( |
| 372 |
rend.parameterStyle) |
| 373 |
if not rend.checkedRenderer: |
| 374 |
metaStuff += " This is an unchecked renderer." |
| 375 |
content.addNormalizedPara(metaStuff+"*") |
| 376 |
content.addNormalizedPara(rend.__doc__) |
| 377 |
return content.content |
| 378 |
|
| 379 |
|
| 380 |
def getTriggerDocs(docStructure): |
| 381 |
from gavo.rscdef import rowtriggers |
| 382 |
return getStructDocsFromRegistry(rowtriggers._triggerRegistry, docStructure) |
| 383 |
|
| 384 |
|
| 385 |
def _documentParameters(content, pars): |
| 386 |
content.makeSpace() |
| 387 |
for par in sorted(pars, key=lambda p: p.key): |
| 388 |
# not all procs have the concept of late, so be defensive here |
| 389 |
if getattr(par, "late", False): |
| 390 |
doc = ["Late p"] |
| 391 |
else: |
| 392 |
doc = ["P"] |
| 393 |
doc.append("arameter *%s*\n"%par.key) |
| 394 |
if par.content_: |
| 395 |
doc.append(" defaults to ``%s``;\n"%par.content_) |
| 396 |
if par.description: |
| 397 |
doc.append(utils.fixIndentation(par.description, " ")) |
| 398 |
else: |
| 399 |
doc.append(" UNDOCUMENTED") |
| 400 |
content.addRaw(''.join(doc)+"\n") |
| 401 |
content.makeSpace() |
| 402 |
|
| 403 |
|
| 404 |
def getMixinDocs(docStructure, mixinIds): |
| 405 |
content = RSTFragment() |
| 406 |
for name in sorted(mixinIds): |
| 407 |
mixin = base.resolveId(None, name) |
| 408 |
content.addHead1("The %s Mixin"%name) |
| 409 |
if mixin.doc is None: |
| 410 |
content.addNormalizedPara("NOT DOCUMENTED") |
| 411 |
else: |
| 412 |
content.addNormalizedPara(mixin.doc) |
| 413 |
if mixin.pars: |
| 414 |
content.addNormalizedPara( |
| 415 |
"This mixin has the following parameters:\n") |
| 416 |
_documentParameters(content, mixin.pars) |
| 417 |
return content.content |
| 418 |
|
| 419 |
|
| 420 |
def _getModuleFunctionDocs(module): |
| 421 |
"""returns documentation for all functions marked with @document in the |
| 422 |
namespace module. |
| 423 |
""" |
| 424 |
res = [] |
| 425 |
for name in dir(module): |
| 426 |
if name.startswith("_"): |
| 427 |
# ignore all private attributes, whatever else happens |
| 428 |
continue |
| 429 |
|
| 430 |
ob = getattr(module, name) |
| 431 |
if hasattr(ob, "buildDocsForThis"): |
| 432 |
if ob.__doc__ is None: # silently ignore if no docstring |
| 433 |
continue |
| 434 |
res.append("``"+name+str(inspect.signature(ob))+"``") |
| 435 |
res.append(utils.fixIndentation(ob.__doc__, " ", 1)) |
| 436 |
res.append("") |
| 437 |
return "\n".join(res) |
| 438 |
|
| 439 |
|
| 440 |
def getRmkFuncs(docStructure): |
| 441 |
from gavo.rscdef import rmkfuncs |
| 442 |
return _getModuleFunctionDocs(rmkfuncs) |
| 443 |
|
| 444 |
|
| 445 |
def getRegtestAssertions(docStructure): |
| 446 |
from gavo.rscdef import regtest |
| 447 |
return _getModuleFunctionDocs(regtest.RegTest) |
| 448 |
|
| 449 |
|
| 450 |
def _getProcdefDocs(procDefs): |
| 451 |
"""returns documentation for the ProcDefs in the sequence procDefs. |
| 452 |
""" |
| 453 |
content = RSTFragment() |
| 454 |
for id, pd in procDefs: |
| 455 |
content.addHead2(id) |
| 456 |
if pd.doc is None: |
| 457 |
content.addNormalizedPara("NOT DOCUMENTED") |
| 458 |
else: |
| 459 |
content.addNormalizedPara(pd.doc) |
| 460 |
content.makeSpace() |
| 461 |
if pd.getSetupPars(): |
| 462 |
content.addNormalizedPara("Setup parameters for the procedure are:\n") |
| 463 |
_documentParameters(content, pd.getSetupPars()) |
| 464 |
return content.content |
| 465 |
|
| 466 |
|
| 467 |
def _makeProcsDocumenter(idList): |
| 468 |
def buildDocs(docStructure): |
| 469 |
return _getProcdefDocs([(id, base.resolveId(None, id)) |
| 470 |
for id in sorted(idList)]) |
| 471 |
return buildDocs |
| 472 |
|
| 473 |
|
| 474 |
def _makeTableDoc(tableDef): |
| 475 |
content = RSTFragment() |
| 476 |
content.addHead1(tableDef.getQName()) |
| 477 |
content.addNormalizedPara("Defined in %s"% |
| 478 |
tableDef.rd.sourceId.replace("__system__", "/")) |
| 479 |
content.addNormalizedPara(base.getMetaText(tableDef, |
| 480 |
"description", default="UNDOCUMENTED")) |
| 481 |
content.makeSpace() |
| 482 |
for col in tableDef: |
| 483 |
content.addDLItem(col.name, |
| 484 |
"(%s) -- %s"%(col.type, col.description)) |
| 485 |
content.makeSpace() |
| 486 |
return "".join(content.content) |
| 487 |
|
| 488 |
|
| 489 |
def makeSystemTablesList(docStructure): |
| 490 |
parts = [] |
| 491 |
for rdName in pkg_resources.resource_listdir( |
| 492 |
"gavo", "resources/inputs/__system__"): |
| 493 |
if not rdName.endswith(".rd"): |
| 494 |
continue |
| 495 |
|
| 496 |
try: |
| 497 |
for tableDef in base.caches.getRD("//"+rdName).tables: |
| 498 |
if tableDef.onDisk: |
| 499 |
parts.append((tableDef.getQName(), _makeTableDoc(tableDef))) |
| 500 |
except base.Error: |
| 501 |
base.ui.notifyError("Bad system RD: %s"%rdName) |
| 502 |
|
| 503 |
return "\n".join(content for _, content in sorted(parts)) |
| 504 |
|
| 505 |
|
| 506 |
def getStreamsDoc(idList): |
| 507 |
content = RSTFragment() |
| 508 |
for id in idList: |
| 509 |
stream = base.resolveId(None, id) |
| 510 |
content.addHead2(id) |
| 511 |
if stream.doc is None: |
| 512 |
raise base.ReportableError("Stream %s has no doc -- don't include in" |
| 513 |
" reference documentation."%id) |
| 514 |
content.addNormalizedPara(stream.doc) |
| 515 |
content.makeSpace() |
| 516 |
|
| 517 |
if stream.DEFAULTS and stream.DEFAULTS.defaults: |
| 518 |
content.addNormalizedPara("*Defaults* for macros used in this stream:") |
| 519 |
content.makeSpace() |
| 520 |
for key, value in sorted(stream.DEFAULTS.defaults.items()): |
| 521 |
content.addULItem("%s: '%s'"%(key, value)) |
| 522 |
content.makeSpace() |
| 523 |
|
| 524 |
return content.content |
| 525 |
|
| 526 |
|
| 527 |
def getMetaKeyDocs(): |
| 528 |
from gavo.base import meta |
| 529 |
content = RSTFragment() |
| 530 |
d = meta.META_CLASSES_FOR_KEYS |
| 531 |
for metaKey in sorted(d): |
| 532 |
content.addDefinition(metaKey, |
| 533 |
d[metaKey].__doc__ or "NOT DOCUMENTED") |
| 534 |
return content.content |
| 535 |
|
| 536 |
|
| 537 |
NO_API_SYMBOLS = frozenset(["AdhocQuerier", |
| 538 |
"addCartesian", |
| 539 |
"combinePMs", "getBinaryName", "getDefaultValueParsers", "getHTTPPar", |
| 540 |
"makeProc", "ParseOptions"]) |
| 541 |
|
| 542 |
def getAPIDocs(docStructure): |
| 543 |
from gavo import api |
| 544 |
content = RSTFragment() |
| 545 |
|
| 546 |
for name in sorted(dir(api)): |
| 547 |
if name.startswith("_"): |
| 548 |
continue |
| 549 |
|
| 550 |
obj = getattr(api, name) |
| 551 |
if (name in NO_API_SYMBOLS |
| 552 |
or type(obj)==type(re) |
| 553 |
or not obj.__doc__): |
| 554 |
continue |
| 555 |
|
| 556 |
whatsit = "" |
| 557 |
if type(obj)==type(getMetaKeyDocs): |
| 558 |
whatsit = "Function " |
| 559 |
elif type(obj)==type: |
| 560 |
whatsit = "Class " |
| 561 |
elif isinstance(obj, float): |
| 562 |
whatsit = "Constant " |
| 563 |
|
| 564 |
content.addHead2(whatsit+name) |
| 565 |
content.makeSpace() |
| 566 |
if whatsit=="Function ": |
| 567 |
content.addNormalizedPara( |
| 568 |
"Signature: ``{}{}``".format(name, str(inspect.signature(obj)))) |
| 569 |
content.makeSpace() |
| 570 |
|
| 571 |
if whatsit=="Constant ": |
| 572 |
content.addNormalizedPara("A constant, valued %s"%obj) |
| 573 |
else: |
| 574 |
content.addNormalizedPara(obj.__doc__) |
| 575 |
|
| 576 |
return content.content |
| 577 |
|
| 578 |
|
| 579 |
_replaceWithResultPat = re.compile(".. replaceWithResult (.*)") |
| 580 |
|
| 581 |
def makeReferenceDocs(): |
| 582 |
"""returns a restructured text containing the reference documentation |
| 583 |
built from the template in refdoc.rstx. |
| 584 |
|
| 585 |
**WARNING**: refdoc.rstx can execute arbitrary code right now. We |
| 586 |
probably want to change this to having macros here. |
| 587 |
""" |
| 588 |
if not os.path.exists("refdoc.rstx"): |
| 589 |
raise base.ReportableError("This needs to be run in the docs" |
| 590 |
" directory of a checkout or source tarball (the location" |
| 591 |
" of refdoc.rstx).") |
| 592 |
|
| 593 |
res, docStructure = [], DocumentStructure() |
| 594 |
f = open("refdoc.rstx", "rb") |
| 595 |
|
| 596 |
parseState = "content" |
| 597 |
code = [] |
| 598 |
|
| 599 |
for lnCount, ln in enumerate(f): |
| 600 |
ln = ln.decode("utf-8") |
| 601 |
if parseState=="content": |
| 602 |
mat = _replaceWithResultPat.match(ln) |
| 603 |
if mat: |
| 604 |
code.append(mat.group(1)) |
| 605 |
parseState = "code" |
| 606 |
else: |
| 607 |
res.append(ln) |
| 608 |
|
| 609 |
elif parseState=="code": |
| 610 |
if ln.strip(): |
| 611 |
code.append(ln) |
| 612 |
else: |
| 613 |
try: |
| 614 |
res.extend(eval(" ".join(code))) |
| 615 |
except Exception: |
| 616 |
sys.stderr.write("Invalid code near line %s: '%s'\n"%( |
| 617 |
lnCount, " ".join(code))) |
| 618 |
raise |
| 619 |
code = [] |
| 620 |
parseState = "content" |
| 621 |
res.append("\n") |
| 622 |
|
| 623 |
else: |
| 624 |
# unknown state |
| 625 |
assert False |
| 626 |
|
| 627 |
f.close() |
| 628 |
docStructure.fillOut(res) |
| 629 |
return ("..\n WARNING: GENERATED DOCUMENT.\n" |
| 630 |
" Edit this in refdoc.rstx or the DaCHS source code.\n\n")+"".join(res) |
| 631 |
|
| 632 |
|
| 633 |
def _getAnnotationsForStructure(structClass): |
| 634 |
"""returns extra mypy annotations for structClass. |
| 635 |
|
| 636 |
This is a helper for collectCreatedAttributes. |
| 637 |
""" |
| 638 |
attrs = [ |
| 639 |
("managedAttrs", "Dict[str, Any]"), |
| 640 |
# really, attrSeq: List[base.AttributeDef], but I'm not sure |
| 641 |
# how to sneak that name in whereever we might need it. |
| 642 |
("attrSeq", "List[]")] |
| 643 |
for attName, att in structClass.managedAttrs.items(): |
| 644 |
attrs.append((attName, att.typingType_)) |
| 645 |
|
| 646 |
for methName, meth in att.iterParentMethods(): |
| 647 |
typeAnn = "Callable" |
| 648 |
if getattr(meth, "__annotations__", None): |
| 649 |
# TODO: we should annotate the arguments, too |
| 650 |
typeAnn = 'Callable[..., "{}"]'.format( |
| 651 |
meth.__annotations__["return"].__name__) |
| 652 |
attrs.append((methName, typeAnn)) |
| 653 |
|
| 654 |
return attrs |
| 655 |
|
| 656 |
|
| 657 |
def _getAnnotationsForElement(element): |
| 658 |
"""returns extra mypy annotations for a stanxml element |
| 659 |
|
| 660 |
This is a helper for collectCreatedAttributes. |
| 661 |
""" |
| 662 |
attrs = [("_nodeAttrs", "List")] |
| 663 |
for name, default in element._nodeAttrs: |
| 664 |
attrs.append((name, "Any")) |
| 665 |
return attrs |
| 666 |
|
| 667 |
|
| 668 |
def collectCreatedAttributes(): |
| 669 |
"""Collects attributes created from DaCHS metaclasses for mypy type |
| 670 |
checking. |
| 671 |
|
| 672 |
This records the global class name, as well as the names of |
| 673 |
the attributes and their attribute descriptors, and writes it |
| 674 |
next to the mypy plugin for dealing with our Structure-s and stanxml |
| 675 |
Elements. |
| 676 |
|
| 677 |
In the case of structures, it relies on annotation left by |
| 678 |
base.structure.buildstructure; I'm still planning on migrating from |
| 679 |
the StructType metaclass to class decorators. |
| 680 |
""" |
| 681 |
import gc |
| 682 |
|
| 683 |
classes = {} |
| 684 |
for item in gc.get_objects(): |
| 685 |
if isinstance(item, type): |
| 686 |
if hasattr(item, "STRUCT_SENTINEL"): |
| 687 |
ann = _getAnnotationsForStructure(item) |
| 688 |
elif issubclass(item, stanxml.Element): |
| 689 |
ann = _getAnnotationsForElement(item) |
| 690 |
else: |
| 691 |
# something that's not our business |
| 692 |
continue |
| 693 |
classes[".".join([item.__module__, item.__qualname__])] = ann |
| 694 |
|
| 695 |
return classes |
| 696 |
|
| 697 |
|
| 698 |
@exposedFunction([], help="Writes ReStructuredText for the reference" |
| 699 |
" documentation to stdout. As a side effect, it also records" |
| 700 |
" struct attributes for mypy use.") |
| 701 |
def refdoc(args): |
| 702 |
sys.stdout.buffer.write(makeReferenceDocs( |
| 703 |
).replace("\t", " " |
| 704 |
).encode("utf-8")) |
| 705 |
|
| 706 |
attrs = collectCreatedAttributes() |
| 707 |
with open("../utils/struct-attrs.json", "w") as f: |
| 708 |
json.dump(attrs, f) |
| 709 |
|
| 710 |
|
| 711 |
@exposedFunction([Arg(help="Input file name", dest="src")], |
| 712 |
help="Turns ReStructured text (with DaCHS extensions) to LaTeX source") |
| 713 |
def latex(args): |
| 714 |
from docutils import core |
| 715 |
locale.setlocale(locale.LC_ALL, '') |
| 716 |
sys.argv[1:] = ( |
| 717 |
"--documentoptions=11pt,a4paper --stylesheet stylesheet.tex" |
| 718 |
" --use-latex-citations").split() |
| 719 |
|
| 720 |
# Hm... I need to record *somewhere* that the two big documents |
| 721 |
# ought to use book. This isn't a good place, but the doc Makefile |
| 722 |
# isn't either. Hm. |
| 723 |
if (args.src.endswith("tutorial.rstx") |
| 724 |
or args.src.endswith("ref.rstx")): |
| 725 |
sys.argv.append("--documentclass=book") |
| 726 |
|
| 727 |
sys.argv.append(args.src) |
| 728 |
|
| 729 |
core.publish_cmdline(writer_name='latex', description="(DaCHS rst2latex)") |
| 730 |
|
| 731 |
|
| 732 |
@exposedFunction([Arg(help="Input file name", dest="src")], |
| 733 |
help="Turns ReStructured text (with DaCHS extensions) to HTML") |
| 734 |
def html(args): |
| 735 |
from docutils import core |
| 736 |
locale.setlocale(locale.LC_ALL, '') |
| 737 |
# TODO: actually determine template path |
| 738 |
sys.argv[1:] = ("--template rst2html-template.txt --stylesheet ref.css" |
| 739 |
" --link-stylesheet").split() |
| 740 |
sys.argv.append(args.src) |
| 741 |
core.publish_cmdline(writer_name='html', description="(DaCHS rst2html)") |
| 742 |
|
| 743 |
|
| 744 |
def main(): |
| 745 |
args = makeCLIParser(globals()).parse_args() |
| 746 |
args.subAction(args) |
| 747 |
|
| 748 |
|
| 749 |
if __name__=="__main__": # pragma: no cover |
| 750 |
docStructure = DocumentStructure() |
| 751 |
print("".join(getStructDocs(docStructure))) |