Last active
December 22, 2021 21:33
-
-
Save gwerbin/7d5705b5605c5b60a3c157efd0d19d26 to your computer and use it in GitHub Desktop.
Convert a filename into a Python module name
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env zsh | |
setopt \ | |
err_exit \ | |
pipe_fail \ | |
warn_create_global \ | |
warn_nested_var \ | |
no_unset | |
version='1.0.0' | |
help='Usage: | |
python-module-name [options] <file> [files...] | |
Options: | |
-V/--version Show the program version and exit. | |
-h/--help Show this text and exit. | |
-t/--toplevel <path> Set the "top level" directory for module names. Defaults to | |
`-t .` if omitted. Similar to Python `unittest -t`.' | |
typeset -A opts=( | |
'--toplevel' '.' | |
) | |
zparseopts -D -K -M -A opts \ | |
-help h=-help \ | |
-version V=-version \ | |
-toplevel: t:=-toplevel | |
if (( ${+opts[--help]} != 0 )); then | |
print -- "$help" | |
exit 0 | |
fi | |
if (( ${+opts[--version]} != 0 )); then | |
print -- "$version" | |
exit 0 | |
fi | |
toplevel=${opts[--toplevel]:a} | |
if (( $# < 1 )); then | |
print -u2 -- 'Not enough arguments: at least one filename is required.' | |
print -u2 -- '' | |
print -u2 -- "$help" | |
exit 2 | |
fi | |
for file in "$@"; do | |
module_source=${file:a} | |
if [[ ${module_source:t} = '__init__.py' ]]; then | |
module_source=${module_source:h} | |
fi | |
module_name=${${${${module_source%.py}#$toplevel}#/}//\//.} | |
print -- $module_name | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment