アクセス機能文書

アクセス機能文書

Bashでドックストリングにアクセスする方法はありますか? Bashの関数定義にドックストリングを含める方法は?

具体的には、次の関数にドックストリングを追加してアクセスするにはどうすればよいですか?

    funky() {
    echo "Violent and funky!"
    }

ベストアンサー1

最適ではありませんが、次の方法は緊急事態でうまく機能します。

declare -A fundocs_;
doc() { fundocs_[$1]=$2; }
help_doc() { echo "$1:  ${fundocs_[$1]}"; }

doc hi_from_fun "Send a short greeting"
hi_from_fun() { echo "Hi there"; }

help_doc hi_from_fun

文書は次のように印刷されます。

hi_from_fun:  Send a short greeting

最初のパラメータは関数名と一致する必要があるため、このメソッドはエラーが発生しやすいです。長期的なエラーを防ぐには、次のように関数本体内で関数文書を定義できます。

docd() { :; }  # dummy function
# for debug trap based documentation, redefined later
#  should be called with documentation as arguments
#  near the top of function body

fun2() {
    echo "Hi, I'm fun2 without documentation, just doing my job."; }

fun3() {
    docd "says hi3"
    echo "Hi, I'm fun3 with documentation, doing useful work." ; }

fun4() {
    docd "says hi4"
    echo "hi from fun4 doing other useful work"; }

次のように一時DEBUGトラップを使用してドックストリングにアクセスできます。

docd_() {
    # process args as documentation string
    # and return from nth level caller
    local n=${1:-2}; shift; local c=${FUNCNAME[$n]}
    local f=${1:-'echo $c: $@'}; shift
    [ -n "$c" -a "$c" != source ] && {
        eval $f
        trap "trap - DEBUG; return 2" DEBUG; } }

pdoc() {  #  redefine docd to call docd_ defined above
    docd() {
        docd_ 2 "" $@
        # default action: echo "function_name:  document_string"
    }

    for f; do $f; done  # arguments are function names

    docd() { : # so that the next call to function runs normally
    }
 }

だから

pdoc fun1 fun4 fun2 docd_ fun3

以下を印刷します。

bash: fun1: command not found
fun4: says hi4
Hi, I'm fun2 without documentation, just doing my job.
fun3: says hi3

メニューを作成するためにドキュメントを配列としてキャプチャできます。たとえば、

prepdoc() {  # collect documentation of functions
    declare -Ag fundocs_
    docd() { docd_ 2 "fundocs_[\$c]=\"\$*\"" $@; }
    for f; do $f; done
    docd() { :; }
    declare -p fundocs_; }

prepdoc fun1 fun4 fun2 docd_ fun3

以下を印刷します。

bash: fun1: command not found
Hi, I'm fun2 without documentation, just doing my job.
declare -A fundocs_='([fun3]="says hi3" [fun4]="says hi4" )'

存在しないfun1と文書化されていないfun2は例外であり、通常スキャン中に回避する必要がありますが、呼び出し時に何が起こるかを示すために上記に含まれています。

最後に、各機能が正しく機能していることを確認してください。

for f in fun1 fun4 fun2 docd_ fun3; do $f; done

以下を印刷します。

bash: fun1: command not found
hi from fun4 doing other useful work
Hi, I'm fun2 without documentation, just doing my job.
Hi, I'm fun3 with documentation, doing useful work.

おすすめ記事