Skip to content

Self documenting functions

Michael Lockhart edited this page Mar 17, 2018 · 8 revisions

Self documenting shell functions

This idea came from languages like Java and particularly Python and Emacs Lisp: It should be possible to query the system to learn how to use functions, what arguments thep expect and what they return.

To this end there are a few conventions used

Coding conventions

  • Functions contain a local $FUNCDESC variable that describes the function.
  • Only "interactive" functions that would be called from a command-line MUST have a $FUNCDESC
  • See below for more on this variable.

The $FUNCDESC variable

  • The comment SHOULD begin with a single-line sentence that describes the function's purpose or action.
  • Following the single descriptive sentence, the rest of the string MAY list details of any parameters or special pre-post conditions.
  • The focus in this description SHOULD be on what and why, not how

Why a $FUNCDESC variable?

  • Inspired by Bash's $FUNCNAME
  • Shell comments are not tokenised, so printing the function definition with type would miss them.

Function usage

There is a usage function in 10_meta.sh (self-documented) that can be used to show function usage with parameters. Use that.

Meta-functions

There are functions on functions for exploring the code:

functions

alias: fns lists all shell functions that have been sourced.

describe

The describe function in 10_meta.sh which will print the first line of any $FUNCDESC that the function contains. It also tells you which file the function was sourced from.

list

The list function (inspired by LIST from BASIC, and the %list magic of IPython) is like describe but it also shows the in-memory representation of the function, after it was sourced from the file.

Clone this wiki locally