From 312f5909fad882a7a8c23c8ec068d290ae32220a Mon Sep 17 00:00:00 2001 From: William Melody Date: Fri, 20 Mar 2015 18:06:00 -0700 Subject: [PATCH] Add ability to add an option comment when adding a record This addition requires a number of changes including: - the addition of a new `_join` function - reformatting of the `add` function to facilitate the longer lines --- Readme.md | 6 +++--- hosts | 45 +++++++++++++++++++++++++++++++++++++-------- 2 files changed, 40 insertions(+), 11 deletions(-) diff --git a/Readme.md b/Readme.md index 4be8426..1f08d26 100644 --- a/Readme.md +++ b/Readme.md @@ -16,7 +16,7 @@ To install with homebrew, use the following command: Usage: hosts - hosts add + hosts add [comment] hosts remove ( | | ) [--force] hosts list [enabled | disabled | ] hosts show ( | | ) @@ -37,9 +37,9 @@ For help with a particular command, try: ## Commands -###### `hosts add ` +###### `hosts add [comment]` -Add a given IP address and hostname pair. +Add a given IP address and hostname pair, along with an optional comment. ###### `hosts remove ( | | ) [--force]` diff --git a/hosts b/hosts index 0a17d6b..a869b5b 100755 --- a/hosts +++ b/hosts @@ -365,6 +365,22 @@ _contains() { return 1 } +# _join() +# +# Takes a separator and a list of items, joining that list of items with the +# separator. +# +# Usage: +# _join "," a b c +# _join "${an_array[@]}" +_join() { + local separator="$1" + local target_array=(${@:2}) + local dirty="$(printf "${separator}%s" "${target_array[@]}")" + local clean="${dirty:${#separator}}" + printf "%s" "${clean}" +} + # _command_argv_includes() # # Takes a possible command argument and determines whether it is included in @@ -494,7 +510,7 @@ Version: $_VERSION Usage: $_me - $_me add + $_me add [comment] $_me remove ( | | ) [--force] $_me list [enabled | disabled | ] $_me show ( | | ) @@ -573,15 +589,16 @@ commands() { desc add < + $_me add [comment] Description: - Add a given IP address and hostname pair. + Add a given IP address and hostname pair, along with an optional comment. EOM add() { _verify_write_permissions local ip=${1:-} local hostname=${2:-} + local comment=${*:3} if [[ -z ${ip} ]]; then $_me help add exit 1 @@ -589,12 +606,24 @@ add() { printf "Please include a hostname\n" $_me help add exit 1 - elif grep "^${ip}.*[^A-Za-z0-9\.]${hostname}$" "${HOSTS_PATH}" ; then - _die printf \ - "Duplicate address/host combination, %s unchanged.\n" \ - "${HOSTS_PATH}" + elif grep \ + -e "^${ip}\t${hostname}$" \ + -e "^${ip}\t${hostname}\t.*$" "${HOSTS_PATH}" ; then + _die printf \ + "Duplicate address/host combination, %s unchanged.\n" \ + "${HOSTS_PATH}" else - printf "%s\t%s\n" "${ip}" "${hostname}" >> "${HOSTS_PATH}" + if [[ -n ${comment} ]]; then + local formmatted_comment=$(_join " " "${comment[@]}") + printf "%s\t%s\t# %s\n" \ + "${ip}" \ + "${hostname}" \ + "${formmatted_comment}" >> "${HOSTS_PATH}" + else + printf "%s\t%s\n" \ + "${ip}" \ + "${hostname}" >> "${HOSTS_PATH}" + fi fi }