Skip to content

Commit

Permalink
Auto format all python files with black
Browse files Browse the repository at this point in the history
Excluding the parser files which are auto-generated once upon a time
possibly best left out for the moment.
  • Loading branch information
michaeljones committed Sep 28, 2021
1 parent 2b4924d commit 5520890
Show file tree
Hide file tree
Showing 32 changed files with 1,486 additions and 1,256 deletions.
3 changes: 2 additions & 1 deletion breathe-apidoc.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import sys

if __name__ == '__main__':
if __name__ == "__main__":
from breathe.apidoc import main

sys.exit(main())
8 changes: 2 additions & 6 deletions breathe/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,12 @@

from sphinx.application import Sphinx

__version__ = '4.31.0'
__version__ = "4.31.0"


def setup(app: Sphinx):
directive_setup(app)
file_state_cache_setup(app)
renderer_setup(app)

return {
'version': __version__,
'parallel_read_safe': True,
'parallel_write_safe': True
}
return {"version": __version__, "parallel_read_safe": True, "parallel_write_safe": True}
169 changes: 104 additions & 65 deletions breathe/apidoc.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,22 +35,18 @@
# Reference: Doxygen XSD schema file, CompoundKind only
# Only what breathe supports are included
# Translates identifier to English
TYPEDICT = {'class': 'Class',
'interface': 'Interface',
'struct': 'Struct',
'union': 'Union',
'file': 'File',
'namespace': 'Namespace',
'group': 'Group'}
TYPEDICT = {
"class": "Class",
"interface": "Interface",
"struct": "Struct",
"union": "Union",
"file": "File",
"namespace": "Namespace",
"group": "Group",
}

# Types that accept the :members: option.
MEMBERS_TYPES = [
'class',
'group',
'interface',
'namespace',
'struct'
]
MEMBERS_TYPES = ["class", "group", "interface", "namespace", "struct"]


def print_info(msg, args):
Expand All @@ -60,47 +56,49 @@ def print_info(msg, args):

def write_file(name, text, args):
"""Write the output file for module/package <name>."""
fname = os.path.join(args.destdir, '%s.%s' % (name, args.suffix))
fname = os.path.join(args.destdir, "%s.%s" % (name, args.suffix))
if args.dryrun:
print_info('Would create file %s.' % fname, args)
print_info("Would create file %s." % fname, args)
return
if not args.force and os.path.isfile(fname):
print_info('File %s already exists, skipping.' % fname, args)
print_info("File %s already exists, skipping." % fname, args)
else:
print_info('Creating file %s.' % fname, args)
print_info("Creating file %s." % fname, args)
if not os.path.exists(os.path.dirname(fname)):
try:
os.makedirs(os.path.dirname(fname))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise
try:
with open(fname, 'r') as target:
with open(fname, "r") as target:
orig = target.read()
if orig == text:
print_info('File %s up to date, skipping.' % fname, args)
print_info("File %s up to date, skipping." % fname, args)
return
except FileNotFoundError:
# Don't mind if it isn't there
pass

with open(fname, 'w') as target:
with open(fname, "w") as target:
target.write(text)


def format_heading(level, text):
"""Create a heading of <level> [1, 2 or 3 supported]."""
underlining = ['=', '-', '~', ][level - 1] * len(text)
return '%s\n%s\n\n' % (text, underlining)
underlining = ["=", "-", "~",][
level - 1
] * len(text)
return "%s\n%s\n\n" % (text, underlining)


def format_directive(package_type, package, args):
"""Create the breathe directive and add the options."""
directive = '.. doxygen%s:: %s\n' % (package_type, package)
directive = ".. doxygen%s:: %s\n" % (package_type, package)
if args.project:
directive += ' :project: %s\n' % args.project
directive += " :project: %s\n" % args.project
if args.members and package_type in MEMBERS_TYPES:
directive += ' :members:\n'
directive += " :members:\n"
return directive


Expand All @@ -109,7 +107,7 @@ def create_package_file(package, package_type, package_id, args):
# Skip over types that weren't requested
if package_type not in args.outtypes:
return
text = format_heading(1, '%s %s' % (TYPEDICT[package_type], package))
text = format_heading(1, "%s %s" % (TYPEDICT[package_type], package))
text += format_directive(package_type, package, args)

