Zsh Mailing List Archive
Messages sorted by:
Reverse Date,
Date,
Thread,
Author
Re: How to “namespace” an autoloaded function?
On Mon, Oct 25, 2021 at 12:36 AM Marlon Richert
<marlon.richert@xxxxxxxxx> wrote:
>
> On 10/25/21, Bart Schaefer <schaefer@xxxxxxxxxxxxxxxx> wrote:
> > On Sun, Oct 24, 2021 at 2:17 AM Marlon Richert <marlon.richert@xxxxxxxxx>
> > wrote:
> >>
> >> What would be the canonical way to make the body of function 'foo.bar' be
> >> autoloaded from '/some/path/to/bar'?
> >
> > There isn't a "canonical" way, really. The autoload mechanism is
> > entirely dependent on the file name and the function name being the
> > same.
>
> Can you think of another way to do this than to autoload the function
> and copy it to a new function?
No. There is no mechanism for changing the name of a function while
autoloading it.
There is a way you could automatically initialize such a namespace,
but it's not exactly the same as loading it on demand in the way your
use of the term "autoload" implies. Also, if a function bar calls
another function baz, invoking the body of bar as foo.bar won't run
foo.baz under any circumstances I can imagine, so this whole idea of
namespaces falls apart pretty quickly if there is any interdependency
(or recursion that doesn't reference $0).
> Also, what would be the best way to do this in batch form? That is, I
> want to autoload _all_ function files from a particular dir as
> foo.<filename> instead of just <filename>.
Initializing the namespace goes something like this:
source <(
unfunction -m \*
fpath=(/some/path/to)
autoload +X $^fpath/*(N)
for f in ${(k)functions}
do
functions -c $f foo.$f
unfunction $f
done
functions
)
To get something more like on-demand loading, replace the "functions"
at the end with
zcompile -c $TMPPREFIX.foo
print "fpath+=($TMPPREFIX.foo.zwc);
autoload ${(k)functions}"
but that mostly saves memory rather than time because you still have
to pre-load all the function sources. (Note I did not actually test
this, so it may need adjustment.)
If your namespaces are known in advance you can create the zcompile
files in a more permanent location, and then you only have to build
them once (or each time /some/path/to changes contents).
> > alias -s bar='namespacedfunction'
>
> Would this work when calling foo.bar from inside a function that was
> loaded with `autoload -U`?
No, it would not.
Messages sorted by:
Reverse Date,
Date,
Thread,
Author