diff --git a/.hunspell.en.dic b/.hunspell.en.dic index d7acd730f..93a9f1f87 100644 --- a/.hunspell.en.dic +++ b/.hunspell.en.dic @@ -753,6 +753,7 @@ readModuleContent readline readlink repo +reindex reportError reportUsage reportWarning diff --git a/INSTALL.rst b/INSTALL.rst index 335c9a420..fa8ee55d7 100644 --- a/INSTALL.rst +++ b/INSTALL.rst @@ -2019,6 +2019,8 @@ installation. | :mconfig:`sticky_purge` | ``error`` | :instopt:`--with-sticky-purge`, | | | | | | :envvar:`MODULES_STICKY_PURGE` | | | +-----------------------------------+----------------------------------------------+----------------------------------------------+--------------+-----------+ +| :mconfig:`subcmd_alias` | *Empty by default* | :envvar:`MODULES_SUBCMD_ALIAS` | | | ++-----------------------------------+----------------------------------------------+----------------------------------------------+--------------+-----------+ | :mconfig:`tag_abbrev` | auto-loaded=aL:loaded=L:hidden=H:\ | :instopt:`--with-tag-abbrev`, | | | | | hidden-loaded=H:forbidden=F:nearly-\ | :envvar:`MODULES_TAG_ABBREV` | | | | | forbidden=nF:sticky=S:super-sticky=sS:\ | | | | diff --git a/MIGRATING.rst b/MIGRATING.rst index acdc7d5f8..42474c8b8 100644 --- a/MIGRATING.rst +++ b/MIGRATING.rst @@ -158,6 +158,46 @@ meantime. :mfcmd:`umask` applies to the shells and scripting languages that are able to change their own mask. See the :ref:`Shell support` section for details. +Defining sub-command aliases +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +People using several tools side by side may expect the same action to bear +the same name in each of them. The :mconfig:`subcmd_alias` configuration +option is introduced to define additional names for the sub-commands of the +:command:`module` and :command:`ml` commands. Its value is a colon-separated +list of ``alias=target`` definitions. + +.. parsed-literal:: + + :ps:`$` module config subcmd_alias find=avail:loaded=list + :ps:`$` module find -t foo + /path/to/modulefiles: + foo/1.0 + foo/2.0 + :ps:`$` ml loaded + No Modulefiles Currently Loaded. + +An alias may bear the name of an existing sub-command, which is then +shadowed. Alias target is always a sub-command of :command:`module`, never +another alias: in the following example ``find`` still designates +:subcmd:`avail`. + +.. parsed-literal:: + + :ps:`$` module config subcmd_alias find=avail:avail=spider + +Defined aliases are listed at the end of the :subcmd:`module help` +usage message and are completed like the sub-command they designate. Aliases +apply to the command line only: :mfcmd:`module` commands written in +modulefiles are not affected. + +When the configuration option is changed from its default value using the +:subcmd:`config` sub-command, the :envvar:`MODULES_SUBCMD_ALIAS` environment +variable is defined accordingly. See the :envvar:`MODULES_SUBCMD_ALIAS` +description for details and the :ref:`spack-like-sub-command-names` cookbook +recipe for a complete example that maps the command names of the Spack +package manager. + v5.7 ---- diff --git a/NEWS.rst b/NEWS.rst index 250c2271b..484a5f2f1 100644 --- a/NEWS.rst +++ b/NEWS.rst @@ -101,6 +101,12 @@ Modules 5.8.0 (not yet released) modulefile command. (fix issue #532) * Fix :command:`ml` command to correctly call a sub-command when command line switches like :option:`--tag` are set before the sub-command name. +* Add the :mconfig:`subcmd_alias` configuration option to define aliases for + module sub-commands. An alias may shadow an existing sub-command and always + designates a sub-command, never another alias. Defined aliases are reported + on usage message and handled by shell completion. When set, the + :envvar:`MODULES_SUBCMD_ALIAS` environment variable supersedes the option + value. (fix issue #712) .. _5.7 release notes: diff --git a/doc/source/changes.rst b/doc/source/changes.rst index 029fdc729..4e879ce01 100644 --- a/doc/source/changes.rst +++ b/doc/source/changes.rst @@ -1162,7 +1162,7 @@ The following environment variables appeared on Modules 5. | | :envvar:`MODULES_SPIDER_JSON_OUTPUT`, | | | :envvar:`__MODULES_PRIORITY_\`, | | | :envvar:`MODULES_FAMILY_\_VERSION`, | -| | :envvar:`__MODULES_UMASK` | +| | :envvar:`__MODULES_UMASK`, :envvar:`MODULES_SUBCMD_ALIAS` | +------------+-----------------------------------------------------------------+ Modules Specific Tcl Commands @@ -1400,7 +1400,7 @@ The following Modules configuration option has been introduced on Modules 5. | | :mconfig:`ignore_cache_subcmds` | +------------+-----------------------------------------------------------------+ | 5.8 | :mconfig:`avail_json_output`, :mconfig:`list_json_output`, | -| | :mconfig:`spider_json_output` | +| | :mconfig:`spider_json_output`, :mconfig:`subcmd_alias` | +------------+-----------------------------------------------------------------+ :mconfig:`auto_handling` diff --git a/doc/source/cookbook/spack-like-sub-command-names.rst b/doc/source/cookbook/spack-like-sub-command-names.rst new file mode 100644 index 000000000..a961fe8f3 --- /dev/null +++ b/doc/source/cookbook/spack-like-sub-command-names.rst @@ -0,0 +1,159 @@ +.. _spack-like-sub-command-names: + +Spack-like sub-command names +============================ + +People using both Modules and the `Spack`_ package manager regularly type the +command name of one tool when using the other. For instance ``spack find`` +lists the installed packages and ``spack list`` the packages that could be +installed, whereas ``module avail`` lists the available modulefiles and +``module list`` the loaded ones. + +This recipe describes how to make the :command:`module` command understand +the command names of Spack. + +.. _Spack: https://spack.io/ + +Implementation +-------------- + +Starting version 5.8, the :mconfig:`subcmd_alias` configuration option defines +additional names for module sub-commands. Its value is a colon-separated list +of ``alias=target`` definitions. + +Following table lists the Spack commands that have an equivalent among module +sub-commands and the alias definition required, if any, to make +:command:`module` accept the Spack name. + ++---------------------+-------------------------------+-------------------------+ +| Spack command | Module sub-command | Alias definition | ++=====================+===============================+=========================+ +| ``spack load`` | :subcmd:`load` | *Same name* | ++---------------------+-------------------------------+-------------------------+ +| ``spack unload`` | :subcmd:`unload` | *Same name* | ++---------------------+-------------------------------+-------------------------+ +| ``spack find`` | :subcmd:`avail` | ``find=avail`` | ++---------------------+-------------------------------+-------------------------+ +| ``spack list`` | :subcmd:`spider` | ``list=spider`` | ++---------------------+-------------------------------+-------------------------+ +| ``spack versions`` | :subcmd:`avail` | ``versions=avail`` | ++---------------------+-------------------------------+-------------------------+ +| ``spack info`` | :subcmd:`help` | ``info=help`` | ++---------------------+-------------------------------+-------------------------+ +| ``spack spec`` | :subcmd:`display` | ``spec=display`` | ++---------------------+-------------------------------+-------------------------+ +| ``spack location`` | :subcmd:`path` | ``location=path`` | ++---------------------+-------------------------------+-------------------------+ +| ``spack edit`` | :subcmd:`edit` | *Same name* | ++---------------------+-------------------------------+-------------------------+ +| ``spack test`` | :subcmd:`test` | *Same name* | ++---------------------+-------------------------------+-------------------------+ +| ``spack audit`` | :subcmd:`lint` | ``audit=lint`` | ++---------------------+-------------------------------+-------------------------+ +| ``spack reindex`` | :subcmd:`cachebuild` | ``reindex=cachebuild`` | ++---------------------+-------------------------------+-------------------------+ +| ``spack clean`` | :subcmd:`cacheclear` | ``clean=cacheclear`` | ++---------------------+-------------------------------+-------------------------+ +| ``spack config`` | :subcmd:`config` | *Same name* | ++---------------------+-------------------------------+-------------------------+ +| ``spack commands`` | :subcmd:`help` | ``commands=help`` | ++---------------------+-------------------------------+-------------------------+ +| ``spack help`` | :subcmd:`help` | *Same name* | ++---------------------+-------------------------------+-------------------------+ + +An installed package in Spack corresponds to a modulefile available in the +enabled modulepaths. The packages Spack knows and could install correspond to +the modulefiles found by :subcmd:`spider` in all the modulepaths, including +those that are not enabled yet. + +The ``list`` alias bears the name of an existing sub-command: it shadows the +:subcmd:`list` sub-command that reports the loaded modulefiles. Spack has no +dedicated command for this, as loaded packages are reported with +``spack find --loaded``. Loaded modulefiles are still obtained with the +:command:`ml` command without argument or with an abbreviation of the +shadowed sub-command, as aliases do not apply to abbreviations. An additional alias may also be defined for this purpose, like +``loaded=list``. + +.. note:: Alias target is always a sub-command of :command:`module` and never + another alias. The ``find=avail`` definition designates the + :subcmd:`avail` sub-command, and would still do if an alias named + ``avail`` was also defined. + +Spack commands that install, build or describe the dependency graph of +packages (``install``, ``uninstall``, ``graph``, ``dependencies``, etc) have +no equivalent, as Modules does not build software. Commands made of several +words, like ``spack env activate``, cannot be mapped either: an alias only +stands for the sub-command name. + +**Compatible with Modules v5.8+** + +Installation +------------ + +To define these aliases for all users, set the configuration option in the +:file:`initrc` configuration file, which is located in the configuration +directory designated by the :instopt:`--etcdir` installation option. + +.. code-block:: none + :caption: initrc + + #%Module + module config subcmd_alias find=avail:list=spider:info=help:spec=display:location=path:versions=avail:commands=help:audit=lint:reindex=cachebuild:clean=cacheclear + +A user may define them on its own by running the same :subcmd:`config` +sub-command in a shell session or by setting the +:envvar:`MODULES_SUBCMD_ALIAS` environment variable in its shell startup +files. + +.. parsed-literal:: + + :ps:`$` module config subcmd_alias find=avail:list=spider:info=help:spec=display:location=path:versions=avail:commands=help:audit=lint:reindex=cachebuild:clean=cacheclear + +When aliases are defined site-wide, a user may add its own definitions or +withdraw some of the site by prefixing the value with ``+`` or ``-``. For +instance to get a ``loaded`` alias in addition to those defined above: + +.. parsed-literal:: + + :ps:`$` module config subcmd_alias +loaded=list + +Usage example +------------- + +With the above configuration set, the Spack command names are accepted by the +:command:`module` and :command:`ml` commands and are completed like the +sub-command they designate: + +.. parsed-literal:: + + :ps:`$` module find -t foo + /path/to/modulefiles: + foo/1.0 + foo/2.0 + :ps:`$` module load foo/2.0 + :ps:`$` module location foo/2.0 + /path/to/modulefiles/foo/2.0 + :ps:`$` module loaded + Currently Loaded Modulefiles: + 1) foo/2.0 + +Defined aliases are reported at the end of the usage message: + +.. parsed-literal:: + + :ps:`$` module help + ... + Sub-command aliases: + audit Alias for 'lint' sub-command + clean Alias for 'cacheclear' sub-command + commands Alias for 'help' sub-command + find Alias for 'avail' sub-command + info Alias for 'help' sub-command + list Alias for 'spider' sub-command + loaded Alias for 'list' sub-command + location Alias for 'path' sub-command + reindex Alias for 'cachebuild' sub-command + spec Alias for 'display' sub-command + versions Alias for 'avail' sub-command + +.. vim:set tabstop=2 shiftwidth=2 expandtab autoindent: diff --git a/doc/source/design/subcmd-alias.rst b/doc/source/design/subcmd-alias.rst new file mode 100644 index 000000000..aa4bd0f69 --- /dev/null +++ b/doc/source/design/subcmd-alias.rst @@ -0,0 +1,131 @@ +.. _subcmd-alias: + +Sub-command aliases +=================== + +This design document describes the :mconfig:`subcmd_alias` configuration +option that defines additional names for the sub-commands of the +:command:`module` command. + +Configuration +------------- + +- :mconfig:`subcmd_alias` configuration option + + - Colon-separated list of ``alias=target`` definitions + - Empty by default, no installation option + - Superseded by the :envvar:`MODULES_SUBCMD_ALIAS` environment variable + - As a list option, elements may be appended or subtracted with the ``+`` + and ``-`` prefixes of the :subcmd:`config` sub-command. A user is this way + able to adapt the definitions made site-wide in :file:`initrc`. + +Definition validity +------------------- + +A definition is taken into account if: + +- it is made of exactly one alias name and one target separated by an equal + sign +- alias name is composed of letters, digits, underscore and hyphen-minus + characters and does not start with an hyphen-minus +- alias name is not ``ml``, which is not a sub-command but a way to call the + :command:`ml` command through :file:`modulecmd.tcl` +- target is a sub-command, designated by its name, one of its predefined + aliases (e.g., ``add``) or abbreviations (e.g., ``av``) + +Other definitions are silently ignored, like done for the other configuration +options holding a list of definitions. When an alias is defined several times, +last definition applies. + +The character set allowed for alias names is restricted on purpose. Alias +names are consumed by the shell completion scripts, where candidate words go +through constructs that expand them. Restricting names to characters that have +no special meaning for the supported shells guarantees that the content of an +environment variable cannot be evaluated as shell code. + +Value reported by :subcmd:`config` sub-command is the list of the valid +definitions, in definition order, with target expressed as the sub-command +name it resolves to. + +Resolution +---------- + +Sub-command name resolution is a two-step process: + +1. if the name matches an alias defined in :mconfig:`subcmd_alias`, it is + replaced by the alias target +2. the result is resolved as before among the sub-command names, their + predefined aliases and abbreviations + +First step is applied once and its result is never passed through it again. +This leads to the following properties: + +- An alias always designates a sub-command, never another alias. Definitions + cannot be chained and cannot loop. With ``find=avail:avail=spider``, + ``find`` designates :subcmd:`avail`. +- An alias may bear the name of a sub-command, of a predefined alias or of an + abbreviation. This name is then shadowed: it designates the alias target. + Two names may be swapped (``avail=list:list=avail``). +- Alias match is exact. An alias cannot be abbreviated, and the abbreviations + of a shadowed sub-command still designate this sub-command. + +No sub-command name is protected against shadowing. If a definition makes +:subcmd:`config` unreachable, unsetting :envvar:`MODULES_SUBCMD_ALIAS` gives +back access to it. + +Scope +----- + +Aliases apply to the sub-command name set on the command line of the +:command:`module` and :command:`ml` commands. Translation occurs when the +command line is parsed, before any other processing. As a result everything +that depends on the sub-command name behaves as if the target name was typed: +command-line switch parsing, pager activation, result of +:mfcmd:`module-info command`, logged event, configuration options +whose value is a list of sub-command names, etc. + +With :command:`ml`, the word that may be an alias is the first argument that +is not a command-line switch. An alias name takes precedence over a module of +the same name, like sub-command names do. + +Aliases do not apply to the :mfcmd:`module` command evaluated in modulefiles, +run-command files, initialization rc files or sourced script files. What a +modulefile does must not depend on the aliases defined by the user who loads +it, especially as an alias may shadow a sub-command. + +Reporting +--------- + +Defined aliases are listed, sorted by name, in a dedicated section at the end +of the usage message returned by :subcmd:`help` sub-command without argument +and :option:`--help` option. This section is omitted when no alias is defined. + +Shell completion +---------------- + +Completion scripts read :envvar:`MODULES_SUBCMD_ALIAS` to: + +- propose alias names among the sub-command candidates +- translate the sub-command word into its target prior selecting the kind of + candidates to return + +Definitions are filtered with the same character set rule than the +:command:`module` command. Target is not checked against the list of +sub-commands: an unknown target just leads to no specific completion. + +bash, zsh and fish scripts read the environment variable each time completion +is triggered. tcsh completion relies on static rules: alias rules are +generated from the rule of their target when the completion script is sourced. +Aliases defined afterward in a tcsh session are not completed until this +script is sourced again. + +Completion scripts call :command:`module` to fetch candidates (available +modules, loaded modules, collections). :envvar:`MODULES_SUBCMD_ALIAS` is +cleared for these calls to get the expected result even if the name of the +called sub-command is shadowed. + +The value set in :file:`initrc` during initialization is exported in +:envvar:`MODULES_SUBCMD_ALIAS`, which makes site-wide definitions visible to +completion scripts. + +.. vim:set tabstop=2 shiftwidth=2 expandtab autoindent: diff --git a/doc/source/module.rst b/doc/source/module.rst index 6653519da..4aa2fa480 100644 --- a/doc/source/module.rst +++ b/doc/source/module.rst @@ -1878,6 +1878,19 @@ Module Sub-Commands .. versionadded:: 5.4 + .. mconfig:: subcmd_alias + + Aliases defined for module sub-commands. + + Default is an empty list. The :envvar:`MODULES_SUBCMD_ALIAS` environment + variable is defined by :subcmd:`config` sub-command when changing this + configuration option from its default value. See + :envvar:`MODULES_SUBCMD_ALIAS` description for details. + + .. only:: html or latex + + .. versionadded:: 5.8 + .. mconfig:: tag_abbrev Abbreviations to use to report module tags. @@ -6490,6 +6503,56 @@ ENVIRONMENT .. versionadded:: 5.4 +.. envvar:: MODULES_SUBCMD_ALIAS + + Specifies the aliases to define for module sub-commands. An alias is an + additional name that designates a sub-command when set in its place on the + :command:`module` or :command:`ml` command line. An alias accepts the same + arguments and options than the sub-command it designates. + + Value is a colon-separated list of alias definitions. Each definition has + the form ``alias=target``, like for instance ``find=avail:loaded=list``. + + Alias name may be composed of letters, digits, underscore (``_``) and + hyphen-minus (``-``) characters and cannot start with a hyphen-minus. It + cannot be ``ml``. An alias may bear the name of an existing sub-command: in + this case the alias shadows this sub-command, which cannot be designated by + this name anymore. + + Alias target is always a sub-command of the :command:`module` command, + designated by its name, one of its predefined aliases (like ``add`` for + :subcmd:`load`) or abbreviations. A target is never resolved as an alias + defined in this list. For instance with ``find=avail:avail=spider`` value, + ``find`` designates the :subcmd:`avail` sub-command even if ``avail`` name is + itself aliased to :subcmd:`spider`. + + Definitions that do not comply with these rules are ignored. When the same + alias is defined several times, last definition applies. Alias name should be + fully typed to match: it cannot be abbreviated. Abbreviations of a shadowed + sub-command still designate this sub-command. + + Aliases only apply to the sub-command name specified on the command line. + They are not taken into account for the :mfcmd:`module` command evaluated in + modulefiles, run-command files or initialization rc files. Defined aliases + are listed at the end of the usage message returned by the :subcmd:`help` + sub-command and they are taken into account by shell completion. On *tcsh* + shell, aliases should be defined prior shell completion setup to be + completed. + + See the :ref:`spack-like-sub-command-names` cookbook recipe for a complete + example that maps the command names of the Spack package manager. + + When an alias makes a sub-command unreachable, like :subcmd:`config`, unset + this environment variable to get back to the default sub-command names. + + This environment variable value supersedes the default value set in the + :mconfig:`subcmd_alias` configuration option. It can be defined with the + :subcmd:`config` sub-command. + + .. only:: html or latex + + .. versionadded:: 5.8 + .. envvar:: MODULES_TAG_ABBREV Specifies the abbreviation strings used to report module tags (see `Module diff --git a/init/Makefile b/init/Makefile index cf70dbec8..7ea4dcebb 100644 --- a/init/Makefile +++ b/init/Makefile @@ -154,7 +154,7 @@ comp_stashpop_opts := --force -f comp_source_opts := --auto --no-auto --force -f comp_path_opts := -d --delim --duplicates --priority comp_rm_path_opts := -d --delim --index -comp_config_opts := --dump-state --reset abort_on_error advanced_version_spec auto_handling avail_indepth avail_json_output avail_output avail_terse_output cache_buffer_bytes cache_expiry_secs collection_pin_version collection_pin_tag collection_target color colors conflict_unload contact csh_limit domainname editor extended_default extra_siteconfig hide_auto_loaded home icase ignore_cache ignore_cache_subcmds ignore_user_rc ignored_dirs implicit_default implicit_requirement init_envvars info_extension linked_envvars list_json_output list_output list_terse_output locked_configs logged_events logger mcookie_check mcookie_version_check ml modulepath_ignore nearly_forbidden_days non_exportable_tags pager paginate path_entry_reorder protected_envvars quarantine_support rcfile redirect_output require_via reset_target_state run_quarantine search_match set_shell_startup shells_with_ksh_fpath silent_shell_debug siteconfig source_cache spider_indepth spider_json_output spider_output spider_terse_output sticky_purge tag_abbrev tag_color_name tcl_ext_lib tcl_linter term_background term_width unique_name_loaded unload_match_order variant_shortcut verbosity wa_277 +comp_config_opts := --dump-state --reset abort_on_error advanced_version_spec auto_handling avail_indepth avail_json_output avail_output avail_terse_output cache_buffer_bytes cache_expiry_secs collection_pin_version collection_pin_tag collection_target color colors conflict_unload contact csh_limit domainname editor extended_default extra_siteconfig hide_auto_loaded home icase ignore_cache ignore_cache_subcmds ignore_user_rc ignored_dirs implicit_default implicit_requirement init_envvars info_extension linked_envvars list_json_output list_output list_terse_output locked_configs logged_events logger mcookie_check mcookie_version_check ml modulepath_ignore nearly_forbidden_days non_exportable_tags pager paginate path_entry_reorder protected_envvars quarantine_support rcfile redirect_output require_via reset_target_state run_quarantine search_match set_shell_startup shells_with_ksh_fpath silent_shell_debug siteconfig source_cache spider_indepth spider_json_output spider_output spider_terse_output sticky_purge subcmd_alias tag_abbrev tag_color_name tcl_ext_lib tcl_linter term_background term_width unique_name_loaded unload_match_order variant_shortcut verbosity wa_277 define translate-in-script $(ECHO_GEN) diff --git a/init/bash_completion.in b/init/bash_completion.in index 8514bbc81..c2834113b 100644 --- a/init/bash_completion.in +++ b/init/bash_completion.in @@ -33,7 +33,7 @@ _module_avail() { local cur="${1:-}" # skip avail call if word currently being completed is an option keyword if [ -z "$cur" ] || [ "${cur:0:1}" != '-' ]; then - module avail --color=never -s -t -S --no-indepth -o 'alias:indesym' "$cur" 2>&1 + MODULES_SUBCMD_ALIAS='' module avail --color=never -s -t -S --no-indepth -o 'alias:indesym' "$cur" 2>&1 fi } @@ -41,19 +41,19 @@ _module_spider() { local cur="${1:-}" # skip spider call if word currently being completed is an option keyword if [ -z "$cur" ] || [ "${cur:0:1}" != '-' ]; then - module spider --color=never -s -t -S --no-indepth -o 'alias:indesym' "$cur" 2>&1 + MODULES_SUBCMD_ALIAS='' module spider --color=never -s -t -S --no-indepth -o 'alias:indesym' "$cur" 2>&1 fi } _module_savelist() { - module savelist --color=never -s -t 2>&1 | sed ' + MODULES_SUBCMD_ALIAS='' module savelist --color=never -s -t 2>&1 | sed ' /No named collection\.$/d; /Named collection list$/d; /:$/d;' } _module_stashlist() { - module stashlist --color=never -s -t 2>&1 | sed ' + MODULES_SUBCMD_ALIAS='' module stashlist --color=never -s -t 2>&1 | sed ' /No stash collection\.$/d; /Stash collection list$/d; /:$/d;' @@ -63,6 +63,50 @@ _module_not_yet_loaded() { _module_avail "${1:-}" | sort | @SED_ERE@ "\%^(${LOADEDMODULES//:/|})$%d" } +# Set REPLY to the sub-command designated by the word passed as argument if +# this word is an alias defined in MODULES_SUBCMD_ALIAS, or to this word +# otherwise. Set _module_alias_list to the names of the defined aliases. +_module_subcmd_alias() { + local -a defs + local def name target + local name_re='^[A-Za-z0-9_][A-Za-z0-9_-]*$' target_re='^[a-z][a-z-]*$' + + REPLY="$1" + _module_alias_list='' + IFS=: read -r -a defs <<<"${MODULES_SUBCMD_ALIAS:-}" + for def in "${defs[@]}"; do + name="${def%%=*}" + target="${def#*=}" + # like module does, skip definitions made with unexpected characters: + # names kept can safely be used as completion candidates + if [[ $def == *=* && $name != ml && $name =~ $name_re\ + && $target =~ $target_re ]]; then + _module_alias_list+=" $name" + if [ "$name" = "$1" ]; then + REPLY="$target" + fi + fi + done +} + +# Translate previous word if it is an alias set as sub-command name, which is +# the first word that is not an option. Expect prev and aliases variables to +# be local to the calling function. +_module_resolve_prev() { + local i + + _module_subcmd_alias "$prev" + aliases="$_module_alias_list" + for ((i = 1; i < COMP_CWORD; i++)); do + if [[ ${COMP_WORDS[i]} != -* && ${COMP_WORDS[i]} != "$1" ]]; then + if [ "$i" -eq $((COMP_CWORD - 1)) ]; then + prev="$REPLY" + fi + break + fi + done +} + _module_long_arg_list() { local cur="$1" i @@ -72,7 +116,8 @@ _module_long_arg_list() { return fi for ((i = COMP_CWORD - 1; i > 0; i--)) - do case ${COMP_WORDS[$i]} in + do _module_subcmd_alias "${COMP_WORDS[$i]}" + case $REPLY in add|load) _module_comgen_words_and_files "$(_module_not_yet_loaded "$cur")" "$cur" break;; @@ -84,9 +129,10 @@ _module_long_arg_list() { } _module() { - local cur="$2" prev="$3" + local cur="$2" prev="$3" aliases COMPREPLY=() + _module_resolve_prev '' case "$prev" in add|add-any|load|load-any|try-add|try-load) @@ -155,7 +201,7 @@ _module() { sw*) COMPREPLY=( "switch" );; -*) COMPREPLY=( $(compgen -W "@comp_opts@" -- "$cur") );; - *) COMPREPLY=( $(compgen -W "@comp_opts@ @comp_cmds@" -- "$cur") );; + *) COMPREPLY=( $(compgen -W "@comp_opts@ @comp_cmds@$aliases" -- "$cur") );; esac fi;; esac @@ -164,9 +210,11 @@ _module() { # define completion for ml command if command exists if type -t ml >/dev/null; then _ml() { - local cur="$2" prev="$3" + local cur="$2" prev="$3" aliases COMPREPLY=() + # sub-command name comes after ml word when called through module + _module_resolve_prev ml case "$prev" in add|add-any|load|load-any|try-add|try-load) @@ -241,7 +289,7 @@ if type -t ml >/dev/null; then done _module_comgen_words "@comp_load_opts@ $loaded_modules" "$cur";; *) _module_comgen_words_and_files "@comp_load_opts@ $(_module_not_yet_loaded "$cur")" "$cur" - COMPREPLY=( "${COMPREPLY[@]}" $(compgen -W "@comp_opts@ @comp_cmds@" -- "$cur") ) + COMPREPLY=( "${COMPREPLY[@]}" $(compgen -W "@comp_opts@ @comp_cmds@$aliases" -- "$cur") ) loaded_modules="" for i in ${LOADEDMODULES//:/ }; do loaded_modules+="-${i} " diff --git a/init/fish_completion b/init/fish_completion index ec68bfb4f..e26116be9 100644 --- a/init/fish_completion +++ b/init/fish_completion @@ -1,7 +1,44 @@ #completion for modules +function __fish_module_subcmd_aliases --description 'Print name and target of each sub-command alias defined in MODULES_SUBCMD_ALIAS' + # like module does, skip definitions made with unexpected characters + for def in (string split : -- "$MODULES_SUBCMD_ALIAS") + set -l elts (string match -r '^([A-Za-z0-9_][A-Za-z0-9_-]*)=([a-z][a-z-]*)$' -- $def) + if test (count $elts) -eq 3; and test $elts[2] != ml + echo $elts[2] $elts[3] + end + end +end + +function __fish_module_alias_candidates --description 'Print sub-command aliases as completion candidates' + for def in (__fish_module_subcmd_aliases) + set -l elts (string split ' ' -- $def) + printf "%s\tAlias for '%s' sub-command\n" $elts[1] $elts[2] + end +end + +function __fish_module_tokens --description 'Print command line tokens with sub-command name translated if it is an alias' + set -l tokens (commandline -opc) + # sub-command name is the first token after command name that is not an option + set -l idx 2 + while test $idx -le (count $tokens) + if not string match -q -- '-*' $tokens[$idx] + set -l name $tokens[$idx] + for def in (__fish_module_subcmd_aliases) + set -l elts (string split ' ' -- $def) + if test "$elts[1]" = "$name" + set tokens[$idx] $elts[2] + end + end + break + end + set idx (math $idx + 1) + end + printf '%s\n' $tokens +end + function __fish_module_no_subcommand --description 'Test if modulecmd has yet to be given the subcommand' - for i in (commandline -opc) + for i in (__fish_module_tokens) if contains -- $i add add-any load load-any try-add try-load rm remove delete unload swap switch show display lint list avail is-loaded is-saved is-used is-avail info-loaded aliases use unuse refresh reload purge source whatis apropos keyword search test save reset restore saverm saveshow savelist stash stashclear stashlist stashpop stashrm stashshow path paths append-path prepend-path remove-path clear config sh-to-mod edit state mod-to-sh cachebuild cacheclear spider update disable describe return 1 end @@ -10,7 +47,7 @@ function __fish_module_no_subcommand --description 'Test if modulecmd has yet to end function __fish_module_use_avail --description 'Test if module command should have available packages as potential completion' - for i in (commandline -opc) + for i in (__fish_module_tokens) if contains -- $i help add add-any load load-any try-add try-load swap switch show display avail is-loaded is-avail info-loaded whatis test path paths edit lint mod-to-sh return 0 end @@ -19,7 +56,7 @@ function __fish_module_use_avail --description 'Test if module command should ha end function __fish_module_use_spider --description 'Test if module command should have spidered packages as potential completion' - for i in (commandline -opc) + for i in (__fish_module_tokens) if contains -- $i spider return 0 end @@ -28,7 +65,7 @@ function __fish_module_use_spider --description 'Test if module command should h end function __fish_module_use_list --description 'Test if module command should have loaded packages as potential completion' - for i in (commandline -opc) + for i in (__fish_module_tokens) if contains -- $i swap switch rm remove delete unload return 0 end @@ -37,7 +74,7 @@ function __fish_module_use_list --description 'Test if module command should hav end function __fish_module_use_savelist --description 'Test if module command should have saved collections as potential completion' - for i in (commandline -opc) + for i in (__fish_module_tokens) if contains -- $i save restore saverm disable saveshow describe savelist is-saved return 0 end @@ -46,7 +83,7 @@ function __fish_module_use_savelist --description 'Test if module command should end function __fish_module_use_stashlist --description 'Test if module command should have stash collections as potential completion' - for i in (commandline -opc) + for i in (__fish_module_tokens) if contains -- $i stashpop stashrm stashshow return 0 end @@ -55,7 +92,7 @@ function __fish_module_use_stashlist --description 'Test if module command shoul end function __fish_module_use_config --description 'Test if module command should have configuration parameters as potential completion' - for i in (commandline -opc) + for i in (__fish_module_tokens) if contains -- $i config return 0 end @@ -63,21 +100,22 @@ function __fish_module_use_config --description 'Test if module command should h return 1 end -complete -c module -n '__fish_module_use_avail' -f -a "(module avail --color=never -s -t -S --no-indepth -o 'alias:indesym' (commandline -ct) 2>&1)" -complete -c module -n '__fish_module_use_spider' -f -a "(module spider --color=never -s -t -S --no-indepth -o 'alias:indesym' (commandline -ct) 2>&1)" -complete -c module -n '__fish_module_use_list' -f -a "(module list --color=never -s -t -o '' 2>&1)" -complete -c module -n '__fish_module_use_savelist' -f -a "(module savelist --color=never -s -t 2>&1 | sed '\ +complete -c module -n '__fish_module_use_avail' -f -a "(set -lx MODULES_SUBCMD_ALIAS; module avail --color=never -s -t -S --no-indepth -o 'alias:indesym' (commandline -ct) 2>&1)" +complete -c module -n '__fish_module_use_spider' -f -a "(set -lx MODULES_SUBCMD_ALIAS; module spider --color=never -s -t -S --no-indepth -o 'alias:indesym' (commandline -ct) 2>&1)" +complete -c module -n '__fish_module_use_list' -f -a "(set -lx MODULES_SUBCMD_ALIAS; module list --color=never -s -t -o '' 2>&1)" +complete -c module -n '__fish_module_use_savelist' -f -a "(set -lx MODULES_SUBCMD_ALIAS; module savelist --color=never -s -t 2>&1 | sed '\ /No named collection\.\$/d; \ /Named collection list\$/d; \ /:\$/d; \ /:ERROR:/d;')" -complete -c module -n '__fish_module_use_stashlist' -f -a "(module stashlist --color=never -s -t 2>&1 | sed '\ +complete -c module -n '__fish_module_use_stashlist' -f -a "(set -lx MODULES_SUBCMD_ALIAS; module stashlist --color=never -s -t 2>&1 | sed '\ /No stash collection\.\$/d; \ /Stash collection list\$/d; \ /:\$/d; \ /:ERROR:/d;')" -complete -c module -n '__fish_module_use_config' -f -a "--dump-state --reset abort_on_error advanced_version_spec auto_handling avail_indepth avail_json_output avail_output avail_terse_output cache_buffer_bytes cache_expiry_secs collection_pin_version collection_pin_tag collection_target color colors conflict_unload contact csh_limit domainname editor extended_default extra_siteconfig hide_auto_loaded home icase ignore_cache ignore_cache_subcmds ignore_user_rc ignored_dirs implicit_default implicit_requirement init_envvars info_extension linked_envvars list_json_output list_output list_terse_output locked_configs logged_events logger mcookie_check mcookie_version_check ml modulepath_ignore nearly_forbidden_days non_exportable_tags pager paginate path_entry_reorder protected_envvars quarantine_support rcfile redirect_output require_via reset_target_state run_quarantine search_match set_shell_startup shells_with_ksh_fpath silent_shell_debug siteconfig source_cache spider_indepth spider_json_output spider_output spider_terse_output sticky_purge tag_abbrev tag_color_name tcl_ext_lib tcl_linter term_background term_width unique_name_loaded unload_match_order variant_shortcut verbosity wa_277" +complete -c module -n '__fish_module_use_config' -f -a "--dump-state --reset abort_on_error advanced_version_spec auto_handling avail_indepth avail_json_output avail_output avail_terse_output cache_buffer_bytes cache_expiry_secs collection_pin_version collection_pin_tag collection_target color colors conflict_unload contact csh_limit domainname editor extended_default extra_siteconfig hide_auto_loaded home icase ignore_cache ignore_cache_subcmds ignore_user_rc ignored_dirs implicit_default implicit_requirement init_envvars info_extension linked_envvars list_json_output list_output list_terse_output locked_configs logged_events logger mcookie_check mcookie_version_check ml modulepath_ignore nearly_forbidden_days non_exportable_tags pager paginate path_entry_reorder protected_envvars quarantine_support rcfile redirect_output require_via reset_target_state run_quarantine search_match set_shell_startup shells_with_ksh_fpath silent_shell_debug siteconfig source_cache spider_indepth spider_json_output spider_output spider_terse_output sticky_purge subcmd_alias tag_abbrev tag_color_name tcl_ext_lib tcl_linter term_background term_width unique_name_loaded unload_match_order variant_shortcut verbosity wa_277" +complete -f -n '__fish_module_no_subcommand' -c module -a '(__fish_module_alias_candidates)' complete -f -n '__fish_module_no_subcommand' -c module -a 'help' --description 'Print this or modulefile(s) help info' complete -f -n '__fish_module_no_subcommand' -c module -a 'avail' --description 'List all or matching available modules' complete -f -n '__fish_module_no_subcommand' -c module -a 'spider' --description 'Scan all modulepaths and list all or matching available modules' diff --git a/init/tcsh_completion.in b/init/tcsh_completion.in index f84bf37ec..8de1c58c4 100644 --- a/init/tcsh_completion.in +++ b/init/tcsh_completion.in @@ -3,22 +3,22 @@ # alias _module_avail '\\ - @TCLSH@ "@libexecdir@/modulecmd.tcl" tcsh avail --color=never -s -t -S -o "alias:indesym" |& cat' + env MODULES_SUBCMD_ALIAS= @TCLSH@ "@libexecdir@/modulecmd.tcl" tcsh avail --color=never -s -t -S -o "alias:indesym" |& cat' alias _module_spider '\\ - @TCLSH@ "@libexecdir@/modulecmd.tcl" tcsh spider --color=never -s -t -S -o "alias:indesym" |& cat' + env MODULES_SUBCMD_ALIAS= @TCLSH@ "@libexecdir@/modulecmd.tcl" tcsh spider --color=never -s -t -S -o "alias:indesym" |& cat' alias _module_loaded '\\ - @TCLSH@ "@libexecdir@/modulecmd.tcl" tcsh list --color=never -s -t -o "" |& cat' + env MODULES_SUBCMD_ALIAS= @TCLSH@ "@libexecdir@/modulecmd.tcl" tcsh list --color=never -s -t -o "" |& cat' alias _module_savelist '\\ - @TCLSH@ "@libexecdir@/modulecmd.tcl" tcsh savelist --color=never -s -t |& sed '"'"'\\ + env MODULES_SUBCMD_ALIAS= @TCLSH@ "@libexecdir@/modulecmd.tcl" tcsh savelist --color=never -s -t |& sed '"'"'\\ /No named collection\.$/d; \\ /Named collection list$/d; \\ /:$/d; '"'" alias _module_stashlist '\\ - @TCLSH@ "@libexecdir@/modulecmd.tcl" tcsh stashlist --color=never -s -t |& sed '"'"'\\ + env MODULES_SUBCMD_ALIAS= @TCLSH@ "@libexecdir@/modulecmd.tcl" tcsh stashlist --color=never -s -t |& sed '"'"'\\ /No stash collection\.$/d; \\ /Stash collection list$/d; \\ /:$/d; '"'" @@ -111,6 +111,38 @@ complete module 'C,/*,f,' 'C,.*,f,' 'C,~/*,f,' \ "p/1/(@comp_cmds@ @comp_opts@)/" \ "n/-*/(@comp_cmds@)/" +# give each sub-command alias defined in MODULES_SUBCMD_ALIAS when this script +# is sourced the completion rule of its target. Alias rules are set first to +# take precedence over the rule of a sub-command they shadow. Like module does, +# definitions made with unexpected characters are skipped +if ($?MODULES_SUBCMD_ALIAS) then + # disable filename substitution on the rules passed to eval + set _module_noglob = $?noglob + set noglob + eval `complete module | awk 'BEGIN { \ + getline line; rules = ""; names = ""; \ + n = split(ENVIRON["MODULES_SUBCMD_ALIAS"], defs, ":"); \ + for (i = 1; i <= n; i++) { \ + if (match(defs[i], /^[A-Za-z0-9_][A-Za-z0-9_-]*=[a-z][a-z-]*/) \ + && RLENGTH == length(defs[i])) { \ + split(defs[i], def, "="); \ + if (def[1] == "ml") continue; \ + names = names def[1] " "; \ + if (match(line, "\047n/" def[2] "/[^\047]*\047")) { \ + rule = substr(line, RSTART, RLENGTH); \ + sub("n/" def[2] "/", "n/" def[1] "/", rule); \ + rules = rule " " rules; \ + } \ + } \ + } \ + sub(/\047p\/1\/\(/, "&" names, line); \ + sub(/\047n\/-\*\/\(/, "&" names, line); \ + print "complete module " rules line; \ + }'` + if ($_module_noglob == 0) unset noglob + unset _module_noglob +endif + complete ml \ "C/--*/(@comp_long_opts@)/" \ 'c/-/`_module_loaded`/' \ diff --git a/init/zsh-functions/_module.in b/init/zsh-functions/_module.in index 16f398d78..2a8c3367a 100644 --- a/init/zsh-functions/_module.in +++ b/init/zsh-functions/_module.in @@ -9,7 +9,7 @@ _module_avail() { local cur="${1:-}"; # skip avail call if word currently being completed is an option keyword if [ -z "$cur" -o "${cur:0:1}" != '-' ]; then - module avail --color=never -s -t -S --no-indepth -o 'alias:indesym' $cur 2>&1 + MODULES_SUBCMD_ALIAS='' module avail --color=never -s -t -S --no-indepth -o 'alias:indesym' $cur 2>&1 fi } @@ -17,24 +17,38 @@ _module_spider() { local cur="${1:-}"; # skip spider call if word currently being completed is an option keyword if [ -z "$cur" -o "${cur:0:1}" != '-' ]; then - module spider --color=never -s -t -S --no-indepth -o 'alias:indesym' $cur 2>&1 + MODULES_SUBCMD_ALIAS='' module spider --color=never -s -t -S --no-indepth -o 'alias:indesym' $cur 2>&1 fi } _module_savelist() { - module savelist --color=never -s -t 2>&1 | sed ' + MODULES_SUBCMD_ALIAS='' module savelist --color=never -s -t 2>&1 | sed ' /No named collection\.$/d; /Named collection list$/d; /:$/d;' } _module_stashlist() { - module stashlist --color=never -s -t 2>&1 | sed ' + MODULES_SUBCMD_ALIAS='' module stashlist --color=never -s -t 2>&1 | sed ' /No stash collection\.$/d; /Stash collection list$/d; /:$/d;' } +# Set reply array to the name and target of each sub-command alias defined +# in MODULES_SUBCMD_ALIAS. Like module does, skip definitions made with +# unexpected characters. +_module_subcmd_aliases() { + local def + reply=() + for def in ${(s.:.)MODULES_SUBCMD_ALIAS}; do + if [[ $def =~ '^([A-Za-z0-9_][A-Za-z0-9_-]*)=([a-z][a-z-]*)$' \ + && $match[1] != ml ]]; then + reply+=($match[1] $match[2]) + fi + done +} + _module_not_yet_loaded() { _module_avail ${1:-} | sort | @SED_ERE@ "\%^(${LOADEDMODULES//:/|})$%d" } @@ -209,6 +223,12 @@ _module() { 'cachebuild:Create cache file for modulepath(s)' 'cacheclear:Delete cache file in enabled modulepath(s)' ) + # add defined aliases, that replace sub-command of the same name + local name target + _module_subcmd_aliases + for name target in $reply; do + cmds=(${cmds:#${name}:*} "${name}:Alias for '${target}' sub-command") + done # show commands only with compatible options if (( !$+opt_args[-h] && !$+opt_args[--help] \ && !$+opt_args[-V] && !$+opt_args[--version] \ @@ -219,6 +239,14 @@ _module() { (arg) local cmd="${words[1]}" local cur="${words[CURRENT]}" + # translate sub-command name if it is an alias + local name target + _module_subcmd_aliases + for name target in $reply; do + if [[ $name == ${words[1]} ]]; then + cmd=$target + fi + done case $cmd in (load|add|load-any|add-any|try-load|try-add) _arguments \ @@ -411,7 +439,7 @@ _module() { _arguments \ '--dump-state[Report each state value of current Modules execution]' \ '--reset[Unset environment variable relative to configuration key]' \ - '1:configuration key:(abort_on_error advanced_version_spec auto_handling avail_indepth avail_json_output avail_output avail_terse_output cache_buffer_bytes cache_expiry_secs collection_pin_version collection_pin_tag collection_target color colors conflict_unload contact csh_limit domainname editor extended_default extra_siteconfig hide_auto_loaded home icase ignore_cache ignore_cache_subcmds ignore_user_rc ignored_dirs implicit_default implicit_requirement init_envvars info_extension linked_envvars list_json_output list_output list_terse_output locked_configs logged_events logger mcookie_check mcookie_version_check ml modulepath_ignore nearly_forbidden_days non_exportable_tags pager paginate path_entry_reorder protected_envvars quarantine_support rcfile redirect_output require_via reset_target_state run_quarantine search_match set_shell_startup shells_with_ksh_fpath silent_shell_debug siteconfig source_cache spider_indepth spider_json_output spider_output spider_terse_output sticky_purge tag_abbrev tag_color_name tcl_ext_lib tcl_linter term_background term_width unique_name_loaded unload_match_order variant_shortcut verbosity wa_277)' \ + '1:configuration key:(abort_on_error advanced_version_spec auto_handling avail_indepth avail_json_output avail_output avail_terse_output cache_buffer_bytes cache_expiry_secs collection_pin_version collection_pin_tag collection_target color colors conflict_unload contact csh_limit domainname editor extended_default extra_siteconfig hide_auto_loaded home icase ignore_cache ignore_cache_subcmds ignore_user_rc ignored_dirs implicit_default implicit_requirement init_envvars info_extension linked_envvars list_json_output list_output list_terse_output locked_configs logged_events logger mcookie_check mcookie_version_check ml modulepath_ignore nearly_forbidden_days non_exportable_tags pager paginate path_entry_reorder protected_envvars quarantine_support rcfile redirect_output require_via reset_target_state run_quarantine search_match set_shell_startup shells_with_ksh_fpath silent_shell_debug siteconfig source_cache spider_indepth spider_json_output spider_output spider_terse_output sticky_purge subcmd_alias tag_abbrev tag_color_name tcl_ext_lib tcl_linter term_background term_width unique_name_loaded unload_match_order variant_shortcut verbosity wa_277)' \ && ret=0 ;; (edit) diff --git a/tcl/init.tcl.in b/tcl/init.tcl.in index 62ec9fb7e..8be66bae6 100644 --- a/tcl/init.tcl.in +++ b/tcl/init.tcl.in @@ -165,6 +165,7 @@ array set g_config_defs [list\ source_cache {MODULES_SOURCE_CACHE @sourcecache@ 0 b {0 1}}\ sticky_purge {MODULES_STICKY_PURGE {@stickypurge@} 0 s {error warning\ silent}}\ + subcmd_alias {MODULES_SUBCMD_ALIAS {} 0 l {} {} initConfSubcmdAlias}\ tag_abbrev {MODULES_TAG_ABBREV {@tagabbrev@} 0 l {} {} initConfTagAbbrev}\ tag_color_name {MODULES_TAG_COLOR_NAME {@tagcolorname@} 0 l {} {}\ initConfTagColorName}\ @@ -491,7 +492,8 @@ proc initStatePaginate {} { # some module sub-commands turn off pager set nopager_subcmd_list [list clear edit] if {[getState subcmd] in $nopager_subcmd_list || ([getState subcmd] eq\ - {ml} && [lindex [getState subcmd_args] 0] in $nopager_subcmd_list)} { + {ml} && [resolveSubcmdAlias [lindex [getState subcmd_args] 0]] in\ + $nopager_subcmd_list)} { return 0 } @@ -910,6 +912,45 @@ proc initConfVariantShortcut {envvar value validvallist intvallist} { return $value } +# Initialize sub-command alias table +proc initConfSubcmdAlias {envvar value validvallist intvallist} { + if {[isEnvVarDefined $envvar]} { + set value $::env($envvar) + } + + # table may already be filled if option value is changed during run + array unset ::g_subcmdAlias + set alias_list {} + foreach elt [split $value :] { + set elt_split [split $elt =] + lassign $elt_split alias target + # alias names are restricted to a set of characters shell completion + # scripts can safely handle. ml is not a sub-command: it cannot be + # shadowed + if {[llength $elt_split] == 2 && $alias ne {ml} && [regexp\ + {^[A-Za-z0-9_][A-Za-z0-9_-]*$} $alias]} { + # target is resolved among the sub-commands known by module, never + # among aliases defined here: an alias cannot point to another one + lassign [parseModuleCommandName $target {}] target cmdvalid + if {$cmdvalid} { + # last definition of an alias wins + if {![info exists ::g_subcmdAlias($alias)]} { + lappend alias_list $alias + } + set ::g_subcmdAlias($alias) $target + } + } + } + + # update value after above filtering step + set value {} + foreach alias $alias_list { + lappend value $alias=$::g_subcmdAlias($alias) + } + + return [join $value :] +} + # Is currently set verbosity level is equal or higher than level passed as arg proc isVerbosityLevel {name} { return [expr {[lsearch -exact [lindex $::g_config_defs(verbosity) 4]\ diff --git a/tcl/main.tcl.in b/tcl/main.tcl.in index 0bd66bb60..fc3554749 100644 --- a/tcl/main.tcl.in +++ b/tcl/main.tcl.in @@ -68,6 +68,17 @@ proc ongoingCommandName {commandName} { return [expr {[lsearch -exact [getState commandname] $commandName] != -1}] } +# Translate name into the sub-command it designates if it is an alias defined +# in subcmd_alias config. Result is not an alias anymore, it should not be +# passed again to this procedure. +proc resolveSubcmdAlias {name} { + getConf subcmd_alias + if {[info exists ::g_subcmdAlias($name)]} { + set name $::g_subcmdAlias($name) + } + return $name +} + # analyze/translate command name passed to module proc parseModuleCommandName {command defaultcmd} { set cmdempty 0 @@ -558,8 +569,8 @@ proc ml {args} { addpath_pos not_req tag_list fargs # determine if first argument is a known module sub-command - lassign [parseModuleCommandName [lindex $fargs 0] list] command cmdvalid\ - cmdempty + lassign [parseModuleCommandName [resolveSubcmdAlias [lindex $fargs 0]]\ + list] command cmdvalid cmdempty if {$cmdempty} { # consider empty string supplied as first argument as module name @@ -712,6 +723,14 @@ if {[catch { set $nextargisval $arg unset nextargisval } else { + # translate sub-command name if it is an alias. when ml is used, + # sub-command name is translated later by ml procedure + if {![llength $otherargv] && [string index $arg 0] ne {-}} { + set arg [resolveSubcmdAlias $arg] + } elseif {$otherargv eq {ml} && [resolveSubcmdAlias $arg] in\ + {append-path prepend-path remove-path}} { + set ddelimarg 1 + } switch -glob -- $arg { -T - --trace { set asked_verbosity trace diff --git a/tcl/report.tcl.in b/tcl/report.tcl.in index 74588623a..93caf815b 100644 --- a/tcl/report.tcl.in +++ b/tcl/report.tcl.in @@ -2237,6 +2237,16 @@ Options: Skip evaluation of user-specific module rc file --no-modulepath-ignore Do not apply modulepath-ignore pattern definitions} + + # aliases defined by configuration are part of the available sub-commands + getConf subcmd_alias + if {[array size ::g_subcmdAlias]} { + report "\nSub-command aliases:" + foreach alias [lsort [array names ::g_subcmdAlias]] { + report [format { %-15s Alias for '%s' sub-command} $alias\ + $::g_subcmdAlias($alias)] + } + } } # create appropriate message and kind of report when a requirement is not diff --git a/testsuite/completion.00-init/021-bash.exp b/testsuite/completion.00-init/021-bash.exp index 51da2fac0..d8b90f488 100644 --- a/testsuite/completion.00-init/021-bash.exp +++ b/testsuite/completion.00-init/021-bash.exp @@ -564,6 +564,49 @@ unsetenv_path_var MODULEPATH file delete -force $marker +# +# sub-command aliases defined in MODULES_SUBCMD_ALIAS: alias names are +# proposed as sub-commands and complete like their target, even when they +# bear the name of an existing sub-command. Definitions made with unexpected +# characters are ignored and cannot reach a shell expansion step +# + +set marker "$env(TESTSUITEDIR)/completion-injection-marker" +file delete -force $marker + +setenv_path_var MODULEPATH $modpath +setenv_var MODULES_SUBCMD_ALIAS "find=avail:avail=list:list=avail:ls=list:\$(touch>$marker)=avail:`touch>$marker`=avail:x;touch>$marker=avail" + +completion_bash_start + +set got [completion_bash_list {module }] +completion_assert_no_exec $marker +completion_assert_contains $got {find ls avail list load} +completion_assert_not_contains $got [list $marker] + +set got [completion_bash_list {module find }] +completion_assert_no_exec $marker +completion_assert_contains $got {advvers/ bar/ baz/ foo/} + +## list alias shadows list sub-command and targets avail, whose name is +## itself aliased: modules are still fetched with the avail sub-command +set got [completion_bash_list {module list }] +completion_assert_contains $got {advvers/ bar/ baz/ foo/} + +set got [completion_bash_list {module ls -}] +completion_assert_contains $got {--terse --json} +completion_assert_not_contains $got {--icase --no-indepth} + +set got [completion_bash_list {ml find }] +completion_assert_contains $got {advvers/ bar/ baz/ foo/} + +completion_bash_close +unsetenv_var MODULES_SUBCMD_ALIAS +unsetenv_path_var MODULEPATH + +file delete -force $marker + + # # Cleanup # diff --git a/testsuite/completion.00-init/031-zsh.exp b/testsuite/completion.00-init/031-zsh.exp index 1960ce970..16566f787 100644 --- a/testsuite/completion.00-init/031-zsh.exp +++ b/testsuite/completion.00-init/031-zsh.exp @@ -480,6 +480,46 @@ unsetenv_path_var MODULEPATH file delete -force $marker +# +# sub-command aliases defined in MODULES_SUBCMD_ALIAS: alias names are +# proposed as sub-commands and complete like their target, even when they +# bear the name of an existing sub-command. Definitions made with unexpected +# characters are ignored and cannot reach a shell expansion step +# + +set marker "$env(TESTSUITEDIR)/completion-injection-marker" +file delete -force $marker + +setenv_path_var MODULEPATH $modpath +setenv_var MODULES_SUBCMD_ALIAS "find=avail:avail=list:list=avail:ls=list:\$(touch>$marker)=avail:`touch>$marker`=avail:x;touch>$marker=avail" + +completion_zsh_start + +set got [completion_zsh_list {module }] +completion_assert_no_exec $marker +completion_assert_contains $got {find ls avail list load} +completion_assert_not_contains $got [list $marker] + +set got [completion_zsh_list {module find }] +completion_assert_no_exec $marker +completion_assert_contains $got {advvers/ bar/ baz/ foo/} + +## list alias shadows list sub-command and targets avail, whose name is +## itself aliased: modules are still fetched with the avail sub-command +set got [completion_zsh_list {module list }] +completion_assert_contains $got {advvers/ bar/ baz/ foo/} + +set got [completion_zsh_list {module ls -}] +completion_assert_contains $got {--terse --json} +completion_assert_not_contains $got {--icase --no-indepth} + +completion_zsh_close +unsetenv_var MODULES_SUBCMD_ALIAS +unsetenv_path_var MODULEPATH + +file delete -force $marker + + # # Cleanup # diff --git a/testsuite/completion.00-init/041-fish.exp b/testsuite/completion.00-init/041-fish.exp index 54f4178d2..91d50ccda 100644 --- a/testsuite/completion.00-init/041-fish.exp +++ b/testsuite/completion.00-init/041-fish.exp @@ -445,6 +445,42 @@ unsetenv_loaded_module file delete -force $marker +# +# sub-command aliases defined in MODULES_SUBCMD_ALIAS: alias names are +# proposed as sub-commands and complete like their target, even when they +# bear the name of an existing sub-command. Definitions made with unexpected +# characters are ignored and cannot reach a shell expansion step +# + +set marker "$env(TESTSUITEDIR)/completion-injection-marker" +file delete -force $marker + +setenv_path_var MODULEPATH $modpath +setenv_var MODULES_SUBCMD_ALIAS "find=avail:avail=list:list=avail:ls=list:\$(touch>$marker)=avail:`touch>$marker`=avail:x;touch>$marker=avail" + +completion_fish_start + +set got [completion_fish_list {module }] +completion_assert_no_exec $marker +completion_assert_contains $got {find ls avail list load} +completion_assert_not_contains $got [list $marker] + +set got [completion_fish_list {module find }] +completion_assert_no_exec $marker +completion_assert_contains $got {advvers/ bar/ baz/ foo/} + +## list alias shadows list sub-command and targets avail, whose name is +## itself aliased: modules are still fetched with the avail sub-command +set got [completion_fish_list {module list }] +completion_assert_contains $got {advvers/ bar/ baz/ foo/} + +completion_fish_close +unsetenv_var MODULES_SUBCMD_ALIAS +unsetenv_path_var MODULEPATH + +file delete -force $marker + + # # Cleanup # diff --git a/testsuite/completion.00-init/051-tcsh.exp b/testsuite/completion.00-init/051-tcsh.exp index da1f484e5..4a12fd8bc 100644 --- a/testsuite/completion.00-init/051-tcsh.exp +++ b/testsuite/completion.00-init/051-tcsh.exp @@ -544,6 +544,46 @@ set timeout $old_timeout file delete -force $marker +# +# sub-command aliases defined in MODULES_SUBCMD_ALIAS: alias names are +# proposed as sub-commands and complete like their target, even when they +# bear the name of an existing sub-command. Definitions made with unexpected +# characters are ignored and cannot reach a shell expansion step +# + +set marker "$env(TESTSUITEDIR)/completion-injection-marker" +file delete -force $marker + +setenv_path_var MODULEPATH $modpath +setenv_var MODULES_SUBCMD_ALIAS "find=avail:avail=list:list=avail:ls=list:\$(touch>$marker)=avail:`touch>$marker`=avail:x;touch>$marker=avail" + +completion_tcsh_start + +set got [completion_tcsh_list {module }] +completion_assert_no_exec $marker +completion_assert_contains $got {find ls avail list load} +completion_assert_not_contains $got [list $marker] + +set got [completion_tcsh_list {module find }] +completion_assert_no_exec $marker +completion_assert_contains $got {advvers/ bar/ baz/ foo/} + +## list alias shadows list sub-command and targets avail, whose name is +## itself aliased: modules are still fetched with the avail sub-command +set got [completion_tcsh_list {module list }] +completion_assert_contains $got {advvers/ bar/ baz/ foo/} + +set got [completion_tcsh_list {module ls -}] +completion_assert_contains $got {--terse --json} +completion_assert_not_contains $got {--icase --no-indepth} + +completion_tcsh_close +unsetenv_var MODULES_SUBCMD_ALIAS +unsetenv_path_var MODULEPATH + +file delete -force $marker + + # # Cleanup # diff --git a/testsuite/install.00-init/010-environ.exp b/testsuite/install.00-init/010-environ.exp index 2bfe083b2..71442bc7c 100644 --- a/testsuite/install.00-init/010-environ.exp +++ b/testsuite/install.00-init/010-environ.exp @@ -176,6 +176,9 @@ unsetenv_var MODULES_IGNORE_CACHE_SUBCMDS unsetenv_var MODULES_CACHE_BUFFER_BYTES unsetenv_var MODULES_CACHE_EXPIRY_SECS +# clean any sub-command alias configuration +unsetenv_var MODULES_SUBCMD_ALIAS + # clean any user rc configuration unsetenv_var MODULES_IGNORE_USER_RC unsetenv_var MODULES_MODULEPATH_IGNORE diff --git a/testsuite/modules.00-init/010-environ.exp b/testsuite/modules.00-init/010-environ.exp index a51f9dde9..9ba20aef9 100644 --- a/testsuite/modules.00-init/010-environ.exp +++ b/testsuite/modules.00-init/010-environ.exp @@ -177,6 +177,9 @@ unsetenv_var MODULES_IGNORE_CACHE_SUBCMDS unsetenv_var MODULES_CACHE_BUFFER_BYTES unsetenv_var MODULES_CACHE_EXPIRY_SECS +# clean any sub-command alias configuration +unsetenv_var MODULES_SUBCMD_ALIAS + # clean any user rc configuration unsetenv_var MODULES_IGNORE_USER_RC unsetenv_var MODULES_MODULEPATH_IGNORE diff --git a/testsuite/modules.70-maint/220-config.exp b/testsuite/modules.70-maint/220-config.exp index fb05318d6..b1189e9ab 100644 --- a/testsuite/modules.70-maint/220-config.exp +++ b/testsuite/modules.70-maint/220-config.exp @@ -129,6 +129,7 @@ array set configdfl [list\ sticky_purge $install_stickypurge\ tcl_ext_lib lib/libtclenvmodules$install_shlib_suffix\ tcl_linter $install_tcllintercmd\ + subcmd_alias {}\ tag_abbrev $install_tagabbrev\ tag_color_name $install_tagcolorname\ term_background $install_termbg\ @@ -203,6 +204,7 @@ array set configvar [list\ spider_output MODULES_SPIDER_OUTPUT\ spider_terse_output MODULES_SPIDER_TERSE_OUTPUT\ sticky_purge MODULES_STICKY_PURGE\ + subcmd_alias MODULES_SUBCMD_ALIAS\ tag_abbrev MODULES_TAG_ABBREV\ tag_color_name MODULES_TAG_COLOR_NAME\ tcl_linter MODULES_TCL_LINTER\ @@ -314,6 +316,7 @@ array set configkind [list\ spider_json_output l\ spider_output l\ spider_terse_output l\ + subcmd_alias l\ tag_abbrev l\ tag_color_name l\ variant_shortcut l\ @@ -447,6 +450,8 @@ foreach param [array names configvar] { set val err=31 } elseif {$param eq {tag_abbrev}} { set val loaded=L + } elseif {$param eq {subcmd_alias}} { + set val foo=avail } elseif {$param eq {variant_shortcut}} { set val foo=% } elseif {$param eq {pager}} { diff --git a/testsuite/modules.70-maint/460-subcmd_alias.exp b/testsuite/modules.70-maint/460-subcmd_alias.exp new file mode 100644 index 000000000..b5b66f92e --- /dev/null +++ b/testsuite/modules.70-maint/460-subcmd_alias.exp @@ -0,0 +1,131 @@ +############################################################################## +# Modules Revision 3.0 +# Providing a flexible user environment +# +# File: modules.70-maint/%M% +# Revision: %I% +# First Edition: 2026/11/20 +# Last Mod.: %U%, %G% +# +# Authors: Xavier Delaruelle, xavier.delaruelle@cea.fr +# +# Description: Testuite testsequence +# Command: avail, list, ml, append-path, config, help, load +# Modulefiles: loc_rc1, modbad +# Sub-Command: +# +# Comment: %C{ +# Test subcmd_alias configuration option +# }C% +# +############################################################################## + +set mp $modpath +setenv_var MODULEPATH $mp + +set tserr_avail "$mp: +loc_rc1/1.0(foo) +loc_rc1/2.0" +set avail_args {-t loc_rc1} + +# no alias defined +testouterr_cmd sh "find $avail_args" ERR [err_invcmd find] +testouterr_cmd sh "ml find $avail_args" ERR "$err_path'find'" + +# simple alias +setenv_var MODULES_SUBCMD_ALIAS find=avail +testouterr_cmd sh "find $avail_args" OK $tserr_avail +testouterr_cmd sh "avail $avail_args" OK $tserr_avail +testouterr_cmd sh "ml find $avail_args" OK $tserr_avail +# switch set prior alias name +testouterr_cmd sh {-t find loc_rc1} OK $tserr_avail +testouterr_cmd sh {ml -t find loc_rc1} OK $tserr_avail +# alias name is not abbreviated and only matches as sub-command name +testouterr_cmd sh "fin $avail_args" ERR [err_invcmd fin] +testouterr_cmd sh {is-avail find} ERR {} + +# alias shadows an existing sub-command, a built-in alias or an abbreviation +setenv_var MODULES_SUBCMD_ALIAS avail=list:show=avail:li=avail +testouterr_cmd sh "avail $avail_args" OK $no_loaded +testouterr_cmd sh "ml avail $avail_args" OK $no_loaded +testouterr_cmd sh "show $avail_args" OK $tserr_avail +testouterr_cmd sh "li $avail_args" OK $tserr_avail +# abbreviation of shadowed sub-command still designates it +testouterr_cmd sh "av $avail_args" OK $tserr_avail +testouterr_cmd sh "lis $avail_args" OK $no_loaded + +# alias target is never resolved as an alias +setenv_var MODULES_SUBCMD_ALIAS find=avail:avail=list +testouterr_cmd sh "find $avail_args" OK $tserr_avail +testouterr_cmd sh "ml find $avail_args" OK $tserr_avail +testouterr_cmd sh "avail $avail_args" OK $no_loaded +setenv_var MODULES_SUBCMD_ALIAS avail=list:list=avail +testouterr_cmd sh "avail $avail_args" OK $no_loaded +testouterr_cmd sh "list $avail_args" OK $tserr_avail +testouterr_cmd sh "ml list $avail_args" OK $tserr_avail + +# target set as built-in alias or abbreviation +setenv_var MODULES_SUBCMD_ALIAS find=av:see=show +testouterr_cmd sh "find $avail_args" OK $tserr_avail +testouterr_cmd_re sh {see loc_rc1/1.0} OK "$modlin\n[escre\ + $mp/loc_rc1/1.0]:\n\n.*$modlin" + +# last definition wins +setenv_var MODULES_SUBCMD_ALIAS find=list:find=avail +testouterr_cmd sh "find $avail_args" OK $tserr_avail + +# invalid definitions are ignored +setenv_var MODULES_SUBCMD_ALIAS\ + unk=foo:ml=avail:toml=ml:-x=avail:f?=avail:a=b=c:noeq:=avail:em=::find=avail +testouterr_cmd sh "find $avail_args" OK $tserr_avail +testouterr_cmd sh {unk} ERR [err_invcmd unk] +testouterr_cmd sh {toml} ERR [err_invcmd toml] +testouterr_cmd sh {f?} ERR [err_invcmd f?] +testouterr_cmd sh {a} ERR [err_invcmd a] +testouterr_cmd sh {noeq} ERR [err_invcmd noeq] +testouterr_cmd sh {em} ERR [err_invcmd em] +testouterr_cmd sh {ml} OK $no_loaded +testouterr_cmd_re sh {config subcmd_alias} OK\ + ".*\nsubcmd_alias\\s+find=avail \\(env-var\\)" + +# value is reported with resolved target, in definition order +setenv_var MODULES_SUBCMD_ALIAS ls=li:find=av:ls=list +testouterr_cmd_re sh {config subcmd_alias} OK\ + ".*\nsubcmd_alias\\s+ls=list:find=avail \\(env-var\\)" + +# alias on sub-command with specific option parsing +setenv_var MODULES_SUBCMD_ALIAS ap=append-path:cfg=config +set ans [list [list set FOO a,b]] +testouterr_cmd sh {ap -d , FOO a,b,a} $ans {} +testouterr_cmd sh {ml ap -d , FOO a,b,a} $ans {} +testouterr_cmd_re sh {cfg subcmd_alias} OK\ + ".*\nsubcmd_alias\\s+ap=append-path:cfg=config \\(env-var\\)" +set ans [list [list set MODULES_SUBCMD_ALIAS ap=append-path:cfg=config:ls=list]] +testouterr_cmd sh {cfg subcmd_alias +ls=list} $ans {} +set ans [list [list set MODULES_SUBCMD_ALIAS ap=append-path]] +testouterr_cmd sh {config subcmd_alias -cfg=config} $ans {} + +# aliases are listed on usage message +setenv_var MODULES_SUBCMD_ALIAS ls=list:find=avail +set tserr ".*\n\\s*--no-modulepath-ignore\n\\s*Do not apply modulepath-ignore\ +pattern definitions\n\nSub-command aliases:\n find Alias for\ +'avail' sub-command\n ls Alias for 'list' sub-command" +testouterr_cmd_re sh {--help} OK $tserr +testouterr_cmd_re sh {help} OK $tserr +setenv_var MODULES_SUBCMD_ALIAS unk=foo +testouterr_cmd_re sh {help} OK ".*\n\\s*--no-modulepath-ignore\n\\s*Do not apply\ +modulepath-ignore pattern definitions" + +# alias is not resolved on module command evaluated in modulefile +setenv_var MODULES_SUBCMD_ALIAS foo=avail +set tserr [msg_load modbad/foo [msg_moderr {module: Invalid command 'foo'}\ + {module foo} $mp/modbad/foo 27]] +testouterr_cmd sh {load modbad/foo} ERR $tserr +testouterr_cmd sh "foo $avail_args" OK $tserr_avail + + +# +# Cleanup +# + +reset_test_env