zsh-users
 help / color / Atom feed
From: Sebastian Gniazdowski <sgniazdowski@gmail.com>
To: Zsh Users <zsh-users@zsh.org>
Subject: A way to write type-agnostic script/function runnables
Date: Mon, 25 Nov 2019 15:22:53 +0100
Message-ID: <CAKc7PVCy_yUz6Yrxn6xprKohBP=o_zj-pRnJVY-tdsdx=gf3wg@mail.gmail.com> (raw)

Hello,
I thought that I share a way of writing runnable objects in such a way
that they can be both invoked as a script and as a function. The main
contribution is a concise method of getting the directory path where
the object is located:

# Run as script? ZSH_SCRIPT is a Zsh 5.3 addition
if [[ $0 != example-script || -n $ZSH_SCRIPT ]]; then
    0=${${ZERO:-${0:#$ZSH_ARGZERO}}:-${(%):-%N}}
    0=${${(M)0##/*}:-$PWD/$0}

    # Such global variable is expected to be typeset'd -g
    # in the plugin.zsh file. Here it's restored in case
    # of the function being ran as a script
    typeset MY_PLUGIN_DIR=${0:h}
fi

The code is also available at Zplugin's repo – it is being added as an
example object when creating a plugin with the `create' subcommand:

https://github.com/zdharma/zplugin/blob/master/doc/example-script

I wonder if one could get the directory where the function is being
located directly, without the global *_DIR parameter? Without use of
the $*trace parameters (I don't trust them;).

-- 
Sebastian Gniazdowski
News: https://twitter.com/ZdharmaI
IRC: https://kiwiirc.com/client/chat.freenode.net:+6697/#zplugin
Blog: http://zdharma.org

             reply index

Thread overview: 2+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2019-11-25 14:22 Sebastian Gniazdowski [this message]
2019-12-05 11:15 ` Sebastian Gniazdowski

Reply instructions:

You may reply publically to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to='CAKc7PVCy_yUz6Yrxn6xprKohBP=o_zj-pRnJVY-tdsdx=gf3wg@mail.gmail.com' \
    --to=sgniazdowski@gmail.com \
    --cc=zsh-users@zsh.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link

zsh-users

Archives are clonable: git clone --mirror http://inbox.vuxu.org/zsh-users

Example config snippet for mirrors

Newsgroup available over NNTP:
	nntp://inbox.vuxu.org/vuxu.archive.zsh.users


AGPL code for this site: git clone https://public-inbox.org/public-inbox.git