write_file(os.path.join(package_type, package_id), text, args)
Expand All @@ -119,35 +117,36 @@ def create_modules_toc_file(key, value, args):
"""Create the module's index."""
if not os.path.isdir(os.path.join(args.destdir, key)):
return
text = format_heading(1, '%s list' % value)
text += '.. toctree::\n'
text += ' :glob:\n\n'
text += ' %s/*\n' % key
text = format_heading(1, "%s list" % value)
text += ".. toctree::\n"
text += " :glob:\n\n"
text += " %s/*\n" % key

write_file('%slist' % key, text, args)
write_file("%slist" % key, text, args)


def recurse_tree(args):
"""
Look for every file in the directory tree and create the corresponding
ReST files.
"""
index = xml.etree.ElementTree.parse(os.path.join(args.rootpath, 'index.xml'))
index = xml.etree.ElementTree.parse(os.path.join(args.rootpath, "index.xml"))

# Assuming this is a valid Doxygen XML
for compound in index.getroot():
create_package_file(compound.findtext('name'), compound.get('kind'),
compound.get('refid'), args)
create_package_file(
compound.findtext("name"), compound.get("kind"), compound.get("refid"), args
)


class TypeAction(argparse.Action):
def __init__(self, option_strings, dest, **kwargs):
super(TypeAction, self).__init__(option_strings, dest, **kwargs)
self.default = TYPEDICT.keys()
self.metavar = ','.join(TYPEDICT.keys())
self.metavar = ",".join(TYPEDICT.keys())

