← history for iron/libexec/iron/iron-help
5c7af362iron/libexec/iron/iron-help101 lines⬡ raw↓ download
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
#!/usr/bin/env bash
set -e

print_summaries() {
  local commands=()
  local summaries=()
  local longest_command=0
  local command

  for command in $(iron-commands); do
    local file="$(command_path "$command")"
    if [ ! -h "$file" ]; then
      local summary="$(summary "$file")"
      if [ -n "$summary" ]; then
        commands["${#commands[@]}"]="$command"
        summaries["${#summaries[@]}"]="$summary"

        if [ "${#command}" -gt "$longest_command" ]; then
          longest_command="${#command}"
        fi
      fi
    fi
  done

  local index
  local columns="$(tput cols)"
  local summary_length=$(( $columns - $longest_command - 5 ))

  for (( index=0; index < ${#commands[@]}; index++ )); do
    printf "   %-${longest_command}s  %s\n" "${commands[$index]}" \
      "$(truncate "$summary_length" "${summaries[$index]}")"
  done
}

print_help() {
  local file="$1"
  local usage="$(usage "$file")"

  if [ -n "$usage" ]; then
    echo "$usage"

    local help="$(help "$file")"
    [ -n "$help" ] && echo && echo "$help"
  else
    echo "Sorry, this command isn't documented yet."
  fi
}

command_path() {
  command -v "iron-$command" || command -v "iron-sh-$command" || true
}

summary() {
  sed -n "s/^# Summary: \(.*\)/\1/p" "$1"
}

usage() {
  sed -n "s/^# \(Usage: .*\)/\1/p" "$1"
}

help() {
  awk '/^[^#]/{p=0} /^# Help:/{p=1} p' "$1" | sed "s/^# Help: //;s/^# //;s/^#//"
}

truncate() {
  local max_length="$1"
  local string="$2"

  if [ "${#string}" -gt "$max_length" ]; then
    local length=$(( $max_length - 3 ))
    echo "${string:0:$length}..."
  else
    echo "$string"
  fi
}

# Provide iron completions
if [ "$1" = "--complete" ]; then
  exec "iron-commands"
  exit
fi

command="$1"
case "$command" in
"") echo "Usage: iron <command> [<args>]

Some useful iron commands are:
$(print_summaries)

See 'iron help <command>' for information on a specific command."
;;
*)
  file="$(command_path "$command")"

  if [ -n "$file" ]; then
    print_help "$file"
  else
    echo "iron: no such command \`$command'" >&2
    exit 1
  fi
esac