jw-pkg/scripts/python-tools.sh
Jan Lindemann fc6f2fbb65
python-tools.sh: Fix __init__.py linter complaints
The __init__.py files as gnerated by python-tools.sh contain multiple
issues, fix them:

  - Make the machinery fail if the same type name is imported from
    different modules

  - Support relative imports from .Module import Module instead of
    having to use the entire module path as import source

  - Import types explicitly re-exported with "as":

      from .Module import Module as Module

    Otherwise ruff will regard the type as "imported but not used"

  - Add "# ruff: noqa: E501" near the top. The import lines can get
    long and are beyond manual control (except for renaming the
    modules themselves, that is). This can cause ruff to fail, so get
    it to accept long lines in __init__.py. The style violation
    doesn't make much of a difference in generated code, anyway,
    because nobody reads that. Plus what's happening in the code
    isn't rocket science, so good style wouldn't help much with
    understanding, either.

This promptly digs up two symbol name conflicts lib.pm.dpkg and
lib.pm.rpm. Fix them along with this commit to keep it from breaking the build.

Signed-off-by: Jan Lindemann <jan@janware.com>
2026-05-31 17:51:51 +02:00

95 lines
1.5 KiB
Shell

#!/bin/bash
log()
{
echo "$myname: $*" >&2
}
fatal()
{
echo "$myname: Fatal: $*" >&2
exit 1
}
usage()
{
cat <<-EOT
usage $myname [-e sed-extract-command] [-m module] file.py ...
EOT
[ "$1" ] && exit $1
}
module_path()
{
if [ "$module" = "." ]; then
echo .$1
elif [ "$module" ]; then
echo $module.$1
else
echo $1
fi
}
cmd_create_init()
{
local import_submodules=0
local files="$*"
local del="-------------------------- generated by $myname"
echo "# >> $del >>"
echo "# ruff: noqa: E501"
echo "from pkgutil import extend_path"
echo "__path__ = extend_path(__path__, __name__)"
local f
local -A seen=()
for f in $files; do
test -d $f && continue
local base=${f##*/}
base=${base%.py}
if [ "$sed_extract_command" ]; then
local type types=`sed "$sed_extract_command" $f`
for type in $types; do
echo "from `module_path $base` import $type as $type"
[[ -n "${seen[$type]+x}" ]] && fatal "Duplicate symbol: $type"
seen["$type"]=1
done
fi
done
if [ "$import_submodules" = 1 ]; then
for f in $files; do
[ -f $f/__init__.py ] && echo "import `module_path $f` as $f"
done
fi
echo "# << $del <<"
}
# --------------------- here we go
myname=`basename $0`
eval set -- `getopt -o 'he:m:' "$@"`
while [ "$1" != -- ]; do
case $1 in
-e)
sed_extract_command="$2"
shift
;;
-m)
module=$2
shift
;;
-h)
usage 0;;
*)
echo unknown argument $1
usage 1;;
esac
shift
done
shift
cmd=cmd_${1//-/_}
shift
eval $cmd $*