def __call__(self, parser, namespace, values, option_string=None):
value_list = values.split(',')
value_list = values.split(",")
for value in value_list:
if value not in TYPEDICT:
raise ValueError("%s not a valid option" % value)
Expand All @@ -162,39 +161,79 @@ def main():
breathe generation directives per definition in the <DESTDIR>.
Note: By default this script will not overwrite already created files.""",
formatter_class=argparse.RawDescriptionHelpFormatter)

parser.add_argument('-o', '--output-dir', action='store', dest='destdir',
help='Directory to place all output', required=True)
parser.add_argument('-f', '--force', action='store_true', dest='force',
help='Overwrite existing files')
parser.add_argument('-m', '--members', action='store_true', dest='members',
help='Include members for types: %s' % MEMBERS_TYPES)
parser.add_argument('-n', '--dry-run', action='store_true', dest='dryrun',
help='Run the script without creating files')
parser.add_argument('-T', '--no-toc', action='store_true', dest='notoc',
help='Don\'t create a table of contents file')
parser.add_argument('-s', '--suffix', action='store', dest='suffix',
help='file suffix (default: rst)', default='rst')
parser.add_argument('-p', '--project', action='store', dest='project',
help='project to add to generated directives')
parser.add_argument('-g', '--generate', action=TypeAction, dest='outtypes',
help='types of output to generate, comma-separated list')
parser.add_argument('-q', '--quiet', action='store_true', dest='quiet',
help='suppress informational messages')
parser.add_argument('--version', action='version',
version='Breathe (breathe-apidoc) %s' % __version__)
parser.add_argument('rootpath', type=str,
help='The directory contains index.xml')
formatter_class=argparse.RawDescriptionHelpFormatter,
)

parser.add_argument(
"-o",
"--output-dir",
action="store",
dest="destdir",
help="Directory to place all output",
required=True,
)
parser.add_argument(
"-f", "--force", action="store_true", dest="force", help="Overwrite existing files"
)
parser.add_argument(
"-m",
"--members",
action="store_true",
dest="members",
help="Include members for types: %s" % MEMBERS_TYPES,
)
parser.add_argument(
"-n",
"--dry-run",
action="store_true",
dest="dryrun",
help="Run the script without creating files",
)
parser.add_argument(
"-T",
"--no-toc",
action="store_true",
dest="notoc",
help="Don't create a table of contents file",
)
parser.add_argument(
"-s",
"--suffix",
action="store",
dest="suffix",
help="file suffix (default: rst)",
default="rst",
)
parser.add_argument(
"-p",
"--project",
action="store",
dest="project",
help="project to add to generated directives",
)
parser.add_argument(
"-g",
"--generate",
action=TypeAction,
dest="outtypes",
help="types of output to generate, comma-separated list",
)
parser.add_argument(
"-q", "--quiet", action="store_true", dest="quiet", help="suppress informational messages"
)
parser.add_argument(
"--version", action="version", version="Breathe (breathe-apidoc) %s" % __version__
)
parser.add_argument("rootpath", type=str, help="The directory contains index.xml")
args = parser.parse_args()

if args.suffix.startswith('.'):
if args.suffix.startswith("."):
args.suffix = args.suffix[1:]
if not os.path.isdir(args.rootpath):
print('%s is not a directory.' % args.rootpath, file=sys.stderr)
print("%s is not a directory." % args.rootpath, file=sys.stderr)
sys.exit(1)
if 'index.xml' not in os.listdir(args.rootpath):
print('%s does not contain a index.xml' % args.rootpath, file=sys.stderr)
if "index.xml" not in os.listdir(args.rootpath):
print("%s does not contain a index.xml" % args.rootpath, file=sys.stderr)
sys.exit(1)
if not os.path.isdir(args.destdir):
if not args.dryrun:
Expand Down
57 changes: 34 additions & 23 deletions breathe/directives/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,19 @@ def __init__(self, state, context: Dict[str, Any]) -> None:
self.state = state
self.context = context

def warn(self, raw_text: str, *, rendered_nodes: Sequence[nodes.Node] = None,
unformatted_suffix: str = '') -> List[nodes.Node]:
def warn(
self,
raw_text: str,
*,
rendered_nodes: Sequence[nodes.Node] = None,
unformatted_suffix: str = ""
) -> List[nodes.Node]:
raw_text = self.format(raw_text) + unformatted_suffix
if rendered_nodes is None:
rendered_nodes = [nodes.paragraph("", "", nodes.Text(raw_text))]
return [
nodes.warning("", *rendered_nodes),
self.state.document.reporter.warning(raw_text, line=self.context['lineno'])
self.state.document.reporter.warning(raw_text, line=self.context["lineno"]),
]

def format(self, text: str) -> str:
Expand All @@ -42,10 +47,13 @@ class BaseDirective(SphinxDirective):
has_content: bool
final_argument_whitespace: bool

def __init__(self, finder_factory: FinderFactory,
project_info_factory: ProjectInfoFactory,
parser_factory: DoxygenParserFactory,
*args) -> None:
def __init__(
self,
finder_factory: FinderFactory,
project_info_factory: ProjectInfoFactory,
parser_factory: DoxygenParserFactory,
*args
) -> None:
super().__init__(*args)
self.directive_args = list(args) # Convert tuple to list to allow modification.

Expand All @@ -61,22 +69,23 @@ def kind(self) -> str:
def create_warning(self, project_info: Optional[ProjectInfo], **kwargs) -> _WarningHandler:
if project_info:
tail = 'in doxygen xml output for project "{project}" from directory: {path}'.format(
project=project_info.name(),
path=project_info.project_path()
project=project_info.name(), path=project_info.project_path()
)
else:
tail = ''
tail = ""

context = dict(
lineno=self.lineno,
tail=tail,
**kwargs
)
context = dict(lineno=self.lineno, tail=tail, **kwargs)
return _WarningHandler(self.state, context)

def render(self, node_stack, project_info: ProjectInfo, filter_: Filter,
target_handler: TargetHandler, mask_factory: MaskFactoryBase,
directive_args) -> List[Node]:
def render(
self,
node_stack,
project_info: ProjectInfo,
filter_: Filter,
target_handler: TargetHandler,
mask_factory: MaskFactoryBase,
directive_args,
) -> List[Node]:
"Standard render process used by subclasses"

try:
Expand All @@ -88,14 +97,16 @@ def render(self, node_stack, project_info: ProjectInfo, filter_: Filter,
self.state.document,
target_handler,
self.parser_factory.create_compound_parser(project_info),
filter_
filter_,
)
except ParserError as e:
return format_parser_error("doxygenclass", e.error, e.filename, self.state,
self.lineno, True)
return format_parser_error(
"doxygenclass", e.error, e.filename, self.state, self.lineno, True
)
except FileIOError as e:
return format_parser_error("doxygenclass", e.error, e.filename, self.state,
self.lineno, True)
return format_parser_error(
"doxygenclass", e.error, e.filename, self.state, self.lineno, True
)

context = RenderContext(node_stack, mask_factory, directive_args)
return object_renderer.render(node_stack[0], context)
Loading

0 comments on commit 5520890

Please sign in to comment.