Skip to content

Instantly share code, notes, and snippets.

@rhowardiv
Created March 16, 2012 13:41
Show Gist options
  • Save rhowardiv/2050107 to your computer and use it in GitHub Desktop.
Save rhowardiv/2050107 to your computer and use it in GitHub Desktop.
ack + context for php
#!/bin/bash
# A wrapper for ack to provide context for results; i.e. name of surrounding function or class
# context regex: match lines that qualify as "context"
# this could certainly be improved but it's okay for now
CONT='\<function\>.*(\|\<class\s\+[a-zA-Z_]\+'
proceed() {
while read LINE; do
# just repeat blank lines
if [ -z "$LINE" ]; then
echo "$LINE"
continue
fi
# is the line already a "context" line?
IS_CONT=$(echo "$LINE" | grep "$CONT")
if [ -n "$IS_CONT" ]; then
echo "$LINE"
continue
fi
# grab location
FILE=$(echo "$LINE" | sed 's/^\s*\([^:]\+\):[0-9]\+:.*$/\1/')
LINE_NUM=$(echo "$LINE" | sed 's/^[^:]\+:\([0-9]\+\).*$/\1/')
# nothing found?
if [ -z "$FILE" -o -z "$LINE_NUM" ]; then
echo "$LINE"
continue
fi
# look for context
SEARCH=$(head "$FILE" -n "$LINE_NUM" 2>/dev/null | tac | grep -m 1 "$CONT" | sed 's/^M$//')
if [ -n "$SEARCH" ]; then
echo "--$SEARCH"
fi
echo "$LINE"
done
}
# This tool can be called as ack, or can have ack output passed to it:
if [ -n "$*" ]; then
ack "$@" | proceed
else
proceed
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment