Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Auto-format python code with 'black' #743

Merged
merged 5 commits into from
Sep 29, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,12 @@ jobs:
- name: install dependencies
run: |
pip install -r requirements/development.txt
pip install flake8

- name: lint the source code
run: make flake8

- name: check source code formatting
run: make black

- name: type check the source code
run: make type-check
4 changes: 4 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ flake8:
breathe/renderer/filter.py \
breathe/parser/compound.py

.PHONY: black
black:
black --check .

.PHONY: type-check
type-check:
mypy breathe tests
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
Loading