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
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:
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:
case "$cur" in
__autopkgcomp "--help ****"
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.