Now We Have bash Completion For Munki

I’m on a roll. I’ve written the bash completions for Munki.

(tl;dr The completions are on Github )

It’s getting easier to write them. There was one little trick I used that I didn’t
mention in my last post that I thought I’d share. How to use find and replace with
regular expressions to generate some of your code.

For this I use Find... in BBEdit. I started with a list of the commands, one on each
line.

The first thing we need to do is generate a string with each command separated by
a space. This one is trivial. We just find \n and replace it with ` `. The second one is the
hardest. We want each of the switches in the case statement like this:

	repo-add) _autopkg_repo-add ;; 
	repo-delete) _autopkg_repo-delete ;; 
	repo-list) _autopkg_list_processors ;; 
	repo-update) _autopkg_repo-update ;;

when we start with:

repo-add
repo-delete
repo-list
repo-update

The “Find” is the easy part. We want to match everything on a line up to, but not
including, the newline at the end. This looks like (.*)\n – the parentheses define the
part we want to match. Now for the replace – we want a tab, then the name, then a
parenthesis and so on. You can see we need to insert the name into a template twice.
This ends up as \t\1) _autopkg_\1 ;;\n – the \1 means “the first match in the Find”.

So I just enter those into the dialog and hit “Replace All” and the list of commands is
changed into the required bash code. After pasting the result into my script I can
hit “Undo” and the list is back ready for me to use it again. I can even generate
boilerplate code using a different replace:

_autopkg_\1() {
  local cur="${COMP_WORDS[COMP_CWORD]}"
  case "$cur" in
    --*)
      __autopkgcomp "--help ****"
      return
      ;;
  esac
}

The advantage of doing things this way is not just less typing. By generating the code
I can be sure that the switches and the function names are correct and match
each other. (BTW – notice that I have a **** in the boilerplate. This marks where I
need to alter the function and also marks it as not finished.)

Many years ago I was tutored by two of Brain Kernighan’s books – ‘Software Tools’ and
‘The Unix Programming Environment’ and this is exactly the sort of thing he evangelised.
If you can use a tool to write your code, all the better.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s