Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: Creating A Clean Environment For Autoloaded Functions



On Dec 30,  4:44am, Russell Harmon wrote:
>
> If I want to write a function which can be autoloaded, how can I
> prevent functions defined outside of my function from being accessible
> from within my function? For example, I have a function ls { gls "$@"
> }, and I know of no way to prevent that function from leaking into the
> definition of all the functions I've autoloaded which use ls.

This amounts to asking how to violate a basic tenet of shell function
behavior.  They're supposed to act like commands that are always at the
front of the search path, and the search path doesn't change based on
the order in which every other command was added to it.

The way you avoid this is to write every function that explicitly does
not want this behavior so as to explicitly override it; for examply by
using "command ls" instead of "ls".

However, you could do something like this, assuming zsh/parameter is
loaded:

    ls() {
      if (( $#funcstack > 1 ))
      then command ls "$@"
      else gls "$@"
      fi
    }

This will prevent gls from being run inside any other function, although
it won't bypass the ls wrapper function entirely.

> Additionally, is it possible to zmodload a module which is
> automatically unloaded from the environment after my function
> completes _only if_ that module was not already loaded?

There isn't a property of modules that supports this, but you can do it
yourself explicitly with something like this:

    {
      zmodload -e zsh/mathfunc	# for example
      local unload_mathfunc=$?
      zmodload zsh/mathfunc

      : do what you need to with math functions

    } always {
      (( unload_mathfunc )) && zmodload -u zsh/mathfunc
    }

If the zsh/parameter module is not itself one of the ones you care about
unloading in this way, you can be more generic:

    {
      zmodload zsh/parameter
      local -a existing_modules
      existing_modules=( ${(k)modules[(R)loaded]} ) 

      : do whatever zmodloads you want ...

    } always {
      # Requires zsh 5.0, otherwise you need a loop
      zmodload -u ${(k)modules[(R)loaded]:|existing_modules}
    }

I'm not sure that zmodload is clever enough to notice that inter-module
dependencies have been satisfied by the list provided to -u and thus
unload the modules in the correct order to be sure it succeeds, so a
bit of tweaking to the above may be required for full generality.



Messages sorted by: Reverse Date, Date, Thread, Author