Skip to content
Draft
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
117 changes: 29 additions & 88 deletions ament_pep257/ament_pep257/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,32 +14,33 @@
# See the License for the specific language governing permissions and
# limitations under the License.


import argparse
import logging
from importlib.util import find_spec
import os
import shutil
import sys
import time
from typing import Literal
from xml.sax.saxutils import escape
from xml.sax.saxutils import quoteattr

import pydocstyle
from pydocstyle import check

try: # as of version 1.1.0
from pydocstyle.config import ConfigurationParser
from pydocstyle.violations import Error
from pydocstyle.utils import log
except ImportError: # try version 1.0.0
from pydocstyle import ConfigurationParser
from pydocstyle import Error
from pydocstyle import log

log.setLevel(logging.INFO)
ruff_installed = False
pydocstyle_installed = False

if shutil.which('ruff'):
ruff_installed = True
else:
ruff_installed = False

_conventions = set(pydocstyle.conventions.keys())
_conventions.add('ament')
if find_spec('pydocstyle'):
pydocstyle_installed = True
import pydocstyle
_conventions = set(pydocstyle.conventions.keys())
_conventions.add('ament')
else:
pydocstyle_installed = False
_conventions = {'pep257', 'numpy', 'google', 'ament'}

_ament_ignore = [
'D100',
Expand Down Expand Up @@ -123,8 +124,18 @@ def main(argv: list[str] = sys.argv[1:]) -> Literal[0, 1]:
args.ignore = ','.join(_ament_ignore)

excludes = [os.path.abspath(e) for e in args.excludes]
report = generate_pep257_report(args.paths, excludes, args.ignore, args.select,
args.convention, args.add_ignore, args.add_select)

if ruff_installed:
from ament_pep257.ruff_impl import generate_ruff_report
report = generate_ruff_report(args.paths, excludes, args.ignore, args.select,
args.convention, args.add_ignore, args.add_select)
elif pydocstyle_installed:
from ament_pep257.pydocstyle_impl import generate_pep257_report
report = generate_pep257_report(args.paths, excludes, args.ignore, args.select,
args.convention, args.add_ignore, args.add_select)
else:
print('Neither ruff or pydocstyle installed')
return 1
error_count = sum(len(r[1]) for r in report)

# print summary
Expand Down Expand Up @@ -162,76 +173,6 @@ def _filename_in_excludes(filename, excludes):
return any(os.path.commonpath([absname, e]) == e for e in excludes)


def generate_pep257_report(paths, excludes, ignore, select, convention, add_ignore, add_select):
conf = ConfigurationParser()
sys_argv = sys.argv
sys.argv = [
'main',
'--match', r'.*\.py',
'--match-dir', r'[^\._].*',
]
if ignore:
sys.argv += ['--ignore', ignore]
elif select:
sys.argv += ['--select', select]
else:
sys.argv += ['--convention', convention]
if add_ignore:
sys.argv += ['--add-ignore', add_ignore]
if add_select:
sys.argv += ['--add-select', add_select]
sys.argv += paths
conf.parse()
sys.argv = sys_argv
files_to_check = conf.get_files_to_check()

report = []

files_dict = {}
# Unpack 3 values for pydocstyle <= 6.1.1 and 4 values for pydocstyle >= 6.2.0
for filename, checked_codes, ignore_decorators, *_ in files_to_check:
if _filename_in_excludes(filename, excludes):
continue
files_dict[filename] = {
'select': checked_codes,
'ignore_decorators': ignore_decorators,
}

for filename in sorted(files_dict.keys()):
print('checking', filename)
errors = []
pep257_errors = check(
[filename],
**files_dict[filename])
for pep257_error in pep257_errors:
if isinstance(pep257_error, Error):
errors.append({
'category': pep257_error.code,
'linenumber': pep257_error.line,
'message': pep257_error.message,
})
print(
'%s:%d %s: %s' %
(pep257_error.filename, pep257_error.line, pep257_error.definition,
pep257_error.message), file=sys.stderr)
elif isinstance(pep257_error, SyntaxError):
errors.append({
'category': str(type(pep257_error)),
'linenumber': '-',
'message': 'invalid syntax in file',
})
print('%s: invalid syntax' % filename, file=sys.stderr)
else:
errors.append({
'category': 'unknown',
'linenumber': '-',
'message': str(pep257_error),
})
print('%s: %s' % (filename, pep257_error), file=sys.stderr)
report.append((filename, errors))
return report


def get_xunit_content(report, testname, elapsed):
test_count = sum(max(len(r[1]), 1) for r in report)
error_count = sum(len(r[1]) for r in report)
Expand Down
103 changes: 103 additions & 0 deletions ament_pep257/ament_pep257/pydocstyle_impl.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
#!/usr/bin/env python3

# Copyright 2026 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import logging
import sys

from ament_pep257.main import _filename_in_excludes
from pydocstyle import check

try: # as of version 1.1.0
from pydocstyle.config import ConfigurationParser
from pydocstyle.violations import Error
from pydocstyle.utils import log
except ImportError: # try version 1.0.0
from pydocstyle import ConfigurationParser
from pydocstyle import Error
from pydocstyle import log


log.setLevel(logging.INFO)


def generate_pep257_report(paths, excludes, ignore, select, convention, add_ignore, add_select):
conf = ConfigurationParser()
sys_argv = sys.argv
sys.argv = [
'main',
'--match', r'.*\.py',
'--match-dir', r'[^\._].*',
]
if ignore:
sys.argv += ['--ignore', ignore]
elif select:
sys.argv += ['--select', select]
else:
sys.argv += ['--convention', convention]
if add_ignore:
sys.argv += ['--add-ignore', add_ignore]
if add_select:
sys.argv += ['--add-select', add_select]
sys.argv += paths
conf.parse()
sys.argv = sys_argv
files_to_check = conf.get_files_to_check()

report = []

files_dict = {}
# Unpack 3 values for pydocstyle <= 6.1.1 and 4 values for pydocstyle >= 6.2.0
for filename, checked_codes, ignore_decorators, *_ in files_to_check:
if _filename_in_excludes(filename, excludes):
continue
files_dict[filename] = {
'select': checked_codes,
'ignore_decorators': ignore_decorators,
}

for filename in sorted(files_dict.keys()):
print('checking', filename)
errors = []
pep257_errors = check(
[filename],
**files_dict[filename])
for pep257_error in pep257_errors:
if isinstance(pep257_error, Error):
errors.append({
'category': pep257_error.code,
'linenumber': pep257_error.line,
'message': pep257_error.message,
})
print(
'%s:%d %s: %s' %
(pep257_error.filename, pep257_error.line, pep257_error.definition,
pep257_error.message), file=sys.stderr)
elif isinstance(pep257_error, SyntaxError):
errors.append({
'category': str(type(pep257_error)),
'linenumber': '-',
'message': 'invalid syntax in file',
})
print('%s: invalid syntax' % filename, file=sys.stderr)
else:
errors.append({
'category': 'unknown',
'linenumber': '-',
'message': str(pep257_error),
})
print('%s: %s' % (filename, pep257_error), file=sys.stderr)
report.append((filename, errors))
return report
114 changes: 114 additions & 0 deletions ament_pep257/ament_pep257/ruff_impl.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
# Copyright 2026 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


import json
import os
import subprocess
import sys
import re

from ament_pep257.main import _filename_in_excludes


def generate_ruff_report(paths: list[str], excludes: list[str], ignore: str, select: str,
convention: str, add_ignore: str, add_select: str):

cmd = ['ruff', 'check', '--output-format', 'json', '--select', 'D']

if ignore:
cmd += ['--ignore', ignore]
elif select:
cmd += ['--select', select]
else:
cmd += ['--convention', convention]

if add_ignore:
cmd += ['--ignore', add_ignore]

if add_select:
cmd += ['--select', add_select]

# excludes
for e in excludes:
cmd += ['--exclude', e]

# paths
cmd += paths

result = subprocess.run(
cmd,
capture_output=True,
text=True,
)

data = json.loads(result.stdout)

report = []

# Handles missing files
if result.stderr:
warnings = result.stderr.splitlines()
for line in warnings:
match = re.search(r"Failed to lint (.*?):", line)
if match:
filename = match.group(1)
report.append((filename, [
{'category': 'unknown',
'linenumber': 'N/A',
'message': line
}]))
print(
'%s:%s %s: %s' % (
filename,
'N/A',
'N/A',
line,
),
file=sys.stderr,
)
files_dict = {}

for item in data:
filename = os.path.relpath(item['filename'])

if _filename_in_excludes(filename, excludes):
continue

files_dict.setdefault(filename, []).append(item)

for filename in sorted(files_dict.keys()):
print('checking', filename)
errors = []

for err in files_dict[filename]:
errors.append({
'category': err.get('code', 'unknown'),
'linenumber': err.get('location', {}).get('row', '-'),
'message': err.get('message', ''),
})

print(
'%s:%s %s: %s' % (
filename,
err.get('location', {}).get('row', '-'),
err.get('code', 'unknown'),
err.get('message', ''),
),
file=sys.stderr,
)

report.append((filename, errors))

return report
3 changes: 3 additions & 0 deletions ament_pep257/package.xml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@
<author email="michel@ekumenlabs.com">Michel Hidalgo</author>

<exec_depend>ament_lint</exec_depend>

<!-- change on rosdistro to pydocstyle_impl -->
<!-- ruff on rhel 10 and pydocstyle elsewhere -->
<exec_depend>pydocstyle</exec_depend>

<test_depend>ament_flake8</test_depend>
Expand Down
Loading